code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::Snowball
module Types
# The address that you want the Snowball or Snowballs associated with a
# specific job to be shipped to. Addresses are validated at the time of
# creation. The address you provide must be located within the
# serviceable area of your region. Although no individual elements of
# the `Address` are required, if the address is invalid or unsupported,
# then an exception is thrown.
#
# @note When making an API call, you may pass Address
# data as a hash:
#
# {
# address_id: "AddressId",
# name: "String",
# company: "String",
# street_1: "String",
# street_2: "String",
# street_3: "String",
# city: "String",
# state_or_province: "String",
# prefecture_or_district: "String",
# landmark: "String",
# country: "String",
# postal_code: "String",
# phone_number: "String",
# is_restricted: false,
# }
#
# @!attribute [rw] address_id
# The unique ID for an address.
# @return [String]
#
# @!attribute [rw] name
# The name of a person to receive a Snowball at an address.
# @return [String]
#
# @!attribute [rw] company
# The name of the company to receive a Snowball at an address.
# @return [String]
#
# @!attribute [rw] street_1
# The first line in a street address that a Snowball is to be
# delivered to.
# @return [String]
#
# @!attribute [rw] street_2
# The second line in a street address that a Snowball is to be
# delivered to.
# @return [String]
#
# @!attribute [rw] street_3
# The third line in a street address that a Snowball is to be
# delivered to.
# @return [String]
#
# @!attribute [rw] city
# The city in an address that a Snowball is to be delivered to.
# @return [String]
#
# @!attribute [rw] state_or_province
# The state or province in an address that a Snowball is to be
# delivered to.
# @return [String]
#
# @!attribute [rw] prefecture_or_district
# This field is no longer used and the value is ignored.
# @return [String]
#
# @!attribute [rw] landmark
# This field is no longer used and the value is ignored.
# @return [String]
#
# @!attribute [rw] country
# The country in an address that a Snowball is to be delivered to.
# @return [String]
#
# @!attribute [rw] postal_code
# The postal code in an address that a Snowball is to be delivered to.
# @return [String]
#
# @!attribute [rw] phone_number
# The phone number associated with an address that a Snowball is to be
# delivered to.
# @return [String]
#
# @!attribute [rw] is_restricted
# If the address you are creating is a primary address, then set this
# option to true. This field is not supported in most regions.
# @return [Boolean]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/Address AWS API Documentation
#
class Address < Struct.new(
:address_id,
:name,
:company,
:street_1,
:street_2,
:street_3,
:city,
:state_or_province,
:prefecture_or_district,
:landmark,
:country,
:postal_code,
:phone_number,
:is_restricted)
include Aws::Structure
end
# @note When making an API call, you may pass CancelClusterRequest
# data as a hash:
#
# {
# cluster_id: "ClusterId", # required
# }
#
# @!attribute [rw] cluster_id
# The 39-character ID for the cluster that you want to cancel, for
# example `CID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CancelClusterRequest AWS API Documentation
#
class CancelClusterRequest < Struct.new(
:cluster_id)
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CancelClusterResult AWS API Documentation
#
class CancelClusterResult < Aws::EmptyStructure; end
# @note When making an API call, you may pass CancelJobRequest
# data as a hash:
#
# {
# job_id: "JobId", # required
# }
#
# @!attribute [rw] job_id
# The 39-character job ID for the job that you want to cancel, for
# example `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CancelJobRequest AWS API Documentation
#
class CancelJobRequest < Struct.new(
:job_id)
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CancelJobResult AWS API Documentation
#
class CancelJobResult < Aws::EmptyStructure; end
# Contains a cluster's state, a cluster's ID, and other important
# information.
#
# @!attribute [rw] cluster_id
# The 39-character ID for the cluster that you want to list, for
# example `CID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] cluster_state
# The current state of this cluster. For information about the state
# of a specific node, see JobListEntry$JobState.
# @return [String]
#
# @!attribute [rw] creation_date
# The creation date for this cluster.
# @return [Time]
#
# @!attribute [rw] description
# Defines an optional description of the cluster, for example
# `Environmental Data Cluster-01`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ClusterListEntry AWS API Documentation
#
class ClusterListEntry < Struct.new(
:cluster_id,
:cluster_state,
:creation_date,
:description)
include Aws::Structure
end
# Contains metadata about a specific cluster.
#
# @!attribute [rw] cluster_id
# The automatically generated ID for a cluster.
# @return [String]
#
# @!attribute [rw] description
# The optional description of the cluster.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The `KmsKeyARN` Amazon Resource Name (ARN) associated with this
# cluster. This ARN was created using the [CreateKey][1] API action in
# AWS Key Management Service (AWS KMS).
#
#
#
# [1]: http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html
# @return [String]
#
# @!attribute [rw] role_arn
# The role ARN associated with this cluster. This ARN was created
# using the [CreateRole][1] API action in AWS Identity and Access
# Management (IAM).
#
#
#
# [1]: http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
# @return [String]
#
# @!attribute [rw] cluster_state
# The current status of the cluster.
# @return [String]
#
# @!attribute [rw] job_type
# The type of job for this cluster. Currently, the only job type
# supported for clusters is `LOCAL_USE`.
# @return [String]
#
# @!attribute [rw] snowball_type
# The type of AWS Snowball device to use for this cluster. Currently,
# the only supported device type for cluster jobs is `EDGE`.
# @return [String]
#
# @!attribute [rw] creation_date
# The creation date for this cluster.
# @return [Time]
#
# @!attribute [rw] resources
# The arrays of JobResource objects that can include updated
# S3Resource objects or LambdaResource objects.
# @return [Types::JobResource]
#
# @!attribute [rw] address_id
# The automatically generated ID for a specific address.
# @return [String]
#
# @!attribute [rw] shipping_option
# The shipping speed for each node in this cluster. This speed
# doesn't dictate how soon you'll get each Snowball Edge device,
# rather it represents how quickly each device moves to its
# destination while in transit. Regional shipping speeds are as
# follows:
#
# * In Australia, you have access to express shipping. Typically,
# devices shipped express are delivered in about a day.
#
# * In the European Union (EU), you have access to express shipping.
# Typically, Snowball Edges shipped express are delivered in about a
# day. In addition, most countries in the EU have access to standard
# shipping, which typically takes less than a week, one way.
#
# * In India, Snowball Edges are delivered in one to seven days.
#
# * In the US, you have access to one-day shipping and two-day
# shipping.
# @return [String]
#
# @!attribute [rw] notification
# The Amazon Simple Notification Service (Amazon SNS) notification
# settings for this cluster.
# @return [Types::Notification]
#
# @!attribute [rw] forwarding_address_id
# The ID of the address that you want a cluster shipped to, after it
# will be shipped to its primary address. This field is not supported
# in most regions.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ClusterMetadata AWS API Documentation
#
class ClusterMetadata < Struct.new(
:cluster_id,
:description,
:kms_key_arn,
:role_arn,
:cluster_state,
:job_type,
:snowball_type,
:creation_date,
:resources,
:address_id,
:shipping_option,
:notification,
:forwarding_address_id)
include Aws::Structure
end
# A JSON-formatted object that describes a compatible Amazon Machine
# Image (AMI), including the ID and name for a Snowball Edge AMI. This
# AMI is compatible with the device's physical hardware requirements,
# and it should be able to be run in an SBE1 instance on the device.
#
# @!attribute [rw] ami_id
# The unique identifier for an individual Snowball Edge AMI.
# @return [String]
#
# @!attribute [rw] name
# The optional name of a compatible image.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CompatibleImage AWS API Documentation
#
class CompatibleImage < Struct.new(
:ami_id,
:name)
include Aws::Structure
end
# @note When making an API call, you may pass CreateAddressRequest
# data as a hash:
#
# {
# address: { # required
# address_id: "AddressId",
# name: "String",
# company: "String",
# street_1: "String",
# street_2: "String",
# street_3: "String",
# city: "String",
# state_or_province: "String",
# prefecture_or_district: "String",
# landmark: "String",
# country: "String",
# postal_code: "String",
# phone_number: "String",
# is_restricted: false,
# },
# }
#
# @!attribute [rw] address
# The address that you want the Snowball shipped to.
# @return [Types::Address]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateAddressRequest AWS API Documentation
#
class CreateAddressRequest < Struct.new(
:address)
include Aws::Structure
end
# @!attribute [rw] address_id
# The automatically generated ID for a specific address. You'll use
# this ID when you create a job to specify which address you want the
# Snowball for that job shipped to.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateAddressResult AWS API Documentation
#
class CreateAddressResult < Struct.new(
:address_id)
include Aws::Structure
end
# @note When making an API call, you may pass CreateClusterRequest
# data as a hash:
#
# {
# job_type: "IMPORT", # required, accepts IMPORT, EXPORT, LOCAL_USE
# resources: { # required
# s3_resources: [
# {
# bucket_arn: "ResourceARN",
# key_range: {
# begin_marker: "String",
# end_marker: "String",
# },
# },
# ],
# lambda_resources: [
# {
# lambda_arn: "ResourceARN",
# event_triggers: [
# {
# event_resource_arn: "ResourceARN",
# },
# ],
# },
# ],
# ec2_ami_resources: [
# {
# ami_id: "AmiId", # required
# snowball_ami_id: "String",
# },
# ],
# },
# description: "String",
# address_id: "AddressId", # required
# kms_key_arn: "KmsKeyARN",
# role_arn: "RoleARN", # required
# snowball_type: "STANDARD", # accepts STANDARD, EDGE
# shipping_option: "SECOND_DAY", # required, accepts SECOND_DAY, NEXT_DAY, EXPRESS, STANDARD
# notification: {
# sns_topic_arn: "SnsTopicARN",
# job_states_to_notify: ["New"], # accepts New, PreparingAppliance, PreparingShipment, InTransitToCustomer, WithCustomer, InTransitToAWS, WithAWS, InProgress, Complete, Cancelled, Listing, Pending
# notify_all: false,
# },
# forwarding_address_id: "AddressId",
# }
#
# @!attribute [rw] job_type
# The type of job for this cluster. Currently, the only job type
# supported for clusters is `LOCAL_USE`.
# @return [String]
#
# @!attribute [rw] resources
# The resources associated with the cluster job. These resources
# include Amazon S3 buckets and optional AWS Lambda functions written
# in the Python language.
# @return [Types::JobResource]
#
# @!attribute [rw] description
# An optional description of this specific cluster, for example
# `Environmental Data Cluster-01`.
# @return [String]
#
# @!attribute [rw] address_id
# The ID for the address that you want the cluster shipped to.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The `KmsKeyARN` value that you want to associate with this cluster.
# `KmsKeyARN` values are created by using the [CreateKey][1] API
# action in AWS Key Management Service (AWS KMS).
#
#
#
# [1]: http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html
# @return [String]
#
# @!attribute [rw] role_arn
# The `RoleARN` that you want to associate with this cluster.
# `RoleArn` values are created by using the [CreateRole][1] API action
# in AWS Identity and Access Management (IAM).
#
#
#
# [1]: http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
# @return [String]
#
# @!attribute [rw] snowball_type
# The type of AWS Snowball device to use for this cluster. Currently,
# the only supported device type for cluster jobs is `EDGE`.
# @return [String]
#
# @!attribute [rw] shipping_option
# The shipping speed for each node in this cluster. This speed
# doesn't dictate how soon you'll get each Snowball Edge device,
# rather it represents how quickly each device moves to its
# destination while in transit. Regional shipping speeds are as
# follows:
#
# * In Australia, you have access to express shipping. Typically,
# devices shipped express are delivered in about a day.
#
# * In the European Union (EU), you have access to express shipping.
# Typically, Snowball Edges shipped express are delivered in about a
# day. In addition, most countries in the EU have access to standard
# shipping, which typically takes less than a week, one way.
#
# * In India, Snowball Edges are delivered in one to seven days.
#
# * In the US, you have access to one-day shipping and two-day
# shipping.
# @return [String]
#
# @!attribute [rw] notification
# The Amazon Simple Notification Service (Amazon SNS) notification
# settings for this cluster.
# @return [Types::Notification]
#
# @!attribute [rw] forwarding_address_id
# The forwarding address ID for a cluster. This field is not supported
# in most regions.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateClusterRequest AWS API Documentation
#
class CreateClusterRequest < Struct.new(
:job_type,
:resources,
:description,
:address_id,
:kms_key_arn,
:role_arn,
:snowball_type,
:shipping_option,
:notification,
:forwarding_address_id)
include Aws::Structure
end
# @!attribute [rw] cluster_id
# The automatically generated ID for a cluster.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateClusterResult AWS API Documentation
#
class CreateClusterResult < Struct.new(
:cluster_id)
include Aws::Structure
end
# @note When making an API call, you may pass CreateJobRequest
# data as a hash:
#
# {
# job_type: "IMPORT", # accepts IMPORT, EXPORT, LOCAL_USE
# resources: {
# s3_resources: [
# {
# bucket_arn: "ResourceARN",
# key_range: {
# begin_marker: "String",
# end_marker: "String",
# },
# },
# ],
# lambda_resources: [
# {
# lambda_arn: "ResourceARN",
# event_triggers: [
# {
# event_resource_arn: "ResourceARN",
# },
# ],
# },
# ],
# ec2_ami_resources: [
# {
# ami_id: "AmiId", # required
# snowball_ami_id: "String",
# },
# ],
# },
# description: "String",
# address_id: "AddressId",
# kms_key_arn: "KmsKeyARN",
# role_arn: "RoleARN",
# snowball_capacity_preference: "T50", # accepts T50, T80, T100, NoPreference
# shipping_option: "SECOND_DAY", # accepts SECOND_DAY, NEXT_DAY, EXPRESS, STANDARD
# notification: {
# sns_topic_arn: "SnsTopicARN",
# job_states_to_notify: ["New"], # accepts New, PreparingAppliance, PreparingShipment, InTransitToCustomer, WithCustomer, InTransitToAWS, WithAWS, InProgress, Complete, Cancelled, Listing, Pending
# notify_all: false,
# },
# cluster_id: "ClusterId",
# snowball_type: "STANDARD", # accepts STANDARD, EDGE
# forwarding_address_id: "AddressId",
# }
#
# @!attribute [rw] job_type
# Defines the type of job that you're creating.
# @return [String]
#
# @!attribute [rw] resources
# Defines the Amazon S3 buckets associated with this job.
#
# With `IMPORT` jobs, you specify the bucket or buckets that your
# transferred data will be imported into.
#
# With `EXPORT` jobs, you specify the bucket or buckets that your
# transferred data will be exported from. Optionally, you can also
# specify a `KeyRange` value. If you choose to export a range, you
# define the length of the range by providing either an inclusive
# `BeginMarker` value, an inclusive `EndMarker` value, or both. Ranges
# are UTF-8 binary sorted.
# @return [Types::JobResource]
#
# @!attribute [rw] description
# Defines an optional description of this specific job, for example
# `Important Photos 2016-08-11`.
# @return [String]
#
# @!attribute [rw] address_id
# The ID for the address that you want the Snowball shipped to.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The `KmsKeyARN` that you want to associate with this job.
# `KmsKeyARN`s are created using the [CreateKey][1] AWS Key Management
# Service (KMS) API action.
#
#
#
# [1]: http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html
# @return [String]
#
# @!attribute [rw] role_arn
# The `RoleARN` that you want to associate with this job. `RoleArn`s
# are created using the [CreateRole][1] AWS Identity and Access
# Management (IAM) API action.
#
#
#
# [1]: http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
# @return [String]
#
# @!attribute [rw] snowball_capacity_preference
# If your job is being created in one of the US regions, you have the
# option of specifying what size Snowball you'd like for this job. In
# all other regions, Snowballs come with 80 TB in storage capacity.
# @return [String]
#
# @!attribute [rw] shipping_option
# The shipping speed for this job. This speed doesn't dictate how
# soon you'll get the Snowball, rather it represents how quickly the
# Snowball moves to its destination while in transit. Regional
# shipping speeds are as follows:
#
# * In Australia, you have access to express shipping. Typically,
# Snowballs shipped express are delivered in about a day.
#
# * In the European Union (EU), you have access to express shipping.
# Typically, Snowballs shipped express are delivered in about a day.
# In addition, most countries in the EU have access to standard
# shipping, which typically takes less than a week, one way.
#
# * In India, Snowballs are delivered in one to seven days.
#
# * In the US, you have access to one-day shipping and two-day
# shipping.
# @return [String]
#
# @!attribute [rw] notification
# Defines the Amazon Simple Notification Service (Amazon SNS)
# notification settings for this job.
# @return [Types::Notification]
#
# @!attribute [rw] cluster_id
# The ID of a cluster. If you're creating a job for a node in a
# cluster, you need to provide only this `clusterId` value. The other
# job attributes are inherited from the cluster.
# @return [String]
#
# @!attribute [rw] snowball_type
# The type of AWS Snowball device to use for this job. Currently, the
# only supported device type for cluster jobs is `EDGE`.
# @return [String]
#
# @!attribute [rw] forwarding_address_id
# The forwarding address ID for a job. This field is not supported in
# most regions.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateJobRequest AWS API Documentation
#
class CreateJobRequest < Struct.new(
:job_type,
:resources,
:description,
:address_id,
:kms_key_arn,
:role_arn,
:snowball_capacity_preference,
:shipping_option,
:notification,
:cluster_id,
:snowball_type,
:forwarding_address_id)
include Aws::Structure
end
# @!attribute [rw] job_id
# The automatically generated ID for a job, for example
# `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/CreateJobResult AWS API Documentation
#
class CreateJobResult < Struct.new(
:job_id)
include Aws::Structure
end
# Defines the real-time status of a Snowball's data transfer while the
# device is at AWS. This data is only available while a job has a
# `JobState` value of `InProgress`, for both import and export jobs.
#
# @!attribute [rw] bytes_transferred
# The number of bytes transferred between a Snowball and Amazon S3.
# @return [Integer]
#
# @!attribute [rw] objects_transferred
# The number of objects transferred between a Snowball and Amazon S3.
# @return [Integer]
#
# @!attribute [rw] total_bytes
# The total bytes of data for a transfer between a Snowball and Amazon
# S3. This value is set to 0 (zero) until all the keys that will be
# transferred have been listed.
# @return [Integer]
#
# @!attribute [rw] total_objects
# The total number of objects for a transfer between a Snowball and
# Amazon S3. This value is set to 0 (zero) until all the keys that
# will be transferred have been listed.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DataTransfer AWS API Documentation
#
class DataTransfer < Struct.new(
:bytes_transferred,
:objects_transferred,
:total_bytes,
:total_objects)
include Aws::Structure
end
# @note When making an API call, you may pass DescribeAddressRequest
# data as a hash:
#
# {
# address_id: "AddressId", # required
# }
#
# @!attribute [rw] address_id
# The automatically generated ID for a specific address.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeAddressRequest AWS API Documentation
#
class DescribeAddressRequest < Struct.new(
:address_id)
include Aws::Structure
end
# @!attribute [rw] address
# The address that you want the Snowball or Snowballs associated with
# a specific job to be shipped to.
# @return [Types::Address]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeAddressResult AWS API Documentation
#
class DescribeAddressResult < Struct.new(
:address)
include Aws::Structure
end
# @note When making an API call, you may pass DescribeAddressesRequest
# data as a hash:
#
# {
# max_results: 1,
# next_token: "String",
# }
#
# @!attribute [rw] max_results
# The number of `ADDRESS` objects to return.
# @return [Integer]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. To identify what object comes "next"
# in the list of `ADDRESS` objects, you have the option of specifying
# a value for `NextToken` as the starting point for your list of
# returned addresses.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeAddressesRequest AWS API Documentation
#
class DescribeAddressesRequest < Struct.new(
:max_results,
:next_token)
include Aws::Structure
end
# @!attribute [rw] addresses
# The Snowball shipping addresses that were created for this account.
# @return [Array<Types::Address>]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. If you use the automatically generated
# `NextToken` value in your next `DescribeAddresses` call, your list
# of returned addresses will start from this point in the array.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeAddressesResult AWS API Documentation
#
class DescribeAddressesResult < Struct.new(
:addresses,
:next_token)
include Aws::Structure
end
# @note When making an API call, you may pass DescribeClusterRequest
# data as a hash:
#
# {
# cluster_id: "ClusterId", # required
# }
#
# @!attribute [rw] cluster_id
# The automatically generated ID for a cluster.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeClusterRequest AWS API Documentation
#
class DescribeClusterRequest < Struct.new(
:cluster_id)
include Aws::Structure
end
# @!attribute [rw] cluster_metadata
# Information about a specific cluster, including shipping
# information, cluster status, and other important metadata.
# @return [Types::ClusterMetadata]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeClusterResult AWS API Documentation
#
class DescribeClusterResult < Struct.new(
:cluster_metadata)
include Aws::Structure
end
# @note When making an API call, you may pass DescribeJobRequest
# data as a hash:
#
# {
# job_id: "JobId", # required
# }
#
# @!attribute [rw] job_id
# The automatically generated ID for a job, for example
# `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeJobRequest AWS API Documentation
#
class DescribeJobRequest < Struct.new(
:job_id)
include Aws::Structure
end
# @!attribute [rw] job_metadata
# Information about a specific job, including shipping information,
# job status, and other important metadata.
# @return [Types::JobMetadata]
#
# @!attribute [rw] sub_job_metadata
# Information about a specific job part (in the case of an export
# job), including shipping information, job status, and other
# important metadata.
# @return [Array<Types::JobMetadata>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/DescribeJobResult AWS API Documentation
#
class DescribeJobResult < Struct.new(
:job_metadata,
:sub_job_metadata)
include Aws::Structure
end
# A JSON-formatted object that contains the IDs for an Amazon Machine
# Image (AMI), including the Amazon EC2 AMI ID and the Snowball Edge AMI
# ID. Each AMI has these two IDs to simplify identifying the AMI in both
# the AWS Cloud and on the device.
#
# @note When making an API call, you may pass Ec2AmiResource
# data as a hash:
#
# {
# ami_id: "AmiId", # required
# snowball_ami_id: "String",
# }
#
# @!attribute [rw] ami_id
# The ID of the AMI in Amazon EC2.
# @return [String]
#
# @!attribute [rw] snowball_ami_id
# The ID of the AMI on the Snowball Edge device.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/Ec2AmiResource AWS API Documentation
#
class Ec2AmiResource < Struct.new(
:ami_id,
:snowball_ami_id)
include Aws::Structure
end
# The container for the EventTriggerDefinition$EventResourceARN.
#
# @note When making an API call, you may pass EventTriggerDefinition
# data as a hash:
#
# {
# event_resource_arn: "ResourceARN",
# }
#
# @!attribute [rw] event_resource_arn
# The Amazon Resource Name (ARN) for any local Amazon S3 resource that
# is an AWS Lambda function's event trigger associated with this job.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/EventTriggerDefinition AWS API Documentation
#
class EventTriggerDefinition < Struct.new(
:event_resource_arn)
include Aws::Structure
end
# @note When making an API call, you may pass GetJobManifestRequest
# data as a hash:
#
# {
# job_id: "JobId", # required
# }
#
# @!attribute [rw] job_id
# The ID for a job that you want to get the manifest file for, for
# example `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/GetJobManifestRequest AWS API Documentation
#
class GetJobManifestRequest < Struct.new(
:job_id)
include Aws::Structure
end
# @!attribute [rw] manifest_uri
# The Amazon S3 presigned URL for the manifest file associated with
# the specified `JobId` value.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/GetJobManifestResult AWS API Documentation
#
class GetJobManifestResult < Struct.new(
:manifest_uri)
include Aws::Structure
end
# @note When making an API call, you may pass GetJobUnlockCodeRequest
# data as a hash:
#
# {
# job_id: "JobId", # required
# }
#
# @!attribute [rw] job_id
# The ID for the job that you want to get the `UnlockCode` value for,
# for example `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/GetJobUnlockCodeRequest AWS API Documentation
#
class GetJobUnlockCodeRequest < Struct.new(
:job_id)
include Aws::Structure
end
# @!attribute [rw] unlock_code
# The `UnlockCode` value for the specified job. The `UnlockCode` value
# can be accessed for up to 90 days after the job has been created.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/GetJobUnlockCodeResult AWS API Documentation
#
class GetJobUnlockCodeResult < Struct.new(
:unlock_code)
include Aws::Structure
end
# @api private
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/GetSnowballUsageRequest AWS API Documentation
#
class GetSnowballUsageRequest < Aws::EmptyStructure; end
# @!attribute [rw] snowball_limit
# The service limit for number of Snowballs this account can have at
# once. The default service limit is 1 (one).
# @return [Integer]
#
# @!attribute [rw] snowballs_in_use
# The number of Snowballs that this account is currently using.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/GetSnowballUsageResult AWS API Documentation
#
class GetSnowballUsageResult < Struct.new(
:snowball_limit,
:snowballs_in_use)
include Aws::Structure
end
# Each `JobListEntry` object contains a job's state, a job's ID, and a
# value that indicates whether the job is a job part, in the case of an
# export job.
#
# @!attribute [rw] job_id
# The automatically generated ID for a job, for example
# `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] job_state
# The current state of this job.
# @return [String]
#
# @!attribute [rw] is_master
# A value that indicates that this job is a master job. A master job
# represents a successful request to create an export job. Master jobs
# aren't associated with any Snowballs. Instead, each master job will
# have at least one job part, and each job part is associated with a
# Snowball. It might take some time before the job parts associated
# with a particular master job are listed, because they are created
# after the master job is created.
# @return [Boolean]
#
# @!attribute [rw] job_type
# The type of job.
# @return [String]
#
# @!attribute [rw] snowball_type
# The type of device used with this job.
# @return [String]
#
# @!attribute [rw] creation_date
# The creation date for this job.
# @return [Time]
#
# @!attribute [rw] description
# The optional description of this specific job, for example
# `Important Photos 2016-08-11`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/JobListEntry AWS API Documentation
#
class JobListEntry < Struct.new(
:job_id,
:job_state,
:is_master,
:job_type,
:snowball_type,
:creation_date,
:description)
include Aws::Structure
end
# Contains job logs. Whenever Snowball is used to import data into or
# export data out of Amazon S3, you'll have the option of downloading a
# PDF job report. Job logs are returned as a part of the response syntax
# of the `DescribeJob` action in the `JobMetadata` data type. The job
# logs can be accessed for up to 60 minutes after this request has been
# made. To access any of the job logs after 60 minutes have passed,
# you'll have to make another call to the `DescribeJob` action.
#
# For import jobs, the PDF job report becomes available at the end of
# the import process. For export jobs, your job report typically becomes
# available while the Snowball for your job part is being delivered to
# you.
#
# The job report provides you insight into the state of your Amazon S3
# data transfer. The report includes details about your job or job part
# for your records.
#
# For deeper visibility into the status of your transferred objects, you
# can look at the two associated logs: a success log and a failure log.
# The logs are saved in comma-separated value (CSV) format, and the name
# of each log includes the ID of the job or job part that the log
# describes.
#
# @!attribute [rw] job_completion_report_uri
# A link to an Amazon S3 presigned URL where the job completion report
# is located.
# @return [String]
#
# @!attribute [rw] job_success_log_uri
# A link to an Amazon S3 presigned URL where the job success log is
# located.
# @return [String]
#
# @!attribute [rw] job_failure_log_uri
# A link to an Amazon S3 presigned URL where the job failure log is
# located.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/JobLogs AWS API Documentation
#
class JobLogs < Struct.new(
:job_completion_report_uri,
:job_success_log_uri,
:job_failure_log_uri)
include Aws::Structure
end
# Contains information about a specific job including shipping
# information, job status, and other important metadata. This
# information is returned as a part of the response syntax of the
# `DescribeJob` action.
#
# @!attribute [rw] job_id
# The automatically generated ID for a job, for example
# `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] job_state
# The current status of the jobs.
# @return [String]
#
# @!attribute [rw] job_type
# The type of job.
# @return [String]
#
# @!attribute [rw] snowball_type
# The type of device used with this job.
# @return [String]
#
# @!attribute [rw] creation_date
# The creation date for this job.
# @return [Time]
#
# @!attribute [rw] resources
# An array of `S3Resource` objects. Each `S3Resource` object
# represents an Amazon S3 bucket that your transferred data will be
# exported from or imported into.
# @return [Types::JobResource]
#
# @!attribute [rw] description
# The description of the job, provided at job creation.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The Amazon Resource Name (ARN) for the AWS Key Management Service
# (AWS KMS) key associated with this job. This ARN was created using
# the [CreateKey][1] API action in AWS KMS.
#
#
#
# [1]: http://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html
# @return [String]
#
# @!attribute [rw] role_arn
# The role ARN associated with this job. This ARN was created using
# the [CreateRole][1] API action in AWS Identity and Access Management
# (IAM).
#
#
#
# [1]: http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
# @return [String]
#
# @!attribute [rw] address_id
# The ID for the address that you want the Snowball shipped to.
# @return [String]
#
# @!attribute [rw] shipping_details
# A job's shipping information, including inbound and outbound
# tracking numbers and shipping speed options.
# @return [Types::ShippingDetails]
#
# @!attribute [rw] snowball_capacity_preference
# The Snowball capacity preference for this job, specified at job
# creation. In US regions, you can choose between 50 TB and 80 TB
# Snowballs. All other regions use 80 TB capacity Snowballs.
# @return [String]
#
# @!attribute [rw] notification
# The Amazon Simple Notification Service (Amazon SNS) notification
# settings associated with a specific job. The `Notification` object
# is returned as a part of the response syntax of the `DescribeJob`
# action in the `JobMetadata` data type.
# @return [Types::Notification]
#
# @!attribute [rw] data_transfer_progress
# A value that defines the real-time status of a Snowball's data
# transfer while the device is at AWS. This data is only available
# while a job has a `JobState` value of `InProgress`, for both import
# and export jobs.
# @return [Types::DataTransfer]
#
# @!attribute [rw] job_log_info
# Links to Amazon S3 presigned URLs for the job report and logs. For
# import jobs, the PDF job report becomes available at the end of the
# import process. For export jobs, your job report typically becomes
# available while the Snowball for your job part is being delivered to
# you.
# @return [Types::JobLogs]
#
# @!attribute [rw] cluster_id
# The 39-character ID for the cluster, for example
# `CID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] forwarding_address_id
# The ID of the address that you want a job shipped to, after it will
# be shipped to its primary address. This field is not supported in
# most regions.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/JobMetadata AWS API Documentation
#
class JobMetadata < Struct.new(
:job_id,
:job_state,
:job_type,
:snowball_type,
:creation_date,
:resources,
:description,
:kms_key_arn,
:role_arn,
:address_id,
:shipping_details,
:snowball_capacity_preference,
:notification,
:data_transfer_progress,
:job_log_info,
:cluster_id,
:forwarding_address_id)
include Aws::Structure
end
# Contains an array of AWS resource objects. Each object represents an
# Amazon S3 bucket, an AWS Lambda function, or an Amazon Machine Image
# (AMI) based on Amazon EC2 that is associated with a particular job.
#
# @note When making an API call, you may pass JobResource
# data as a hash:
#
# {
# s3_resources: [
# {
# bucket_arn: "ResourceARN",
# key_range: {
# begin_marker: "String",
# end_marker: "String",
# },
# },
# ],
# lambda_resources: [
# {
# lambda_arn: "ResourceARN",
# event_triggers: [
# {
# event_resource_arn: "ResourceARN",
# },
# ],
# },
# ],
# ec2_ami_resources: [
# {
# ami_id: "AmiId", # required
# snowball_ami_id: "String",
# },
# ],
# }
#
# @!attribute [rw] s3_resources
# An array of `S3Resource` objects.
# @return [Array<Types::S3Resource>]
#
# @!attribute [rw] lambda_resources
# The Python-language Lambda functions for this job.
# @return [Array<Types::LambdaResource>]
#
# @!attribute [rw] ec2_ami_resources
# The Amazon Machine Images (AMIs) associated with this job.
# @return [Array<Types::Ec2AmiResource>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/JobResource AWS API Documentation
#
class JobResource < Struct.new(
:s3_resources,
:lambda_resources,
:ec2_ami_resources)
include Aws::Structure
end
# Contains a key range. For export jobs, a `S3Resource` object can have
# an optional `KeyRange` value. The length of the range is defined at
# job creation, and has either an inclusive `BeginMarker`, an inclusive
# `EndMarker`, or both. Ranges are UTF-8 binary sorted.
#
# @note When making an API call, you may pass KeyRange
# data as a hash:
#
# {
# begin_marker: "String",
# end_marker: "String",
# }
#
# @!attribute [rw] begin_marker
# The key that starts an optional key range for an export job. Ranges
# are inclusive and UTF-8 binary sorted.
# @return [String]
#
# @!attribute [rw] end_marker
# The key that ends an optional key range for an export job. Ranges
# are inclusive and UTF-8 binary sorted.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/KeyRange AWS API Documentation
#
class KeyRange < Struct.new(
:begin_marker,
:end_marker)
include Aws::Structure
end
# Identifies
#
# @note When making an API call, you may pass LambdaResource
# data as a hash:
#
# {
# lambda_arn: "ResourceARN",
# event_triggers: [
# {
# event_resource_arn: "ResourceARN",
# },
# ],
# }
#
# @!attribute [rw] lambda_arn
# An Amazon Resource Name (ARN) that represents an AWS Lambda function
# to be triggered by PUT object actions on the associated local Amazon
# S3 resource.
# @return [String]
#
# @!attribute [rw] event_triggers
# The array of ARNs for S3Resource objects to trigger the
# LambdaResource objects associated with this job.
# @return [Array<Types::EventTriggerDefinition>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/LambdaResource AWS API Documentation
#
class LambdaResource < Struct.new(
:lambda_arn,
:event_triggers)
include Aws::Structure
end
# @note When making an API call, you may pass ListClusterJobsRequest
# data as a hash:
#
# {
# cluster_id: "ClusterId", # required
# max_results: 1,
# next_token: "String",
# }
#
# @!attribute [rw] cluster_id
# The 39-character ID for the cluster that you want to list, for
# example `CID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] max_results
# The number of `JobListEntry` objects to return.
# @return [Integer]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. To identify what object comes "next"
# in the list of `JobListEntry` objects, you have the option of
# specifying `NextToken` as the starting point for your returned list.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListClusterJobsRequest AWS API Documentation
#
class ListClusterJobsRequest < Struct.new(
:cluster_id,
:max_results,
:next_token)
include Aws::Structure
end
# @!attribute [rw] job_list_entries
# Each `JobListEntry` object contains a job's state, a job's ID, and
# a value that indicates whether the job is a job part, in the case of
# export jobs.
# @return [Array<Types::JobListEntry>]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. If you use the automatically generated
# `NextToken` value in your next `ListClusterJobsResult` call, your
# list of returned jobs will start from this point in the array.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListClusterJobsResult AWS API Documentation
#
class ListClusterJobsResult < Struct.new(
:job_list_entries,
:next_token)
include Aws::Structure
end
# @note When making an API call, you may pass ListClustersRequest
# data as a hash:
#
# {
# max_results: 1,
# next_token: "String",
# }
#
# @!attribute [rw] max_results
# The number of `ClusterListEntry` objects to return.
# @return [Integer]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. To identify what object comes "next"
# in the list of `ClusterListEntry` objects, you have the option of
# specifying `NextToken` as the starting point for your returned list.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListClustersRequest AWS API Documentation
#
class ListClustersRequest < Struct.new(
:max_results,
:next_token)
include Aws::Structure
end
# @!attribute [rw] cluster_list_entries
# Each `ClusterListEntry` object contains a cluster's state, a
# cluster's ID, and other important status information.
# @return [Array<Types::ClusterListEntry>]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. If you use the automatically generated
# `NextToken` value in your next `ClusterListEntry` call, your list of
# returned clusters will start from this point in the array.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListClustersResult AWS API Documentation
#
class ListClustersResult < Struct.new(
:cluster_list_entries,
:next_token)
include Aws::Structure
end
# @note When making an API call, you may pass ListCompatibleImagesRequest
# data as a hash:
#
# {
# max_results: 1,
# next_token: "String",
# }
#
# @!attribute [rw] max_results
# The maximum number of results for the list of compatible images.
# Currently, a Snowball Edge device can store 10 AMIs.
# @return [Integer]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. To identify what object comes "next"
# in the list of compatible images, you can specify a value for
# `NextToken` as the starting point for your list of returned images.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListCompatibleImagesRequest AWS API Documentation
#
class ListCompatibleImagesRequest < Struct.new(
:max_results,
:next_token)
include Aws::Structure
end
# @!attribute [rw] compatible_images
# A JSON-formatted object that describes a compatible AMI, including
# the ID and name for a Snowball Edge AMI.
# @return [Array<Types::CompatibleImage>]
#
# @!attribute [rw] next_token
# Because HTTP requests are stateless, this is the starting point for
# your next list of returned images.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListCompatibleImagesResult AWS API Documentation
#
class ListCompatibleImagesResult < Struct.new(
:compatible_images,
:next_token)
include Aws::Structure
end
# @note When making an API call, you may pass ListJobsRequest
# data as a hash:
#
# {
# max_results: 1,
# next_token: "String",
# }
#
# @!attribute [rw] max_results
# The number of `JobListEntry` objects to return.
# @return [Integer]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. To identify what object comes "next"
# in the list of `JobListEntry` objects, you have the option of
# specifying `NextToken` as the starting point for your returned list.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListJobsRequest AWS API Documentation
#
class ListJobsRequest < Struct.new(
:max_results,
:next_token)
include Aws::Structure
end
# @!attribute [rw] job_list_entries
# Each `JobListEntry` object contains a job's state, a job's ID, and
# a value that indicates whether the job is a job part, in the case of
# export jobs.
# @return [Array<Types::JobListEntry>]
#
# @!attribute [rw] next_token
# HTTP requests are stateless. If you use this automatically generated
# `NextToken` value in your next `ListJobs` call, your returned
# `JobListEntry` objects will start from this point in the array.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ListJobsResult AWS API Documentation
#
class ListJobsResult < Struct.new(
:job_list_entries,
:next_token)
include Aws::Structure
end
# The Amazon Simple Notification Service (Amazon SNS) notification
# settings associated with a specific job. The `Notification` object is
# returned as a part of the response syntax of the `DescribeJob` action
# in the `JobMetadata` data type.
#
# When the notification settings are defined during job creation, you
# can choose to notify based on a specific set of job states using the
# `JobStatesToNotify` array of strings, or you can specify that you want
# to have Amazon SNS notifications sent out for all job states with
# `NotifyAll` set to true.
#
# @note When making an API call, you may pass Notification
# data as a hash:
#
# {
# sns_topic_arn: "SnsTopicARN",
# job_states_to_notify: ["New"], # accepts New, PreparingAppliance, PreparingShipment, InTransitToCustomer, WithCustomer, InTransitToAWS, WithAWS, InProgress, Complete, Cancelled, Listing, Pending
# notify_all: false,
# }
#
# @!attribute [rw] sns_topic_arn
# The new SNS `TopicArn` that you want to associate with this job. You
# can create Amazon Resource Names (ARNs) for topics by using the
# [CreateTopic][1] Amazon SNS API action.
#
# You can subscribe email addresses to an Amazon SNS topic through the
# AWS Management Console, or by using the [Subscribe][2] AWS Simple
# Notification Service (SNS) API action.
#
#
#
# [1]: http://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html
# [2]: http://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html
# @return [String]
#
# @!attribute [rw] job_states_to_notify
# The list of job states that will trigger a notification for this
# job.
# @return [Array<String>]
#
# @!attribute [rw] notify_all
# Any change in job state will trigger a notification for this job.
# @return [Boolean]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/Notification AWS API Documentation
#
class Notification < Struct.new(
:sns_topic_arn,
:job_states_to_notify,
:notify_all)
include Aws::Structure
end
# Each `S3Resource` object represents an Amazon S3 bucket that your
# transferred data will be exported from or imported into. For export
# jobs, this object can have an optional `KeyRange` value. The length of
# the range is defined at job creation, and has either an inclusive
# `BeginMarker`, an inclusive `EndMarker`, or both. Ranges are UTF-8
# binary sorted.
#
# @note When making an API call, you may pass S3Resource
# data as a hash:
#
# {
# bucket_arn: "ResourceARN",
# key_range: {
# begin_marker: "String",
# end_marker: "String",
# },
# }
#
# @!attribute [rw] bucket_arn
# The Amazon Resource Name (ARN) of an Amazon S3 bucket.
# @return [String]
#
# @!attribute [rw] key_range
# For export jobs, you can provide an optional `KeyRange` within a
# specific Amazon S3 bucket. The length of the range is defined at job
# creation, and has either an inclusive `BeginMarker`, an inclusive
# `EndMarker`, or both. Ranges are UTF-8 binary sorted.
# @return [Types::KeyRange]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/S3Resource AWS API Documentation
#
class S3Resource < Struct.new(
:bucket_arn,
:key_range)
include Aws::Structure
end
# The `Status` and `TrackingNumber` information for an inbound or
# outbound shipment.
#
# @!attribute [rw] status
# Status information for a shipment.
# @return [String]
#
# @!attribute [rw] tracking_number
# The tracking number for this job. Using this tracking number with
# your region's carrier's website, you can track a Snowball as the
# carrier transports it.
#
# For India, the carrier is Amazon Logistics. For all other regions,
# UPS is the carrier.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/Shipment AWS API Documentation
#
class Shipment < Struct.new(
:status,
:tracking_number)
include Aws::Structure
end
# A job's shipping information, including inbound and outbound tracking
# numbers and shipping speed options.
#
# @!attribute [rw] shipping_option
# The shipping speed for a particular job. This speed doesn't dictate
# how soon you'll get the Snowball from the job's creation date.
# This speed represents how quickly it moves to its destination while
# in transit. Regional shipping speeds are as follows:
#
# * In Australia, you have access to express shipping. Typically,
# Snowballs shipped express are delivered in about a day.
#
# * In the European Union (EU), you have access to express shipping.
# Typically, Snowballs shipped express are delivered in about a day.
# In addition, most countries in the EU have access to standard
# shipping, which typically takes less than a week, one way.
#
# * In India, Snowballs are delivered in one to seven days.
#
# * In the United States of America (US), you have access to one-day
# shipping and two-day shipping.
# @return [String]
#
# @!attribute [rw] inbound_shipment
# The `Status` and `TrackingNumber` values for a Snowball being
# returned to AWS for a particular job.
# @return [Types::Shipment]
#
# @!attribute [rw] outbound_shipment
# The `Status` and `TrackingNumber` values for a Snowball being
# delivered to the address that you specified for a particular job.
# @return [Types::Shipment]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/ShippingDetails AWS API Documentation
#
class ShippingDetails < Struct.new(
:shipping_option,
:inbound_shipment,
:outbound_shipment)
include Aws::Structure
end
# @note When making an API call, you may pass UpdateClusterRequest
# data as a hash:
#
# {
# cluster_id: "ClusterId", # required
# role_arn: "RoleARN",
# description: "String",
# resources: {
# s3_resources: [
# {
# bucket_arn: "ResourceARN",
# key_range: {
# begin_marker: "String",
# end_marker: "String",
# },
# },
# ],
# lambda_resources: [
# {
# lambda_arn: "ResourceARN",
# event_triggers: [
# {
# event_resource_arn: "ResourceARN",
# },
# ],
# },
# ],
# ec2_ami_resources: [
# {
# ami_id: "AmiId", # required
# snowball_ami_id: "String",
# },
# ],
# },
# address_id: "AddressId",
# shipping_option: "SECOND_DAY", # accepts SECOND_DAY, NEXT_DAY, EXPRESS, STANDARD
# notification: {
# sns_topic_arn: "SnsTopicARN",
# job_states_to_notify: ["New"], # accepts New, PreparingAppliance, PreparingShipment, InTransitToCustomer, WithCustomer, InTransitToAWS, WithAWS, InProgress, Complete, Cancelled, Listing, Pending
# notify_all: false,
# },
# forwarding_address_id: "AddressId",
# }
#
# @!attribute [rw] cluster_id
# The cluster ID of the cluster that you want to update, for example
# `CID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] role_arn
# The new role Amazon Resource Name (ARN) that you want to associate
# with this cluster. To create a role ARN, use the [CreateRole][1] API
# action in AWS Identity and Access Management (IAM).
#
#
#
# [1]: http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
# @return [String]
#
# @!attribute [rw] description
# The updated description of this cluster.
# @return [String]
#
# @!attribute [rw] resources
# The updated arrays of JobResource objects that can include updated
# S3Resource objects or LambdaResource objects.
# @return [Types::JobResource]
#
# @!attribute [rw] address_id
# The ID of the updated Address object.
# @return [String]
#
# @!attribute [rw] shipping_option
# The updated shipping option value of this cluster's ShippingDetails
# object.
# @return [String]
#
# @!attribute [rw] notification
# The new or updated Notification object.
# @return [Types::Notification]
#
# @!attribute [rw] forwarding_address_id
# The updated ID for the forwarding address for a cluster. This field
# is not supported in most regions.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/UpdateClusterRequest AWS API Documentation
#
class UpdateClusterRequest < Struct.new(
:cluster_id,
:role_arn,
:description,
:resources,
:address_id,
:shipping_option,
:notification,
:forwarding_address_id)
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/UpdateClusterResult AWS API Documentation
#
class UpdateClusterResult < Aws::EmptyStructure; end
# @note When making an API call, you may pass UpdateJobRequest
# data as a hash:
#
# {
# job_id: "JobId", # required
# role_arn: "RoleARN",
# notification: {
# sns_topic_arn: "SnsTopicARN",
# job_states_to_notify: ["New"], # accepts New, PreparingAppliance, PreparingShipment, InTransitToCustomer, WithCustomer, InTransitToAWS, WithAWS, InProgress, Complete, Cancelled, Listing, Pending
# notify_all: false,
# },
# resources: {
# s3_resources: [
# {
# bucket_arn: "ResourceARN",
# key_range: {
# begin_marker: "String",
# end_marker: "String",
# },
# },
# ],
# lambda_resources: [
# {
# lambda_arn: "ResourceARN",
# event_triggers: [
# {
# event_resource_arn: "ResourceARN",
# },
# ],
# },
# ],
# ec2_ami_resources: [
# {
# ami_id: "AmiId", # required
# snowball_ami_id: "String",
# },
# ],
# },
# address_id: "AddressId",
# shipping_option: "SECOND_DAY", # accepts SECOND_DAY, NEXT_DAY, EXPRESS, STANDARD
# description: "String",
# snowball_capacity_preference: "T50", # accepts T50, T80, T100, NoPreference
# forwarding_address_id: "AddressId",
# }
#
# @!attribute [rw] job_id
# The job ID of the job that you want to update, for example
# `JID123e4567-e89b-12d3-a456-426655440000`.
# @return [String]
#
# @!attribute [rw] role_arn
# The new role Amazon Resource Name (ARN) that you want to associate
# with this job. To create a role ARN, use the [CreateRole][1]AWS
# Identity and Access Management (IAM) API action.
#
#
#
# [1]: http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
# @return [String]
#
# @!attribute [rw] notification
# The new or updated Notification object.
# @return [Types::Notification]
#
# @!attribute [rw] resources
# The updated `JobResource` object, or the updated JobResource object.
# @return [Types::JobResource]
#
# @!attribute [rw] address_id
# The ID of the updated Address object.
# @return [String]
#
# @!attribute [rw] shipping_option
# The updated shipping option value of this job's ShippingDetails
# object.
# @return [String]
#
# @!attribute [rw] description
# The updated description of this job's JobMetadata object.
# @return [String]
#
# @!attribute [rw] snowball_capacity_preference
# The updated `SnowballCapacityPreference` of this job's JobMetadata
# object. The 50 TB Snowballs are only available in the US regions.
# @return [String]
#
# @!attribute [rw] forwarding_address_id
# The updated ID for the forwarding address for a job. This field is
# not supported in most regions.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/UpdateJobRequest AWS API Documentation
#
class UpdateJobRequest < Struct.new(
:job_id,
:role_arn,
:notification,
:resources,
:address_id,
:shipping_option,
:description,
:snowball_capacity_preference,
:forwarding_address_id)
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/snowball-2016-06-30/UpdateJobResult AWS API Documentation
#
class UpdateJobResult < Aws::EmptyStructure; end
end
end
| llooker/aws-sdk-ruby | gems/aws-sdk-snowball/lib/aws-sdk-snowball/types.rb | Ruby | apache-2.0 | 68,036 |
using System;
using System.Web.Mvc;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.TypeRules;
using StructureMap;
using StructureMap.Graph.Scanning;
namespace FailTracker.Web.Infrastructure
{
public class ControllerConvention : IRegistrationConvention
{
//public void Process(Type type, Registry registry)
//{
// if (type.CanBeCastTo(typeof (Controller)) && !type.IsAbstract)
// {
// registry.For(type).LifecycleIs(new UniquePerRequestLifecycle());
// }
//}
public void ScanTypes(TypeSet types, Registry registry)
{
System.Collections.Generic.IEnumerable<Type> allTypes = types.AllTypes();
foreach (var type in allTypes)
{
if (type.CanBeCastTo(typeof(Controller)) && !type.IsAbstract)
{
registry.For(type).LifecycleIs(new UniquePerRequestLifecycle());
}
}
}
}
} | ytodorov/AntServices | AdvancedNetToolsSolution/AntWeb/Infrastructure/ControllerConvention.cs | C# | apache-2.0 | 1,073 |
import pytest
import gen.template
from gen.template import (For, Replacement, Switch, Tokenizer, UnsetParameter,
parse_str)
just_text = "foo"
more_complex_text = "foo {"
def get_tokens(str):
return Tokenizer(str).tokens
def test_lex():
assert(get_tokens("foo") == [("blob", "foo"), ("eof", None)])
assert(get_tokens("{") == [('blob', '{'), ('eof', None)])
assert(get_tokens("{#") == [('blob', '{'), ('blob', '#'), ('eof', None)])
assert(get_tokens("{ foo ") == [
('blob', '{'), ('blob', ' foo '), ('eof', None)])
assert(get_tokens("{ foo {{{{ {{{{{ ") == [('blob', '{'), ('blob', ' foo '), (
'blob', '{{'), ('blob', ' '), ('blob', '{{'), ('blob', '{'), ('blob', ' '), ('eof', None)])
assert(get_tokens("{{ test }}") == [
('replacement', ('test', None)), ('eof', None)])
assert(get_tokens("{{ test | foo }}") == [
('replacement', ('test', 'foo')), ('eof', None)])
assert(get_tokens(" {{ test }}") == [
('blob', ' '), ('replacement', ('test', None)), ('eof', None)])
assert(get_tokens("{{ test }}}}") == [
('replacement', ('test', None)), ('blob', '}}'), ('eof', None)])
assert(get_tokens('{% switch foo %}{% case "as\\"df" %}foobar{% endswitch %}}}') == [
('switch', 'foo'),
('case', 'as"df'),
('blob', 'foobar'),
('endswitch', None),
('blob', '}}'),
('eof', None)])
assert(get_tokens('{% switch foo %} \n \r {% case "as\\"df" %}foobar{% endswitch %}}}') == [
('switch', 'foo'),
('blob', ' \n \r '),
('case', 'as"df'),
('blob', 'foobar'),
('endswitch', None),
('blob', '}}'),
('eof', None)])
assert(get_tokens("a{% switch foo %}{% case \"test\" %}{{ a | baz }}b{{ a | bar }}{% endswitch %}c{{ c | bar }}{{ a | foo }}") == [ # noqa
('blob', 'a'),
('switch', 'foo'),
('case', 'test'),
('replacement', ('a', 'baz')),
('blob', 'b'),
('replacement', ('a', 'bar')),
('endswitch', None),
('blob', 'c'),
('replacement', ('c', 'bar')),
('replacement', ('a', 'foo')),
('eof', None)
])
assert(get_tokens("{% for foo in bar %}{{ foo }}{% endfor %}") == [
('for', ('foo', 'bar')),
('replacement', ('foo', None)),
('endfor', None),
('eof', None)])
with pytest.raises(gen.template.SyntaxError):
get_tokens("{{ test |}}")
with pytest.raises(gen.template.SyntaxError):
get_tokens("{{ test| }}")
with pytest.raises(gen.template.SyntaxError):
get_tokens("{{ test | }}")
with pytest.raises(gen.template.SyntaxError):
get_tokens("{{ test }}")
with pytest.raises(gen.template.SyntaxError):
get_tokens("{{test}}")
with pytest.raises(gen.template.SyntaxError):
get_tokens("{{ test}}")
def test_parse():
assert(parse_str("a").ast == ["a"])
assert(parse_str("{{ a }}").ast == [Replacement(("a", None))])
assert(parse_str("a {{ a | foo }}{{ b }} c {{ d | bar }}").ast == [
"a ",
Replacement(("a", 'foo')),
Replacement(("b", None)),
" c ",
Replacement(("d", 'bar'))
])
assert(parse_str('{% switch foo %}{% case "as\\"df" %}foobar{% endswitch %}}}').ast ==
[Switch("foo", {'as"df': ["foobar"]}), '}}'])
assert(parse_str('{{ a }}b{{ c }}{% switch foo %} \n {% case "as\\"df" %}foobar{% endswitch %}}}').ast == [
Replacement(("a", None)),
"b",
Replacement(("c", None)),
Switch("foo", {'as"df': ["foobar"]}),
"}}"
])
# TODO(cmaloney): Add parse syntax error tests
assert parse_str("{% for foo in bar %}{{ foo }}{% endfor %}").ast == [For("foo", "bar", [Replacement('foo')])]
def test_get_variables():
assert(parse_str("a").get_scoped_arguments() ==
{'variables': set(), 'sub_scopes': dict()})
assert(parse_str("{{ a }}").get_scoped_arguments() ==
{'variables': {"a"}, 'sub_scopes': dict()})
assert(parse_str("{{ a | foo }}").get_scoped_arguments() ==
{'variables': {"a"}, 'sub_scopes': dict()})
assert(parse_str("a{{ a }}b{{ c }}").get_scoped_arguments() ==
{'variables': {"a", "c"}, 'sub_scopes': dict()})
assert(parse_str("a{{ a }}b{{ a }}c{{ c | baz }}").get_scoped_arguments() ==
{'variables': {"a", "c"}, 'sub_scopes': dict()})
assert(parse_str("a{{ a }}b{{ a | bar }}c{{ c }}").get_scoped_arguments() ==
{'variables': {"a", "c"}, 'sub_scopes': dict()})
assert(parse_str("{{ a }}{% switch b %}{% case \"c\" %}{{ d }}{% endswitch %}{{ e }}").get_scoped_arguments() == {
'variables': {'a', 'e'},
'sub_scopes': {
'b': {
'c': {
'variables': {'d'},
'sub_scopes': {}
}
}
}
})
assert (parse_str("{% for foo in bar %}{{ foo }}{{ bar }}{{ baz }}{% endfor %}").get_scoped_arguments() ==
{'variables': {'bar', 'baz'}, 'sub_scopes': dict()})
# TODO(cmaloney): Disallow reusing a for new variable as a general variable.
assert (parse_str("{% for foo in bar %}{{ foo }}{{ bar }}{{ baz }}{% endfor %}{{ foo }}").get_scoped_arguments() ==
{'variables': {'foo', 'bar', 'baz'}, 'sub_scopes': dict()})
def test_get_filters():
assert(parse_str("{{ a }}").get_filters() == set())
assert(parse_str("{{ a | foo }}").get_filters() == {"foo"})
assert(parse_str(
"a{{ a | baz }}b{{ a | bar }}c{{ c | bar }}").get_filters() == {"baz", "bar"})
assert(parse_str("a{% switch foo %}{% case \"test\" %}{{ a | baz }}b{{ a | bar }}{% endswitch %}c{{ c | bar }}{{ a | foo }}").get_filters() == {"foo", "baz", "bar"}) # noqa
assert parse_str("{% for foo in bar %}{{ foo | bang }}{% endfor %}").get_filters() == {'bang'}
def test_render():
assert(parse_str("a").render({}) == "a")
assert(parse_str("{{ a }}a{{ b }}").render({"a": "1", "b": "2"}) == "1a2")
assert(parse_str("{{ a | foo }}a{{ b }}").render(
{"a": "1", "b": "2"},
{'foo': lambda x: x + 'foo'}
) == "1fooa2")
with pytest.raises(UnsetParameter):
parse_str("{{ a }}a{{ b }}").render({"a": "1"})
with pytest.raises(UnsetParameter):
parse_str("{{ a }}").render({"c": "1"})
with pytest.raises(UnsetParameter):
parse_str("{{ a | foo }}").render({"a": "1"})
assert parse_str("{% for a in b %}{{ a }}{% endfor %}").render({"b": ['a', 'test']}) == "atest"
assert (parse_str("{% for a in b %}{{ a }}{% endfor %}else{{ a }}").render({"b": ['b', 't', 'c'], "a": "foo"}) ==
"btcelsefoo")
with pytest.raises(UnsetParameter):
parse_str("{% for a in b %}{{ a }}{% endfor %}else{{ a }}").render({"b": ['b', 't', 'c']})
| movicha/dcos | gen/test_template.py | Python | apache-2.0 | 6,998 |
<?
/**
* Cesta comun de cualquier tienda
* @version 1.0 06.2014 creacion
* @version 1.1 11.2014 quitamos los metodos que calculaban la fecha de entrega para ponerlos en portes
*/
class Cesta extends Tienda_Instanciador {
public $listArticulos = null;
public function __construct(){
$this->listArticulos = array();
}
/**
* Comprueba si la cesta tiene articulos
*/
public function hayCesta(){
return (count($this->listArticulos)>0)?1:0;
}
/**
* Elimina el articulo indicado de la cesta
*/
public function borrarArticulo($articulo){
parent::$log->debug("Borrar $articulo de la cesta");
$cesta = new ArrayObject($this->listArticulos);
$iterador = $cesta->getIterator();
while($iterador->valid()){
if (strtolower($iterador->current()->id) == $articulo){
unset($this->listArticulos[$iterador->key()]);
return;
}
$iterador->next();
}
}
/** Busca en la cesta indicado y si existe devuelve true */
public function existeArticulo($articulo){
$articulo = $this->getArticulo($articulo);
if ( $articulo!=null )
return true;
parent::$log->debug("No tengo $articulo en la cesta");
return false;
}
/**
* Itera en el array de la cesta para entregar el articulo deseado. Esta operacion
* es comun a practicamente todos los metodos de la clase
*/
public function getArticulo($variedad){
$cesta = new ArrayObject($this->listArticulos);
$iterador = $cesta->getIterator();
while($iterador->valid()){
parent::$log->debug( ">>>iterando ".$iterador->current()->id );
if ($iterador->current()->id == $variedad){
parent::$log->debug( ">>>iguales" );
return $iterador->current();
}
$iterador->next();
}
parent::$log->error(">>>>no encontre la variedad:$variedad");
return null;
}
/** devuelve el numero total de articulos de la cesta */
public function total_articulos(){
if (count($this->listArticulos)==0) return 0;
$total = 0;
foreach ($this->listArticulos as $elArticulo)
$total+=$elArticulo->unidades;
return $total;
}
/** calcula el valor de la cesta sin iva */
public function cesta_sin_iva(){
$total = 0;
foreach ($this->listArticulos as $elArticulo){
$precio = $elArticulo->oferta>0?$elArticulo->oferta:$elArticulo->precio;
$total+= round($elArticulo->unidades*$precio,2);
}
return $total;
}
/** igual que la funcion anterior pero formateada la cantidad */
public function cesta_sin_iva_formato(){
$importe = $this->cesta_sin_iva();
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($importe, 'EUR');
}
/** calcula el valor de la cesta con iva */
public function cesta_con_iva(){
$total = 0;
foreach ($this->listArticulos as $elArticulo){
$precio = $elArticulo->oferta_iva>0?$elArticulo->oferta_iva:$elArticulo->precio_iva;
$total+= round($elArticulo->unidades*$precio,2);
}
return $total;
}
/** igual que la funcion anterior pero formateada la cantidad */
public function cesta_con_iva_formato(){
$importe = $this->cesta_con_iva();
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($importe, 'EUR');
}
/**
* Impuestos resultantes de esta cesta... solo impuestos
*/
public function iva_articulos(){
$total = $this->cesta_con_iva()-$this->cesta_sin_iva();
return $total;
}
/** igual que la funcion anterior pero formateada la cantidad */
public function iva_articulos_formato(){
$importe = $this->iva_articulos();
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($importe, 'EUR');
}
/** peso de la cesta */
public function peso_cesta(){
$peso = 0;
foreach ($this->listArticulos as $elArticulo){
$peso+=($elArticulo->peso*$elArticulo->unidades);
parent::$log->debug("Peso $elArticulo->articulo= $elArticulo->peso(kg) * $elArticulo->unidades(u) = ".($elArticulo->unidades*$elArticulo->peso)." Peso acumulado de la cesta=".$peso);
}
return $peso;
}
/** igual que la funcion anterior pero formateado */
public function peso_cesta_formato(){
$p = $this->peso_cesta();
return number_format($p,2,",",".");
}
/** Cual es el iva de la cesta... me vale con leer este valor del primer articulo */
public function tipo_iva_cesta(){
foreach ($this->listArticulos as $elArticulo)
return $elArticulo->iva;
}
/** tipo de de iva de la cesta pero con formato */
public function tipo_iva_cesta_formato(){
$iva = $this->tipo_iva_cesta();
return number_format($iva,2,",",".").'%';
}
}
?> | IbericaSoft/vestirarte | web/backoffice/kernel/negocio/classes/Cesta.class.php | PHP | apache-2.0 | 4,904 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 storage::dell::fluidfs::snmp::mode::components::overall;
use strict;
use warnings;
my $mapping = {
fluidFSNASApplianceApplianceServiceTag => { oid => '.1.3.6.1.4.1.674.11000.2000.200.1.16.1.3' },
fluidFSNASApplianceStatus => { oid => '.1.3.6.1.4.1.674.11000.2000.200.1.16.1.5' },
fluidFSNASApplianceModel => { oid => '.1.3.6.1.4.1.674.11000.2000.200.1.16.1.6' },
};
my $oid_fluidFSNASApplianceEntry = '.1.3.6.1.4.1.674.11000.2000.200.1.16.1';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_fluidFSNASApplianceEntry };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking nas overall");
$self->{components}->{overall} = {name => 'overall', total => 0, skip => 0};
return if ($self->check_filter(section => 'overall'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_fluidFSNASApplianceEntry}})) {
next if ($oid !~ /^$mapping->{fluidFSNASApplianceStatus}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_fluidFSNASApplianceEntry}, instance => $instance);
next if ($self->check_filter(section => 'overall', instance => $instance));
$self->{components}->{overall}->{total}++;
$self->{output}->output_add(long_msg => sprintf("nas '%s/%s' overall status is '%s' [instance = %s]",
$result->{fluidFSNASApplianceApplianceServiceTag}, $result->{fluidFSNASApplianceModel},
$result->{fluidFSNASApplianceStatus}, $instance
));
my $exit = $self->get_severity(label => 'default', section => 'overall', value => $result->{fluidFSNASApplianceStatus});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("nas '%s/%s' overall status is '%s'",
$result->{fluidFSNASApplianceApplianceServiceTag}, $result->{fluidFSNASApplianceModel},
$result->{fluidFSNASApplianceStatus}
));
}
}
}
1; | Tpo76/centreon-plugins | storage/dell/fluidfs/snmp/mode/components/overall.pm | Perl | apache-2.0 | 3,163 |
#!/bin/bash
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -o errexit
set -o nounset
set -o pipefail
set -o xtrace
TESTINFRA_ROOT=$(git rev-parse --show-toplevel)
for output in gs://k8s-testgrid-canary/config gs://k8s-testgrid/config; do
dir="$(dirname "${BASH_SOURCE}")"
bazel run //testgrid/cmd/configurator -- \
--yaml="${TESTINFRA_ROOT}/config/testgrids" \
--default="${TESTINFRA_ROOT}/config/testgrids/default.yaml" \
--prow-config="${TESTINFRA_ROOT}/prow/config.yaml" \
--prow-job-config="${TESTINFRA_ROOT}/config/jobs/" \
--output="${output}" \
--oneshot \
--world-readable
done
| krzyzacy/test-infra | testgrid/config-upload.sh | Shell | apache-2.0 | 1,165 |
// Copyright 2013 Traceur 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.
System.set('@traceur/module', (function() {
'use strict';
var {resolveUrl, isStandardModuleUrl} = System.get('@traceur/url');
var modules = Object.create(null);
var refererUrl = './';
function setRefererUrl(url) {
refererUrl = url || './';
}
function getRefererUrl() {
return refererUrl;
}
class PendingModule {
constructor(name, func, self) {
this.name = name;
this.func = func;
this.self = self;
}
toModule() {
var oldName = refererUrl;
refererUrl = this.name;
try {
return this.func.call(this.self);
} finally {
refererUrl = oldName
}
}
}
function registerModule(name, func, self) {
var url = resolveUrl(refererUrl, name);
modules[url] = new PendingModule(name, func, self);
}
// Now it is safe to override System.{get,set} to use resolveUrl.
var $get = System.get;
var $set = System.set;
System.get = function(name) {
if (isStandardModuleUrl(name))
return $get(name);
var url = resolveUrl(refererUrl, name);
var module = modules[url];
if (module instanceof PendingModule)
return modules[url] = module.toModule();
return module;
};
System.set = function(name, object) {
if (isStandardModuleUrl(name))
$set(name, object);
else
modules[resolveUrl(refererUrl, name)] = object;
};
return {
getRefererUrl,
registerModule,
setRefererUrl,
};
})());
| rwaldron/traceur-compiler | src/runtime/modules.js | JavaScript | apache-2.0 | 2,054 |
/***********************************************/
/* assgnment.5 Shu Z. A00042813 for CS453 */
/* using the tokenizer and stream module */
/* print_tokens.c Code */
/***********************************************/
/***********************************************/
/* NAME: print_tokens */
/* INPUT: a filename */
/* OUTPUT: print out the token stream */
/* DESCRIPTION: using the tokenizer interface */
/* to print out the token stream */
/***********************************************/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "tokens.h"
#define TRUE 1
#define FALSE 0
main(argc,argv)
int argc;
char *argv[3];
{ char *fname;
token tok;
token_stream tp;
if(argc==1) /* if not given filename,take as '""' */
{
fname= (char *) malloc(sizeof(char));
*fname = '\0';
}
else if(argc==2)
fname= argv[1];
else
{ fprintf(stdout, "Error!,please give the token stream\n");
exit(0);
}
tp=open_token_stream(fname); /* open token stream */
tok=get_token(tp);
while (is_eof_token(tok) ==FALSE) /* take one token each time until eof */
{
print_token(tok);
tok=get_token(tp);
}
print_token(tok); /* print eof signal */
exit(0);
}
/* stream.c code */
/***********************************************/
/* NMAE: open_character_stream */
/* INPUT: a filename */
/* OUTPUT: a pointer to chacracter_stream */
/* DESCRIPTION: when not given a filename, */
/* open stdin,otherwise open */
/* the existed file */
/***********************************************/
character_stream open_character_stream(fname)
char *fname;
{ character_stream fp;
if(fname == NULL)
fp=stdin;
else if ((fp=fopen(fname,"r"))== NULL)
{
fprintf(stdout, "The file %s doesn't exists\n",fname);
exit(0);
}
return(fp);
}
/**********************************************/
/* NAME: get_char */
/* INPUT: a pointer to char_stream */
/* OUTPUT: a character */
/**********************************************/
char get_char(fp)
character_stream fp;
{ char ch;
ch=getc(fp);
return(ch);
}
/***************************************************/
/* NAME: unget_char */
/* INPUT: a pointer to char_stream,a character */
/* OUTPUT: a character */
/* DESCRIPTION:when unable to put back,return EOF */
/***************************************************/
char unget_char(ch,fp)
character_stream fp;
char ch;
{ char c;
c=ungetc(ch,fp);
if(c ==EOF)
{
return(c);
}
else
return(c);
}
/* tokenizer.c code */
char buffer[81]; /* fixed array length MONI */ /* to store the token temporar */
static int is_spec_symbol();
static int is_token_end();
static unget_error();
static int is_keyword();
static int is_identifier();
static int is_num_constant();
static int is_char_constant();
static int is_str_constant();
static int is_comment();
static void print_spec_symbol();
/********************************************************/
/* NAME: open_token_stream */
/* INPUT: a filename */
/* OUTPUT: a pointer to a token_stream */
/* DESCRIPTION: when filename is EMPTY,choice standard */
/* input device as input source */
/********************************************************/
token_stream open_token_stream(fname)
char *fname;
{
token_stream fp;
if(strcmp(fname,"")==0)
fp=open_character_stream(NULL);
else
fp=open_character_stream(fname);
return(fp);
}
/********************************************************/
/* NAME : get_token */
/* INPUT: a pointer to the tokens_stream */
/* OUTPUT: a token */
/* DESCRIPTION: according the syntax of tokens,dealing */
/* with different case and get one token */
/********************************************************/
token get_token(tp)
token_stream tp;
{
int i=0,j;
int id=0;
char ch,ch1[2];
for (j=0;j<=80;j++) /* initial the buffer */
{ buffer[j]='\0';}
ch1[0]='\0';
ch1[1]='\0';
ch=get_char(tp);
while(ch==' '||ch=='\n') /* strip all blanks until meet characters */
{
ch=get_char(tp);
}
buffer[i]=ch;
if(is_eof_token(buffer)==TRUE)return(buffer);
if(is_spec_symbol(buffer)==TRUE)return(buffer);
if(ch =='"')id=1; /* prepare for string */
if(ch ==59)id=2; /* prepare for comment */
ch=get_char(tp);
while (is_token_end(id,ch) == FALSE)/* until meet the end character */
{
i++;
buffer[i]=ch;
ch=get_char(tp);
}
ch1[0]=ch; /* hold the end charcater */
if(is_eof_token(ch1)==TRUE) /* if end character is eof token */
{ ch=unget_char(ch,tp); /* then put back eof on token_stream */
if(ch==EOF)unget_error(tp);
return(buffer);
}
if(is_spec_symbol(ch1)==TRUE) /* if end character is special_symbol */
{ ch=unget_char(ch,tp); /* then put back this character */
if(ch==EOF)unget_error(tp);
return(buffer);
}
if(id==1) /* if end character is " and is string */
{ i++; /* case,hold the second " in buffer */
buffer[i]=ch;
return(buffer);
}
if(id==0 && ch==59)
/* when not in string or comment,meet ";" */
{ ch=unget_char(ch,tp); /* then put back this character */
if(ch==EOF)unget_error(tp);
return(buffer);
}
return(buffer); /* return nomal case token */
}
/*******************************************************/
/* NAME: is_token_end */
/* INPUT: a character,a token status */
/* OUTPUT: a BOOLEAN value */
/*******************************************************/
static int is_token_end(str_com_id,ch)
char ch;
int str_com_id;
{ char ch1[2]; /* fixed array declaration MONI */
ch1[0]=ch;
ch1[1]='\0';
if(is_eof_token(ch1)==TRUE)return(TRUE); /* is eof token? */
if(str_com_id==1) /* is string token */
{ if(ch=='"' | ch=='\n') /* for string until meet another " */
return(TRUE);
else
return(FALSE);
}
if(str_com_id==2) /* is comment token */
{ if(ch=='\n') /* for comment until meet end of line */
return(TRUE);
else
return(FALSE);
}
if(is_spec_symbol(ch1)==TRUE) return(TRUE); /* is special_symbol? */
if(ch ==' ' || ch=='\n' || ch==59) return(TRUE);
/* others until meet blank or tab or 59 */
return(FALSE); /* other case,return FALSE */
}
/****************************************************/
/* NAME : token_type */
/* INPUT: a pointer to the token */
/* OUTPUT: an integer value */
/* DESCRIPTION: the integer value is corresponding */
/* to the different token type */
/****************************************************/
static int token_type(tok)
token tok;
{
if(is_keyword(tok))return(keyword);
if(is_spec_symbol(tok))return(spec_symbol);
if(is_identifier(tok))return(identifier);
if(is_num_constant(tok))return(num_constant);
if(is_str_constant(tok))return(str_constant);
if(is_char_constant(tok))return(char_constant);
if(is_comment(tok))return(comment);
if(is_eof_token(tok))return(end);
return(error); /* else look as error token */
}
/****************************************************/
/* NAME: print_token */
/* INPUT: a pointer to the token */
/* OUTPUT: a BOOLEAN value,print out the token */
/* according the forms required */
/****************************************************/
int print_token(tok)
token tok;
{ int type;
type=token_type(tok);
if(type==error)
{ fprintf(stdout, "error,\"%s\".\n",tok);
}
if(type==keyword)
{fprintf(stdout, "keyword,\"%s\".\n",tok);
}
if(type==spec_symbol)print_spec_symbol(tok);
if(type==identifier)
{fprintf(stdout, "identifier,\"%s\".\n",tok);
}
if(type==num_constant)
{fprintf(stdout, "numeric,%s.\n",tok);
}
if(type==str_constant)
{fprintf(stdout, "string,%s.\n",tok);
}
if(type==char_constant)
{tok=tok+1;
fprintf(stdout, "character,\"%s\".\n",tok);
}
if(type==end)
fprintf(stdout, "eof.\n");
}
/* the code for tokens judgment function */
/*************************************/
/* NAME: is_eof_token */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
int is_eof_token(tok)
token tok;
{
if( *tok==EOF)
return(TRUE);
else
return(FALSE);
}
/*************************************/
/* NAME: is_comment */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_comment(ident)
token ident;
{
if( (*ident) ==59 ) /* the char is 59 */
return(TRUE);
else
return(FALSE);
}
/*************************************/
/* NAME: is_keyword */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_keyword(str)
token str;
{
if (!strcmp(str,"and") || !strcmp(str,"or") || !strcmp(str,"if") ||
!strcmp(str,"xor")||!strcmp(str,"lambda")||!strcmp(str,"=>"))
return(TRUE);
else
return(FALSE);
}
/*************************************/
/* NAME: is_char_constant */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_char_constant(str)
token str;
{
if ((*str)=='#' && isalpha(*(str+1)))
return(TRUE);
else
return(FALSE);
}
/*************************************/
/* NAME: is_num_constant */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_num_constant(str)
token str;
{
int i=1;
if ( isdigit(*str))
{
while ( *(str+i) != '\0' ) /* until meet token end sign */
{
if(isdigit(*(str+i)))
i++;
else
return(FALSE);
} /* end WHILE */
return(TRUE);
}
else
return(FALSE); /* other return FALSE */
}
/*************************************/
/* NAME: is_str_constant */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_str_constant(str)
token str;
{
int i=1;
if ( *str =='"')
{ while (*(str)!='\0') /* until meet the token end sign */
{ if(*(str+i)=='"')
return(TRUE); /* meet the second '"' */
else
i++;
} /* end WHILE */
return(FALSE);
}
else
return(FALSE); /* other return FALSE */
}
/*************************************/
/* NAME: is_identifier */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_identifier(str)
token str;
{
int i=1;
if ( isalpha( *str) )
{
while( *(str+i) !='\0' ) /* unti meet the end token sign */
{
if(isalpha(*(str+i)) || isdigit(*(str+i)))
i++;
else
return(FALSE);
} /* end WHILE */
return(TRUE);
}
else
return(FALSE);
}
/******************************************/
/* NAME: unget_error */
/* INPUT: a pointer to token stream */
/* OUTPUT: print error message */
/******************************************/
static unget_error(fp)
character_stream *fp;
{
fprintf(stdout,"It can not get charcter\n");
}
/*************************************************/
/* NAME: print_spec_symbol */
/* INPUT: a pointer to a spec_symbol token */
/* OUTPUT : print out the spec_symbol token */
/* according to the form required */
/*************************************************/
static void print_spec_symbol(str)
token str;
{
if (!strcmp(str,"("))
{
fprintf(stdout, "%s\n","lparen.");
return;
}
if (!strcmp(str,")"))
{
fprintf(stdout, "%s\n","rparen.");
return;
}
if (!strcmp(str,"["))
{
fprintf(stdout, "%s\n","lsquare.");
return;
}
if (!strcmp(str,"]"))
{
fprintf(stdout, "%s\n","rsquare.");
return;
}
if (!strcmp(str,"'"))
{
fprintf(stdout, "%s\n","quote.");
return;
}
if (!strcmp(str,"`"))
{
fprintf(stdout, "%s\n","bquote.");
return;
}
fprintf(stdout, "%s\n","comma.");
}
/*************************************/
/* NAME: is_spec_symbol */
/* INPUT: a pointer to a token */
/* OUTPUT: a BOOLEAN value */
/*************************************/
static int is_spec_symbol(str)
token str;
{
if (!strcmp(str,"("))
{
return(TRUE);
}
if (!strcmp(str,")"))
{
return(TRUE);
}
if (!strcmp(str,"["))
{
return(TRUE);
}
if (!strcmp(str,"]"))
{
return(TRUE);
}
if (!strcmp(str,"'"))
{
return(TRUE);
}
if (!strcmp(str,"`"))
{
return(TRUE);
}
if (!strcmp(str,","))
{
return(TRUE);
}
return(FALSE); /* others return FALSE */
}
| ssvlab/esbmc-gpu | regression/ieee-tse_benchmarks/siemens/print_tokens2.c | C | apache-2.0 | 14,113 |
<?xml version="1.0" encoding="utf-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&view=category&id=10&Itemid=210&lang=en&format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&searchword={searchTerms}&Itemid=188"/></OpenSearchDescription>
| cmaere/lwb | templates/protostar/indexbff1.php | PHP | apache-2.0 | 759 |
# Agaricus licmophorus Berk. & Broome, 1883 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Ann. Mag. nat. Hist. , Ser. 5 12: 370 (1883)
#### Original name
Agaricus licmophorus Berk. & Broome, 1883
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Agaricaceae/Leucocoprinus/Leucocoprinus fragilissimus/ Syn. Agaricus licmophorus/README.md | Markdown | apache-2.0 | 275 |
/*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.druid.segment;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.base.Strings;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.metamx.common.guava.CloseQuietly;
import com.metamx.common.guava.Sequence;
import com.metamx.common.guava.Sequences;
import io.druid.granularity.QueryGranularity;
import io.druid.query.QueryInterruptedException;
import io.druid.query.extraction.ExtractionFn;
import io.druid.query.filter.Filter;
import io.druid.segment.column.Column;
import io.druid.segment.column.ColumnCapabilities;
import io.druid.segment.column.ComplexColumn;
import io.druid.segment.column.DictionaryEncodedColumn;
import io.druid.segment.column.GenericColumn;
import io.druid.segment.column.ValueType;
import io.druid.segment.data.Indexed;
import io.druid.segment.data.IndexedInts;
import io.druid.segment.data.Offset;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
/**
*/
public class QueryableIndexStorageAdapter implements StorageAdapter
{
private static final NullDimensionSelector NULL_DIMENSION_SELECTOR = new NullDimensionSelector();
private final QueryableIndex index;
public QueryableIndexStorageAdapter(
QueryableIndex index
)
{
this.index = index;
}
@Override
public String getSegmentIdentifier()
{
throw new UnsupportedOperationException();
}
@Override
public Interval getInterval()
{
return index.getDataInterval();
}
@Override
public Indexed<String> getAvailableDimensions()
{
return index.getAvailableDimensions();
}
@Override
public Iterable<String> getAvailableMetrics()
{
return Sets.difference(Sets.newHashSet(index.getColumnNames()), Sets.newHashSet(index.getAvailableDimensions()));
}
@Override
public int getDimensionCardinality(String dimension)
{
if (dimension == null) {
return 0;
}
Column column = index.getColumn(dimension);
if (column == null) {
return 0;
}
if (!column.getCapabilities().isDictionaryEncoded()) {
return Integer.MAX_VALUE;
}
return column.getDictionaryEncoding().getCardinality();
}
@Override
public int getNumRows()
{
return index.getNumRows();
}
@Override
public DateTime getMinTime()
{
GenericColumn column = null;
try {
column = index.getColumn(Column.TIME_COLUMN_NAME).getGenericColumn();
return new DateTime(column.getLongSingleValueRow(0));
}
finally {
CloseQuietly.close(column);
}
}
@Override
public DateTime getMaxTime()
{
GenericColumn column = null;
try {
column = index.getColumn(Column.TIME_COLUMN_NAME).getGenericColumn();
return new DateTime(column.getLongSingleValueRow(column.length() - 1));
}
finally {
CloseQuietly.close(column);
}
}
@Override
public Capabilities getCapabilities()
{
return Capabilities.builder().dimensionValuesSorted(true).build();
}
@Override
public ColumnCapabilities getColumnCapabilities(String column)
{
return index.getColumn(column).getCapabilities();
}
@Override
public DateTime getMaxIngestedEventTime()
{
// For immutable indexes, maxIngestedEventTime is maxTime.
return getMaxTime();
}
@Override
public Sequence<Cursor> makeCursors(Filter filter, Interval interval, QueryGranularity gran)
{
Interval actualInterval = interval;
final Interval dataInterval = new Interval(
getMinTime().getMillis(),
gran.next(gran.truncate(getMaxTime().getMillis()))
);
if (!actualInterval.overlaps(dataInterval)) {
return Sequences.empty();
}
if (actualInterval.getStart().isBefore(dataInterval.getStart())) {
actualInterval = actualInterval.withStart(dataInterval.getStart());
}
if (actualInterval.getEnd().isAfter(dataInterval.getEnd())) {
actualInterval = actualInterval.withEnd(dataInterval.getEnd());
}
final Offset offset;
if (filter == null) {
offset = new NoFilterOffset(0, index.getNumRows());
} else {
final ColumnSelectorBitmapIndexSelector selector = new ColumnSelectorBitmapIndexSelector(
index.getBitmapFactoryForDimensions(),
index
);
offset = new BitmapOffset(selector.getBitmapFactory(), filter.getBitmapIndex(selector));
}
return Sequences.filter(
new CursorSequenceBuilder(index, actualInterval, gran, offset).build(),
Predicates.<Cursor>notNull()
);
}
private static class CursorSequenceBuilder
{
private final ColumnSelector index;
private final Interval interval;
private final QueryGranularity gran;
private final Offset offset;
public CursorSequenceBuilder(
ColumnSelector index,
Interval interval,
QueryGranularity gran,
Offset offset
)
{
this.index = index;
this.interval = interval;
this.gran = gran;
this.offset = offset;
}
public Sequence<Cursor> build()
{
final Offset baseOffset = offset.clone();
final Map<String, DictionaryEncodedColumn> dictionaryColumnCache = Maps.newHashMap();
final Map<String, GenericColumn> genericColumnCache = Maps.newHashMap();
final Map<String, ComplexColumn> complexColumnCache = Maps.newHashMap();
final Map<String, Object> objectColumnCache = Maps.newHashMap();
final GenericColumn timestamps = index.getColumn(Column.TIME_COLUMN_NAME).getGenericColumn();
return Sequences.withBaggage(
Sequences.map(
Sequences.simple(gran.iterable(interval.getStartMillis(), interval.getEndMillis())),
new Function<Long, Cursor>()
{
@Override
public Cursor apply(final Long input)
{
final long timeStart = Math.max(interval.getStartMillis(), input);
while (baseOffset.withinBounds()
&& timestamps.getLongSingleValueRow(baseOffset.getOffset()) < timeStart) {
baseOffset.increment();
}
final Offset offset = new TimestampCheckingOffset(
baseOffset, timestamps, Math.min(interval.getEndMillis(), gran.next(input))
);
return new Cursor()
{
private final Offset initOffset = offset.clone();
private final DateTime myBucket = gran.toDateTime(input);
private Offset cursorOffset = offset;
@Override
public DateTime getTime()
{
return myBucket;
}
@Override
public void advance()
{
if (Thread.interrupted()) {
throw new QueryInterruptedException();
}
cursorOffset.increment();
}
@Override
public void advanceTo(int offset)
{
int count = 0;
while (count < offset && !isDone()) {
advance();
count++;
}
}
@Override
public boolean isDone()
{
return !cursorOffset.withinBounds();
}
@Override
public void reset()
{
cursorOffset = initOffset.clone();
}
@Override
public DimensionSelector makeDimensionSelector(
final String dimension,
@Nullable final ExtractionFn extractionFn
)
{
final Column columnDesc = index.getColumn(dimension);
if (columnDesc == null) {
return NULL_DIMENSION_SELECTOR;
}
if (dimension.equals(Column.TIME_COLUMN_NAME)) {
return new SingleScanTimeDimSelector(makeLongColumnSelector(dimension), extractionFn);
}
DictionaryEncodedColumn cachedColumn = dictionaryColumnCache.get(dimension);
if (cachedColumn == null) {
cachedColumn = columnDesc.getDictionaryEncoding();
dictionaryColumnCache.put(dimension, cachedColumn);
}
final DictionaryEncodedColumn column = cachedColumn;
if (column == null) {
return NULL_DIMENSION_SELECTOR;
} else if (columnDesc.getCapabilities().hasMultipleValues()) {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
return column.getMultiValueRow(cursorOffset.getOffset());
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
final String value = column.lookupName(id);
return extractionFn == null ?
Strings.nullToEmpty(value) :
extractionFn.apply(Strings.nullToEmpty(value));
}
@Override
public int lookupId(String name)
{
if (extractionFn != null) {
throw new UnsupportedOperationException(
"cannot perform lookup when applying an extraction function"
);
}
return column.lookupId(name);
}
};
} else {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
// using an anonymous class is faster than creating a class that stores a copy of the value
return new IndexedInts()
{
@Override
public int size()
{
return 1;
}
@Override
public int get(int index)
{
return column.getSingleValueRow(cursorOffset.getOffset());
}
@Override
public Iterator<Integer> iterator()
{
return Iterators.singletonIterator(column.getSingleValueRow(cursorOffset.getOffset()));
}
@Override
public void fill(int index, int[] toFill)
{
throw new UnsupportedOperationException("fill not supported");
}
@Override
public void close() throws IOException
{
}
};
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
final String value = column.lookupName(id);
return extractionFn == null ? value : extractionFn.apply(value);
}
@Override
public int lookupId(String name)
{
if (extractionFn != null) {
throw new UnsupportedOperationException(
"cannot perform lookup when applying an extraction function"
);
}
return column.lookupId(name);
}
};
}
}
@Override
public FloatColumnSelector makeFloatColumnSelector(String columnName)
{
GenericColumn cachedMetricVals = genericColumnCache.get(columnName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(columnName);
if (holder != null && (holder.getCapabilities().getType() == ValueType.FLOAT
|| holder.getCapabilities().getType() == ValueType.LONG)) {
cachedMetricVals = holder.getGenericColumn();
genericColumnCache.put(columnName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return new FloatColumnSelector()
{
@Override
public float get()
{
return 0.0f;
}
};
}
final GenericColumn metricVals = cachedMetricVals;
return new FloatColumnSelector()
{
@Override
public float get()
{
return metricVals.getFloatSingleValueRow(cursorOffset.getOffset());
}
};
}
@Override
public LongColumnSelector makeLongColumnSelector(String columnName)
{
GenericColumn cachedMetricVals = genericColumnCache.get(columnName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(columnName);
if (holder != null && (holder.getCapabilities().getType() == ValueType.LONG
|| holder.getCapabilities().getType() == ValueType.FLOAT)) {
cachedMetricVals = holder.getGenericColumn();
genericColumnCache.put(columnName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return new LongColumnSelector()
{
@Override
public long get()
{
return 0L;
}
};
}
final GenericColumn metricVals = cachedMetricVals;
return new LongColumnSelector()
{
@Override
public long get()
{
return metricVals.getLongSingleValueRow(cursorOffset.getOffset());
}
};
}
@Override
public ObjectColumnSelector makeObjectColumnSelector(String column)
{
Object cachedColumnVals = objectColumnCache.get(column);
if (cachedColumnVals == null) {
Column holder = index.getColumn(column);
if (holder != null) {
final ColumnCapabilities capabilities = holder.getCapabilities();
if (capabilities.isDictionaryEncoded()) {
cachedColumnVals = holder.getDictionaryEncoding();
} else if (capabilities.getType() == ValueType.COMPLEX) {
cachedColumnVals = holder.getComplexColumn();
} else {
cachedColumnVals = holder.getGenericColumn();
}
}
if (cachedColumnVals != null) {
objectColumnCache.put(column, cachedColumnVals);
}
}
if (cachedColumnVals == null) {
return null;
}
if (cachedColumnVals instanceof GenericColumn) {
final GenericColumn columnVals = (GenericColumn) cachedColumnVals;
final ValueType type = columnVals.getType();
if (columnVals.hasMultipleValues()) {
throw new UnsupportedOperationException(
"makeObjectColumnSelector does not support multivalued GenericColumns"
);
}
if (type == ValueType.FLOAT) {
return new ObjectColumnSelector<Float>()
{
@Override
public Class classOfObject()
{
return Float.TYPE;
}
@Override
public Float get()
{
return columnVals.getFloatSingleValueRow(cursorOffset.getOffset());
}
};
}
if (type == ValueType.LONG) {
return new ObjectColumnSelector<Long>()
{
@Override
public Class classOfObject()
{
return Long.TYPE;
}
@Override
public Long get()
{
return columnVals.getLongSingleValueRow(cursorOffset.getOffset());
}
};
}
if (type == ValueType.STRING) {
return new ObjectColumnSelector<String>()
{
@Override
public Class classOfObject()
{
return String.class;
}
@Override
public String get()
{
return columnVals.getStringSingleValueRow(cursorOffset.getOffset());
}
};
}
}
if (cachedColumnVals instanceof DictionaryEncodedColumn) {
final DictionaryEncodedColumn columnVals = (DictionaryEncodedColumn) cachedColumnVals;
if (columnVals.hasMultipleValues()) {
return new ObjectColumnSelector<Object>()
{
@Override
public Class classOfObject()
{
return Object.class;
}
@Override
public Object get()
{
final IndexedInts multiValueRow = columnVals.getMultiValueRow(cursorOffset.getOffset());
if (multiValueRow.size() == 0) {
return null;
} else if (multiValueRow.size() == 1) {
return columnVals.lookupName(multiValueRow.get(0));
} else {
final String[] strings = new String[multiValueRow.size()];
for (int i = 0; i < multiValueRow.size(); i++) {
strings[i] = columnVals.lookupName(multiValueRow.get(i));
}
return strings;
}
}
};
} else {
return new ObjectColumnSelector<String>()
{
@Override
public Class classOfObject()
{
return String.class;
}
@Override
public String get()
{
return columnVals.lookupName(columnVals.getSingleValueRow(cursorOffset.getOffset()));
}
};
}
}
final ComplexColumn columnVals = (ComplexColumn) cachedColumnVals;
return new ObjectColumnSelector()
{
@Override
public Class classOfObject()
{
return columnVals.getClazz();
}
@Override
public Object get()
{
return columnVals.getRowValue(cursorOffset.getOffset());
}
};
}
};
}
}
),
new Closeable()
{
@Override
public void close() throws IOException
{
CloseQuietly.close(timestamps);
for (DictionaryEncodedColumn column : dictionaryColumnCache.values()) {
CloseQuietly.close(column);
}
for (GenericColumn column : genericColumnCache.values()) {
CloseQuietly.close(column);
}
for (ComplexColumn complexColumn : complexColumnCache.values()) {
CloseQuietly.close(complexColumn);
}
for (Object column : objectColumnCache.values()) {
if (column instanceof Closeable) {
CloseQuietly.close((Closeable) column);
}
}
}
}
);
}
}
private static class TimestampCheckingOffset implements Offset
{
private final Offset baseOffset;
private final GenericColumn timestamps;
private final long threshold;
private final boolean allWithinThreshold;
public TimestampCheckingOffset(
Offset baseOffset,
GenericColumn timestamps,
long threshold
)
{
this.baseOffset = baseOffset;
this.timestamps = timestamps;
this.threshold = threshold;
// checks if all the values are within the Threshold specified, skips timestamp lookups and checks if all values are within threshold.
this.allWithinThreshold = timestamps.getLongSingleValueRow(timestamps.length() - 1) < threshold;
}
@Override
public int getOffset()
{
return baseOffset.getOffset();
}
@Override
public Offset clone()
{
return new TimestampCheckingOffset(baseOffset.clone(), timestamps, threshold);
}
@Override
public boolean withinBounds()
{
return baseOffset.withinBounds() && (allWithinThreshold
|| timestamps.getLongSingleValueRow(baseOffset.getOffset()) < threshold);
}
@Override
public void increment()
{
baseOffset.increment();
}
}
private static class NoFilterOffset implements Offset
{
private final int rowCount;
private volatile int currentOffset;
NoFilterOffset(int currentOffset, int rowCount)
{
this.currentOffset = currentOffset;
this.rowCount = rowCount;
}
@Override
public void increment()
{
currentOffset++;
}
@Override
public boolean withinBounds()
{
return currentOffset < rowCount;
}
@Override
public Offset clone()
{
return new NoFilterOffset(currentOffset, rowCount);
}
@Override
public int getOffset()
{
return currentOffset;
}
}
}
| wenjixin/druid | processing/src/main/java/io/druid/segment/QueryableIndexStorageAdapter.java | Java | apache-2.0 | 26,596 |
/**
* Copyright (C) 2009 - 2013 SC 4ViewSoft SRL
*
* 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 org.achartengine.chart;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import org.achartengine.model.Point;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.util.MathHelper;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
/**
* The XY chart rendering class.
*/
public abstract class XYChart extends AbstractChart {
/** The multiple series dataset. */
protected XYMultipleSeriesDataset mDataset;
/** The multiple series renderer. */
protected XYMultipleSeriesRenderer mRenderer;
/** The current scale value. */
private float mScale;
/** The current translate value. */
private float mTranslate;
/** The canvas center point. */
private Point mCenter;
/** The visible chart area, in screen coordinates. */
private Rect mScreenR;
/** The calculated range. */
private final Map<Integer, double[]> mCalcRange = new HashMap<Integer, double[]>();
/** The paint to be used when drawing the grid lines. */
private transient Paint mGridPaint;
/**
* The clickable areas for all points. The array index is the series index,
* and the RectF list index is the point index in that series.
*/
private Map<Integer, List<ClickableArea>> clickableAreas = new HashMap<Integer, List<ClickableArea>>();
protected XYChart() {
}
/**
* Builds a new XY chart instance.
*
* @param dataset the multiple series dataset
* @param renderer the multiple series renderer
*/
public XYChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) {
mDataset = dataset;
mRenderer = renderer;
}
// TODO: javadoc
protected void setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer) {
mDataset = dataset;
mRenderer = renderer;
}
/**
* The graphical representation of the XY chart.
*
* @param canvas the canvas to paint to
* @param x the top left x value of the view to draw to
* @param y the top left y value of the view to draw to
* @param width the width of the view to draw to
* @param height the height of the view to draw to
* @param paint the paint
*/
public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) {
paint.setAntiAlias(mRenderer.isAntialiasing());
int legendSize = getLegendSize(mRenderer, height / 5, mRenderer.getAxisTitleTextSize());
int[] margins = mRenderer.getMargins();
int left = x + margins[1];
int top = y + margins[0];
int right = x + width - margins[3];
int sLength = mDataset.getSeriesCount();
String[] titles = new String[sLength];
for (int i = 0; i < sLength; i++) {
titles[i] = mDataset.getSeriesAt(i).getTitle();
}
if (mRenderer.isFitLegend() && mRenderer.isShowLegend()) {
legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize,
paint, true);
}
int bottom = y + height - margins[2] - legendSize;
if (mScreenR == null) {
mScreenR = new Rect();
}
mScreenR.set(left, top, right, bottom);
drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR);
if (paint.getTypeface() == null
|| (mRenderer.getTextTypeface() != null && paint.getTypeface().equals(
mRenderer.getTextTypeface()))
|| !paint.getTypeface().toString().equals(mRenderer.getTextTypefaceName())
|| paint.getTypeface().getStyle() != mRenderer.getTextTypefaceStyle()) {
if (mRenderer.getTextTypeface() != null) {
paint.setTypeface(mRenderer.getTextTypeface());
} else {
paint.setTypeface(Typeface.create(mRenderer.getTextTypefaceName(),
mRenderer.getTextTypefaceStyle()));
}
}
Orientation or = mRenderer.getOrientation();
if (or == Orientation.VERTICAL) {
right -= legendSize;
bottom += legendSize - 20;
}
int angle = or.getAngle();
boolean rotate = angle == 90;
mScale = (float) (height) / width;
mTranslate = Math.abs(width - height) / 2;
if (mScale < 1) {
mTranslate *= -1;
}
mCenter = new Point((x + width) / 2, (y + height) / 2);
if (rotate) {
transform(canvas, angle, false);
}
int maxScaleNumber = -Integer.MAX_VALUE;
for (int i = 0; i < sLength; i++) {
maxScaleNumber = Math.max(maxScaleNumber, mDataset.getSeriesAt(i).getScaleNumber());
}
maxScaleNumber++;
if (maxScaleNumber < 0) {
return;
}
double[] minX = new double[maxScaleNumber];
double[] maxX = new double[maxScaleNumber];
double[] minY = new double[maxScaleNumber];
double[] maxY = new double[maxScaleNumber];
boolean[] isMinXSet = new boolean[maxScaleNumber];
boolean[] isMaxXSet = new boolean[maxScaleNumber];
boolean[] isMinYSet = new boolean[maxScaleNumber];
boolean[] isMaxYSet = new boolean[maxScaleNumber];
for (int i = 0; i < maxScaleNumber; i++) {
minX[i] = mRenderer.getXAxisMin(i);
maxX[i] = mRenderer.getXAxisMax(i);
minY[i] = mRenderer.getYAxisMin(i);
maxY[i] = mRenderer.getYAxisMax(i);
isMinXSet[i] = mRenderer.isMinXSet(i);
isMaxXSet[i] = mRenderer.isMaxXSet(i);
isMinYSet[i] = mRenderer.isMinYSet(i);
isMaxYSet[i] = mRenderer.isMaxYSet(i);
if (mCalcRange.get(i) == null) {
mCalcRange.put(i, new double[4]);
}
}
double[] xPixelsPerUnit = new double[maxScaleNumber];
double[] yPixelsPerUnit = new double[maxScaleNumber];
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
if (!isMinXSet[scale]) {
double minimumX = series.getMinX();
minX[scale] = Math.min(minX[scale], minimumX);
mCalcRange.get(scale)[0] = minX[scale];
}
if (!isMaxXSet[scale]) {
double maximumX = series.getMaxX();
maxX[scale] = Math.max(maxX[scale], maximumX);
mCalcRange.get(scale)[1] = maxX[scale];
}
if (!isMinYSet[scale]) {
double minimumY = series.getMinY();
minY[scale] = Math.min(minY[scale], (float) minimumY);
mCalcRange.get(scale)[2] = minY[scale];
}
if (!isMaxYSet[scale]) {
double maximumY = series.getMaxY();
maxY[scale] = Math.max(maxY[scale], (float) maximumY);
mCalcRange.get(scale)[3] = maxY[scale];
}
}
for (int i = 0; i < maxScaleNumber; i++) {
if (maxX[i] - minX[i] != 0) {
xPixelsPerUnit[i] = (right - left) / (maxX[i] - minX[i]);
}
if (maxY[i] - minY[i] != 0) {
yPixelsPerUnit[i] = (float) ((bottom - top) / (maxY[i] - minY[i]));
}
// the X axis on multiple scales was wrong without this fix
if (i > 0) {
xPixelsPerUnit[i] = xPixelsPerUnit[0];
minX[i] = minX[0];
maxX[i] = maxX[0];
}
}
boolean hasValues = false;
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
if (series.getItemCount() == 0) {
continue;
}
hasValues = true;
}
boolean showLabels = mRenderer.isShowLabels() && hasValues;
boolean showGridX = mRenderer.isShowGridX();
boolean showGridY = mRenderer.isShowGridY();
if (showGridX || showGridY) {
// Draw the grid lines under everything else.
List<Double> xLabels = getValidLabels(getXLabels(minX[0], maxX[0], mRenderer.getXLabels()));
Map<Integer, List<Double>> allYLabels = getYLabels(minY, maxY, maxScaleNumber);
int xLabelsLeft = left;
boolean showXLabels = mRenderer.isShowXLabels();
boolean showYLabels = mRenderer.isShowYLabels();
// Only draw the grid.
mRenderer.setShowLabels(false);
if (mGridPaint == null) {
mGridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
drawXLabels(xLabels, mRenderer.getXTextLabelLocations(), canvas, paint, xLabelsLeft, top,
bottom, xPixelsPerUnit[0], minX[0], maxX[0]);
drawYLabels(allYLabels, canvas, paint, maxScaleNumber, left, right, bottom, yPixelsPerUnit,
minY);
mRenderer.setShowLabels(showXLabels, showYLabels);
}
// use a linked list for these reasons:
// 1) Avoid a large contiguous memory allocation
// 2) We don't need random seeking, only sequential reading/writing, so
// linked list makes sense
clickableAreas = new HashMap<Integer, List<ClickableArea>>();
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
XYSeriesRenderer seriesRenderer = (XYSeriesRenderer) mRenderer.getSeriesRendererAt(i);
// int originalValuesLength = series.getItemCount();
// int valuesLength = originalValuesLength;
// int length = valuesLength * 2;
List<Float> points = new ArrayList<Float>();
List<Double> values = new ArrayList<Double>();
float yAxisValue = Math.min(bottom, (float) (bottom + yPixelsPerUnit[scale] * minY[scale]));
LinkedList<ClickableArea> clickableArea = new LinkedList<ClickableArea>();
clickableAreas.put(i, clickableArea);
synchronized (series) {
SortedMap<Double, Double> range = series.getRange(minX[scale], maxX[scale],
seriesRenderer.isDisplayBoundingPoints());
int startIndex = -1;
for (Entry<Double, Double> value : range.entrySet()) {
double xValue = value.getKey();
double yValue = value.getValue();
if (startIndex < 0 && (!isNullValue(yValue) || isRenderNullValues())) {
startIndex = series.getIndexForKey(xValue);
}
// points.add((float) (left + xPixelsPerUnit[scale]
// * (value.getKey().floatValue() - minX[scale])));
// points.add((float) (bottom - yPixelsPerUnit[scale]
// * (value.getValue().floatValue() - minY[scale])));
values.add(value.getKey());
values.add(value.getValue());
if (!isNullValue(yValue)) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (yValue - minY[scale])));
} else if (isRenderNullValues()) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (-minY[scale])));
} else {
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or,
startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
points.clear();
values.clear();
startIndex = -1;
}
clickableArea.add(null);
}
}
int count = series.getAnnotationCount();
if (count > 0) {
paint.setColor(seriesRenderer.getAnnotationsColor());
paint.setTextSize(seriesRenderer.getAnnotationsTextSize());
paint.setTextAlign(seriesRenderer.getAnnotationsTextAlign());
Rect bound = new Rect();
for (int j = 0; j < count; j++) {
float xS = (float) (left + xPixelsPerUnit[scale]
* (series.getAnnotationX(j) - minX[scale]));
float yS = (float) (bottom - yPixelsPerUnit[scale]
* (series.getAnnotationY(j) - minY[scale]));
paint.getTextBounds(series.getAnnotationAt(j), 0, series.getAnnotationAt(j).length(),
bound);
if (xS < (xS + bound.width()) && yS < canvas.getHeight()) {
drawString(canvas, series.getAnnotationAt(j), xS, yS, paint);
}
}
}
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or, startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
}
}
}
// draw stuff over the margins so that data doesn't render on these areas
drawBackground(mRenderer, canvas, x, bottom, width, height - bottom, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, width, margins[0], paint, true,
mRenderer.getMarginsColor());
if (or == Orientation.HORIZONTAL) {
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, right, y, margins[3], height - y, paint, true,
mRenderer.getMarginsColor());
} else if (or == Orientation.VERTICAL) {
drawBackground(mRenderer, canvas, right, y, width - right, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
}
boolean showTickMarks = mRenderer.isShowTickMarks();
// boolean showCustomTextGridX = mRenderer.isShowCustomTextGridX();
boolean showCustomTextGridY = mRenderer.isShowCustomTextGridY();
if (showLabels) {
List<Double> xLabels = getValidLabels(getXLabels(minX[0], maxX[0], mRenderer.getXLabels()));
Map<Integer, List<Double>> allYLabels = getYLabels(minY, maxY, maxScaleNumber);
int xLabelsLeft = left;
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
paint.setTextSize(mRenderer.getLabelsTextSize());
paint.setTextAlign(mRenderer.getXLabelsAlign());
// if (mRenderer.getXLabelsAlign() == Align.LEFT) {
// xLabelsLeft += mRenderer.getLabelsTextSize() / 4;
// }
}
// Draw just the labels and not the grid lines.
mRenderer.setShowGrid(false);
drawXLabels(xLabels, mRenderer.getXTextLabelLocations(), canvas, paint, xLabelsLeft, top,
bottom, xPixelsPerUnit[0], minX[0], maxX[0]);
drawYLabels(allYLabels, canvas, paint, maxScaleNumber, left, right, bottom, yPixelsPerUnit,
minY);
mRenderer.setShowGridX(showGridX);
mRenderer.setShowGridY(showGridY);
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
Double[] yTextLabelLocations = mRenderer.getYTextLabelLocations(i);
for (Double location : yTextLabelLocations) {
if (minY[i] <= location && location <= maxY[i]) {
float yLabel = (float) (bottom - yPixelsPerUnit[i]
* (location.doubleValue() - minY[i]));
String label = mRenderer.getYTextLabel(location, i);
paint.setColor(mRenderer.getYLabelsColor(i));
paint.setTextAlign(mRenderer.getYLabelsAlign(i));
if (or == Orientation.HORIZONTAL) {
if (axisAlign == Align.LEFT) {
if (showTickMarks) {
canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint);
}
drawText(canvas, label, left - mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint,
mRenderer.getYLabelsAngle());
} else {
if (showTickMarks) {
canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel,
paint);
}
drawText(canvas, label, right - mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint,
mRenderer.getYLabelsAngle());
}
if (showCustomTextGridY) {
paint.setColor(mRenderer.getGridColor(i));
canvas.drawLine(left, yLabel, right, yLabel, paint);
}
} else {
if (showTickMarks) {
canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint);
}
drawText(canvas, label, right + 10, yLabel - mRenderer.getYLabelsVerticalPadding(),
paint, mRenderer.getYLabelsAngle());
if (showCustomTextGridY) {
paint.setColor(mRenderer.getGridColor(i));
canvas.drawLine(right, yLabel, left, yLabel, paint);
}
}
}
}
}
}
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
float size = mRenderer.getAxisTitleTextSize();
paint.setTextSize(size);
paint.setTextAlign(Align.CENTER);
if (or == Orientation.HORIZONTAL) {
drawText(
canvas,
mRenderer.getXTitle(),
x + width / 2,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding() + size,
paint, 0);
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
if (axisAlign == Align.LEFT) {
drawText(canvas, mRenderer.getYTitle(i), x + size, y + height / 2, paint, -90);
} else {
drawText(canvas, mRenderer.getYTitle(i), x + width, y + height / 2, paint, -90);
}
}
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + width / 2,
y + mRenderer.getChartTitleTextSize(), paint, 0);
} else if (or == Orientation.VERTICAL) {
drawText(canvas, mRenderer.getXTitle(), x + width / 2,
y + height - size + mRenderer.getXLabelsPadding(), paint, -90);
drawText(canvas, mRenderer.getYTitle(), right + 20, y + height / 2, paint, 0);
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + size, top + height / 2, paint, 0);
}
}
}
if (or == Orientation.HORIZONTAL) {
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
} else if (or == Orientation.VERTICAL) {
transform(canvas, angle, true);
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
transform(canvas, angle, false);
}
if (mRenderer.isShowAxes()) {
paint.setColor(mRenderer.getXAxisColor());
canvas.drawLine(left, bottom, right, bottom, paint);
paint.setColor(mRenderer.getYAxisColor());
boolean rightAxis = false;
for (int i = 0; i < maxScaleNumber && !rightAxis; i++) {
rightAxis = mRenderer.getYAxisAlign(i) == Align.RIGHT;
}
if (or == Orientation.HORIZONTAL) {
canvas.drawLine(left, top, left, bottom, paint);
if (rightAxis) {
canvas.drawLine(right, top, right, bottom, paint);
}
} else if (or == Orientation.VERTICAL) {
canvas.drawLine(right, top, right, bottom, paint);
}
}
if (rotate) {
transform(canvas, angle, true);
}
}
protected List<Double> getXLabels(double min, double max, int count) {
return MathHelper.getLabels(min, max, count);
}
protected Map<Integer, List<Double>> getYLabels(double[] minY, double[] maxY, int maxScaleNumber) {
Map<Integer, List<Double>> allYLabels = new HashMap<Integer, List<Double>>();
for (int i = 0; i < maxScaleNumber; i++) {
allYLabels.put(i,
getValidLabels(MathHelper.getLabels(minY[i], maxY[i], mRenderer.getYLabels())));
}
return allYLabels;
}
protected Rect getScreenR() {
return mScreenR;
}
protected void setScreenR(Rect screenR) {
mScreenR = screenR;
}
private List<Double> getValidLabels(List<Double> labels) {
List<Double> result = new ArrayList<Double>(labels);
for (Double label : labels) {
if (label.isNaN()) {
result.remove(label);
}
}
return result;
}
/**
* Draws the series.
*
* @param series the series
* @param canvas the canvas
* @param paint the paint object
* @param pointsList the points to be rendered
* @param seriesRenderer the series renderer
* @param yAxisValue the y axis value in pixels
* @param seriesIndex the series index
* @param or the orientation
* @param startIndex the start index of the rendering points
*/
protected void drawSeries(XYSeries series, Canvas canvas, Paint paint, List<Float> pointsList,
XYSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, Orientation or,
int startIndex) {
BasicStroke stroke = seriesRenderer.getStroke();
Cap cap = paint.getStrokeCap();
Join join = paint.getStrokeJoin();
float miter = paint.getStrokeMiter();
PathEffect pathEffect = paint.getPathEffect();
Style style = paint.getStyle();
if (stroke != null) {
PathEffect effect = null;
if (stroke.getIntervals() != null) {
effect = new DashPathEffect(stroke.getIntervals(), stroke.getPhase());
}
setStroke(stroke.getCap(), stroke.getJoin(), stroke.getMiter(), Style.FILL_AND_STROKE,
effect, paint);
}
// float[] points = MathHelper.getFloats(pointsList);
drawSeries(canvas, paint, pointsList, seriesRenderer, yAxisValue, seriesIndex, startIndex);
drawPoints(canvas, paint, pointsList, seriesRenderer, yAxisValue, seriesIndex, startIndex);
paint.setTextSize(seriesRenderer.getChartValuesTextSize());
if (or == Orientation.HORIZONTAL) {
paint.setTextAlign(Align.CENTER);
} else {
paint.setTextAlign(Align.LEFT);
}
if (seriesRenderer.isDisplayChartValues()) {
paint.setTextAlign(seriesRenderer.getChartValuesTextAlign());
drawChartValuesText(canvas, series, seriesRenderer, paint, pointsList, seriesIndex,
startIndex);
}
if (stroke != null) {
setStroke(cap, join, miter, style, pathEffect, paint);
}
}
/**
* Draws the series points.
*
* @param canvas the canvas
* @param paint the paint object
* @param pointsList the points to be rendered
* @param seriesRenderer the series renderer
* @param yAxisValue the y axis value in pixels
* @param seriesIndex the series index
* @param startIndex the start index of the rendering points
*/
protected void drawPoints(Canvas canvas, Paint paint, List<Float> pointsList,
XYSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex) {
if (isRenderPoints(seriesRenderer)) {
ScatterChart pointsChart = getPointsChart();
if (pointsChart != null) {
pointsChart.drawSeries(canvas, paint, pointsList, seriesRenderer, yAxisValue, seriesIndex,
startIndex);
}
}
}
private void setStroke(Cap cap, Join join, float miter, Style style, PathEffect pathEffect,
Paint paint) {
paint.setStrokeCap(cap);
paint.setStrokeJoin(join);
paint.setStrokeMiter(miter);
paint.setPathEffect(pathEffect);
paint.setStyle(style);
}
/**
* The graphical representation of the series values as text.
*
* @param canvas the canvas to paint to
* @param series the series to be painted
* @param renderer the series renderer
* @param paint the paint to be used for drawing
* @param points the array of points to be used for drawing the series
* @param seriesIndex the index of the series currently being drawn
* @param startIndex the start index of the rendering points
*/
protected void drawChartValuesText(Canvas canvas, XYSeries series, XYSeriesRenderer renderer,
Paint paint, List<Float> points, int seriesIndex, int startIndex) {
if (points.size() > 2) { // there are more than one point
// record the first point's position
float previousPointX = points.get(0);
float previousPointY = points.get(1);
for (int k = 0; k < points.size(); k += 2) {
if (k == 2) { // decide whether to display first two points' values or
// not
if (Math.abs(points.get(2) - points.get(0)) > renderer.getDisplayChartValuesDistance()
|| Math.abs(points.get(3) - points.get(1)) > renderer.getDisplayChartValuesDistance()) {
// first point
drawText(canvas, getLabel(renderer.getChartValuesFormat(), series.getY(startIndex)),
points.get(0), points.get(1) - renderer.getChartValuesSpacing(), paint, 0);
// second point
drawText(canvas,
getLabel(renderer.getChartValuesFormat(), series.getY(startIndex + 1)),
points.get(2), points.get(3) - renderer.getChartValuesSpacing(), paint, 0);
previousPointX = points.get(2);
previousPointY = points.get(3);
}
} else if (k > 2) {
// compare current point's position with the previous point's, if they
// are not too close, display
if (Math.abs(points.get(k) - previousPointX) > renderer.getDisplayChartValuesDistance()
|| Math.abs(points.get(k + 1) - previousPointY) > renderer
.getDisplayChartValuesDistance()) {
drawText(canvas,
getLabel(renderer.getChartValuesFormat(), series.getY(startIndex + k / 2)),
points.get(k), points.get(k + 1) - renderer.getChartValuesSpacing(), paint, 0);
previousPointX = points.get(k);
previousPointY = points.get(k + 1);
}
}
}
} else { // if only one point, display it
for (int k = 0; k < points.size(); k += 2) {
drawText(canvas,
getLabel(renderer.getChartValuesFormat(), series.getY(startIndex + k / 2)),
points.get(k), points.get(k + 1) - renderer.getChartValuesSpacing(), paint, 0);
}
}
}
/**
* The graphical representation of a text, to handle both HORIZONTAL and
* VERTICAL orientations and extra rotation angles.
*
* @param canvas the canvas to paint to
* @param text the text to be rendered
* @param x the X axis location of the text
* @param y the Y axis location of the text
* @param paint the paint to be used for drawing
* @param extraAngle the text angle
*/
protected void drawText(Canvas canvas, String text, float x, float y, Paint paint,
float extraAngle) {
float angle = -mRenderer.getOrientation().getAngle() + extraAngle;
if (angle != 0) {
// canvas.scale(1 / mScale, mScale);
canvas.rotate(angle, x, y);
}
drawString(canvas, text, x, y, paint);
if (angle != 0) {
canvas.rotate(-angle, x, y);
// canvas.scale(mScale, 1 / mScale);
}
}
/**
* Transform the canvas such as it can handle both HORIZONTAL and VERTICAL
* orientations.
*
* @param canvas the canvas to paint to
* @param angle the angle of rotation
* @param inverse if the inverse transform needs to be applied
*/
private void transform(Canvas canvas, float angle, boolean inverse) {
if (inverse) {
canvas.scale(1 / mScale, mScale);
canvas.translate(mTranslate, -mTranslate);
canvas.rotate(-angle, mCenter.getX(), mCenter.getY());
} else {
canvas.rotate(angle, mCenter.getX(), mCenter.getY());
canvas.translate(-mTranslate, mTranslate);
canvas.scale(mScale, 1 / mScale);
}
}
/**
* The graphical representation of the labels on the X axis.
*
* @param xLabels the X labels values
* @param xTextLabelLocations the X text label locations
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param left the left value of the labels area
* @param top the top value of the labels area
* @param bottom the bottom value of the labels area
* @param xPixelsPerUnit the amount of pixels per one unit in the chart labels
* @param minX the minimum value on the X axis in the chart
* @param maxX the maximum value on the X axis in the chart
*/
protected void drawXLabels(List<Double> xLabels, Double[] xTextLabelLocations, Canvas canvas,
Paint paint, int left, int top, int bottom, double xPixelsPerUnit, double minX, double maxX) {
int length = xLabels.size();
boolean showXLabels = mRenderer.isShowXLabels();
boolean showGridY = mRenderer.isShowGridY();
if (showGridY) {
mGridPaint.setStyle(Style.STROKE);
mGridPaint.setStrokeWidth(mRenderer.getGridLineWidth());
}
boolean showTickMarks = mRenderer.isShowTickMarks();
for (int i = 0; i < length; i++) {
double label = xLabels.get(i);
float xLabel = (float) (left + xPixelsPerUnit * (label - minX));
if (showXLabels) {
paint.setColor(mRenderer.getXLabelsColor());
if (showTickMarks) {
canvas
.drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint);
}
drawText(canvas, getLabel(mRenderer.getXLabelFormat(), label), xLabel,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding(), paint,
mRenderer.getXLabelsAngle());
}
if (showGridY) {
mGridPaint.setColor(mRenderer.getGridColor(0));
canvas.drawLine(xLabel, bottom, xLabel, top, mGridPaint);
}
}
drawXTextLabels(xTextLabelLocations, canvas, paint, showXLabels, left, top, bottom,
xPixelsPerUnit, minX, maxX);
}
/**
* The graphical representation of the labels on the Y axis.
*
* @param allYLabels the Y labels values
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param maxScaleNumber the maximum scale number
* @param left the left value of the labels area
* @param right the right value of the labels area
* @param bottom the bottom value of the labels area
* @param yPixelsPerUnit the amount of pixels per one unit in the chart labels
* @param minY the minimum value on the Y axis in the chart
*/
protected void drawYLabels(Map<Integer, List<Double>> allYLabels, Canvas canvas, Paint paint,
int maxScaleNumber, int left, int right, int bottom, double[] yPixelsPerUnit, double[] minY) {
Orientation or = mRenderer.getOrientation();
boolean showGridX = mRenderer.isShowGridX();
if (showGridX) {
mGridPaint.setStyle(Style.STROKE);
mGridPaint.setStrokeWidth(mRenderer.getGridLineWidth());
}
boolean showYLabels = mRenderer.isShowYLabels();
boolean showTickMarks = mRenderer.isShowTickMarks();
for (int i = 0; i < maxScaleNumber; i++) {
paint.setTextAlign(mRenderer.getYLabelsAlign(i));
List<Double> yLabels = allYLabels.get(i);
int length = yLabels.size();
for (int j = 0; j < length; j++) {
double label = yLabels.get(j);
Align axisAlign = mRenderer.getYAxisAlign(i);
boolean textLabel = mRenderer.getYTextLabel(label, i) != null;
float yLabel = (float) (bottom - yPixelsPerUnit[i] * (label - minY[i]));
if (or == Orientation.HORIZONTAL) {
if (showYLabels && !textLabel) {
paint.setColor(mRenderer.getYLabelsColor(i));
if (axisAlign == Align.LEFT) {
if (showTickMarks) {
canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint);
}
drawText(canvas, getLabel(mRenderer.getYLabelFormat(i), label),
left - mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint,
mRenderer.getYLabelsAngle());
} else {
if (showTickMarks) {
canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint);
}
drawText(canvas, getLabel(mRenderer.getYLabelFormat(i), label),
right + mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint,
mRenderer.getYLabelsAngle());
}
}
if (showGridX) {
mGridPaint.setColor(mRenderer.getGridColor(i));
canvas.drawLine(left, yLabel, right, yLabel, mGridPaint);
}
} else if (or == Orientation.VERTICAL) {
if (showYLabels && !textLabel) {
paint.setColor(mRenderer.getYLabelsColor(i));
if (showTickMarks) {
canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint);
}
drawText(canvas, getLabel(mRenderer.getLabelFormat(), label),
right + 10 + mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint, mRenderer.getYLabelsAngle());
}
if (showGridX) {
mGridPaint.setColor(mRenderer.getGridColor(i));
if (showTickMarks) {
canvas.drawLine(right, yLabel, left, yLabel, mGridPaint);
}
}
}
}
}
}
/**
* The graphical representation of the text labels on the X axis.
*
* @param xTextLabelLocations the X text label locations
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param left the left value of the labels area
* @param top the top value of the labels area
* @param bottom the bottom value of the labels area
* @param xPixelsPerUnit the amount of pixels per one unit in the chart labels
* @param minX the minimum value on the X axis in the chart
* @param maxX the maximum value on the X axis in the chart
*/
protected void drawXTextLabels(Double[] xTextLabelLocations, Canvas canvas, Paint paint,
boolean showLabels, int left, int top, int bottom, double xPixelsPerUnit, double minX,
double maxX) {
boolean showCustomTextGridX = mRenderer.isShowCustomTextGridX();
boolean showTickMarks = mRenderer.isShowTickMarks();
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
for (Double location : xTextLabelLocations) {
if (minX <= location && location <= maxX) {
float xLabel = (float) (left + xPixelsPerUnit * (location.doubleValue() - minX));
paint.setColor(mRenderer.getXLabelsColor());
if (showTickMarks) {
canvas.drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3,
paint);
}
drawText(canvas, mRenderer.getXTextLabel(location), xLabel,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding(),
paint, mRenderer.getXLabelsAngle());
if (showCustomTextGridX) {
paint.setColor(mRenderer.getGridColor(0));
canvas.drawLine(xLabel, bottom, xLabel, top, paint);
}
}
}
}
}
// TODO: docs
public XYMultipleSeriesRenderer getRenderer() {
return mRenderer;
}
public XYMultipleSeriesDataset getDataset() {
return mDataset;
}
public double[] getCalcRange(int scale) {
return mCalcRange.get(scale);
}
public void setCalcRange(double[] range, int scale) {
mCalcRange.put(scale, range);
}
public double[] toRealPoint(float screenX, float screenY) {
return toRealPoint(screenX, screenY, 0);
}
public double[] toScreenPoint(double[] realPoint) {
return toScreenPoint(realPoint, 0);
}
private int getLabelLinePos(Align align) {
int pos = 4;
if (align == Align.LEFT) {
pos = -pos;
}
return pos;
}
/**
* Transforms a screen point to a real coordinates point.
*
* @param screenX the screen x axis value
* @param screenY the screen y axis value
* @return the real coordinates point
*/
public double[] toRealPoint(float screenX, float screenY, int scale) {
double realMinX = mRenderer.getXAxisMin(scale);
double realMaxX = mRenderer.getXAxisMax(scale);
double realMinY = mRenderer.getYAxisMin(scale);
double realMaxY = mRenderer.getYAxisMax(scale);
if (!mRenderer.isMinXSet(scale) || !mRenderer.isMaxXSet(scale) || !mRenderer.isMinYSet(scale)
|| !mRenderer.isMaxYSet(scale)) {
double[] calcRange = getCalcRange(scale);
if (calcRange != null) {
realMinX = calcRange[0];
realMaxX = calcRange[1];
realMinY = calcRange[2];
realMaxY = calcRange[3];
}
}
if (mScreenR != null) {
return new double[] {
(screenX - mScreenR.left) * (realMaxX - realMinX) / mScreenR.width() + realMinX,
(mScreenR.top + mScreenR.height() - screenY) * (realMaxY - realMinY) / mScreenR.height()
+ realMinY };
} else {
return new double[] { screenX, screenY };
}
}
public double[] toScreenPoint(double[] realPoint, int scale) {
double realMinX = mRenderer.getXAxisMin(scale);
double realMaxX = mRenderer.getXAxisMax(scale);
double realMinY = mRenderer.getYAxisMin(scale);
double realMaxY = mRenderer.getYAxisMax(scale);
if (!mRenderer.isMinXSet(scale) || !mRenderer.isMaxXSet(scale) || !mRenderer.isMinYSet(scale)
|| !mRenderer.isMaxYSet(scale)) {
double[] calcRange = getCalcRange(scale);
realMinX = calcRange[0];
realMaxX = calcRange[1];
realMinY = calcRange[2];
realMaxY = calcRange[3];
}
if (mScreenR != null) {
return new double[] {
(realPoint[0] - realMinX) * mScreenR.width() / (realMaxX - realMinX) + mScreenR.left,
(realMaxY - realPoint[1]) * mScreenR.height() / (realMaxY - realMinY) + mScreenR.top };
} else {
return realPoint;
}
}
public SeriesSelection getSeriesAndPointForScreenCoordinate(final Point screenPoint) {
if (clickableAreas != null)
for (int seriesIndex = clickableAreas.size() - 1; seriesIndex >= 0; seriesIndex--) {
// series 0 is drawn first. Then series 1 is drawn on top, and series 2
// on top of that.
// we want to know what the user clicked on, so traverse them in the
// order they appear on the screen.
int pointIndex = 0;
if (clickableAreas.get(seriesIndex) != null) {
RectF rectangle;
for (ClickableArea area : clickableAreas.get(seriesIndex)) {
if (area != null) {
rectangle = area.getRect();
if (rectangle != null && rectangle.contains(screenPoint.getX(), screenPoint.getY())) {
return new SeriesSelection(seriesIndex, pointIndex, area.getX(), area.getY());
}
}
pointIndex++;
}
}
}
return super.getSeriesAndPointForScreenCoordinate(screenPoint);
}
/**
* The graphical representation of a series.
*
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param points the array of points to be used for drawing the series
* @param seriesRenderer the series renderer
* @param yAxisValue the minimum value of the y axis
* @param seriesIndex the index of the series currently being drawn
* @param startIndex the start index of the rendering points
*/
public abstract void drawSeries(Canvas canvas, Paint paint, List<Float> points,
XYSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex);
/**
* Returns the clickable areas for all passed points
*
* @param points the array of points
* @param values the array of values of each point
* @param yAxisValue the minimum value of the y axis
* @param seriesIndex the index of the series to which the points belong
* @return an array of rectangles with the clickable area
* @param startIndex the start index of the rendering points
*/
protected abstract ClickableArea[] clickableAreasForPoints(List<Float> points,
List<Double> values, float yAxisValue, int seriesIndex, int startIndex);
/**
* Returns if the chart should display the null values.
*
* @return if null values should be rendered
*/
protected boolean isRenderNullValues() {
return false;
}
/**
* Returns if the chart should display the points as a certain shape.
*
* @param renderer the series renderer
*/
public boolean isRenderPoints(SimpleSeriesRenderer renderer) {
return false;
}
/**
* Returns the default axis minimum.
*
* @return the default axis minimum
*/
public double getDefaultMinimum() {
return MathHelper.NULL_VALUE;
}
/**
* Returns the scatter chart to be used for drawing the data points.
*
* @return the data points scatter chart
*/
public ScatterChart getPointsChart() {
return null;
}
/**
* Returns the chart type identifier.
*
* @return the chart type
*/
public abstract String getChartType();
}
| liupeng3425/StepSensorTest | app/src/main/java/org/achartengine/chart/XYChart.java | Java | apache-2.0 | 42,814 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sanselan.formats.jpeg.segments;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.sanselan.ImageReadException;
import org.apache.sanselan.formats.jpeg.JpegImageParser;
public class SOFNSegment extends Segment
{
public final int width, height;
public final int numberOfComponents;
public final int precision;
public SOFNSegment(int marker, byte segmentData[])
throws ImageReadException, IOException
{
this(marker, segmentData.length, new ByteArrayInputStream(segmentData));
}
public SOFNSegment(int marker, int marker_length, InputStream is)
throws ImageReadException, IOException
{
super(marker, marker_length);
if (getDebug())
System.out.println("SOF0Segment marker_length: " + marker_length);
{
precision = readByte("Data_precision", is, "Not a Valid JPEG File");
height = read2Bytes("Image_height", is, "Not a Valid JPEG File");
width = read2Bytes("Image_Width", is, "Not a Valid JPEG File");
numberOfComponents = readByte("Number_of_components", is,
"Not a Valid JPEG File");
// ignore the rest of the segment for now...
skipBytes(is, marker_length - 6,
"Not a Valid JPEG File: SOF0 Segment");
// int Each_component1 = read_byte("Each_component1", is,
// "Not a Valid JPEG File");
// int Each_component2 = read_byte("Each_component2", is,
// "Not a Valid JPEG File");
// int Each_component3 = read_byte("Each_component3", is,
// "Not a Valid JPEG File");
}
if (getDebug())
System.out.println("");
}
public String getDescription()
{
return "SOFN (SOF" + (marker - JpegImageParser.SOF0Marker) + ") ("
+ getSegmentType() + ")";
}
} | mike10004/appengine-imaging | gaecompat-awt-imaging/src/sanselan/org/apache/sanselan/formats/jpeg/segments/SOFNSegment.java | Java | apache-2.0 | 2,967 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Plaisance-McLevey Lab</title>
<meta name="viewport" content="width=device-width">
<meta name="description" content="Plaisance-McLevey Lab at the University of Waterloo">
<link rel="canonical" href="/">
<!-- Custom CSS & Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
<link rel="stylesheet" href="/style.css">
<!-- Custom Fonts -->
<link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top" class="index">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand page-scroll" href="#page-top">Plaisance-McLevey Lab</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden">
<a href="#page-top"></a>
</li>
<li>
<a class="page-scroll" href="#why">Why?</a>
</li>
<li>
<a class="page-scroll" href="#research">Research Strategy</a>
</li>
<li>
<a class="page-scroll" href="#team">Team</a>
</li>
<li>
<a class="page-scroll" href="#links">Links</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- Header -->
<header>
<div class="container">
<div class="intro-text">
<!-- <div class="team-member">
<img src="img/team/johnmclevey.jpg" class="img-responsive img-circle" alt="">
</div> -->
<div class="intro-lead-in">We are mapping the uptake of philosophy of science in the natural, physical, and social sciences from 1952-2014.</div>
<a href="#research" class="page-scroll btn btn-xl">Learn More</a>
</div>
</div>
</header>
<!--
<a class="page-link" href="/about/">About</a>
<a class="page-link" href="/Related Projects/">Related Projects</a>
<a class="page-link" href="/team/">Research Team</a>
-->
<!-- Team Section -->
<section id="why" class="bg-light-gray">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Why?</h2>
<h3 class="section-subheading text-muted">Can we include 2-3 sentences on the motivation for the project? Both social and intellectual. This could help with survey response rates.</h3>
</div>
</section>
<!-- Research Section -->
<section id="research">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Research Strategy</h2>
<h3 class="section-subheading text-muted">We are combining citation analysis with a survey of philosophers of science and qualitative case studies.</h3>
</div>
</div>
<div class="row text-left">
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-share-alt fa-stack-1x fa-inverse"></i>
</span>
<h4 class="research-heading">Citation Analysis</h4>
<p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p>
<p class="text-muted">Nullam placerat commodo orci a maximus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum sed nunc sit amet mi pharetra consectetur a a mauris. Donec vestibulum scelerisque vehicula. Quisque ultricies neque eget finibus volutpat. Aliquam consequat eros at erat placerat, nec luctus urna faucibus. Proin placerat dolor mauris, in convallis elit luctus vitae. Morbi a massa ligula. Nunc auctor augue et nunc consectetur aliquet. Vestibulum sagittis lacus ullamcorper lacinia aliquam. Aenean vel urna id neque dapibus lobortis sit amet non sapien.</p>
</div>
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-bar-chart-o fa-stack-1x fa-inverse"></i>
</span>
<h4 class="research-heading">Philosohy of Science Survey</h4>
<p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque viverra ante pretium pharetra tincidunt. Integer nec elit in ligula eleifend congue. Vestibulum consectetur convallis ex eu faucibus. Nulla eu interdum libero. Quisque non scelerisque turpis. Fusce consectetur, diam vitae tempor tempor, nulla nisi vulputate orci, ac mattis ipsum arcu at sem. Sed non enim eros. Cras ipsum justo, ullamcorper nec vulputate eget, mattis eu libero. Nunc feugiat urna placerat ligula fermentum, dignissim congue diam ullamcorper. In sit amet massa lacinia, scelerisque felis id, aliquam risus. Sed mollis eros nec libero bibendum molestie.</p>
</div>
<div class="col-md-4">
<span class="fa-stack fa-4x">
<i class="fa fa-circle fa-stack-2x text-primary"></i>
<i class="fa fa-comment-o fa-stack-1x fa-inverse"></i>
</span>
<h4 class="research-heading">Qualitative Case Studies</h4>
<p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p>
<p class="text-muted">Nullam placerat commodo orci a maximus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum sed nunc sit amet mi pharetra consectetur a a mauris. Donec vestibulum scelerisque vehicula. Quisque ultricies neque eget finibus volutpat. Aliquam consequat eros at erat placerat, nec luctus urna faucibus. Proin placerat dolor mauris, in convallis elit luctus vitae. Morbi a massa ligula. Nunc auctor augue et nunc consectetur aliquet. Vestibulum sagittis lacus ullamcorper lacinia aliquam. Aenean vel urna id neque dapibus lobortis sit amet non sapien.</p>
</div>
</div>
</div>
</section>
<!-- Team Section -->
<section id="team" class="bg-light-gray">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Research Team</h2>
<h3 class="section-subheading text-muted"></h3>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-lg-12 text-center">
<div class="team-member">
<img src="img/team/katie.jpg" class="img-responsive img-circle" alt="">
<h4>Katie Plaisance</h4>
<p class="text-muted">Assistant Professor</p>
<ul class="list-inline social-buttons">
<li><a href="https://uwaterloo.ca/knowledge-integration/faculty-plaisance"><i class="fa fa-link"></i></a>
<li><a href="https://twitter.com/katieplaisance"><i class="fa fa-twitter"></i></a>
<li><a href="https://www.linkedin.com/profile/view?id=126695447&authType=NAME_SEARCH&authToken=g7qN&locale=en_US&trk=tyah2&trkInfo=tarId%3A1412862644454%2Ctas%3Akatie%20plaisance%2Cidx%3A1-1-1"><i class="fa fa-linkedin"></i></a>
</ul>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-lg-12 text-center">
<div class="team-member">
<img src="img/team/john.jpg" class="img-responsive img-circle" alt="">
<h4>John McLevey</h4>
<p class="text-muted">Assistant Professor</p>
<ul class="list-inline social-buttons">
<li><a href="https://twitter.com/johnmclevey"><i class="fa fa-twitter"></i></a>
<li><a href="http://www.johnmclevey.com"><i class="fa fa-link"></i></a>
<li><a href="http://github.com/mclevey"><i class="fa fa-github"></i></a>
</ul>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-lg-12 text-center">
<div class="team-member">
<img src="img/team/janet.jpg" class="img-responsive img-circle" alt="">
<h4>Janet Michaud</h4>
<p class="text-muted">Research Assistant</p>
<ul class="list-inline social-buttons">
<li><a href="https://twitter.com/"><i class="fa fa-twitter"></i></a>
<li><a href=""><i class="fa fa-linkedin"></i></a>
</ul>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-lg-12 text-center">
<div class="team-member">
<img src="img/team/ben.jpg" class="img-responsive img-circle" alt="">
<h4>Ben Nelson</h4>
<p class="text-muted">Research Assistant</p>
<ul class="list-inline social-buttons">
<li><a href="https://twitter.com/"><i class="fa fa-twitter"></i></a>
<li><a href="http://blsnelson.wordpress.com/"><i class="fa fa-link"></i></a>
<li><a href="https://www.linkedin.com/profile/view?id=41502798&goback=%2Enpv_41502798_*1_*1_NAME*4SEARCH_sK8x_*1_en*4US_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1_tyah2_*1"><i class="fa fa-linkedin"></i></a>
</ul>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-lg-12 text-center">
<div class="team-member">
<img src="img/team/sasha.jpg" class="img-responsive img-circle" alt="">
<h4>Sasha Graham</h4>
<p class="text-muted">Research Assistant</p>
<ul class="list-inline social-buttons">
<li><a href="https://twitter.com/SashaVGraham"><i class="fa fa-twitter"></i></a>
<li><a href="https://www.linkedin.com/profile/view?id=158618535&authType=NAME_SEARCH&authToken=bQBl&locale=en_US&trk=tyah2&trkInfo=tarId%3A1412862783253%2Ctas%3Aalexander%20gr%2Cidx%3A2-1-4"><i class="fa fa-linkedin"></i></a>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-left">
<div class="col-lg-12 text-center">
<h3 class="section-heading">Principal Investigators</h3>
</div>
<!--
<div class="team-member">
<img src="img/team/john.jpg" class="img-responsive img-circle" alt="">
<h4>John McLevey</h4>
<p class="text-muted">Assistant Professor</p>
<ul class="list-inline social-buttons">
</div>
-->
<p class="large text-muted"><b>Katie Plaisance</b> is an Assistant Professor in the Department of Knowledge Integration at the University of Waterloo, cross-appointed to the Department of Philosophy...</p>
<p class="large text-muted"><b>John McLevey</b> is an Assistant Professor in the Department of Knowledge Integration at the University of Waterloo, cross-appointed to the Departments of Sociology and Legal Studies, and Environment and Resource Studies...</p>
<div class="col-lg-12 text-center">
<h3 class="section-heading">Research Assistants</h3>
</div>
<p class="large text-muted"><b>Janet Michaud</b> is a PhD student in the philosophy department at Waterloo. Her main areas of research span a number of socially relevant topics in philosophy such as: social and feminist epistemologies, feminist and engaged philosophy of science, experimental philosophy and interdisciplinary collaboration. She is involved in a number of collaborative experimental projects looking at values in science communication and coercion in controversial police interrogation tactics.</p>
<p class="large text-muted"><b>Ben Nelson</b>'s main area of area interest is in the philosophy of law, and specifically on the unpublished aspects of positive law. In addition, he is working on projects in the pragmatics of intellectual good faith, the epistemology of intuitions, and evolutionary game theory in the philosophy of the social sciences. A unifying feature of his work is the idea of tacit normativity, which is an idea he finds weird, and therefore fascinating. His blog can be found <a href="http://blsnelson.wordpress.com/">here</a>, where he posts about issues in the profession of philosophy, including the <a href="http://blsnelson.wordpress.com/2014/05/13/the-natural-sciencephilosophy-connection/">philosophy of science</a>.</p>
<p class="large text-muted"><b>Sasha Graham</b> is a Bachelor of Knowledge Integration Honors student at the University of Waterloo... </p>
</div>
</div>
</div>
</section>
<!-- related Section -->
<section id="links">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Links</h2>
<h3 class="section-subheading text-muted"></h3>
</div>
</div>
<div class="row">
<div class="col-lg-12 text-center">
<div> <p class="large text-muted"><a href="https://uwaterloo.ca/knowledge-integration/node/1"><i class="fa fa-link"></i></a> Knowledge Integration at the University of Waterloo</p>
<div> <p class="large text-muted"><a href="http://communitiesofintegration.weebly.com/"><i class="fa fa-link"></i></a> Communities of Integration</p>
<div> <p class="large text-muted"><a href="http://srpoise.org/"><i class="fa fa-link"></i></a> Socially Relevant Philosophy of / in Science and Engineering</p>
<div> <p class="large text-muted"><a href="http://www.cf.ac.uk/socsi/contactsandpeople/harrycollins/expertise-project/"><i class="fa fa-link"></i></a> Studies of Expertise and Experience</p>
<div> <p class="large text-muted"><a href="http://cns.asu.edu/research/stir"><i class="fa fa-link"></i></a> Socio-Technical Integration Research (STIR)</p>
<div> <p class="large text-muted"><a href="http://www.cals.uidaho.edu/toolbox/"><i class="fa fa-link"></i></a> The Toolbox Project</p>
<div> <p class="large text-muted"><a href="http://communitiesofintegration.weebly.com/trading-zones.html"><i class="fa fa-link"></i></a> Trading Zones</p>
<div> <p class="large text-muted"><a href="http://femmss.org/"><i class="fa fa-link"></i></a> Feminist Epistemologies, Methodologies, Metaphysics, and Science Studies (FEMMSS) </p>
<div> <p class="large text-muted"><a href="http://wici.ca/"><i class="fa fa-link"></i></a> Waterloo Institute for Complexity and Innovation</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-4">
<span class="copyright">Copyright © Plaisance and McLevey 2014</span>
</div>
<div class="col-md-4">
<ul class="list-inline social-buttons">
<li><a href="http://twitter.com/johnmclevey"><i class="fa fa-twitter"></i></a>
</li>
<li><a href="http://github.com/mclevey"><i class="fa fa-github"></i></a>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-inline quicklinks">
<li><a href="#">Powered by Jekyll + Start Bootstrap.</a>
</li>
<!-- <li><a href="#">Terms of Use</a>
</li> -->
</ul>
</div>
</div>
</div>
</footer>
<!-- Portfolio Modals -->
<div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Dreams</h2>
<hr class="star-primary">
<img src="img/portfolio/dreams.png" class="img-responsive img-centered" alt="image-alt">
<p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p>
<ul class="list-inline item-details">
<li>Client:
<strong><a href="http://startbootstrap.com">Start Bootstrap</a>
</strong>
</li>
<li>Date:
<strong><a href="http://startbootstrap.com">April 2014</a>
</strong>
</li>
<li>Service:
<strong><a href="http://startbootstrap.com">Web Development</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Escape</h2>
<hr class="star-primary">
<img src="img/portfolio/escape.png" class="img-responsive img-centered" alt="image-alt">
<p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p>
<ul class="list-inline item-details">
<li>Client:
<strong><a href="http://startbootstrap.com">Start Bootstrap</a>
</strong>
</li>
<li>Date:
<strong><a href="http://startbootstrap.com">April 2014</a>
</strong>
</li>
<li>Service:
<strong><a href="http://startbootstrap.com">Web Development</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Golden</h2>
<hr class="star-primary">
<img src="img/portfolio/golden.png" class="img-responsive img-centered" alt="image-alt">
<p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p>
<ul class="list-inline item-details">
<li>Client:
<strong><a href="http://startbootstrap.com">Start Bootstrap</a>
</strong>
</li>
<li>Date:
<strong><a href="http://startbootstrap.com">April 2014</a>
</strong>
</li>
<li>Service:
<strong><a href="http://startbootstrap.com">Web Development</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Round Icons</h2>
<hr class="star-primary">
<img src="img/portfolio/roundicons.png" class="img-responsive img-centered" alt="image-alt">
<p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p>
<ul class="list-inline item-details">
<li>Client:
<strong><a href="http://startbootstrap.com">Start Bootstrap</a>
</strong>
</li>
<li>Date:
<strong><a href="http://startbootstrap.com">April 2014</a>
</strong>
</li>
<li>Service:
<strong><a href="http://startbootstrap.com">Web Development</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Treehouse</h2>
<hr class="star-primary">
<img src="img/portfolio/treehouse.png" class="img-responsive img-centered" alt="image-alt">
<p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p>
<ul class="list-inline item-details">
<li>Client:
<strong><a href="http://startbootstrap.com">Start Bootstrap</a>
</strong>
</li>
<li>Date:
<strong><a href="http://startbootstrap.com">April 2014</a>
</strong>
</li>
<li>Service:
<strong><a href="http://startbootstrap.com">Web Development</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close-modal" data-dismiss="modal">
<div class="lr">
<div class="rl">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="modal-body">
<h2>Startup Framework</h2>
<hr class="star-primary">
<img src="img/portfolio/startup-framework.png" class="img-responsive img-centered" alt="image-alt">
<p>Lorem ipsum dolor sit amet, usu cu alterum nominavi lobortis. At duo novum diceret. Tantas apeirian vix et, usu sanctus postulant inciderint ut, populo diceret necessitatibus in vim. Cu eum dicam feugiat noluisse.</p>
<ul class="list-inline item-details">
<li>Client:
<strong><a href="http://startbootstrap.com">Start Bootstrap</a>
</strong>
</li>
<li>Date:
<strong><a href="http://startbootstrap.com">April 2014</a>
</strong>
</li>
<li>Service:
<strong><a href="http://startbootstrap.com">Web Development</a>
</strong>
</li>
</ul>
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery Version 1.11.0 -->
<script src="/js/jquery-1.11.0.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="/js/jquery.easing.min.js"></script>
<script src="/js/classie.js"></script>
<script src="/js/cbpAnimatedHeader.js"></script>
<!-- Contact Form JavaScript -->
<script src="/js/jqBootstrapValidation.js"></script>
<script src="/js/contact_me.js"></script>
<!-- Custom Theme JavaScript -->
<script src="/js/agency.js"></script>
</body>
</html> | plaisance-mclevey-lab/plaisance-mclevey-lab.github.com | _site/index.html | HTML | apache-2.0 | 32,913 |
/*
* Copyright 2013-2019 consulo.io
*
* 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 consulo.ui.web.internal.layout;
import com.vaadin.ui.Component;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.ui.layout.VerticalLayout;
import consulo.ui.web.internal.TargetVaddin;
import consulo.ui.web.internal.base.VaadinComponentDelegate;
import consulo.ui.web.internal.base.VaadinComponentContainer;
import javax.annotation.Nonnull;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author VISTALL
* @since 2019-02-19
*/
public class WebVerticalLayoutImpl extends VaadinComponentDelegate<WebVerticalLayoutImpl.Vaadin> implements VerticalLayout {
public static class Vaadin extends VaadinComponentContainer {
private final List<Component> myChildren = new LinkedList<>();
public void add(@Nonnull Component component) {
addComponent(component);
myChildren.add(component);
markAsDirtyRecursive();
}
@Override
public void removeComponent(Component c) {
myChildren.remove(c);
super.removeComponent(c);
}
@Override
public int getComponentCount() {
return myChildren.size();
}
@Override
public Iterator<Component> iterator() {
return myChildren.iterator();
}
}
@Override
@Nonnull
public Vaadin createVaadinComponent() {
return new Vaadin();
}
@RequiredUIAccess
@Nonnull
@Override
public VerticalLayout add(@Nonnull consulo.ui.Component component) {
getVaadinComponent().add(TargetVaddin.to(component));
return this;
}
}
| consulo/consulo | modules/web/web-ui-impl-server/src/main/java/consulo/ui/web/internal/layout/WebVerticalLayoutImpl.java | Java | apache-2.0 | 2,110 |
"""Flask Blueprint adding login functionality to our app. Note that we expect
gluten model and db config to be handled elsewhere
"""
import sys
import traceback
from functools import partial, wraps
from flask import redirect, request, flash, session, abort, g, url_for
from flask.globals import LocalProxy, _lookup_app_object
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
from flask_dance.consumer import (
OAuth2ConsumerBlueprint,
oauth_authorized,
oauth_error
)
from gludb.utils import now_field
from .utils import app_logger
from .models import User
def set_user_session(user_id=None):
if not user_id:
user_id = ''
session['user_id'] = user_id
def get_user():
"""Return current user"""
user_id = session.get('user_id', '')
if not user_id:
return None # Not logged in
return User.find_one(user_id)
def require_login(func):
"""Simple decorator helper for requiring login on functions decorated with
flask route: make sure that it's LAST in the decorator list so that the
flask magic happens (see voice_testing for an example).
Important: we are assuming the blueprint endpoint auth.login exists
"""
@wraps(func)
def wrapper(*args, **kwrds):
try:
user = get_user()
if user:
setattr(g, 'user', user)
return func(*args, **kwrds)
else:
url = url_for('auth.login', redir=request.url)
return redirect(url)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
log = app_logger()
log.warning("Unexpected error: %s", exc_value)
log.error(''.join(traceback.format_exception(
exc_type, exc_value, exc_traceback
)))
return abort(500)
return wrapper
# Make the google blueprint (taken from their contrib code)
auth = OAuth2ConsumerBlueprint(
"auth",
__name__,
client_id=None, # Handled via app config
client_secret=None, # Handled via app config
scope=["profile", "email"],
base_url="https://www.googleapis.com/",
authorization_url="https://accounts.google.com/o/oauth2/auth",
token_url="https://accounts.google.com/o/oauth2/token",
redirect_url=None,
redirect_to=None,
login_url=None,
authorized_url=None,
authorization_url_params={},
session_class=None,
backend=None,
)
auth.from_config["client_id"] = "GOOGLE_OAUTH_CLIENT_ID"
auth.from_config["client_secret"] = "GOOGLE_OAUTH_CLIENT_SECRET"
@auth.before_app_request
def set_applocal_session():
ctx = stack.top
ctx.google_oauth = auth.session
google_api = LocalProxy(partial(_lookup_app_object, "google_oauth"))
def login_fail(msg):
flash(msg, category="error")
app_logger().error(msg)
return False
# create/login local user on successful OAuth login
@oauth_authorized.connect
def log_in_event(blueprint, token):
set_user_session() # Clear previous session
if not token:
return login_fail("Failed to log in")
resp = blueprint.session.get("/oauth2/v1/userinfo")
if not resp.ok:
return login_fail("Failed to login user!")
data = resp.json()
email = data.get('email', '')
if not email:
return login_fail("Google failed to supply an email address")
users = User.find_by_index('idx_email', email)
if users:
user = users[0]
else:
user = User(email=email)
# Update the user info and save the session info
user.name = data.get('name', email)
user.photo = data.get('picture', '/static/anonymous_person.png')
user.logins.append(now_field())
user.save()
set_user_session(user.id)
app_logger().info("Logged in user id %s, email %s" % (user.id, user.email))
# notify on OAuth provider error
@oauth_error.connect
def github_error(blueprint, error, error_description=None, error_uri=None):
login_fail("OAuth login failure: [%s] %s (uri=%s)" % (
error, error_description, error_uri
))
@auth.route('/logout')
def logout():
set_user_session()
redir_url = request.args.get("redir", None)
if not redir_url:
redir_url = '/'
return redirect(redir_url)
| memphis-iis/gluten | gluten/auth.py | Python | apache-2.0 | 4,308 |
package zemberek.examples.morphology;
import java.io.IOException;
import zemberek.core.logging.Log;
import zemberek.core.turkish.PrimaryPos;
import zemberek.core.turkish.RootAttribute;
import zemberek.core.turkish.SecondaryPos;
import zemberek.morphology.TurkishMorphology;
import zemberek.morphology.analysis.SingleAnalysis;
import zemberek.morphology.analysis.WordAnalysis;
import zemberek.morphology.lexicon.DictionaryItem;
public class AddNewDictionaryItem {
TurkishMorphology morphology;
AddNewDictionaryItem(TurkishMorphology morphology) {
this.morphology = morphology;
}
public static void main(String[] args) throws IOException {
TurkishMorphology morphology = TurkishMorphology.createWithDefaults();
AddNewDictionaryItem app = new AddNewDictionaryItem(morphology);
Log.info("Proper Noun Test - 1 :");
app.test("Meydan'a",
new DictionaryItem("Meydan", "meydan", "meydan",
PrimaryPos.Noun, SecondaryPos.ProperNoun));
Log.info("----");
Log.info("Proper Noun Test - 2 :");
app.test("Meeeydan'a",
new DictionaryItem("Meeeydan", "meeeydan", "meeeydan",
PrimaryPos.Noun, SecondaryPos.ProperNoun));
Log.info("----");
Log.info("Verb Test : ");
app.test("tweetleyeyazdım",
new DictionaryItem("tweetlemek", "tweetle", "tivitle",
PrimaryPos.Verb, SecondaryPos.None));
}
private void test(String input, DictionaryItem newItem) throws IOException {
WordAnalysis before = morphology.analyze(input);
Log.info("Parses for " + input + " before adding " + newItem);
printResults(before);
morphology.invalidateCache();
morphology.getMorphotactics().getStemTransitions().addDictionaryItem(newItem);
WordAnalysis after = morphology.analyze(input);
Log.info("Parses for " + input + " after adding " + newItem);
printResults(after);
}
private void printResults(WordAnalysis results) {
int i = 1;
if (results.analysisCount() == 0) {
Log.info("No Analysis.");
}
for (SingleAnalysis result : results) {
String str = result.formatLong();
if (result.getDictionaryItem().attributes.contains(RootAttribute.Runtime)) {
str = str + " (Generated by UnidentifiedTokenParser)";
}
Log.info(i + " - " + str);
i++;
}
}
}
| ahmetaa/turkish-nlp-examples | src/main/java/zemberek/examples/morphology/AddNewDictionaryItem.java | Java | apache-2.0 | 2,327 |
# Pilosella aurantiaca subsp. porphyromelana (Nägeli & Peter) Soják SUBSPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Pilosella/Pilosella aurantiaca/Pilosella aurantiaca porphyromelana/README.md | Markdown | apache-2.0 | 220 |
# Mutisia meyeniana J.Rémy ex Phil. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Mutisia oligodon/ Syn. Mutisia meyeniana/README.md | Markdown | apache-2.0 | 191 |
package com.nimbusds.jose;
import java.text.ParseException;
import junit.framework.TestCase;
import com.nimbusds.jose.util.Base64URL;
/**
* Tests JWS header parsing and serialisation.
*
* @author Vladimir Dzhuvinov
* @version $version$ (2012-10-01)
*/
public class JWSHeaderTest extends TestCase {
public void testParseJSONText() {
// Example header from JWS spec
String s = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
JWSHeader h = null;
try {
h = JWSHeader.parse(s);
} catch (ParseException e) {
fail(e.getMessage());
}
assertNotNull(h);
assertEquals(new JOSEObjectType("JWT"), h.getType());
assertEquals(JWSAlgorithm.HS256, h.getAlgorithm());
assertNull(h.getContentType());
assertTrue(h.getIncludedParameters().contains("alg"));
assertTrue(h.getIncludedParameters().contains("typ"));
assertEquals(2, h.getIncludedParameters().size());
}
public void testParseBase64URLText() {
// Example header from JWS spec
String s = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9";
JWSHeader h = null;
try {
h = JWSHeader.parse(new Base64URL(s));
} catch (ParseException e) {
fail(e.getMessage());
}
assertNotNull(h);
assertEquals(new JOSEObjectType("JWT"), h.getType());
assertEquals(JWSAlgorithm.HS256, h.getAlgorithm());
assertNull(h.getContentType());
}
}
| gesellix/Nimbus-JOSE-JWT | src/test/java/com/nimbusds/jose/JWSHeaderTest.java | Java | apache-2.0 | 1,373 |
/*
libparted - a library for manipulating disk partitions
Copyright (C) 2000, 2003-2005, 2007, 2009-2011 Free Software Foundation,
Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : Guillaume Knispel <k_guillaume@libertysurf.fr>
Report bug to <bug-parted@gnu.org>
*/
#include <config.h>
#include <parted/parted.h>
#include <parted/endian.h>
#include <parted/debug.h>
#include <stdint.h>
#if ENABLE_NLS
# include <libintl.h>
# define _(String) dgettext (PACKAGE, String)
#else
# define _(String) (String)
#endif /* ENABLE_NLS */
#include "hfs.h"
#include "probe.h"
uint8_t* hfs_block = NULL;
uint8_t* hfsp_block = NULL;
unsigned hfs_block_count;
unsigned hfsp_block_count;
#define HFS_BLOCK_SIZES ((int[2]){512, 0})
#define HFSP_BLOCK_SIZES ((int[2]){512, 0})
#define HFSX_BLOCK_SIZES ((int[2]){512, 0})
static PedFileSystemOps hfs_ops = {
probe: hfs_probe,
};
static PedFileSystemOps hfsplus_ops = {
probe: hfsplus_probe,
};
static PedFileSystemOps hfsx_ops = {
probe: hfsx_probe,
};
static PedFileSystemType hfs_type = {
next: NULL,
ops: &hfs_ops,
name: "hfs",
block_sizes: HFS_BLOCK_SIZES
};
static PedFileSystemType hfsplus_type = {
next: NULL,
ops: &hfsplus_ops,
name: "hfs+",
block_sizes: HFSP_BLOCK_SIZES
};
static PedFileSystemType hfsx_type = {
next: NULL,
ops: &hfsx_ops,
name: "hfsx",
block_sizes: HFSX_BLOCK_SIZES
};
void
ped_file_system_hfs_init ()
{
ped_file_system_type_register (&hfs_type);
ped_file_system_type_register (&hfsplus_type);
ped_file_system_type_register (&hfsx_type);
}
void
ped_file_system_hfs_done ()
{
ped_file_system_type_unregister (&hfs_type);
ped_file_system_type_unregister (&hfsplus_type);
ped_file_system_type_unregister (&hfsx_type);
}
| WhiteBearSolutions/WBSAirback | packages/wbsairback-parted/wbsairback-parted-3.0/libparted/fs/hfs/hfs.c | C | apache-2.0 | 2,377 |
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>All Classes (apiguardian-api 1.1.3-SNAPSHOT API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="jquery/jquery-3.5.1.js"></script>
<script type="text/javascript" src="jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="All Classes (apiguardian-api 1.1.3-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
var data = {"i0":32,"i1":4};
var tabs = {65535:["t0","All Classes"],4:["t3","Enum Summary"],32:["t6","Annotation Types Summary"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
var pathtoroot = "./";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="org/apiguardian/api/package-summary.html">Package</a></li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">@API Guardian</div>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<main role="main">
<div class="header">
<h1 title="All&nbsp;Classes" class="title">All Classes</h1>
</div>
<div class="allClassesContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary">
<caption><span id="t0" class="activeTableTab"><span>All Classes</span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Enum Summary</a></span><span class="tabEnd"> </span></span><span id="t6" class="tableTab"><span><a href="javascript:show(32);">Annotation Types Summary</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><a href="org/apiguardian/api/API.html" title="annotation in org.apiguardian.api">API</a></td>
<th class="colLast" scope="row">
<div class="block"><code>@API</code> is used to annotate public types, methods, constructors, and
fields within a framework or application in order to publish their
<a href="org/apiguardian/api/API.html#status()"><code>API.status()</code></a> and level of stability and to indicate how they are intended
to be used by <a href="org/apiguardian/api/API.html#consumers()"><code>API.consumers()</code></a> of the API.</div>
</th>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><a href="org/apiguardian/api/API.Status.html" title="enum in org.apiguardian.api">API.Status</a></td>
<th class="colLast" scope="row">
<div class="block">Indicates the status of an API element and therefore its level of
stability as well.</div>
</th>
</tr>
</table>
</li>
</ul>
</div>
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="org/apiguardian/api/package-summary.html">Package</a></li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">@API Guardian</div>
</div>
<div class="subNav">
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
</footer>
</body>
</html>
| apiguardian-team/apiguardian | docs/snapshot/api/allclasses-index.html | HTML | apache-2.0 | 6,171 |
# Alloplectus calcaratus (Kunth) G. Don SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Gasteranthus/Gasteranthus calcaratus/ Syn. Alloplectus calcaratus/README.md | Markdown | apache-2.0 | 194 |
<div class="modal fade" id="moduleModal" data-backdrop="static" tabindex="-3" role="dialog" aria-labelledby="moduleLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Search for a module</h4>
</div>
<div class="modal-body">
<div id="moduleConfigContent" class="tab-content" style="position:relative;">
<form ng-submit="searchNewModule(moduleSearchText)">
<div class="container-fluid">
<div class="moduleConfig"> <span class="moduleConfigTitles" >Search for a module:<sup>*</sup></span>
<input type="text"
ng-model="moduleSearchText" placeholder="Enter Your Search Query Here"
class="form-control"
/>
</div>
</div>
</form>
</div>
<div id="moduleSearchResultsLoader" ng-class="{'expanded' : searchingModules, 'collapsed' : !searchingModules}">
<div class="col-md-12 text-center">
<span class="searchLoader">
<i class="fa fa-refresh fa-spin"></i>
</span>
</div>
</div>
<div id="moduleSearchResults" ng-class="{'collapsed' : searchingModules, 'expanded' : !searchingModules}">
<div class="container-fluid">
<div ng-repeat="module in moduleResults">
<div class="moduleContent">
<div class="moduleMetaData">
<div class="moduleName col-md-2 pull-left">{{module.name}}</div>
<div class="moduleCurrentReleaseVer col-md-2">
<span class="moduleCurrentVersion">
<i class="fa fa-file-o"></i>
</span> {{module.current_release.version}}
</div>
<div class="moduleSupport col-md-3">
<span class="moduleOfficialSupport">
officialy supported -
<i ng-class="{'fa fa-check':module.supported, 'fa fa-close':!module.supported}"></i>
</span>
</div>
<div class="moduleOwnerDescription col-md-offset-3 col-md-1">
<div class="moduleOwnerGravatar"><img ng-src="http://www.gravatar.com/avatar/{{module.owner.gravatar_id}}"></div>
<div class="moduleOwnerName">{{module.owner.username}}</div>
</div>
</div>
<!--<hr>-->
<div class="moduleDescription">
<!--<a class="btn btn-info" ng-click="downloadNewModule(module)" ng-disabled="module.downloading" ng-init="module.downloadButtonText = 'Download'">
{{module.downloadButtonText}}
</a>-->
<div class="moduleSummary col-md-10">
<span ng-bind="module.current_release.metadata.summary"></span>
</div>
<div class="moduleDownload col-md-1">
<a class="btn btn-success" ng-click="downloadNewModule(module)" ng-disabled="module.downloading" ng-init="module.downloadButtonText = 'Download'"><i class="fa fa-download"></i> {{module.downloadButtonText}}</a>
</div>
</div>
<div class="moduleSearchDataFooter">
<div class="moduleDownloads col-md-4">
<span class="totalModuleDownloads">
<i class="fa fa-download"></i>
</span> {{module.downloads}} downloads so far
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" ng-click="searchNewModule(moduleSearchText)">Search</button>
</div>
</div>
</div>
</div> | BoxUpp/boxupp | page/templates/modals/moduleModal.html | HTML | apache-2.0 | 3,785 |
package org.synyx.urlaubsverwaltung.core.sync.providers.exchange;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.service.item.Appointment;
/**
* Provides exchange specific objects.
*
* @author Christian Lange - <lange@synyx.de>
*/
class ExchangeFactory {
Appointment getNewAppointment(ExchangeService exchangeService) throws ExchangeServiceException {
try {
return new Appointment(exchangeService);
} catch (Exception e) {
throw new ExchangeServiceException(e.getMessage());
}
}
}
| Intera/urlaubsverwaltung | src/main/java/org/synyx/urlaubsverwaltung/core/sync/providers/exchange/ExchangeFactory.java | Java | apache-2.0 | 613 |
package Paws::ELBv2::DeleteRule;
use Moose;
has RuleArn => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'DeleteRule');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ELBv2::DeleteRuleOutput');
class_has _result_key => (isa => 'Str', is => 'ro', default => 'DeleteRuleResult');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ELBv2::DeleteRule - Arguments for method DeleteRule on Paws::ELBv2
=head1 DESCRIPTION
This class represents the parameters used for calling the method DeleteRule on the
Elastic Load Balancing service. Use the attributes of this class
as arguments to method DeleteRule.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DeleteRule.
As an example:
$service_obj->DeleteRule(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> RuleArn => Str
The Amazon Resource Name (ARN) of the rule.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method DeleteRule in L<Paws::ELBv2>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/ELBv2/DeleteRule.pm | Perl | apache-2.0 | 1,583 |
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.WindowsAzure.Mobile.Service;
using tdxplatService.DataObjects;
using tdxplatService.Models;
namespace tdxplatService.Controllers
{
public class TodoItemController : TableController<TodoItem>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
tdxplatContext context = new tdxplatContext();
DomainManager = new EntityDomainManager<TodoItem>(context, Request, Services);
}
// GET tables/TodoItem
public IQueryable<TodoItem> GetAllTodoItems()
{
return Query();
}
// GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<TodoItem> GetTodoItem(string id)
{
return Lookup(id);
}
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<TodoItem> PatchTodoItem(string id, Delta<TodoItem> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/TodoItem
public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
{
TodoItem current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteTodoItem(string id)
{
return DeleteAsync(id);
}
}
} | fabianwilliams/formstodo | tdxplatService/Controllers/TodoItemController.cs | C# | apache-2.0 | 1,628 |
package uk.dangrew.nuts.graphics.tutorial.architecture.tutor;
import org.controlsfx.control.PopOver;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import uk.dangrew.nuts.graphics.tutorial.architecture.tutorial.FriendlyMessageGenerator;
public class TutorPopOver extends PopOver {
private final FriendlyMessageGenerator buttonTextGenerator;
private final BorderPane content;
private final Button confirmationButton;
public TutorPopOver() {
this.buttonTextGenerator = new FriendlyMessageGenerator();
this.setContentNode( content = new BorderPane() );
this.setAutoHide( false );
this.confirmationButton = new Button();
BorderPane.setAlignment( confirmationButton, Pos.CENTER_RIGHT );
this.content.setPadding( new Insets( 5 ) );
}//End Constructor
public void show( TutorMessageBuilder builder ) {
this.setArrowLocation( builder.getArrowDirection() );
this.content.setCenter( builder.getMessage() );
if ( builder.shouldHaveConfirmation() ) {
this.content.setBottom( confirmationButton );
this.confirmationButton.setText( buttonTextGenerator.friendlyConfirmation() );
this.confirmationButton.setOnAction( e -> builder.callback().ifPresent( Runnable::run ) );
} else {
this.content.setBottom( null );
}
this.friendly_show( builder.getComponent() );
}//End Method
public void friendly_hide(){
hide();
}//End Method
public void friendly_show( Node owner ){
show( owner );
}//End Method
BorderPane content(){
return content;
}//End Method
Button confirmationButton(){
return confirmationButton;
}//End Method
}//End Class
| DanGrew/Nuts | nuts/src/uk/dangrew/nuts/graphics/tutorial/architecture/tutor/TutorPopOver.java | Java | apache-2.0 | 1,850 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.lib.parser.delimited;
import com.streamsets.pipeline.api.ErrorCode;
import com.streamsets.pipeline.api.GenerateResourceBundle;
@GenerateResourceBundle
public enum Errors implements ErrorCode {
DELIMITED_PARSER_00("Cannot advance reader '{}' to offset '{}'"),
;
private final String msg;
Errors(String msg) {
this.msg = msg;
}
@Override
public String getCode() {
return name();
}
@Override
public String getMessage() {
return msg;
}
}
| kiritbasu/datacollector | commonlib/src/main/java/com/streamsets/pipeline/lib/parser/delimited/Errors.java | Java | apache-2.0 | 1,313 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Xenon Boostrap Admin Panel" />
<meta name="author" content="" />
<title>Player Ranking!</title>
<link href='http://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic,900|Lato:400,300,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/fonts/linecons/css/linecons.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/fonts/fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/bootstrap.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/bootstrap-social.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/xenon-core.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/xenon-forms.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/xenon-components.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/xenon-skins.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/custom.css?v=1">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/css/rehan_custom.css?v=1">
<script src="<?php echo ROOT_URL ?>assets/js/jquery-2.0.3.min.js"></script>
<!-- <script src="<?php echo ROOT_URL ?>assets/js/jquery-1.11.1.min.js"></script>-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="page-body right-sidebar boxed-container">
<div id="ajax_loader" >
<img src="<?php echo ROOT_URL ?>assets/images/icons/gif-load.GIF" alt="ajax loader"/>
</div>
<div id="ajaxOverlay">
</div>
<div class="settings-pane">
<a href="#" data-toggle="settings-pane" data-animate="true">
×
</a>
<div class="settings-pane-inner">
<div class="row">
<div class="col-md-4">
<div class="user-info">
<div class="user-image">
<a href="#">
<img id="user_pic_topmenu" src="<?php echo ROOT_URL ?>assets/images/user-2.png" class="img-responsive img-circle" />
</a>
</div>
<div class="user-details">
<h3>
<a href="#" id="user_name_topmenu"></a>
<!-- Available statuses: is-online, is-idle, is-busy and is-offline -->
<span class="user-status is-online"></span>
</h3>
<p class="user-title" id="user_point_topmenu"></p>
<p class="user-title" id="user_ranking_topmenu"></p>
<div class="user-links">
<a id='profile_page_url' href="" class="btn btn-primary"><i class="linecons-cog"></i> Profile</a>
<br/>
<a href="#" class="btn btn-primary" onclick="DataActionController.dataaction('logout')"><i class="linecons-lock"></i> Logout</a>
</div>
</div>
</div>
</div>
<div class="col-md-8 link-blocks-env">
</div>
</div>
</div>
</div>
<nav class="navbar navbar-fixed-top horizontal-menu"><!-- set fixed position by adding class "navbar-fixed-top" -->
<div class="navbar-inner">
<!-- Navbar Brand -->
<div class="navbar-brand">
<a href="<?php echo ROOT_URL; ?>" >
<span class="logo1">Guess Food</span>
</a>
</div>
<!-- Mobile Toggles Links -->
<div class="nav navbar-mobile">
<!-- This will toggle the mobile menu and will be visible only on mobile devices -->
<div class="mobile-menu-toggle">
<!-- This will open the popup with user profile settings, you can use for any purpose, just be creative -->
<a href="#" data-toggle="settings-pane" data-animate="true">
<i class="linecons-cog"></i>
</a>
<a href="#" data-toggle="user-info-menu-horizontal">
<i class="fa-bell-o"></i>
</a>
<!-- data-toggle="mobile-menu-horizontal" will show horizontal menu links only -->
<!-- data-toggle="mobile-menu" will show sidebar menu links only -->
<!-- data-toggle="mobile-menu-both" will show sidebar and horizontal menu links -->
<a href="#" data-toggle="mobile-menu-horizontal">
<i class="fa-bars"></i>
</a>
</div>
</div>
<div class="navbar-mobile-clear"></div>
<!-- main menu -->
<ul class="navbar-nav">
<li class="navbarPlay">
<a href="<?php echo ROOT_URL; ?>">
<i class="fa-gamepad"></i>
<span class="title">Play!</span>
</a>
</li>
<li>
<a href="<?php echo ROOT_URL.'ranking/globalranking'; ?>">
<i class="linecons-globe"></i>
<span class="title">Global Ranking</span>
</a>
<ul>
<li>
<a>
<span class="title"><h4><i class="fa-flag"></i> Country Rankings</h4></span></a>
</li>
<li>
<a id="user_selected_country_link" href="<?php echo ROOT_URL.'ranking/countryranking?c=Spain'; ?>">
<img width="18" id="user_selected_country_img" src="assets/images/flags/Spain.png"/>
<span class="title" id="user_selected_country">in Spain</span>
</a>
</li>
<li>
<a href="layout-variants.html">
<span class="title"><strong>All the countries:</strong></span>
</a>
</li>
<div id="dropdown_menu_country_list" class="scrollable scroll" data-max-height="250" style="max-height: 250px;">
</div>
</ul>
</li>
<li ><!-- class="opened active" -->
<a href="#">
<i class="linecons-food"></i><span class="title">Cuisine Rankings</span>
</a>
<ul id="cuisine_list_topmenu">
</ul>
</li>
<li>
<a href=#">
<i class="linecons-search"></i><span class="title">Recipe Database</span>
</a>
</li>
</ul>
<!-- notifications and other links -->
<ul class="nav nav-userinfo navbar-right">
<li class="dropdown user-profile">
<a href="#" data-toggle="settings-pane" style="display: none" id="user_profile">
<img id="user_profile_picture" src="<?php echo ROOT_URL ?>assets/images/user-1.png" alt="user-image" class="img-circle img-inline userpic-32" width="28" />
<span>
<span id="user_name">---</span>
<i class="fa-angle-up"></i>
</span>
</a>
<span id="fb_login_button" style="display: none">
<a class="btn btn-block btn-social btn-lg btn-facebook" onclick="DataActionController.dataaction('login-facebook')">
<i class="fa fa-facebook"></i> Sign in with Facebook
</a>
</span>
<?php if ($loggedIn) { ?>
<script>
var user_profile = document.getElementById('user_profile');
user_profile.style.display = 'block';
var user_name = document.getElementById('user_name');
user_name.innerHTML = '<?php echo $name ?>';
var user_profile_picture = document.getElementById('user_profile_picture');
user_profile_picture.src = '<?php echo $picture ?>';
</script>
<?php } else { ?>
<script>
var fb_login_button = document.getElementById('fb_login_button');
fb_login_button.style.display = 'block';
</script>
<?php } ?>
</li>
</ul>
</div>
</nav>
<div class="page-container"><!-- add class "sidebar-collapsed" to close sidebar by default, "chat-visible" to make chat appear always -->
<!-- Add "fixed" class to make the sidebar fixed always to the browser viewport. -->
<!-- Adding class "toggle-others" will keep only one menu item open at a time. -->
<!-- Adding class "collapsed" collapse sidebar root elements and show only icons. -->
<div class="sidebar-menu toggle-others">
<div id="right_col_Adz">
</div>
<div class="sidebar-menu-inner" id="right_col_without_Adz">
<div class="SidebarJumbo">
<h1>The community to learn about World Food</h1>
<h4>Become a world foodie by playing</h4>
<?php if (!$loggedIn) { ?>
<button id="play_login_btn" type="button" class="btn btn-blue btn-icon-standalone btn-block btn-lg" onclick="DataActionController.dataaction('login-facebook')">
<i class="fa-facebook"></i>
<span >Sign in & play</span>
</button>
<?php } ?>
</div>
<div class="SidebarJumboTeach">
<h3>What are the main dishes of your country?</h3>
<h5>Share your knowledge and contribute</h5>
<button type="button" class="btn btn-secondary btn-icon-standalone ">
<i class="linecons-megaphone"></i>
<span>Teach us!</span>
</button>
</div>
</div>
</div>
<div class="main-content">
<div class="row" id="main_ranking_parent">
<div style="text-align:center">
<h1 style="margin-left:10px; display:inline-block; vertical-align: text-bottom;">
<?php if(isset($ranking_country_name)){?>
<span style="display:inline-block; vertical-align: text-bottom;">
<img width="70" src="<?php echo ROOT_URL.'assets/images/flags/'.$ranking_country_name.'.png'; ?>" alt="country flag"/>
</span>
<?php } else if(isset ($cuisine_name)){ ?>
<span style="display:inline-block; vertical-align: text-bottom;">
<?php echo $cuisine_name; ?>
</span>
<?php } ?>
<?php echo $ranking_type ?></h1><h3 style="margin-left:10px; display:inline-block; vertical-align: text-bottom;"> - <?php echo $current_date; ?></h3></span>
<?php if(isset($ranking_country_name)){?>
<p>People from <?php echo $ranking_country_name; ?> Ranking</p>
<?php } else if(isset ($cuisine_name)){ ?>
<p>Ranking of the users of in <?php echo $cuisine_name; ?> </p>
<?php }else{ ?>
<p>Ranking of the users of our community . </p>
<?php } ?>
</div>
<?php if($loggedIn){ ?>
<div class="YouRanking ReviewRight btn btn-lg">Your Ranking</div>
<?php } ?>
<table class="table table-condensed table-hover">
<thead>
<tr >
<th width="1%"><i class="fa fa-line-chart"></i></th>
<th><i class="fa fa-flag-o"></i></th>
<th>User</th>
<th>Points</th>
<th>% Right</th>
<th>Questions</th>
<th>Right</th>
<th>Wrong</th>
</tr>
</thead>
<tbody id="ranking_rows">
</tbody>
</table>
<div id="pagination_block">
</div>
</div>
</div>
</div>
<!-- Main Footer -->
<!-- Choose between footer styles: "footer-type-1" or "footer-type-2" -->
<!-- Add class "sticky" to always stick the footer to the end of page (if page contents is small) -->
<!-- Or class "fixed" to always fix the footer to the end of page -->
<footer class="main-footer sticky footer-type-1">
<div class="footer-inner">
<!-- Add your copyright text here -->
<div class="footer-text">
© 2014
<strong>Xenon</strong>
theme by <a href="http://laborator.co" target="_blank">Laborator</a>
</div>
<!-- Go to Top Link, just add rel="go-top" to any link to add this functionality -->
<div class="go-up">
<a href="#" rel="go-top">
<i class="fa-angle-up"></i>
</a>
</div>
</div>
</footer>
</div>
<!-- start: Modal Section -->
<div class="modal fade" id="rules">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Rules and Points</h4>
</div>
<div class="modal-body">
The Rules of the Game
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info">Ok</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="chooseCountry">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Choose your Country</h4>
</div>
<div class="modal-body">
<select id="country_list" name="country" size="1">
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" onclick="DataActionController.dataaction('usercountry')">Save</button>
</div>
</div>
</div>
</div>
<!-- end: Chat Section -->
</div>
<!-- Imported styles on this page -->
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/js/daterangepicker/daterangepicker-bs3.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/js/select2/select2.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/js/select2/select2-bootstrap.css">
<link rel="stylesheet" href="<?php echo ROOT_URL ?>assets/js/multiselect/css/multi-select.css">
<!-- Bottom Scripts -->
<script src="<?php echo ROOT_URL ?>assets/js/bootstrap.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/TweenMax.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/resizeable.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/joinable.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/xenon-api.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/xenon-toggles.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/moment.min.js"></script>
<!-- My Own Scripts -->
<script src="<?php echo ROOT_URL ?>assets/js/guessfood/facebook_settings.js?v=1"></script>
<script src="<?php echo ROOT_URL ?>assets/js/guessfood/UserController.js?v=1"></script>
<script src="<?php echo ROOT_URL ?>assets/js/guessfood/MiscController.js?v=1"></script>
<script src="<?php echo ROOT_URL ?>assets/js/guessfood/QuestionAnswerController.js?v=1"></script>
<script src="<?php echo ROOT_URL ?>assets/js/guessfood/DataActionController.js?v=1"></script>
<!-- Imported scripts on this page -->
<script src="<?php echo ROOT_URL ?>assets/js/daterangepicker/daterangepicker.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/datepicker/bootstrap-datepicker.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/timepicker/bootstrap-timepicker.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/colorpicker/bootstrap-colorpicker.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/select2/select2.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/jquery-ui/jquery-ui.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/selectboxit/jquery.selectBoxIt.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/tagsinput/bootstrap-tagsinput.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/typeahead.bundle.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/handlebars.min.js"></script>
<script src="<?php echo ROOT_URL ?>assets/js/multiselect/js/jquery.multi-select.js"></script>
<!-- JavaScripts initializations and stuff -->
<script src="<?php echo ROOT_URL ?>assets/js/xenon-custom.js"></script>
<script>
DataActionController.setBaseUrl('<?php echo ROOT_URL; ?>');
</script>
<?php if ($loggedIn) { ?>
<script>
var name = '<?php echo $name; ?>';
var picture = '<?php echo $picture; ?>';
UserController.updateTopMenuUserProfile({name: name, picture: picture});
UserController.user_loggedIn = true;
</script>
<?php } ?>
<?php if (isset($total_points)) { ?>
<script>
UserController.updateTopUserPoints('<?php echo $total_points; ?>', '<?php echo $global_rank; ?>');
</script>
<?php } ?>
<?php if (!$country_choosen && $loggedIn) { ?>
<script>
MiscController.fillChooseCountryList();
MiscController.showChooseCountryPopup();
</script>
<?php } else if ($loggedIn) { ?>
<script>
UserController.user_country = '<?php echo $country_choosen; ?>';
UserController.updateDOMUserSelectedCountry(true);
</script>
<?php } ?>
<script>
MiscController.populateDrownDownMenu(true);
MiscController.populateCuisines();
QuestionAnswerController.displayAdz(true);
FacebookController.initialize();
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
var c_u=null;
<?php if(isset($u_id)){ ?>
c_u='<?php echo $u_id; ?>';
MiscController.c_u=c_u;
<?php }?>
UserController.dispplayRanking(<?php echo $ranking_data; ?>,c_u);
<?php if(isset($ranking_country_name)){?>
MiscController.rankingType='<?php echo $ranking_country_name ?>';
<?php }else if(isset($cuisine_name)) { ?>
MiscController.rankingType='<?php echo 'cuisine_'.$cuisine_name ?>';
MiscController.current_cusine_id='<?php echo $cuisine_id; ?>';
<?php } else{ ?>
MiscController.rankingType='global';
<?php } ?>
<?php if(isset($total_pages)){ ?>
MiscController.rankngTotalPages='<?php echo $total_pages; ?>';
<?php } ?>
MiscController.createPagination();
</script>
<?php
$this->load->helper('footerscript_helper');
?>
</body>
</html> | ferranmv/FoodProject | application/views/ranking.php | PHP | apache-2.0 | 22,535 |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from .tables import (
BatchCreateRowsRequest,
BatchCreateRowsResponse,
BatchDeleteRowsRequest,
BatchUpdateRowsRequest,
BatchUpdateRowsResponse,
ColumnDescription,
CreateRowRequest,
DeleteRowRequest,
GetRowRequest,
GetTableRequest,
GetWorkspaceRequest,
LabeledItem,
ListRowsRequest,
ListRowsResponse,
ListTablesRequest,
ListTablesResponse,
ListWorkspacesRequest,
ListWorkspacesResponse,
LookupDetails,
RelationshipDetails,
Row,
Table,
UpdateRowRequest,
Workspace,
View,
)
__all__ = (
"BatchCreateRowsRequest",
"BatchCreateRowsResponse",
"BatchDeleteRowsRequest",
"BatchUpdateRowsRequest",
"BatchUpdateRowsResponse",
"ColumnDescription",
"CreateRowRequest",
"DeleteRowRequest",
"GetRowRequest",
"GetTableRequest",
"GetWorkspaceRequest",
"LabeledItem",
"ListRowsRequest",
"ListRowsResponse",
"ListTablesRequest",
"ListTablesResponse",
"ListWorkspacesRequest",
"ListWorkspacesResponse",
"LookupDetails",
"RelationshipDetails",
"Row",
"Table",
"UpdateRowRequest",
"Workspace",
"View",
)
| googleapis/python-area120-tables | google/area120/tables_v1alpha1/types/__init__.py | Python | apache-2.0 | 1,783 |
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
NS_ASSUME_NONNULL_BEGIN
@interface UploadEvent : NSManagedObject
-(void)save;
-(void)destroy;
+(UploadEvent*)eventWithId:(NSString*)eventId;
+(NSArray*)allEvents;
+(void)setupStorage;
+(UploadEvent*)create:(NSDictionary*)info;
-(NSDictionary*)dataRepresentation;
@end
NS_ASSUME_NONNULL_END
| spoonconsulting/cordova-plugin-background-upload | src/ios/UploadEvent.h | C | apache-2.0 | 357 |
/*
* Copyright 2013 must-be.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 com.intellij.compiler.server;
import com.intellij.openapi.project.Project;
import java.io.File;
import java.util.Collection;
/**
* @author VISTALL
* @since 23:49/25.05.13
*/
public class BuildManager {
public static final BuildManager ourInstance = new BuildManager();
public static BuildManager getInstance() {
return ourInstance;
}
public void notifyFilesDeleted(Collection<File> paths) {
}
public void notifyFilesChanged(Collection<File> paths) {
}
public File getProjectSystemDirectory(Project project) {
return null;
}
public void clearState(Project project) {
}
public void runCommand(Runnable runnable) {
runnable.run();
}
}
| ernestp/consulo | platform/compiler-impl/src/com/intellij/compiler/server/BuildManager.java | Java | apache-2.0 | 1,283 |
# Synechoblastus leucocarpus var. minor (F. Wilson) F. Wilson VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Proc. Roy. Soc. Victoria 5: 155 (1893)
#### Original name
Collema leucocarpum var. minus F. Wilson
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Collemataceae/Collema/Collema laeve/ Syn. Synechoblastus leucocarpus minor/README.md | Markdown | apache-2.0 | 286 |
package org.drools.reteoo;
import java.util.Arrays;
import java.util.Comparator;
import org.drools.util.Iterator;
import org.drools.util.LinkedList;
import org.drools.util.ObjectHashMap;
import org.drools.util.ObjectHashMap.ObjectEntry;
import org.drools.reteoo.CompositeObjectSinkAdapter.HashKey;
public class AlphaNetworkCompiler {
private StringBuilder builder;
public void compile(ObjectTypeNode objectTypeNode) {
builder = new StringBuilder();
builder.append( "public class Compiled" + objectTypeNode.getObjectType() + "AlphaNetwork implements ObjectSink { \n" );
createVars( objectTypeNode.getSinkPropagator().getSinks(), 4 );
builder.append( " public void assertObject(....) { \n");
compileAlphaNodes( objectTypeNode.getSinkPropagator(),
8 );
builder.append( " } \n" );
builder.append( "} \n" );
System.out.println( builder.toString() );
}
public void createVars(ObjectSink[] sinks,
int indent) {
for ( ObjectSink sink : sinks ) {
if ( sink instanceof AlphaNode ) {
AlphaNode alphaNode = (AlphaNode) sink;
builder.append( getIndent( indent ) + "AlphaNodeFieldConstraint alphaNodeConstraint" + alphaNode.getId() + ";\n" );
createVars( alphaNode.getSinkPropagator().getSinks(), indent );
} else if ( sink instanceof BetaNode ) {
BetaNode betaNode = (BetaNode) sink;
builder.append( getIndent( indent ) + "ObjectSink sink" + betaNode.getId() + ";\n" );
} else if ( sink instanceof LeftInputAdapterNode ) {
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) sink;
builder.append( getIndent( indent ) + "ObjectSink sink" + liaNode.getId() + ";\n" );
}
}
}
public void compileAlphaNodes(ObjectSinkPropagator adapter,
int indent) {
if ( adapter instanceof SingleObjectSinkAdapter ) {
compileAlphaNodeSingleConstraint( (SingleObjectSinkAdapter) adapter,
indent );
} else if ( adapter instanceof CompositeObjectSinkAdapter ) {
compileAlphaNodeCompositeConstraint( (CompositeObjectSinkAdapter) adapter,
indent );
}
}
private void compileAlphaNodeCompositeConstraint(CompositeObjectSinkAdapter adapter,
int indent) {
ObjectSinkNodeList sinks = adapter.getHashableSinks();
if ( sinks != null ) {
for ( ObjectSinkNode sink = sinks.getFirst(); sink != null; sink = sink.getNextObjectSinkNode() ) {
compileAlphaNodeSingleConstraint( sink,
indent );
}
}
sinks = adapter.getOthers();
if ( sinks != null ) {
for ( ObjectSinkNode sink = sinks.getFirst(); sink != null; sink = sink.getNextObjectSinkNode() ) {
compileAlphaNodeSingleConstraint( sink,
indent );
}
}
ObjectHashMap map = adapter.getHashedSinkMap();
if ( map != null ) {
ObjectEntry[] entries = new ObjectEntry[map.size()];
Iterator it = map.iterator();
int i = 0;
for ( ObjectEntry entry = (ObjectEntry) it.next(); entry != null; entry = (ObjectEntry) it.next() ) {
entries[i++] = entry;
}
// we sort as switch works faster with ordered cases
Arrays.sort( entries,
new Comparator() {
public int compare(Object o1,
Object o2) {
ObjectEntry entry1 = (ObjectEntry) o1;
ObjectEntry entry2 = (ObjectEntry) o2;
return ((ObjectSink) entry1.getValue()).getId() - ((ObjectSink) entry2.getValue()).getId();
}
} );
//final Iterator it = map.newIterator();
builder.append( getIndent( indent ) + "HashKey key = new HashKey(handle);\n" );
builder.append( getIndent( indent ) + "swtich ((ObjectSink)this.hashedSinkedMap(key)).getId() {\n" );
for ( ObjectEntry entry : entries ) {
ObjectSink sink = (ObjectSink) entry.getValue();
builder.append( getIndent( indent + 4 ) + "case " + sink.getId() + ": {\n" );
//builder.append( getIndent( indent + 8 ) + "sink" + sink.getId() + ".assertRight(handle, wm, context);\n" );
if (sink instanceof AlphaNode ) {
compileAlphaNodes( ((AlphaNode)sink).getSinkPropagator(),
indent + 8 );
}
builder.append( getIndent( indent + 4 )+ "};\n" );
}
builder.append( getIndent( indent ) + "};\n" );
}
}
public void compileAlphaNodeSingleConstraint(SingleObjectSinkAdapter adapter,
int indent) {
compileAlphaNodeSingleConstraint( adapter.getSinks()[0],
indent );
}
public void compileAlphaNodeSingleConstraint(ObjectSink sink,
int indent) {
if ( sink instanceof AlphaNode ) {
AlphaNode alphaNode = (AlphaNode) sink;
builder.append( getIndent( indent ) + "if ( alphaNodeConstraint" + alphaNode.getId() + ".isAllowed(handle, wm) ) {\n" );
compileAlphaNodes( alphaNode.getSinkPropagator(),
indent + 4 );
builder.append( getIndent( indent ) + "}\n" );
} else if ( sink instanceof BetaNode ) {
BetaNode betaNode = (BetaNode) sink;
builder.append( getIndent( indent ) + "sink" + betaNode.getId() + ".assertRight(handle, wm, context);\n" );
} else if ( sink instanceof LeftInputAdapterNode ) {
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) sink;
builder.append( getIndent( indent ) + "sink" + liaNode.getId() + ".assertRight(handle, wm, context);\n" );
}
}
public void compileAlphaNodeCompositeConstraint(ObjectSink sink,
int indent) {
if ( sink instanceof AlphaNode ) {
AlphaNode alphaNode = (AlphaNode) sink;
builder.append( getIndent( indent ) + "if ( alphaNodeConstraint" + alphaNode.getId() + ".isAllowed(handle, wm) ) {\n" );
compileAlphaNodes( alphaNode.getSinkPropagator(),
indent + 4 );
builder.append( getIndent( indent ) + "}\n" );
} else if ( sink instanceof BetaNode ) {
BetaNode betaNode = (BetaNode) sink;
builder.append( getIndent( indent ) + "sink" + betaNode.getId() + ".assertRight(handle, wm, context);\n" );
} else if ( sink instanceof LeftInputAdapterNode ) {
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) sink;
builder.append( getIndent( indent ) + "sink" + liaNode.getId() + ".assertRight(handle, wm, context);\n" );
}
}
private String getIndent(int indent) {
char[] spaces = new char[indent];
for ( int i = 0; i < spaces.length; i++ ) {
spaces[i] = ' ';
}
return new String( spaces );
}
}
| bobmcwhirter/drools | drools-core/src/main/java/org/drools/reteoo/AlphaNetworkCompiler.java | Java | apache-2.0 | 7,954 |
# android-tutorial-project
A simple android tutorial project with test projects for teaching purposes.
The project includes a small android application (quadratic equation solver) that is tested
with the help of various test frameworks and specifically (a) Android test framework,
(b) Espresso, (c) UIAutomator and (d) Robolectric.
Execute the android integration tests in a connected device or emulator with the command:
```
gradlew connectedCheck
```
Robolectric tests are executed as ordinary JUnit tests in a standard JVM with the command:
```
gradlew test
```
| bzafiris/android-tutorial-project | README.md | Markdown | apache-2.0 | 567 |
package main
import (
"github.com/astaxie/beego"
//"order/controllers/errorpage"
"test/models"
_ "test/routers"
"os"
)
func init() {
models.Connect()
initArgs()
}
func main() {
//beego.ErrorController(&errorpage.ErrorController{})
beego.Run()
}
func initArgs() {
args := os.Args
for _, v := range args {
if v == "-syncdb" {
models.Syncbd(false)
os.Exit(0)
}
if v == "-syncdb-force" {
models.Syncbd(true)
os.Exit(0)
}
}
}
| Eternally-1139/beego-login-register | main.go | GO | apache-2.0 | 457 |
/*
* Copyright 2003 The Apache Software Foundation
*
* 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 net.sf.cglib.proxy;
import java.lang.reflect.Method;
/**
* {@link java.lang.reflect.InvocationHandler} replacement (unavailable under JDK 1.2).
* This callback type is primarily for use by the {@link Proxy} class but
* may be used with {@link Enhancer} as well.
* @author Neeme Praks <a href="mailto:neeme@apache.org">neeme@apache.org</a>
* @version $Id: InvocationHandler.java,v 1.3 2004-06-24 21:15:20 herbyderby Exp $
*/
public interface InvocationHandler
extends Callback
{
/**
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object)
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
| bric3/nCGLIB | src/main/java/net/sf/cglib/proxy/InvocationHandler.java | Java | apache-2.0 | 1,334 |
# Tetraedroides Kützing, 1845 GENUS
#### Status
ACCEPTED
#### According to
IRMNG Homonym List
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Chlorophyta/Chlorophyceae/Chlorococcales/Oocystaceae/Tetraedroides/README.md | Markdown | apache-2.0 | 163 |
namespace DesktopWidgets.Widgets.PictureSlideshow
{
public static class Metadata
{
public const string FriendlyName = "Slideshow";
}
} | danielchalmers/DesktopWidgets | DesktopWidgets/Widgets/PictureSlideshow/Metadata.cs | C# | apache-2.0 | 157 |
# Clerodendrum eucalycinum Oliv. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Clerodendrum/Clerodendrum eucalycinum/README.md | Markdown | apache-2.0 | 180 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_27) on Thu Nov 28 14:35:56 IRST 2013 -->
<title>org.nise.ux.asl.face Class Hierarchy (Abstract Service Library)</title>
<meta name="date" content="2013-11-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.nise.ux.asl.face Class Hierarchy (Abstract Service Library)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/nise/ux/asl/data/package-tree.html">PREV</a></li>
<li><a href="../../../../../org/nise/ux/asl/lib/package-tree.html">NEXT</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/nise/ux/asl/face/package-tree.html" target="_top">FRAMES</a></li>
<li><a href="package-tree.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.nise.ux.asl.face</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/ClientInfoProfiler.html" title="interface in org.nise.ux.asl.face"><span class="strong">ClientInfoProfiler</span></a><D></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/ClientInfoProfilerFactory.html" title="interface in org.nise.ux.asl.face"><span class="strong">ClientInfoProfilerFactory</span></a><D></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/InputAnalyzer.html" title="interface in org.nise.ux.asl.face"><span class="strong">InputAnalyzer</span></a><D></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/OutputAnalyzer.html" title="interface in org.nise.ux.asl.face"><span class="strong">OutputAnalyzer</span></a><D,R></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/ServiceResponser.html" title="interface in org.nise.ux.asl.face"><span class="strong">ServiceResponser</span></a><D,R></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/ServiceResponserFactory.html" title="interface in org.nise.ux.asl.face"><span class="strong">ServiceResponserFactory</span></a><D,R></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/SimpleServiceResponser.html" title="interface in org.nise.ux.asl.face"><span class="strong">SimpleServiceResponser</span></a><D,R></li>
<li type="circle">org.nise.ux.asl.face.<a href="../../../../../org/nise/ux/asl/face/SimpleServiceResponserFactory.html" title="interface in org.nise.ux.asl.face"><span class="strong">SimpleServiceResponserFactory</span></a><D,R></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/nise/ux/asl/data/package-tree.html">PREV</a></li>
<li><a href="../../../../../org/nise/ux/asl/lib/package-tree.html">NEXT</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/nise/ux/asl/face/package-tree.html" target="_top">FRAMES</a></li>
<li><a href="package-tree.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>This library is a work of NISE organization User-eXperience team.</i>
</small></p>
</body>
</html>
| yeuser/java-libs | abstract-service-library/dist/abstract-service-library-1.0.0.gamma/api/org/nise/ux/asl/face/package-tree.html | HTML | apache-2.0 | 6,083 |
package com.mikesamuel.cil.parser;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.mikesamuel.cil.ast.NodeType;
/**
* The result of a parse operation.
*/
public class ParseResult {
/** A summary of the result. */
public final Synopsis synopsis;
/**
* If there is a {@link #next} state, then this is an index such that
* all events produced by parsing input up to the index on the start state
* also appear as a prefix of the events on the next state.
* <p>
* If there is no next state or the start state events are a prefix of the
* next state events, then {@link #NO_WRITE_BACK_RESTRICTION} is appropriate.
*/
public final int writeBack;
/** LR exclusions whose failure contributed to this result. */
public final ImmutableSet<NodeType<?, ?>> lrExclusionsTriggered;
private ParseResult(
Synopsis synopsis, int writeBack,
ImmutableSet<NodeType<?, ?>> lrExclusionsTriggered) {
this.synopsis = synopsis;
this.writeBack = writeBack;
this.lrExclusionsTriggered = lrExclusionsTriggered;
}
/** A summary of the result. */
public enum Synopsis {
/**
* Failed but not due to an LR exclusion so the failure can be cached in
* the {@link RatPack}.
*/
FAILURE,
/** Indicates the parse operation passed and there is a next state. */
SUCCESS,
;
}
/**
* The state after the parse operation.
*
* @throws IllegalStateException if {@link #synopsis} is not
* {@link Synopsis#SUCCESS}.
*/
public ParseState next() {
throw new IllegalStateException(synopsis.name());
}
/**
* The most extreme failure mode.
* We use the kind of failure to decide whether to
*/
public static ParseResult mostEpicFail(ParseResult a, ParseResult b) {
Preconditions.checkNotNull(a);
Preconditions.checkNotNull(b);
ImmutableSet<NodeType<?, ?>> allLrExcl = union(
a.lrExclusionsTriggered, b.lrExclusionsTriggered);
boolean success =
a.synopsis == b.synopsis && a.synopsis == Synopsis.SUCCESS;
if (success) {
return success(
a.next(),
Math.min(a.writeBack, b.writeBack),
allLrExcl);
} else {
return failure(allLrExcl);
}
}
@Override
public String toString() {
return synopsis.name();
}
/**
* {@link Integer#MAX_VALUE} per {@link ParseResult#writeBack}.
*/
public static final int NO_WRITE_BACK_RESTRICTION = Integer.MAX_VALUE;
private static final ParseResult FAILURE_INSTANCE = new ParseResult(
Synopsis.FAILURE, NO_WRITE_BACK_RESTRICTION, ImmutableSet.of());
/** @see Synopsis#FAILURE */
public static ParseResult failure() {
return FAILURE_INSTANCE;
}
/** @see Synopsis#FAILURE */
public static ParseResult failure(Set<NodeType<?, ?>> exclusionsTriggered) {
if (exclusionsTriggered.isEmpty()) {
return FAILURE_INSTANCE;
}
return new ParseResult(
Synopsis.FAILURE, NO_WRITE_BACK_RESTRICTION,
ImmutableSet.copyOf(exclusionsTriggered));
}
/**
* @param wroteBack per {@link ParseResult#writeBack}.
* @see Synopsis#SUCCESS
*/
public static ParseResult success(
ParseState after, int wroteBack,
Iterable<NodeType<?, ?>> lrExclusionsTriggered) {
return new Pass(after, wroteBack, lrExclusionsTriggered);
}
private static final class Pass extends ParseResult {
final ParseState next;
@SuppressWarnings("synthetic-access")
Pass(
ParseState next, int wroteBack,
Iterable<NodeType<?, ?>> lrExclusionsTriggereed) {
super(
Synopsis.SUCCESS, wroteBack,
ImmutableSet.copyOf(lrExclusionsTriggereed));
this.next = Preconditions.checkNotNull(next);
}
@Override
public ParseState next() {
return next;
}
}
/** Convenience for unioning two sets of enum values. */
public static ImmutableSet<NodeType<?, ?>> union(
ImmutableSet<NodeType<?, ?>> a, ImmutableSet<NodeType<?, ?>> b) {
if (!a.isEmpty()) {
if (!b.isEmpty()) {
Set<NodeType<?, ?>> u = ImmutableSet.<NodeType<?, ?>>builder()
.addAll(a)
.addAll(b)
.build();
if (u.size() == a.size()) { return a; }
if (u.size() == b.size()) { return b; }
return ImmutableSet.copyOf(u);
}
return a;
} else if (!b.isEmpty()) {
return b;
}
return a;
}
}
| mikesamuel/code-interlingua | src/main/java/com/mikesamuel/cil/parser/ParseResult.java | Java | apache-2.0 | 4,476 |
<!DOCTYPE html>
<html>
<head>
<style>
#list {
list-style-type: none;
}
#list li {
margin: 15px;
}
#list a.btn {
padding: 2px 5px;
border: 1px solid #aaa;
cursor: pointer;
}
#list a.btn:hover {
background-color: #ccc;
}
</style>
<script src="/asset/js/jquery-1.11.3.min.js"></script>
<script src="/asset/js/jquery-ajax-ext.js"></script>
</head>
<body>
<h1>Todo Demo</h1>
<ul id="list">
</ul>
<button id="add">Add</button>
<script>
var refresh = function() {
$.getJSON("/list", function(data){
$('#list').html('');
for (var i = 0, j = data.length; i < j; ++i) {
var todo = data[i];
var $li = $('<li id="' + todo.id + '"><a class="edit btn">edit</a> <a class="delete btn">done</a> <span>' + todo.desc + '</span></li>');
$li.appendTo($('#list'));
}
})
};
$('#add').click(function() {
var desc = prompt("Input description");
if (!desc) {
alert("Todo description required");
return;
}
$.post("/list", {desc: desc}, refresh);
});
$('body').on('click', '.btn.delete', function() {
var id = $(this).parent().attr('id');
$.delete('/list/' + id, refresh);
});
$('body').on('click', '.btn.edit', function() {
var id = $(this).parent().attr('id');
var desc0 = $(this).parent().children('span').text();
var desc = prompt("Type in new description", desc0);
if (!desc) {
alert("Todo description required");
return;
}
$.put('/list/' + id, {desc: desc}, refresh);
});
refresh();
</script> | actframework/act-demo-apps | todo-morphia/src/main/resources/rythm/demo/todo/morphia/Todo/home.html | HTML | apache-2.0 | 1,608 |
/**
* 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.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.core.error;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
/**
* Build error message when an {@link java.util.Optional} should be empty.
*
* @author Jean-Christophe Gay
*/
public class OptionalShouldBeEmpty extends BasicErrorMessageFactory {
private OptionalShouldBeEmpty(Class<?> optionalClass, Object optionalValue) {
super("%nExpecting an empty " + optionalClass.getSimpleName() + " but was containing value: <%s>.", optionalValue);
}
/**
* Indicates that the provided {@link java.util.Optional} should be empty.
*
* @param optional the actual {@link Optional} to test.
* @param <T> the type of the value contained in the {@link java.util.Optional}.
* @return a error message factory.
*/
public static <T> OptionalShouldBeEmpty shouldBeEmpty(Optional<T> optional) {
return new OptionalShouldBeEmpty(optional.getClass(), optional.get());
}
/**
* Indicates that the provided {@link java.util.OptionalDouble} should be empty.
*
* @param optional the actual {@link OptionalDouble} to test.
* @return a error message factory.
*/
public static OptionalShouldBeEmpty shouldBeEmpty(OptionalDouble optional) {
return new OptionalShouldBeEmpty(optional.getClass(), optional.getAsDouble());
}
/**
* Indicates that the provided {@link java.util.OptionalInt} should be empty.
*
* @param optional the actual {@link OptionalInt} to test.
* @return a error message factory.
*/
public static OptionalShouldBeEmpty shouldBeEmpty(OptionalInt optional) {
return new OptionalShouldBeEmpty(optional.getClass(), optional.getAsInt());
}
/**
* Indicates that the provided {@link java.util.OptionalLong} should be empty.
*
* @param optional the actual {@link OptionalLong} to test.
* @return a error message factory.
*/
public static OptionalShouldBeEmpty shouldBeEmpty(OptionalLong optional) {
return new OptionalShouldBeEmpty(optional.getClass(), optional.getAsLong());
}
}
| dorzey/assertj-core | src/main/java/org/assertj/core/error/OptionalShouldBeEmpty.java | Java | apache-2.0 | 2,677 |
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of 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.
#include <limits.h>
#ifndef WIN32
#include <signal.h> // kill
#include <unistd.h> // getpid
#endif // WIN32
#include <string>
#include <map>
#include "v8.h"
#include "api.h"
#include "arguments.h"
#include "cctest.h"
#include "compilation-cache.h"
#include "cpu-profiler.h"
#include "execution.h"
#include "isolate.h"
#include "objects.h"
#include "parser.h"
#include "platform.h"
#include "snapshot.h"
#include "unicode-inl.h"
#include "utils.h"
#include "vm-state.h"
static const bool kLogThreading = false;
using ::v8::AccessorInfo;
using ::v8::Arguments;
using ::v8::Boolean;
using ::v8::BooleanObject;
using ::v8::Context;
using ::v8::Extension;
using ::v8::Function;
using ::v8::FunctionTemplate;
using ::v8::Handle;
using ::v8::HandleScope;
using ::v8::Local;
using ::v8::Message;
using ::v8::MessageCallback;
using ::v8::Object;
using ::v8::ObjectTemplate;
using ::v8::Persistent;
using ::v8::Script;
using ::v8::StackTrace;
using ::v8::String;
using ::v8::TryCatch;
using ::v8::Undefined;
using ::v8::UniqueId;
using ::v8::V8;
using ::v8::Value;
#define THREADED_PROFILED_TEST(Name) \
static void Test##Name(); \
TEST(Name##WithProfiler) { \
RunWithProfiler(&Test##Name); \
} \
THREADED_TEST(Name)
void RunWithProfiler(void (*test)()) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Local<v8::String> profile_name = v8::String::New("my_profile1");
v8::CpuProfiler* cpu_profiler = env->GetIsolate()->GetCpuProfiler();
cpu_profiler->StartCpuProfiling(profile_name);
(*test)();
cpu_profiler->DeleteAllCpuProfiles();
}
static void ExpectString(const char* code, const char* expected) {
Local<Value> result = CompileRun(code);
CHECK(result->IsString());
String::Utf8Value utf8(result);
CHECK_EQ(expected, *utf8);
}
static void ExpectInt32(const char* code, int expected) {
Local<Value> result = CompileRun(code);
CHECK(result->IsInt32());
CHECK_EQ(expected, result->Int32Value());
}
static void ExpectBoolean(const char* code, bool expected) {
Local<Value> result = CompileRun(code);
CHECK(result->IsBoolean());
CHECK_EQ(expected, result->BooleanValue());
}
static void ExpectTrue(const char* code) {
ExpectBoolean(code, true);
}
static void ExpectFalse(const char* code) {
ExpectBoolean(code, false);
}
static void ExpectObject(const char* code, Local<Value> expected) {
Local<Value> result = CompileRun(code);
CHECK(result->Equals(expected));
}
static void ExpectUndefined(const char* code) {
Local<Value> result = CompileRun(code);
CHECK(result->IsUndefined());
}
static int signature_callback_count;
static void IncrementingSignatureCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
signature_callback_count++;
v8::Handle<v8::Array> result = v8::Array::New(args.Length());
for (int i = 0; i < args.Length(); i++)
result->Set(v8::Integer::New(i), args[i]);
args.GetReturnValue().Set(result);
}
static void SignatureCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
v8::Handle<v8::Array> result = v8::Array::New(args.Length());
for (int i = 0; i < args.Length(); i++) {
result->Set(v8::Integer::New(i), args[i]);
}
args.GetReturnValue().Set(result);
}
THREADED_TEST(Handles) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<Context> local_env;
{
LocalContext env;
local_env = env.local();
}
// Local context should still be live.
CHECK(!local_env.IsEmpty());
local_env->Enter();
v8::Handle<v8::Primitive> undef = v8::Undefined();
CHECK(!undef.IsEmpty());
CHECK(undef->IsUndefined());
const char* c_source = "1 + 2 + 3";
Local<String> source = String::New(c_source);
Local<Script> script = Script::Compile(source);
CHECK_EQ(6, script->Run()->Int32Value());
local_env->Exit();
}
THREADED_TEST(IsolateOfContext) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<Context> env = Context::New(v8::Isolate::GetCurrent());
CHECK(!env->InContext());
CHECK(env->GetIsolate() == v8::Isolate::GetCurrent());
env->Enter();
CHECK(env->InContext());
CHECK(env->GetIsolate() == v8::Isolate::GetCurrent());
env->Exit();
CHECK(!env->InContext());
CHECK(env->GetIsolate() == v8::Isolate::GetCurrent());
}
THREADED_TEST(ReceiverSignature) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::FunctionTemplate> fun = v8::FunctionTemplate::New();
v8::Handle<v8::Signature> sig = v8::Signature::New(fun);
fun->PrototypeTemplate()->Set(
v8_str("m"),
v8::FunctionTemplate::New(IncrementingSignatureCallback,
v8::Handle<Value>(),
sig));
env->Global()->Set(v8_str("Fun"), fun->GetFunction());
signature_callback_count = 0;
CompileRun(
"var o = new Fun();"
"o.m();");
CHECK_EQ(1, signature_callback_count);
v8::Handle<v8::FunctionTemplate> sub_fun = v8::FunctionTemplate::New();
sub_fun->Inherit(fun);
env->Global()->Set(v8_str("SubFun"), sub_fun->GetFunction());
CompileRun(
"var o = new SubFun();"
"o.m();");
CHECK_EQ(2, signature_callback_count);
v8::TryCatch try_catch;
CompileRun(
"var o = { };"
"o.m = Fun.prototype.m;"
"o.m();");
CHECK_EQ(2, signature_callback_count);
CHECK(try_catch.HasCaught());
try_catch.Reset();
v8::Handle<v8::FunctionTemplate> unrel_fun = v8::FunctionTemplate::New();
sub_fun->Inherit(fun);
env->Global()->Set(v8_str("UnrelFun"), unrel_fun->GetFunction());
CompileRun(
"var o = new UnrelFun();"
"o.m = Fun.prototype.m;"
"o.m();");
CHECK_EQ(2, signature_callback_count);
CHECK(try_catch.HasCaught());
}
THREADED_TEST(ArgumentSignature) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::FunctionTemplate> cons = v8::FunctionTemplate::New();
cons->SetClassName(v8_str("Cons"));
v8::Handle<v8::Signature> sig =
v8::Signature::New(v8::Handle<v8::FunctionTemplate>(), 1, &cons);
v8::Handle<v8::FunctionTemplate> fun =
v8::FunctionTemplate::New(SignatureCallback, v8::Handle<Value>(), sig);
env->Global()->Set(v8_str("Cons"), cons->GetFunction());
env->Global()->Set(v8_str("Fun1"), fun->GetFunction());
v8::Handle<Value> value1 = CompileRun("Fun1(4) == '';");
CHECK(value1->IsTrue());
v8::Handle<Value> value2 = CompileRun("Fun1(new Cons()) == '[object Cons]';");
CHECK(value2->IsTrue());
v8::Handle<Value> value3 = CompileRun("Fun1() == '';");
CHECK(value3->IsTrue());
v8::Handle<v8::FunctionTemplate> cons1 = v8::FunctionTemplate::New();
cons1->SetClassName(v8_str("Cons1"));
v8::Handle<v8::FunctionTemplate> cons2 = v8::FunctionTemplate::New();
cons2->SetClassName(v8_str("Cons2"));
v8::Handle<v8::FunctionTemplate> cons3 = v8::FunctionTemplate::New();
cons3->SetClassName(v8_str("Cons3"));
v8::Handle<v8::FunctionTemplate> args[3] = { cons1, cons2, cons3 };
v8::Handle<v8::Signature> wsig =
v8::Signature::New(v8::Handle<v8::FunctionTemplate>(), 3, args);
v8::Handle<v8::FunctionTemplate> fun2 =
v8::FunctionTemplate::New(SignatureCallback, v8::Handle<Value>(), wsig);
env->Global()->Set(v8_str("Cons1"), cons1->GetFunction());
env->Global()->Set(v8_str("Cons2"), cons2->GetFunction());
env->Global()->Set(v8_str("Cons3"), cons3->GetFunction());
env->Global()->Set(v8_str("Fun2"), fun2->GetFunction());
v8::Handle<Value> value4 = CompileRun(
"Fun2(new Cons1(), new Cons2(), new Cons3()) =="
"'[object Cons1],[object Cons2],[object Cons3]'");
CHECK(value4->IsTrue());
v8::Handle<Value> value5 = CompileRun(
"Fun2(new Cons1(), new Cons2(), 5) == '[object Cons1],[object Cons2],'");
CHECK(value5->IsTrue());
v8::Handle<Value> value6 = CompileRun(
"Fun2(new Cons3(), new Cons2(), new Cons1()) == ',[object Cons2],'");
CHECK(value6->IsTrue());
v8::Handle<Value> value7 = CompileRun(
"Fun2(new Cons1(), new Cons2(), new Cons3(), 'd') == "
"'[object Cons1],[object Cons2],[object Cons3],d';");
CHECK(value7->IsTrue());
v8::Handle<Value> value8 = CompileRun(
"Fun2(new Cons1(), new Cons2()) == '[object Cons1],[object Cons2]'");
CHECK(value8->IsTrue());
}
THREADED_TEST(HulIgennem) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::Primitive> undef = v8::Undefined();
Local<String> undef_str = undef->ToString();
char* value = i::NewArray<char>(undef_str->Utf8Length() + 1);
undef_str->WriteUtf8(value);
CHECK_EQ(0, strcmp(value, "undefined"));
i::DeleteArray(value);
}
THREADED_TEST(Access) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::Object> obj = v8::Object::New();
Local<Value> foo_before = obj->Get(v8_str("foo"));
CHECK(foo_before->IsUndefined());
Local<String> bar_str = v8_str("bar");
obj->Set(v8_str("foo"), bar_str);
Local<Value> foo_after = obj->Get(v8_str("foo"));
CHECK(!foo_after->IsUndefined());
CHECK(foo_after->IsString());
CHECK_EQ(bar_str, foo_after);
}
THREADED_TEST(AccessElement) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::Object> obj = v8::Object::New();
Local<Value> before = obj->Get(1);
CHECK(before->IsUndefined());
Local<String> bar_str = v8_str("bar");
obj->Set(1, bar_str);
Local<Value> after = obj->Get(1);
CHECK(!after->IsUndefined());
CHECK(after->IsString());
CHECK_EQ(bar_str, after);
Local<v8::Array> value = CompileRun("[\"a\", \"b\"]").As<v8::Array>();
CHECK_EQ(v8_str("a"), value->Get(0));
CHECK_EQ(v8_str("b"), value->Get(1));
}
THREADED_TEST(Script) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* c_source = "1 + 2 + 3";
Local<String> source = String::New(c_source);
Local<Script> script = Script::Compile(source);
CHECK_EQ(6, script->Run()->Int32Value());
}
static uint16_t* AsciiToTwoByteString(const char* source) {
int array_length = i::StrLength(source) + 1;
uint16_t* converted = i::NewArray<uint16_t>(array_length);
for (int i = 0; i < array_length; i++) converted[i] = source[i];
return converted;
}
class TestResource: public String::ExternalStringResource {
public:
explicit TestResource(uint16_t* data, int* counter = NULL)
: data_(data), length_(0), counter_(counter) {
while (data[length_]) ++length_;
}
~TestResource() {
i::DeleteArray(data_);
if (counter_ != NULL) ++*counter_;
}
const uint16_t* data() const {
return data_;
}
size_t length() const {
return length_;
}
private:
uint16_t* data_;
size_t length_;
int* counter_;
};
class TestAsciiResource: public String::ExternalAsciiStringResource {
public:
explicit TestAsciiResource(const char* data, int* counter = NULL)
: data_(data), length_(strlen(data)), counter_(counter) { }
~TestAsciiResource() {
i::DeleteArray(data_);
if (counter_ != NULL) ++*counter_;
}
const char* data() const {
return data_;
}
size_t length() const {
return length_;
}
private:
const char* data_;
size_t length_;
int* counter_;
};
THREADED_TEST(ScriptUsingStringResource) {
int dispose_count = 0;
const char* c_source = "1 + 2 * 3";
uint16_t* two_byte_source = AsciiToTwoByteString(c_source);
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
TestResource* resource = new TestResource(two_byte_source, &dispose_count);
Local<String> source = String::NewExternal(resource);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value());
CHECK(source->IsExternal());
CHECK_EQ(resource,
static_cast<TestResource*>(source->GetExternalStringResource()));
String::Encoding encoding = String::UNKNOWN_ENCODING;
CHECK_EQ(static_cast<const String::ExternalStringResourceBase*>(resource),
source->GetExternalStringResourceBase(&encoding));
CHECK_EQ(String::TWO_BYTE_ENCODING, encoding);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(0, dispose_count);
}
v8::internal::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllAvailableGarbage();
CHECK_EQ(1, dispose_count);
}
THREADED_TEST(ScriptUsingAsciiStringResource) {
int dispose_count = 0;
const char* c_source = "1 + 2 * 3";
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
TestAsciiResource* resource = new TestAsciiResource(i::StrDup(c_source),
&dispose_count);
Local<String> source = String::NewExternal(resource);
CHECK(source->IsExternalAscii());
CHECK_EQ(static_cast<const String::ExternalStringResourceBase*>(resource),
source->GetExternalAsciiStringResource());
String::Encoding encoding = String::UNKNOWN_ENCODING;
CHECK_EQ(static_cast<const String::ExternalStringResourceBase*>(resource),
source->GetExternalStringResourceBase(&encoding));
CHECK_EQ(String::ASCII_ENCODING, encoding);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(0, dispose_count);
}
i::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllAvailableGarbage();
CHECK_EQ(1, dispose_count);
}
THREADED_TEST(ScriptMakingExternalString) {
int dispose_count = 0;
uint16_t* two_byte_source = AsciiToTwoByteString("1 + 2 * 3");
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> source = String::New(two_byte_source);
// Trigger GCs so that the newly allocated string moves to old gen.
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
CHECK_EQ(source->IsExternal(), false);
CHECK_EQ(source->IsExternalAscii(), false);
String::Encoding encoding = String::UNKNOWN_ENCODING;
CHECK_EQ(NULL, source->GetExternalStringResourceBase(&encoding));
CHECK_EQ(String::ASCII_ENCODING, encoding);
bool success = source->MakeExternal(new TestResource(two_byte_source,
&dispose_count));
CHECK(success);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(0, dispose_count);
}
i::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
CHECK_EQ(1, dispose_count);
}
THREADED_TEST(ScriptMakingExternalAsciiString) {
int dispose_count = 0;
const char* c_source = "1 + 2 * 3";
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> source = v8_str(c_source);
// Trigger GCs so that the newly allocated string moves to old gen.
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
bool success = source->MakeExternal(
new TestAsciiResource(i::StrDup(c_source), &dispose_count));
CHECK(success);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(0, dispose_count);
}
i::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
CHECK_EQ(1, dispose_count);
}
TEST(MakingExternalStringConditions) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// Free some space in the new space so that we can check freshness.
HEAP->CollectGarbage(i::NEW_SPACE);
HEAP->CollectGarbage(i::NEW_SPACE);
uint16_t* two_byte_string = AsciiToTwoByteString("s1");
Local<String> small_string = String::New(two_byte_string);
i::DeleteArray(two_byte_string);
// We should refuse to externalize newly created small string.
CHECK(!small_string->CanMakeExternal());
// Trigger GCs so that the newly allocated string moves to old gen.
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
// Old space strings should be accepted.
CHECK(small_string->CanMakeExternal());
two_byte_string = AsciiToTwoByteString("small string 2");
small_string = String::New(two_byte_string);
i::DeleteArray(two_byte_string);
// We should refuse externalizing newly created small string.
CHECK(!small_string->CanMakeExternal());
for (int i = 0; i < 100; i++) {
String::Value value(small_string);
}
// Frequently used strings should be accepted.
CHECK(small_string->CanMakeExternal());
const int buf_size = 10 * 1024;
char* buf = i::NewArray<char>(buf_size);
memset(buf, 'a', buf_size);
buf[buf_size - 1] = '\0';
two_byte_string = AsciiToTwoByteString(buf);
Local<String> large_string = String::New(two_byte_string);
i::DeleteArray(buf);
i::DeleteArray(two_byte_string);
// Large strings should be immediately accepted.
CHECK(large_string->CanMakeExternal());
}
TEST(MakingExternalAsciiStringConditions) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// Free some space in the new space so that we can check freshness.
HEAP->CollectGarbage(i::NEW_SPACE);
HEAP->CollectGarbage(i::NEW_SPACE);
Local<String> small_string = String::New("s1");
// We should refuse to externalize newly created small string.
CHECK(!small_string->CanMakeExternal());
// Trigger GCs so that the newly allocated string moves to old gen.
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
// Old space strings should be accepted.
CHECK(small_string->CanMakeExternal());
small_string = String::New("small string 2");
// We should refuse externalizing newly created small string.
CHECK(!small_string->CanMakeExternal());
for (int i = 0; i < 100; i++) {
String::Value value(small_string);
}
// Frequently used strings should be accepted.
CHECK(small_string->CanMakeExternal());
const int buf_size = 10 * 1024;
char* buf = i::NewArray<char>(buf_size);
memset(buf, 'a', buf_size);
buf[buf_size - 1] = '\0';
Local<String> large_string = String::New(buf);
i::DeleteArray(buf);
// Large strings should be immediately accepted.
CHECK(large_string->CanMakeExternal());
}
TEST(MakingExternalUnalignedAsciiString) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
CompileRun("function cons(a, b) { return a + b; }"
"function slice(a) { return a.substring(1); }");
// Create a cons string that will land in old pointer space.
Local<String> cons = Local<String>::Cast(CompileRun(
"cons('abcdefghijklm', 'nopqrstuvwxyz');"));
// Create a sliced string that will land in old pointer space.
Local<String> slice = Local<String>::Cast(CompileRun(
"slice('abcdefghijklmnopqrstuvwxyz');"));
// Trigger GCs so that the newly allocated string moves to old gen.
SimulateFullSpace(HEAP->old_pointer_space());
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
// Turn into external string with unaligned resource data.
int dispose_count = 0;
const char* c_cons = "_abcdefghijklmnopqrstuvwxyz";
bool success = cons->MakeExternal(
new TestAsciiResource(i::StrDup(c_cons) + 1, &dispose_count));
CHECK(success);
const char* c_slice = "_bcdefghijklmnopqrstuvwxyz";
success = slice->MakeExternal(
new TestAsciiResource(i::StrDup(c_slice) + 1, &dispose_count));
CHECK(success);
// Trigger GCs and force evacuation.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
HEAP->CollectAllGarbage(i::Heap::kReduceMemoryFootprintMask);
}
THREADED_TEST(UsingExternalString) {
i::Factory* factory = i::Isolate::Current()->factory();
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
uint16_t* two_byte_string = AsciiToTwoByteString("test string");
Local<String> string =
String::NewExternal(new TestResource(two_byte_string));
i::Handle<i::String> istring = v8::Utils::OpenHandle(*string);
// Trigger GCs so that the newly allocated string moves to old gen.
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
i::Handle<i::String> isymbol =
factory->InternalizedStringFromString(istring);
CHECK(isymbol->IsInternalizedString());
}
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
THREADED_TEST(UsingExternalAsciiString) {
i::Factory* factory = i::Isolate::Current()->factory();
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
const char* one_byte_string = "test string";
Local<String> string = String::NewExternal(
new TestAsciiResource(i::StrDup(one_byte_string)));
i::Handle<i::String> istring = v8::Utils::OpenHandle(*string);
// Trigger GCs so that the newly allocated string moves to old gen.
HEAP->CollectGarbage(i::NEW_SPACE); // in survivor space now
HEAP->CollectGarbage(i::NEW_SPACE); // in old gen now
i::Handle<i::String> isymbol =
factory->InternalizedStringFromString(istring);
CHECK(isymbol->IsInternalizedString());
}
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
THREADED_TEST(ScavengeExternalString) {
i::FLAG_stress_compaction = false;
i::FLAG_gc_global = false;
int dispose_count = 0;
bool in_new_space = false;
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
uint16_t* two_byte_string = AsciiToTwoByteString("test string");
Local<String> string =
String::NewExternal(new TestResource(two_byte_string,
&dispose_count));
i::Handle<i::String> istring = v8::Utils::OpenHandle(*string);
HEAP->CollectGarbage(i::NEW_SPACE);
in_new_space = HEAP->InNewSpace(*istring);
CHECK(in_new_space || HEAP->old_data_space()->Contains(*istring));
CHECK_EQ(0, dispose_count);
}
HEAP->CollectGarbage(in_new_space ? i::NEW_SPACE : i::OLD_DATA_SPACE);
CHECK_EQ(1, dispose_count);
}
THREADED_TEST(ScavengeExternalAsciiString) {
i::FLAG_stress_compaction = false;
i::FLAG_gc_global = false;
int dispose_count = 0;
bool in_new_space = false;
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
const char* one_byte_string = "test string";
Local<String> string = String::NewExternal(
new TestAsciiResource(i::StrDup(one_byte_string), &dispose_count));
i::Handle<i::String> istring = v8::Utils::OpenHandle(*string);
HEAP->CollectGarbage(i::NEW_SPACE);
in_new_space = HEAP->InNewSpace(*istring);
CHECK(in_new_space || HEAP->old_data_space()->Contains(*istring));
CHECK_EQ(0, dispose_count);
}
HEAP->CollectGarbage(in_new_space ? i::NEW_SPACE : i::OLD_DATA_SPACE);
CHECK_EQ(1, dispose_count);
}
class TestAsciiResourceWithDisposeControl: public TestAsciiResource {
public:
// Only used by non-threaded tests, so it can use static fields.
static int dispose_calls;
static int dispose_count;
TestAsciiResourceWithDisposeControl(const char* data, bool dispose)
: TestAsciiResource(data, &dispose_count),
dispose_(dispose) { }
void Dispose() {
++dispose_calls;
if (dispose_) delete this;
}
private:
bool dispose_;
};
int TestAsciiResourceWithDisposeControl::dispose_count = 0;
int TestAsciiResourceWithDisposeControl::dispose_calls = 0;
TEST(ExternalStringWithDisposeHandling) {
const char* c_source = "1 + 2 * 3";
// Use a stack allocated external string resource allocated object.
TestAsciiResourceWithDisposeControl::dispose_count = 0;
TestAsciiResourceWithDisposeControl::dispose_calls = 0;
TestAsciiResourceWithDisposeControl res_stack(i::StrDup(c_source), false);
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> source = String::NewExternal(&res_stack);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value());
HEAP->CollectAllAvailableGarbage();
CHECK_EQ(0, TestAsciiResourceWithDisposeControl::dispose_count);
}
i::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllAvailableGarbage();
CHECK_EQ(1, TestAsciiResourceWithDisposeControl::dispose_calls);
CHECK_EQ(0, TestAsciiResourceWithDisposeControl::dispose_count);
// Use a heap allocated external string resource allocated object.
TestAsciiResourceWithDisposeControl::dispose_count = 0;
TestAsciiResourceWithDisposeControl::dispose_calls = 0;
TestAsciiResource* res_heap =
new TestAsciiResourceWithDisposeControl(i::StrDup(c_source), true);
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> source = String::NewExternal(res_heap);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(7, value->Int32Value());
HEAP->CollectAllAvailableGarbage();
CHECK_EQ(0, TestAsciiResourceWithDisposeControl::dispose_count);
}
i::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllAvailableGarbage();
CHECK_EQ(1, TestAsciiResourceWithDisposeControl::dispose_calls);
CHECK_EQ(1, TestAsciiResourceWithDisposeControl::dispose_count);
}
THREADED_TEST(StringConcat) {
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* one_byte_string_1 = "function a_times_t";
const char* two_byte_string_1 = "wo_plus_b(a, b) {return ";
const char* one_byte_extern_1 = "a * 2 + b;} a_times_two_plus_b(4, 8) + ";
const char* two_byte_extern_1 = "a_times_two_plus_b(4, 8) + ";
const char* one_byte_string_2 = "a_times_two_plus_b(4, 8) + ";
const char* two_byte_string_2 = "a_times_two_plus_b(4, 8) + ";
const char* two_byte_extern_2 = "a_times_two_plus_b(1, 2);";
Local<String> left = v8_str(one_byte_string_1);
uint16_t* two_byte_source = AsciiToTwoByteString(two_byte_string_1);
Local<String> right = String::New(two_byte_source);
i::DeleteArray(two_byte_source);
Local<String> source = String::Concat(left, right);
right = String::NewExternal(
new TestAsciiResource(i::StrDup(one_byte_extern_1)));
source = String::Concat(source, right);
right = String::NewExternal(
new TestResource(AsciiToTwoByteString(two_byte_extern_1)));
source = String::Concat(source, right);
right = v8_str(one_byte_string_2);
source = String::Concat(source, right);
two_byte_source = AsciiToTwoByteString(two_byte_string_2);
right = String::New(two_byte_source);
i::DeleteArray(two_byte_source);
source = String::Concat(source, right);
right = String::NewExternal(
new TestResource(AsciiToTwoByteString(two_byte_extern_2)));
source = String::Concat(source, right);
Local<Script> script = Script::Compile(source);
Local<Value> value = script->Run();
CHECK(value->IsNumber());
CHECK_EQ(68, value->Int32Value());
}
i::Isolate::Current()->compilation_cache()->Clear();
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
THREADED_TEST(GlobalProperties) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::Object> global = env->Global();
global->Set(v8_str("pi"), v8_num(3.1415926));
Local<Value> pi = global->Get(v8_str("pi"));
CHECK_EQ(3.1415926, pi->NumberValue());
}
template<typename T>
static void CheckReturnValue(const T& t, i::Address callback) {
v8::ReturnValue<v8::Value> rv = t.GetReturnValue();
i::Object** o = *reinterpret_cast<i::Object***>(&rv);
CHECK_EQ(v8::Isolate::GetCurrent(), t.GetIsolate());
CHECK_EQ(t.GetIsolate(), rv.GetIsolate());
CHECK((*o)->IsTheHole() || (*o)->IsUndefined());
// Verify reset
bool is_runtime = (*o)->IsTheHole();
rv.Set(true);
CHECK(!(*o)->IsTheHole() && !(*o)->IsUndefined());
rv.Set(v8::Handle<v8::Object>());
CHECK((*o)->IsTheHole() || (*o)->IsUndefined());
CHECK_EQ(is_runtime, (*o)->IsTheHole());
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(t.GetIsolate());
// If CPU profiler is active check that when API callback is invoked
// VMState is set to EXTERNAL.
if (isolate->cpu_profiler()->is_profiling()) {
CHECK_EQ(i::EXTERNAL, isolate->current_vm_state());
CHECK(isolate->external_callback_scope());
CHECK_EQ(callback, isolate->external_callback_scope()->callback());
}
}
static void handle_callback_impl(const v8::FunctionCallbackInfo<Value>& info,
i::Address callback) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(info, callback);
info.GetReturnValue().Set(v8_str("bad value"));
info.GetReturnValue().Set(v8_num(102));
}
static void handle_callback(const v8::FunctionCallbackInfo<Value>& info) {
return handle_callback_impl(info, FUNCTION_ADDR(handle_callback));
}
static void handle_callback_2(const v8::FunctionCallbackInfo<Value>& info) {
return handle_callback_impl(info, FUNCTION_ADDR(handle_callback_2));
}
static void construct_callback(
const v8::FunctionCallbackInfo<Value>& info) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(info, FUNCTION_ADDR(construct_callback));
info.This()->Set(v8_str("x"), v8_num(1));
info.This()->Set(v8_str("y"), v8_num(2));
info.GetReturnValue().Set(v8_str("bad value"));
info.GetReturnValue().Set(info.This());
}
static void Return239Callback(
Local<String> name, const v8::PropertyCallbackInfo<Value>& info) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(info, FUNCTION_ADDR(Return239Callback));
info.GetReturnValue().Set(v8_str("bad value"));
info.GetReturnValue().Set(v8_num(239));
}
template<typename Handler>
static void TestFunctionTemplateInitializer(Handler handler,
Handler handler_2) {
// Test constructor calls.
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(handler);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("obj"), fun);
Local<Script> script = v8_compile("obj()");
for (int i = 0; i < 30; i++) {
CHECK_EQ(102, script->Run()->Int32Value());
}
}
// Use SetCallHandler to initialize a function template, should work like
// the previous one.
{
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
fun_templ->SetCallHandler(handler_2);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("obj"), fun);
Local<Script> script = v8_compile("obj()");
for (int i = 0; i < 30; i++) {
CHECK_EQ(102, script->Run()->Int32Value());
}
}
}
template<typename Constructor, typename Accessor>
static void TestFunctionTemplateAccessor(Constructor constructor,
Accessor accessor) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(constructor);
fun_templ->SetClassName(v8_str("funky"));
fun_templ->InstanceTemplate()->SetAccessor(v8_str("m"), accessor);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("obj"), fun);
Local<Value> result = v8_compile("(new obj()).toString()")->Run();
CHECK_EQ(v8_str("[object funky]"), result);
CompileRun("var obj_instance = new obj();");
Local<Script> script;
script = v8_compile("obj_instance.x");
for (int i = 0; i < 30; i++) {
CHECK_EQ(1, script->Run()->Int32Value());
}
script = v8_compile("obj_instance.m");
for (int i = 0; i < 30; i++) {
CHECK_EQ(239, script->Run()->Int32Value());
}
}
THREADED_PROFILED_TEST(FunctionTemplate) {
TestFunctionTemplateInitializer(handle_callback, handle_callback_2);
TestFunctionTemplateAccessor(construct_callback, Return239Callback);
}
static void SimpleCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(info, FUNCTION_ADDR(SimpleCallback));
info.GetReturnValue().Set(v8_num(51423 + info.Length()));
}
template<typename Callback>
static void TestSimpleCallback(Callback callback) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::ObjectTemplate> object_template = v8::ObjectTemplate::New();
object_template->Set("callback", v8::FunctionTemplate::New(callback));
v8::Local<v8::Object> object = object_template->NewInstance();
(*env)->Global()->Set(v8_str("callback_object"), object);
v8::Handle<v8::Script> script;
script = v8_compile("callback_object.callback(17)");
for (int i = 0; i < 30; i++) {
CHECK_EQ(51424, script->Run()->Int32Value());
}
script = v8_compile("callback_object.callback(17, 24)");
for (int i = 0; i < 30; i++) {
CHECK_EQ(51425, script->Run()->Int32Value());
}
}
THREADED_PROFILED_TEST(SimpleCallback) {
TestSimpleCallback(SimpleCallback);
}
template<typename T>
void FastReturnValueCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
// constant return values
static int32_t fast_return_value_int32 = 471;
static uint32_t fast_return_value_uint32 = 571;
static const double kFastReturnValueDouble = 2.7;
// variable return values
static bool fast_return_value_bool = false;
enum ReturnValueOddball {
kNullReturnValue,
kUndefinedReturnValue,
kEmptyStringReturnValue
};
static ReturnValueOddball fast_return_value_void;
static bool fast_return_value_object_is_empty = false;
// Helper function to avoid compiler error: insufficient contextual information
// to determine type when applying FUNCTION_ADDR to a template function.
static i::Address address_of(v8::FunctionCallback callback) {
return FUNCTION_ADDR(callback);
}
template<>
void FastReturnValueCallback<int32_t>(
const v8::FunctionCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, address_of(FastReturnValueCallback<int32_t>));
info.GetReturnValue().Set(fast_return_value_int32);
}
template<>
void FastReturnValueCallback<uint32_t>(
const v8::FunctionCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, address_of(FastReturnValueCallback<uint32_t>));
info.GetReturnValue().Set(fast_return_value_uint32);
}
template<>
void FastReturnValueCallback<double>(
const v8::FunctionCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, address_of(FastReturnValueCallback<double>));
info.GetReturnValue().Set(kFastReturnValueDouble);
}
template<>
void FastReturnValueCallback<bool>(
const v8::FunctionCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, address_of(FastReturnValueCallback<bool>));
info.GetReturnValue().Set(fast_return_value_bool);
}
template<>
void FastReturnValueCallback<void>(
const v8::FunctionCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, address_of(FastReturnValueCallback<void>));
switch (fast_return_value_void) {
case kNullReturnValue:
info.GetReturnValue().SetNull();
break;
case kUndefinedReturnValue:
info.GetReturnValue().SetUndefined();
break;
case kEmptyStringReturnValue:
info.GetReturnValue().SetEmptyString();
break;
}
}
template<>
void FastReturnValueCallback<Object>(
const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Handle<v8::Object> object;
if (!fast_return_value_object_is_empty) object = Object::New();
info.GetReturnValue().Set(object);
}
template<typename T>
Handle<Value> TestFastReturnValues() {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::ObjectTemplate> object_template = v8::ObjectTemplate::New();
v8::FunctionCallback callback = &FastReturnValueCallback<T>;
object_template->Set("callback", v8::FunctionTemplate::New(callback));
v8::Local<v8::Object> object = object_template->NewInstance();
(*env)->Global()->Set(v8_str("callback_object"), object);
return scope.Close(CompileRun("callback_object.callback()"));
}
THREADED_PROFILED_TEST(FastReturnValues) {
LocalContext env;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::Value> value;
// check int32_t and uint32_t
int32_t int_values[] = {
0, 234, -723,
i::Smi::kMinValue, i::Smi::kMaxValue
};
for (size_t i = 0; i < ARRAY_SIZE(int_values); i++) {
for (int modifier = -1; modifier <= 1; modifier++) {
int int_value = int_values[i] + modifier;
// check int32_t
fast_return_value_int32 = int_value;
value = TestFastReturnValues<int32_t>();
CHECK(value->IsInt32());
CHECK(fast_return_value_int32 == value->Int32Value());
// check uint32_t
fast_return_value_uint32 = static_cast<uint32_t>(int_value);
value = TestFastReturnValues<uint32_t>();
CHECK(value->IsUint32());
CHECK(fast_return_value_uint32 == value->Uint32Value());
}
}
// check double
value = TestFastReturnValues<double>();
CHECK(value->IsNumber());
CHECK_EQ(kFastReturnValueDouble, value->ToNumber()->Value());
// check bool values
for (int i = 0; i < 2; i++) {
fast_return_value_bool = i == 0;
value = TestFastReturnValues<bool>();
CHECK(value->IsBoolean());
CHECK_EQ(fast_return_value_bool, value->ToBoolean()->Value());
}
// check oddballs
ReturnValueOddball oddballs[] = {
kNullReturnValue,
kUndefinedReturnValue,
kEmptyStringReturnValue
};
for (size_t i = 0; i < ARRAY_SIZE(oddballs); i++) {
fast_return_value_void = oddballs[i];
value = TestFastReturnValues<void>();
switch (fast_return_value_void) {
case kNullReturnValue:
CHECK(value->IsNull());
break;
case kUndefinedReturnValue:
CHECK(value->IsUndefined());
break;
case kEmptyStringReturnValue:
CHECK(value->IsString());
CHECK_EQ(0, v8::String::Cast(*value)->Length());
break;
}
}
// check handles
fast_return_value_object_is_empty = false;
value = TestFastReturnValues<Object>();
CHECK(value->IsObject());
fast_return_value_object_is_empty = true;
value = TestFastReturnValues<Object>();
CHECK(value->IsUndefined());
}
THREADED_TEST(FunctionTemplateSetLength) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
{
Local<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New(
handle_callback, Handle<v8::Value>(), Handle<v8::Signature>(), 23);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("obj"), fun);
Local<Script> script = v8_compile("obj.length");
CHECK_EQ(23, script->Run()->Int32Value());
}
{
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(handle_callback);
fun_templ->SetLength(22);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("obj"), fun);
Local<Script> script = v8_compile("obj.length");
CHECK_EQ(22, script->Run()->Int32Value());
}
{
// Without setting length it defaults to 0.
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(handle_callback);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("obj"), fun);
Local<Script> script = v8_compile("obj.length");
CHECK_EQ(0, script->Run()->Int32Value());
}
}
static void* expected_ptr;
static void callback(const v8::FunctionCallbackInfo<v8::Value>& args) {
void* ptr = v8::External::Cast(*args.Data())->Value();
CHECK_EQ(expected_ptr, ptr);
args.GetReturnValue().Set(true);
}
static void TestExternalPointerWrapping() {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::Value> data = v8::External::New(expected_ptr);
v8::Handle<v8::Object> obj = v8::Object::New();
obj->Set(v8_str("func"),
v8::FunctionTemplate::New(callback, data)->GetFunction());
env->Global()->Set(v8_str("obj"), obj);
CHECK(CompileRun(
"function foo() {\n"
" for (var i = 0; i < 13; i++) obj.func();\n"
"}\n"
"foo(), true")->BooleanValue());
}
THREADED_TEST(ExternalWrap) {
// Check heap allocated object.
int* ptr = new int;
expected_ptr = ptr;
TestExternalPointerWrapping();
delete ptr;
// Check stack allocated object.
int foo;
expected_ptr = &foo;
TestExternalPointerWrapping();
// Check not aligned addresses.
const int n = 100;
char* s = new char[n];
for (int i = 0; i < n; i++) {
expected_ptr = s + i;
TestExternalPointerWrapping();
}
delete[] s;
// Check several invalid addresses.
expected_ptr = reinterpret_cast<void*>(1);
TestExternalPointerWrapping();
expected_ptr = reinterpret_cast<void*>(0xdeadbeef);
TestExternalPointerWrapping();
expected_ptr = reinterpret_cast<void*>(0xdeadbeef + 1);
TestExternalPointerWrapping();
#if defined(V8_HOST_ARCH_X64)
// Check a value with a leading 1 bit in x64 Smi encoding.
expected_ptr = reinterpret_cast<void*>(0x400000000);
TestExternalPointerWrapping();
expected_ptr = reinterpret_cast<void*>(0xdeadbeefdeadbeef);
TestExternalPointerWrapping();
expected_ptr = reinterpret_cast<void*>(0xdeadbeefdeadbeef + 1);
TestExternalPointerWrapping();
#endif
}
THREADED_TEST(FindInstanceInPrototypeChain) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> base = v8::FunctionTemplate::New();
Local<v8::FunctionTemplate> derived = v8::FunctionTemplate::New();
Local<v8::FunctionTemplate> other = v8::FunctionTemplate::New();
derived->Inherit(base);
Local<v8::Function> base_function = base->GetFunction();
Local<v8::Function> derived_function = derived->GetFunction();
Local<v8::Function> other_function = other->GetFunction();
Local<v8::Object> base_instance = base_function->NewInstance();
Local<v8::Object> derived_instance = derived_function->NewInstance();
Local<v8::Object> derived_instance2 = derived_function->NewInstance();
Local<v8::Object> other_instance = other_function->NewInstance();
derived_instance2->Set(v8_str("__proto__"), derived_instance);
other_instance->Set(v8_str("__proto__"), derived_instance2);
// base_instance is only an instance of base.
CHECK_EQ(base_instance,
base_instance->FindInstanceInPrototypeChain(base));
CHECK(base_instance->FindInstanceInPrototypeChain(derived).IsEmpty());
CHECK(base_instance->FindInstanceInPrototypeChain(other).IsEmpty());
// derived_instance is an instance of base and derived.
CHECK_EQ(derived_instance,
derived_instance->FindInstanceInPrototypeChain(base));
CHECK_EQ(derived_instance,
derived_instance->FindInstanceInPrototypeChain(derived));
CHECK(derived_instance->FindInstanceInPrototypeChain(other).IsEmpty());
// other_instance is an instance of other and its immediate
// prototype derived_instance2 is an instance of base and derived.
// Note, derived_instance is an instance of base and derived too,
// but it comes after derived_instance2 in the prototype chain of
// other_instance.
CHECK_EQ(derived_instance2,
other_instance->FindInstanceInPrototypeChain(base));
CHECK_EQ(derived_instance2,
other_instance->FindInstanceInPrototypeChain(derived));
CHECK_EQ(other_instance,
other_instance->FindInstanceInPrototypeChain(other));
}
THREADED_TEST(TinyInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
int32_t value = 239;
Local<v8::Integer> value_obj = v8::Integer::New(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::New(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
THREADED_TEST(BigSmiInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
int32_t value = i::Smi::kMaxValue;
// We cannot add one to a Smi::kMaxValue without wrapping.
if (i::kSmiValueSize < 32) {
CHECK(i::Smi::IsValid(value));
CHECK(!i::Smi::IsValid(value + 1));
Local<v8::Integer> value_obj = v8::Integer::New(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::New(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
}
THREADED_TEST(BigInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// We cannot add one to a Smi::kMaxValue without wrapping.
if (i::kSmiValueSize < 32) {
// The casts allow this to compile, even if Smi::kMaxValue is 2^31-1.
// The code will not be run in that case, due to the "if" guard.
int32_t value =
static_cast<int32_t>(static_cast<uint32_t>(i::Smi::kMaxValue) + 1);
CHECK(value > i::Smi::kMaxValue);
CHECK(!i::Smi::IsValid(value));
Local<v8::Integer> value_obj = v8::Integer::New(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::New(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
}
THREADED_TEST(TinyUnsignedInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
uint32_t value = 239;
Local<v8::Integer> value_obj = v8::Integer::NewFromUnsigned(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::NewFromUnsigned(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
THREADED_TEST(BigUnsignedSmiInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
uint32_t value = static_cast<uint32_t>(i::Smi::kMaxValue);
CHECK(i::Smi::IsValid(value));
CHECK(!i::Smi::IsValid(value + 1));
Local<v8::Integer> value_obj = v8::Integer::NewFromUnsigned(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::NewFromUnsigned(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
THREADED_TEST(BigUnsignedInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
uint32_t value = static_cast<uint32_t>(i::Smi::kMaxValue) + 1;
CHECK(value > static_cast<uint32_t>(i::Smi::kMaxValue));
CHECK(!i::Smi::IsValid(value));
Local<v8::Integer> value_obj = v8::Integer::NewFromUnsigned(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::NewFromUnsigned(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
THREADED_TEST(OutOfSignedRangeUnsignedInteger) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
uint32_t INT32_MAX_AS_UINT = (1U << 31) - 1;
uint32_t value = INT32_MAX_AS_UINT + 1;
CHECK(value > INT32_MAX_AS_UINT); // No overflow.
Local<v8::Integer> value_obj = v8::Integer::NewFromUnsigned(value);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
value_obj = v8::Integer::NewFromUnsigned(value, isolate);
CHECK_EQ(static_cast<int64_t>(value), value_obj->Value());
}
THREADED_TEST(IsNativeError) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<Value> syntax_error = CompileRun(
"var out = 0; try { eval(\"#\"); } catch(x) { out = x; } out; ");
CHECK(syntax_error->IsNativeError());
v8::Handle<Value> not_error = CompileRun("{a:42}");
CHECK(!not_error->IsNativeError());
v8::Handle<Value> not_object = CompileRun("42");
CHECK(!not_object->IsNativeError());
}
THREADED_TEST(StringObject) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<Value> boxed_string = CompileRun("new String(\"test\")");
CHECK(boxed_string->IsStringObject());
v8::Handle<Value> unboxed_string = CompileRun("\"test\"");
CHECK(!unboxed_string->IsStringObject());
v8::Handle<Value> boxed_not_string = CompileRun("new Number(42)");
CHECK(!boxed_not_string->IsStringObject());
v8::Handle<Value> not_object = CompileRun("0");
CHECK(!not_object->IsStringObject());
v8::Handle<v8::StringObject> as_boxed = boxed_string.As<v8::StringObject>();
CHECK(!as_boxed.IsEmpty());
Local<v8::String> the_string = as_boxed->ValueOf();
CHECK(!the_string.IsEmpty());
ExpectObject("\"test\"", the_string);
v8::Handle<v8::Value> new_boxed_string = v8::StringObject::New(the_string);
CHECK(new_boxed_string->IsStringObject());
as_boxed = new_boxed_string.As<v8::StringObject>();
the_string = as_boxed->ValueOf();
CHECK(!the_string.IsEmpty());
ExpectObject("\"test\"", the_string);
}
THREADED_TEST(NumberObject) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<Value> boxed_number = CompileRun("new Number(42)");
CHECK(boxed_number->IsNumberObject());
v8::Handle<Value> unboxed_number = CompileRun("42");
CHECK(!unboxed_number->IsNumberObject());
v8::Handle<Value> boxed_not_number = CompileRun("new Boolean(false)");
CHECK(!boxed_not_number->IsNumberObject());
v8::Handle<v8::NumberObject> as_boxed = boxed_number.As<v8::NumberObject>();
CHECK(!as_boxed.IsEmpty());
double the_number = as_boxed->ValueOf();
CHECK_EQ(42.0, the_number);
v8::Handle<v8::Value> new_boxed_number = v8::NumberObject::New(43);
CHECK(new_boxed_number->IsNumberObject());
as_boxed = new_boxed_number.As<v8::NumberObject>();
the_number = as_boxed->ValueOf();
CHECK_EQ(43.0, the_number);
}
THREADED_TEST(BooleanObject) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<Value> boxed_boolean = CompileRun("new Boolean(true)");
CHECK(boxed_boolean->IsBooleanObject());
v8::Handle<Value> unboxed_boolean = CompileRun("true");
CHECK(!unboxed_boolean->IsBooleanObject());
v8::Handle<Value> boxed_not_boolean = CompileRun("new Number(42)");
CHECK(!boxed_not_boolean->IsBooleanObject());
v8::Handle<v8::BooleanObject> as_boxed =
boxed_boolean.As<v8::BooleanObject>();
CHECK(!as_boxed.IsEmpty());
bool the_boolean = as_boxed->ValueOf();
CHECK_EQ(true, the_boolean);
v8::Handle<v8::Value> boxed_true = v8::BooleanObject::New(true);
v8::Handle<v8::Value> boxed_false = v8::BooleanObject::New(false);
CHECK(boxed_true->IsBooleanObject());
CHECK(boxed_false->IsBooleanObject());
as_boxed = boxed_true.As<v8::BooleanObject>();
CHECK_EQ(true, as_boxed->ValueOf());
as_boxed = boxed_false.As<v8::BooleanObject>();
CHECK_EQ(false, as_boxed->ValueOf());
}
THREADED_TEST(PrimitiveAndWrappedBooleans) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<Value> primitive_false = Boolean::New(false);
CHECK(primitive_false->IsBoolean());
CHECK(!primitive_false->IsBooleanObject());
CHECK(!primitive_false->BooleanValue());
CHECK(!primitive_false->IsTrue());
CHECK(primitive_false->IsFalse());
Local<Value> false_value = BooleanObject::New(false);
CHECK(!false_value->IsBoolean());
CHECK(false_value->IsBooleanObject());
CHECK(false_value->BooleanValue());
CHECK(!false_value->IsTrue());
CHECK(!false_value->IsFalse());
Local<BooleanObject> false_boolean_object = false_value.As<BooleanObject>();
CHECK(!false_boolean_object->IsBoolean());
CHECK(false_boolean_object->IsBooleanObject());
// TODO(svenpanne) Uncomment when BooleanObject::BooleanValue() is deleted.
// CHECK(false_boolean_object->BooleanValue());
CHECK(!false_boolean_object->ValueOf());
CHECK(!false_boolean_object->IsTrue());
CHECK(!false_boolean_object->IsFalse());
Local<Value> primitive_true = Boolean::New(true);
CHECK(primitive_true->IsBoolean());
CHECK(!primitive_true->IsBooleanObject());
CHECK(primitive_true->BooleanValue());
CHECK(primitive_true->IsTrue());
CHECK(!primitive_true->IsFalse());
Local<Value> true_value = BooleanObject::New(true);
CHECK(!true_value->IsBoolean());
CHECK(true_value->IsBooleanObject());
CHECK(true_value->BooleanValue());
CHECK(!true_value->IsTrue());
CHECK(!true_value->IsFalse());
Local<BooleanObject> true_boolean_object = true_value.As<BooleanObject>();
CHECK(!true_boolean_object->IsBoolean());
CHECK(true_boolean_object->IsBooleanObject());
// TODO(svenpanne) Uncomment when BooleanObject::BooleanValue() is deleted.
// CHECK(true_boolean_object->BooleanValue());
CHECK(true_boolean_object->ValueOf());
CHECK(!true_boolean_object->IsTrue());
CHECK(!true_boolean_object->IsFalse());
}
THREADED_TEST(Number) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
double PI = 3.1415926;
Local<v8::Number> pi_obj = v8::Number::New(PI);
CHECK_EQ(PI, pi_obj->NumberValue());
}
THREADED_TEST(ToNumber) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> str = v8_str("3.1415926");
CHECK_EQ(3.1415926, str->NumberValue());
v8::Handle<v8::Boolean> t = v8::True();
CHECK_EQ(1.0, t->NumberValue());
v8::Handle<v8::Boolean> f = v8::False();
CHECK_EQ(0.0, f->NumberValue());
}
THREADED_TEST(Date) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
double PI = 3.1415926;
Local<Value> date = v8::Date::New(PI);
CHECK_EQ(3.0, date->NumberValue());
date.As<v8::Date>()->Set(v8_str("property"), v8::Integer::New(42));
CHECK_EQ(42, date.As<v8::Date>()->Get(v8_str("property"))->Int32Value());
}
THREADED_TEST(Boolean) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::Boolean> t = v8::True();
CHECK(t->Value());
v8::Handle<v8::Boolean> f = v8::False();
CHECK(!f->Value());
v8::Handle<v8::Primitive> u = v8::Undefined();
CHECK(!u->BooleanValue());
v8::Handle<v8::Primitive> n = v8::Null();
CHECK(!n->BooleanValue());
v8::Handle<String> str1 = v8_str("");
CHECK(!str1->BooleanValue());
v8::Handle<String> str2 = v8_str("x");
CHECK(str2->BooleanValue());
CHECK(!v8::Number::New(0)->BooleanValue());
CHECK(v8::Number::New(-1)->BooleanValue());
CHECK(v8::Number::New(1)->BooleanValue());
CHECK(v8::Number::New(42)->BooleanValue());
CHECK(!v8_compile("NaN")->Run()->BooleanValue());
}
static void DummyCallHandler(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(v8_num(13.4));
}
static void GetM(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(v8_num(876));
}
THREADED_TEST(GlobalPrototype) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> func_templ = v8::FunctionTemplate::New();
func_templ->PrototypeTemplate()->Set(
"dummy",
v8::FunctionTemplate::New(DummyCallHandler));
v8::Handle<ObjectTemplate> templ = func_templ->InstanceTemplate();
templ->Set("x", v8_num(200));
templ->SetAccessor(v8_str("m"), GetM);
LocalContext env(0, templ);
v8::Handle<Script> script(v8_compile("dummy()"));
v8::Handle<Value> result(script->Run());
CHECK_EQ(13.4, result->NumberValue());
CHECK_EQ(200, v8_compile("x")->Run()->Int32Value());
CHECK_EQ(876, v8_compile("m")->Run()->Int32Value());
}
THREADED_TEST(ObjectTemplate) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ1 = ObjectTemplate::New();
templ1->Set("x", v8_num(10));
templ1->Set("y", v8_num(13));
LocalContext env;
Local<v8::Object> instance1 = templ1->NewInstance();
env->Global()->Set(v8_str("p"), instance1);
CHECK(v8_compile("(p.x == 10)")->Run()->BooleanValue());
CHECK(v8_compile("(p.y == 13)")->Run()->BooleanValue());
Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New();
fun->PrototypeTemplate()->Set("nirk", v8_num(123));
Local<ObjectTemplate> templ2 = fun->InstanceTemplate();
templ2->Set("a", v8_num(12));
templ2->Set("b", templ1);
Local<v8::Object> instance2 = templ2->NewInstance();
env->Global()->Set(v8_str("q"), instance2);
CHECK(v8_compile("(q.nirk == 123)")->Run()->BooleanValue());
CHECK(v8_compile("(q.a == 12)")->Run()->BooleanValue());
CHECK(v8_compile("(q.b.x == 10)")->Run()->BooleanValue());
CHECK(v8_compile("(q.b.y == 13)")->Run()->BooleanValue());
}
static void GetFlabby(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(v8_num(17.2));
}
static void GetKnurd(Local<String> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(v8_num(15.2));
}
THREADED_TEST(DescriptorInheritance) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> super = v8::FunctionTemplate::New();
super->PrototypeTemplate()->Set("flabby",
v8::FunctionTemplate::New(GetFlabby));
super->PrototypeTemplate()->Set("PI", v8_num(3.14));
super->InstanceTemplate()->SetAccessor(v8_str("knurd"), GetKnurd);
v8::Handle<v8::FunctionTemplate> base1 = v8::FunctionTemplate::New();
base1->Inherit(super);
base1->PrototypeTemplate()->Set("v1", v8_num(20.1));
v8::Handle<v8::FunctionTemplate> base2 = v8::FunctionTemplate::New();
base2->Inherit(super);
base2->PrototypeTemplate()->Set("v2", v8_num(10.1));
LocalContext env;
env->Global()->Set(v8_str("s"), super->GetFunction());
env->Global()->Set(v8_str("base1"), base1->GetFunction());
env->Global()->Set(v8_str("base2"), base2->GetFunction());
// Checks right __proto__ chain.
CHECK(CompileRun("base1.prototype.__proto__ == s.prototype")->BooleanValue());
CHECK(CompileRun("base2.prototype.__proto__ == s.prototype")->BooleanValue());
CHECK(v8_compile("s.prototype.PI == 3.14")->Run()->BooleanValue());
// Instance accessor should not be visible on function object or its prototype
CHECK(CompileRun("s.knurd == undefined")->BooleanValue());
CHECK(CompileRun("s.prototype.knurd == undefined")->BooleanValue());
CHECK(CompileRun("base1.prototype.knurd == undefined")->BooleanValue());
env->Global()->Set(v8_str("obj"),
base1->GetFunction()->NewInstance());
CHECK_EQ(17.2, v8_compile("obj.flabby()")->Run()->NumberValue());
CHECK(v8_compile("'flabby' in obj")->Run()->BooleanValue());
CHECK_EQ(15.2, v8_compile("obj.knurd")->Run()->NumberValue());
CHECK(v8_compile("'knurd' in obj")->Run()->BooleanValue());
CHECK_EQ(20.1, v8_compile("obj.v1")->Run()->NumberValue());
env->Global()->Set(v8_str("obj2"),
base2->GetFunction()->NewInstance());
CHECK_EQ(17.2, v8_compile("obj2.flabby()")->Run()->NumberValue());
CHECK(v8_compile("'flabby' in obj2")->Run()->BooleanValue());
CHECK_EQ(15.2, v8_compile("obj2.knurd")->Run()->NumberValue());
CHECK(v8_compile("'knurd' in obj2")->Run()->BooleanValue());
CHECK_EQ(10.1, v8_compile("obj2.v2")->Run()->NumberValue());
// base1 and base2 cannot cross reference to each's prototype
CHECK(v8_compile("obj.v2")->Run()->IsUndefined());
CHECK(v8_compile("obj2.v1")->Run()->IsUndefined());
}
int echo_named_call_count;
static void EchoNamedProperty(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(v8_str("data"), info.Data());
echo_named_call_count++;
info.GetReturnValue().Set(name);
}
// Helper functions for Interceptor/Accessor interaction tests
void SimpleAccessorGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
Handle<Object> self = info.This();
info.GetReturnValue().Set(
self->Get(String::Concat(v8_str("accessor_"), name)));
}
void SimpleAccessorSetter(Local<String> name, Local<Value> value,
const v8::PropertyCallbackInfo<void>& info) {
Handle<Object> self = info.This();
self->Set(String::Concat(v8_str("accessor_"), name), value);
}
void EmptyInterceptorGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
}
void EmptyInterceptorSetter(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
}
void InterceptorGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
// Intercept names that start with 'interceptor_'.
String::Utf8Value utf8(name);
char* name_str = *utf8;
char prefix[] = "interceptor_";
int i;
for (i = 0; name_str[i] && prefix[i]; ++i) {
if (name_str[i] != prefix[i]) return;
}
Handle<Object> self = info.This();
info.GetReturnValue().Set(self->GetHiddenValue(v8_str(name_str + i)));
}
void InterceptorSetter(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
// Intercept accesses that set certain integer values.
if (value->IsInt32() && value->Int32Value() < 10000) {
Handle<Object> self = info.This();
self->SetHiddenValue(name, value);
info.GetReturnValue().Set(value);
}
}
void AddAccessor(Handle<FunctionTemplate> templ,
Handle<String> name,
v8::AccessorGetterCallback getter,
v8::AccessorSetterCallback setter) {
templ->PrototypeTemplate()->SetAccessor(name, getter, setter);
}
void AddInterceptor(Handle<FunctionTemplate> templ,
v8::NamedPropertyGetterCallback getter,
v8::NamedPropertySetterCallback setter) {
templ->InstanceTemplate()->SetNamedPropertyHandler(getter, setter);
}
THREADED_TEST(EmptyInterceptorDoesNotShadowAccessors) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddAccessor(parent, v8_str("age"),
SimpleAccessorGetter, SimpleAccessorSetter);
AddInterceptor(child, EmptyInterceptorGetter, EmptyInterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"child.age = 10;");
ExpectBoolean("child.hasOwnProperty('age')", false);
ExpectInt32("child.age", 10);
ExpectInt32("child.accessor_age", 10);
}
THREADED_TEST(EmptyInterceptorDoesNotShadowJSAccessors) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddInterceptor(child, EmptyInterceptorGetter, EmptyInterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"var parent = child.__proto__;"
"Object.defineProperty(parent, 'age', "
" {get: function(){ return this.accessor_age; }, "
" set: function(v){ this.accessor_age = v; }, "
" enumerable: true, configurable: true});"
"child.age = 10;");
ExpectBoolean("child.hasOwnProperty('age')", false);
ExpectInt32("child.age", 10);
ExpectInt32("child.accessor_age", 10);
}
THREADED_TEST(EmptyInterceptorDoesNotAffectJSProperties) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddInterceptor(child, EmptyInterceptorGetter, EmptyInterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"var parent = child.__proto__;"
"parent.name = 'Alice';");
ExpectBoolean("child.hasOwnProperty('name')", false);
ExpectString("child.name", "Alice");
CompileRun("child.name = 'Bob';");
ExpectString("child.name", "Bob");
ExpectBoolean("child.hasOwnProperty('name')", true);
ExpectString("parent.name", "Alice");
}
THREADED_TEST(SwitchFromInterceptorToAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> templ = FunctionTemplate::New();
AddAccessor(templ, v8_str("age"),
SimpleAccessorGetter, SimpleAccessorSetter);
AddInterceptor(templ, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Obj"), templ->GetFunction());
CompileRun("var obj = new Obj;"
"function setAge(i){ obj.age = i; };"
"for(var i = 0; i <= 10000; i++) setAge(i);");
// All i < 10000 go to the interceptor.
ExpectInt32("obj.interceptor_age", 9999);
// The last i goes to the accessor.
ExpectInt32("obj.accessor_age", 10000);
}
THREADED_TEST(SwitchFromAccessorToInterceptor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> templ = FunctionTemplate::New();
AddAccessor(templ, v8_str("age"),
SimpleAccessorGetter, SimpleAccessorSetter);
AddInterceptor(templ, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Obj"), templ->GetFunction());
CompileRun("var obj = new Obj;"
"function setAge(i){ obj.age = i; };"
"for(var i = 20000; i >= 9999; i--) setAge(i);");
// All i >= 10000 go to the accessor.
ExpectInt32("obj.accessor_age", 10000);
// The last i goes to the interceptor.
ExpectInt32("obj.interceptor_age", 9999);
}
THREADED_TEST(SwitchFromInterceptorToAccessorWithInheritance) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddAccessor(parent, v8_str("age"),
SimpleAccessorGetter, SimpleAccessorSetter);
AddInterceptor(child, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"function setAge(i){ child.age = i; };"
"for(var i = 0; i <= 10000; i++) setAge(i);");
// All i < 10000 go to the interceptor.
ExpectInt32("child.interceptor_age", 9999);
// The last i goes to the accessor.
ExpectInt32("child.accessor_age", 10000);
}
THREADED_TEST(SwitchFromAccessorToInterceptorWithInheritance) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddAccessor(parent, v8_str("age"),
SimpleAccessorGetter, SimpleAccessorSetter);
AddInterceptor(child, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"function setAge(i){ child.age = i; };"
"for(var i = 20000; i >= 9999; i--) setAge(i);");
// All i >= 10000 go to the accessor.
ExpectInt32("child.accessor_age", 10000);
// The last i goes to the interceptor.
ExpectInt32("child.interceptor_age", 9999);
}
THREADED_TEST(SwitchFromInterceptorToJSAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> templ = FunctionTemplate::New();
AddInterceptor(templ, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Obj"), templ->GetFunction());
CompileRun("var obj = new Obj;"
"function setter(i) { this.accessor_age = i; };"
"function getter() { return this.accessor_age; };"
"function setAge(i) { obj.age = i; };"
"Object.defineProperty(obj, 'age', { get:getter, set:setter });"
"for(var i = 0; i <= 10000; i++) setAge(i);");
// All i < 10000 go to the interceptor.
ExpectInt32("obj.interceptor_age", 9999);
// The last i goes to the JavaScript accessor.
ExpectInt32("obj.accessor_age", 10000);
// The installed JavaScript getter is still intact.
// This last part is a regression test for issue 1651 and relies on the fact
// that both interceptor and accessor are being installed on the same object.
ExpectInt32("obj.age", 10000);
ExpectBoolean("obj.hasOwnProperty('age')", true);
ExpectUndefined("Object.getOwnPropertyDescriptor(obj, 'age').value");
}
THREADED_TEST(SwitchFromJSAccessorToInterceptor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> templ = FunctionTemplate::New();
AddInterceptor(templ, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Obj"), templ->GetFunction());
CompileRun("var obj = new Obj;"
"function setter(i) { this.accessor_age = i; };"
"function getter() { return this.accessor_age; };"
"function setAge(i) { obj.age = i; };"
"Object.defineProperty(obj, 'age', { get:getter, set:setter });"
"for(var i = 20000; i >= 9999; i--) setAge(i);");
// All i >= 10000 go to the accessor.
ExpectInt32("obj.accessor_age", 10000);
// The last i goes to the interceptor.
ExpectInt32("obj.interceptor_age", 9999);
// The installed JavaScript getter is still intact.
// This last part is a regression test for issue 1651 and relies on the fact
// that both interceptor and accessor are being installed on the same object.
ExpectInt32("obj.age", 10000);
ExpectBoolean("obj.hasOwnProperty('age')", true);
ExpectUndefined("Object.getOwnPropertyDescriptor(obj, 'age').value");
}
THREADED_TEST(SwitchFromInterceptorToProperty) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddInterceptor(child, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"function setAge(i){ child.age = i; };"
"for(var i = 0; i <= 10000; i++) setAge(i);");
// All i < 10000 go to the interceptor.
ExpectInt32("child.interceptor_age", 9999);
// The last i goes to child's own property.
ExpectInt32("child.age", 10000);
}
THREADED_TEST(SwitchFromPropertyToInterceptor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> parent = FunctionTemplate::New();
Handle<FunctionTemplate> child = FunctionTemplate::New();
child->Inherit(parent);
AddInterceptor(child, InterceptorGetter, InterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Child"), child->GetFunction());
CompileRun("var child = new Child;"
"function setAge(i){ child.age = i; };"
"for(var i = 20000; i >= 9999; i--) setAge(i);");
// All i >= 10000 go to child's own property.
ExpectInt32("child.age", 10000);
// The last i goes to the interceptor.
ExpectInt32("child.interceptor_age", 9999);
}
THREADED_TEST(NamedPropertyHandlerGetter) {
echo_named_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->InstanceTemplate()->SetNamedPropertyHandler(EchoNamedProperty,
0, 0, 0, 0,
v8_str("data"));
LocalContext env;
env->Global()->Set(v8_str("obj"),
templ->GetFunction()->NewInstance());
CHECK_EQ(echo_named_call_count, 0);
v8_compile("obj.x")->Run();
CHECK_EQ(echo_named_call_count, 1);
const char* code = "var str = 'oddle'; obj[str] + obj.poddle;";
v8::Handle<Value> str = CompileRun(code);
String::Utf8Value value(str);
CHECK_EQ(*value, "oddlepoddle");
// Check default behavior
CHECK_EQ(v8_compile("obj.flob = 10;")->Run()->Int32Value(), 10);
CHECK(v8_compile("'myProperty' in obj")->Run()->BooleanValue());
CHECK(v8_compile("delete obj.myProperty")->Run()->BooleanValue());
}
int echo_indexed_call_count = 0;
static void EchoIndexedProperty(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(v8_num(637), info.Data());
echo_indexed_call_count++;
info.GetReturnValue().Set(v8_num(index));
}
THREADED_TEST(IndexedPropertyHandlerGetter) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->InstanceTemplate()->SetIndexedPropertyHandler(EchoIndexedProperty,
0, 0, 0, 0,
v8_num(637));
LocalContext env;
env->Global()->Set(v8_str("obj"),
templ->GetFunction()->NewInstance());
Local<Script> script = v8_compile("obj[900]");
CHECK_EQ(script->Run()->Int32Value(), 900);
}
v8::Handle<v8::Object> bottom;
static void CheckThisIndexedPropertyHandler(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisIndexedPropertyHandler));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
static void CheckThisNamedPropertyHandler(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisNamedPropertyHandler));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisIndexedPropertySetter(
uint32_t index,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisIndexedPropertySetter));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisNamedPropertySetter(
Local<String> property,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisNamedPropertySetter));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisIndexedPropertyQuery(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Integer>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisIndexedPropertyQuery));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisNamedPropertyQuery(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Integer>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisNamedPropertyQuery));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisIndexedPropertyDeleter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Boolean>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisIndexedPropertyDeleter));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisNamedPropertyDeleter(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Boolean>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisNamedPropertyDeleter));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisIndexedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisIndexedPropertyEnumerator));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
void CheckThisNamedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
CheckReturnValue(info, FUNCTION_ADDR(CheckThisNamedPropertyEnumerator));
ApiTestFuzzer::Fuzz();
CHECK(info.This()->Equals(bottom));
}
THREADED_PROFILED_TEST(PropertyHandlerInPrototype) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// Set up a prototype chain with three interceptors.
v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->InstanceTemplate()->SetIndexedPropertyHandler(
CheckThisIndexedPropertyHandler,
CheckThisIndexedPropertySetter,
CheckThisIndexedPropertyQuery,
CheckThisIndexedPropertyDeleter,
CheckThisIndexedPropertyEnumerator);
templ->InstanceTemplate()->SetNamedPropertyHandler(
CheckThisNamedPropertyHandler,
CheckThisNamedPropertySetter,
CheckThisNamedPropertyQuery,
CheckThisNamedPropertyDeleter,
CheckThisNamedPropertyEnumerator);
bottom = templ->GetFunction()->NewInstance();
Local<v8::Object> top = templ->GetFunction()->NewInstance();
Local<v8::Object> middle = templ->GetFunction()->NewInstance();
bottom->SetPrototype(middle);
middle->SetPrototype(top);
env->Global()->Set(v8_str("obj"), bottom);
// Indexed and named get.
Script::Compile(v8_str("obj[0]"))->Run();
Script::Compile(v8_str("obj.x"))->Run();
// Indexed and named set.
Script::Compile(v8_str("obj[1] = 42"))->Run();
Script::Compile(v8_str("obj.y = 42"))->Run();
// Indexed and named query.
Script::Compile(v8_str("0 in obj"))->Run();
Script::Compile(v8_str("'x' in obj"))->Run();
// Indexed and named deleter.
Script::Compile(v8_str("delete obj[0]"))->Run();
Script::Compile(v8_str("delete obj.x"))->Run();
// Enumerators.
Script::Compile(v8_str("for (var p in obj) ;"))->Run();
}
static void PrePropertyHandlerGet(
Local<String> key,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (v8_str("pre")->Equals(key)) {
info.GetReturnValue().Set(v8_str("PrePropertyHandler: pre"));
}
}
static void PrePropertyHandlerQuery(
Local<String> key,
const v8::PropertyCallbackInfo<v8::Integer>& info) {
if (v8_str("pre")->Equals(key)) {
info.GetReturnValue().Set(static_cast<int32_t>(v8::None));
}
}
THREADED_TEST(PrePropertyHandler) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> desc = v8::FunctionTemplate::New();
desc->InstanceTemplate()->SetNamedPropertyHandler(PrePropertyHandlerGet,
0,
PrePropertyHandlerQuery);
LocalContext env(NULL, desc->InstanceTemplate());
Script::Compile(v8_str(
"var pre = 'Object: pre'; var on = 'Object: on';"))->Run();
v8::Handle<Value> result_pre = Script::Compile(v8_str("pre"))->Run();
CHECK_EQ(v8_str("PrePropertyHandler: pre"), result_pre);
v8::Handle<Value> result_on = Script::Compile(v8_str("on"))->Run();
CHECK_EQ(v8_str("Object: on"), result_on);
v8::Handle<Value> result_post = Script::Compile(v8_str("post"))->Run();
CHECK(result_post.IsEmpty());
}
THREADED_TEST(UndefinedIsNotEnumerable) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<Value> result = Script::Compile(v8_str(
"this.propertyIsEnumerable(undefined)"))->Run();
CHECK(result->IsFalse());
}
v8::Handle<Script> call_recursively_script;
static const int kTargetRecursionDepth = 200; // near maximum
static void CallScriptRecursivelyCall(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
int depth = args.This()->Get(v8_str("depth"))->Int32Value();
if (depth == kTargetRecursionDepth) return;
args.This()->Set(v8_str("depth"), v8::Integer::New(depth + 1));
args.GetReturnValue().Set(call_recursively_script->Run());
}
static void CallFunctionRecursivelyCall(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
int depth = args.This()->Get(v8_str("depth"))->Int32Value();
if (depth == kTargetRecursionDepth) {
printf("[depth = %d]\n", depth);
return;
}
args.This()->Set(v8_str("depth"), v8::Integer::New(depth + 1));
v8::Handle<Value> function =
args.This()->Get(v8_str("callFunctionRecursively"));
args.GetReturnValue().Set(
function.As<Function>()->Call(args.This(), 0, NULL));
}
THREADED_TEST(DeepCrossLanguageRecursion) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> global = ObjectTemplate::New();
global->Set(v8_str("callScriptRecursively"),
v8::FunctionTemplate::New(CallScriptRecursivelyCall));
global->Set(v8_str("callFunctionRecursively"),
v8::FunctionTemplate::New(CallFunctionRecursivelyCall));
LocalContext env(NULL, global);
env->Global()->Set(v8_str("depth"), v8::Integer::New(0));
call_recursively_script = v8_compile("callScriptRecursively()");
call_recursively_script->Run();
call_recursively_script = v8::Handle<Script>();
env->Global()->Set(v8_str("depth"), v8::Integer::New(0));
Script::Compile(v8_str("callFunctionRecursively()"))->Run();
}
static void ThrowingPropertyHandlerGet(
Local<String> key,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(v8::ThrowException(key));
}
static void ThrowingPropertyHandlerSet(
Local<String> key,
Local<Value>,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::ThrowException(key);
info.GetReturnValue().SetUndefined(); // not the same as empty handle
}
THREADED_TEST(CallbackExceptionRegression) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj = ObjectTemplate::New();
obj->SetNamedPropertyHandler(ThrowingPropertyHandlerGet,
ThrowingPropertyHandlerSet);
LocalContext env;
env->Global()->Set(v8_str("obj"), obj->NewInstance());
v8::Handle<Value> otto = Script::Compile(v8_str(
"try { with (obj) { otto; } } catch (e) { e; }"))->Run();
CHECK_EQ(v8_str("otto"), otto);
v8::Handle<Value> netto = Script::Compile(v8_str(
"try { with (obj) { netto = 4; } } catch (e) { e; }"))->Run();
CHECK_EQ(v8_str("netto"), netto);
}
THREADED_TEST(FunctionPrototype) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<v8::FunctionTemplate> Foo = v8::FunctionTemplate::New();
Foo->PrototypeTemplate()->Set(v8_str("plak"), v8_num(321));
LocalContext env;
env->Global()->Set(v8_str("Foo"), Foo->GetFunction());
Local<Script> script = Script::Compile(v8_str("Foo.prototype.plak"));
CHECK_EQ(script->Run()->Int32Value(), 321);
}
THREADED_TEST(InternalFields) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
Local<v8::ObjectTemplate> instance_templ = templ->InstanceTemplate();
instance_templ->SetInternalFieldCount(1);
Local<v8::Object> obj = templ->GetFunction()->NewInstance();
CHECK_EQ(1, obj->InternalFieldCount());
CHECK(obj->GetInternalField(0)->IsUndefined());
obj->SetInternalField(0, v8_num(17));
CHECK_EQ(17, obj->GetInternalField(0)->Int32Value());
}
THREADED_TEST(GlobalObjectInternalFields) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetInternalFieldCount(1);
LocalContext env(NULL, global_template);
v8::Handle<v8::Object> global_proxy = env->Global();
v8::Handle<v8::Object> global = global_proxy->GetPrototype().As<v8::Object>();
CHECK_EQ(1, global->InternalFieldCount());
CHECK(global->GetInternalField(0)->IsUndefined());
global->SetInternalField(0, v8_num(17));
CHECK_EQ(17, global->GetInternalField(0)->Int32Value());
}
THREADED_TEST(GlobalObjectHasRealIndexedProperty) {
LocalContext env;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<v8::Object> global = env->Global();
global->Set(0, v8::String::New("value"));
CHECK(global->HasRealIndexedProperty(0));
}
static void CheckAlignedPointerInInternalField(Handle<v8::Object> obj,
void* value) {
CHECK_EQ(0, static_cast<int>(reinterpret_cast<uintptr_t>(value) & 0x1));
obj->SetAlignedPointerInInternalField(0, value);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(value, obj->GetAlignedPointerFromInternalField(0));
}
THREADED_TEST(InternalFieldsAlignedPointers) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
Local<v8::ObjectTemplate> instance_templ = templ->InstanceTemplate();
instance_templ->SetInternalFieldCount(1);
Local<v8::Object> obj = templ->GetFunction()->NewInstance();
CHECK_EQ(1, obj->InternalFieldCount());
CheckAlignedPointerInInternalField(obj, NULL);
int* heap_allocated = new int[100];
CheckAlignedPointerInInternalField(obj, heap_allocated);
delete[] heap_allocated;
int stack_allocated[100];
CheckAlignedPointerInInternalField(obj, stack_allocated);
void* huge = reinterpret_cast<void*>(~static_cast<uintptr_t>(1));
CheckAlignedPointerInInternalField(obj, huge);
}
static void CheckAlignedPointerInEmbedderData(LocalContext* env,
int index,
void* value) {
CHECK_EQ(0, static_cast<int>(reinterpret_cast<uintptr_t>(value) & 0x1));
(*env)->SetAlignedPointerInEmbedderData(index, value);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(value, (*env)->GetAlignedPointerFromEmbedderData(index));
}
static void* AlignedTestPointer(int i) {
return reinterpret_cast<void*>(i * 1234);
}
THREADED_TEST(EmbedderDataAlignedPointers) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
CheckAlignedPointerInEmbedderData(&env, 0, NULL);
int* heap_allocated = new int[100];
CheckAlignedPointerInEmbedderData(&env, 1, heap_allocated);
delete[] heap_allocated;
int stack_allocated[100];
CheckAlignedPointerInEmbedderData(&env, 2, stack_allocated);
void* huge = reinterpret_cast<void*>(~static_cast<uintptr_t>(1));
CheckAlignedPointerInEmbedderData(&env, 3, huge);
// Test growing of the embedder data's backing store.
for (int i = 0; i < 100; i++) {
env->SetAlignedPointerInEmbedderData(i, AlignedTestPointer(i));
}
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
for (int i = 0; i < 100; i++) {
CHECK_EQ(AlignedTestPointer(i), env->GetAlignedPointerFromEmbedderData(i));
}
}
static void CheckEmbedderData(LocalContext* env,
int index,
v8::Handle<Value> data) {
(*env)->SetEmbedderData(index, data);
CHECK((*env)->GetEmbedderData(index)->StrictEquals(data));
}
THREADED_TEST(EmbedderData) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
CheckEmbedderData(&env, 3, v8::String::New("The quick brown fox jumps"));
CheckEmbedderData(&env, 2, v8::String::New("over the lazy dog."));
CheckEmbedderData(&env, 1, v8::Number::New(1.2345));
CheckEmbedderData(&env, 0, v8::Boolean::New(true));
}
THREADED_TEST(IdentityHash) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// Ensure that the test starts with an fresh heap to test whether the hash
// code is based on the address.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
Local<v8::Object> obj = v8::Object::New();
int hash = obj->GetIdentityHash();
int hash1 = obj->GetIdentityHash();
CHECK_EQ(hash, hash1);
int hash2 = v8::Object::New()->GetIdentityHash();
// Since the identity hash is essentially a random number two consecutive
// objects should not be assigned the same hash code. If the test below fails
// the random number generator should be evaluated.
CHECK_NE(hash, hash2);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
int hash3 = v8::Object::New()->GetIdentityHash();
// Make sure that the identity hash is not based on the initial address of
// the object alone. If the test below fails the random number generator
// should be evaluated.
CHECK_NE(hash, hash3);
int hash4 = obj->GetIdentityHash();
CHECK_EQ(hash, hash4);
// Check identity hashes behaviour in the presence of JS accessors.
// Put a getter for 'v8::IdentityHash' on the Object's prototype:
{
CompileRun("Object.prototype['v8::IdentityHash'] = 42;\n");
Local<v8::Object> o1 = v8::Object::New();
Local<v8::Object> o2 = v8::Object::New();
CHECK_NE(o1->GetIdentityHash(), o2->GetIdentityHash());
}
{
CompileRun(
"function cnst() { return 42; };\n"
"Object.prototype.__defineGetter__('v8::IdentityHash', cnst);\n");
Local<v8::Object> o1 = v8::Object::New();
Local<v8::Object> o2 = v8::Object::New();
CHECK_NE(o1->GetIdentityHash(), o2->GetIdentityHash());
}
}
THREADED_TEST(SymbolProperties) {
i::FLAG_harmony_symbols = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> obj = v8::Object::New();
v8::Local<v8::Symbol> sym1 = v8::Symbol::New(isolate);
v8::Local<v8::Symbol> sym2 = v8::Symbol::New(isolate, "my-symbol");
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
// Check basic symbol functionality.
CHECK(sym1->IsSymbol());
CHECK(sym2->IsSymbol());
CHECK(!obj->IsSymbol());
CHECK(sym1->Equals(sym1));
CHECK(sym2->Equals(sym2));
CHECK(!sym1->Equals(sym2));
CHECK(!sym2->Equals(sym1));
CHECK(sym1->StrictEquals(sym1));
CHECK(sym2->StrictEquals(sym2));
CHECK(!sym1->StrictEquals(sym2));
CHECK(!sym2->StrictEquals(sym1));
CHECK(sym2->Name()->Equals(v8::String::New("my-symbol")));
v8::Local<v8::Value> sym_val = sym2;
CHECK(sym_val->IsSymbol());
CHECK(sym_val->Equals(sym2));
CHECK(sym_val->StrictEquals(sym2));
CHECK(v8::Symbol::Cast(*sym_val)->Equals(sym2));
v8::Local<v8::Value> sym_obj = v8::SymbolObject::New(isolate, sym2);
CHECK(sym_obj->IsSymbolObject());
CHECK(!sym2->IsSymbolObject());
CHECK(!obj->IsSymbolObject());
CHECK(sym_obj->Equals(sym2));
CHECK(!sym_obj->StrictEquals(sym2));
CHECK(v8::SymbolObject::Cast(*sym_obj)->Equals(sym_obj));
CHECK(v8::SymbolObject::Cast(*sym_obj)->ValueOf()->Equals(sym2));
// Make sure delete of a non-existent symbol property works.
CHECK(obj->Delete(sym1));
CHECK(!obj->Has(sym1));
CHECK(obj->Set(sym1, v8::Integer::New(1503)));
CHECK(obj->Has(sym1));
CHECK_EQ(1503, obj->Get(sym1)->Int32Value());
CHECK(obj->Set(sym1, v8::Integer::New(2002)));
CHECK(obj->Has(sym1));
CHECK_EQ(2002, obj->Get(sym1)->Int32Value());
CHECK_EQ(v8::None, obj->GetPropertyAttributes(sym1));
CHECK_EQ(0, obj->GetOwnPropertyNames()->Length());
int num_props = obj->GetPropertyNames()->Length();
CHECK(obj->Set(v8::String::New("bla"), v8::Integer::New(20)));
CHECK_EQ(1, obj->GetOwnPropertyNames()->Length());
CHECK_EQ(num_props + 1, obj->GetPropertyNames()->Length());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
// Add another property and delete it afterwards to force the object in
// slow case.
CHECK(obj->Set(sym2, v8::Integer::New(2008)));
CHECK_EQ(2002, obj->Get(sym1)->Int32Value());
CHECK_EQ(2008, obj->Get(sym2)->Int32Value());
CHECK_EQ(2002, obj->Get(sym1)->Int32Value());
CHECK_EQ(1, obj->GetOwnPropertyNames()->Length());
CHECK(obj->Has(sym1));
CHECK(obj->Has(sym2));
CHECK(obj->Delete(sym2));
CHECK(obj->Has(sym1));
CHECK(!obj->Has(sym2));
CHECK_EQ(2002, obj->Get(sym1)->Int32Value());
CHECK_EQ(1, obj->GetOwnPropertyNames()->Length());
}
class ScopedArrayBufferContents {
public:
explicit ScopedArrayBufferContents(
const v8::ArrayBuffer::Contents& contents)
: contents_(contents) {}
~ScopedArrayBufferContents() { free(contents_.Data()); }
void* Data() const { return contents_.Data(); }
size_t ByteLength() const { return contents_.ByteLength(); }
private:
const v8::ArrayBuffer::Contents contents_;
};
template <typename T>
static void CheckInternalFieldsAreZero(v8::Handle<T> value) {
CHECK_EQ(T::kInternalFieldCount, value->InternalFieldCount());
for (int i = 0; i < value->InternalFieldCount(); i++) {
CHECK_EQ(0, value->GetInternalField(i)->Int32Value());
}
}
THREADED_TEST(ArrayBuffer_ApiInternalToExternal) {
i::FLAG_harmony_array_buffer = true;
i::FLAG_harmony_typed_arrays = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(1024);
CheckInternalFieldsAreZero(ab);
CHECK_EQ(1024, static_cast<int>(ab->ByteLength()));
CHECK(!ab->IsExternal());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
ScopedArrayBufferContents ab_contents(ab->Externalize());
CHECK(ab->IsExternal());
CHECK_EQ(1024, static_cast<int>(ab_contents.ByteLength()));
uint8_t* data = static_cast<uint8_t*>(ab_contents.Data());
ASSERT(data != NULL);
env->Global()->Set(v8_str("ab"), ab);
v8::Handle<v8::Value> result = CompileRun("ab.byteLength");
CHECK_EQ(1024, result->Int32Value());
result = CompileRun("var u8 = new Uint8Array(ab);"
"u8[0] = 0xFF;"
"u8[1] = 0xAA;"
"u8.length");
CHECK_EQ(1024, result->Int32Value());
CHECK_EQ(0xFF, data[0]);
CHECK_EQ(0xAA, data[1]);
data[0] = 0xCC;
data[1] = 0x11;
result = CompileRun("u8[0] + u8[1]");
CHECK_EQ(0xDD, result->Int32Value());
}
THREADED_TEST(ArrayBuffer_JSInternalToExternal) {
i::FLAG_harmony_array_buffer = true;
i::FLAG_harmony_typed_arrays = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Value> result =
CompileRun("var ab1 = new ArrayBuffer(2);"
"var u8_a = new Uint8Array(ab1);"
"u8_a[0] = 0xAA;"
"u8_a[1] = 0xFF; u8_a.buffer");
Local<v8::ArrayBuffer> ab1 = Local<v8::ArrayBuffer>::Cast(result);
CheckInternalFieldsAreZero(ab1);
CHECK_EQ(2, static_cast<int>(ab1->ByteLength()));
CHECK(!ab1->IsExternal());
ScopedArrayBufferContents ab1_contents(ab1->Externalize());
CHECK(ab1->IsExternal());
result = CompileRun("ab1.byteLength");
CHECK_EQ(2, result->Int32Value());
result = CompileRun("u8_a[0]");
CHECK_EQ(0xAA, result->Int32Value());
result = CompileRun("u8_a[1]");
CHECK_EQ(0xFF, result->Int32Value());
result = CompileRun("var u8_b = new Uint8Array(ab1);"
"u8_b[0] = 0xBB;"
"u8_a[0]");
CHECK_EQ(0xBB, result->Int32Value());
result = CompileRun("u8_b[1]");
CHECK_EQ(0xFF, result->Int32Value());
CHECK_EQ(2, static_cast<int>(ab1_contents.ByteLength()));
uint8_t* ab1_data = static_cast<uint8_t*>(ab1_contents.Data());
CHECK_EQ(0xBB, ab1_data[0]);
CHECK_EQ(0xFF, ab1_data[1]);
ab1_data[0] = 0xCC;
ab1_data[1] = 0x11;
result = CompileRun("u8_a[0] + u8_a[1]");
CHECK_EQ(0xDD, result->Int32Value());
}
THREADED_TEST(ArrayBuffer_External) {
i::FLAG_harmony_array_buffer = true;
i::FLAG_harmony_typed_arrays = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
i::ScopedVector<uint8_t> my_data(100);
memset(my_data.start(), 0, 100);
Local<v8::ArrayBuffer> ab3 = v8::ArrayBuffer::New(my_data.start(), 100);
CheckInternalFieldsAreZero(ab3);
CHECK_EQ(100, static_cast<int>(ab3->ByteLength()));
CHECK(ab3->IsExternal());
env->Global()->Set(v8_str("ab3"), ab3);
v8::Handle<v8::Value> result = CompileRun("ab3.byteLength");
CHECK_EQ(100, result->Int32Value());
result = CompileRun("var u8_b = new Uint8Array(ab3);"
"u8_b[0] = 0xBB;"
"u8_b[1] = 0xCC;"
"u8_b.length");
CHECK_EQ(100, result->Int32Value());
CHECK_EQ(0xBB, my_data[0]);
CHECK_EQ(0xCC, my_data[1]);
my_data[0] = 0xCC;
my_data[1] = 0x11;
result = CompileRun("u8_b[0] + u8_b[1]");
CHECK_EQ(0xDD, result->Int32Value());
}
static void CheckDataViewIsNeutered(v8::Handle<v8::DataView> dv) {
CHECK_EQ(0, static_cast<int>(dv->ByteLength()));
CHECK_EQ(0, static_cast<int>(dv->ByteOffset()));
}
static void CheckIsNeutered(v8::Handle<v8::TypedArray> ta) {
CHECK_EQ(0, static_cast<int>(ta->ByteLength()));
CHECK_EQ(0, static_cast<int>(ta->Length()));
CHECK_EQ(0, static_cast<int>(ta->ByteOffset()));
}
static void CheckIsTypedArrayVarNeutered(const char* name) {
i::ScopedVector<char> source(1024);
i::OS::SNPrintF(source,
"%s.byteLength == 0 && %s.byteOffset == 0 && %s.length == 0",
name, name, name);
CHECK(CompileRun(source.start())->IsTrue());
v8::Handle<v8::TypedArray> ta =
v8::Handle<v8::TypedArray>::Cast(CompileRun(name));
CheckIsNeutered(ta);
}
template <typename TypedArray, int kElementSize>
static Handle<TypedArray> CreateAndCheck(Handle<v8::ArrayBuffer> ab,
int byteOffset,
int length) {
v8::Handle<TypedArray> ta = TypedArray::New(ab, byteOffset, length);
CheckInternalFieldsAreZero<v8::ArrayBufferView>(ta);
CHECK_EQ(byteOffset, static_cast<int>(ta->ByteOffset()));
CHECK_EQ(length, static_cast<int>(ta->Length()));
CHECK_EQ(length * kElementSize, static_cast<int>(ta->ByteLength()));
return ta;
}
THREADED_TEST(ArrayBuffer_NeuteringApi) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::ArrayBuffer> buffer = v8::ArrayBuffer::New(1024);
v8::Handle<v8::Uint8Array> u8a =
CreateAndCheck<v8::Uint8Array, 1>(buffer, 1, 1023);
v8::Handle<v8::Uint8ClampedArray> u8c =
CreateAndCheck<v8::Uint8ClampedArray, 1>(buffer, 1, 1023);
v8::Handle<v8::Int8Array> i8a =
CreateAndCheck<v8::Int8Array, 1>(buffer, 1, 1023);
v8::Handle<v8::Uint16Array> u16a =
CreateAndCheck<v8::Uint16Array, 2>(buffer, 2, 511);
v8::Handle<v8::Int16Array> i16a =
CreateAndCheck<v8::Int16Array, 2>(buffer, 2, 511);
v8::Handle<v8::Uint32Array> u32a =
CreateAndCheck<v8::Uint32Array, 4>(buffer, 4, 255);
v8::Handle<v8::Int32Array> i32a =
CreateAndCheck<v8::Int32Array, 4>(buffer, 4, 255);
v8::Handle<v8::Float32Array> f32a =
CreateAndCheck<v8::Float32Array, 4>(buffer, 4, 255);
v8::Handle<v8::Float64Array> f64a =
CreateAndCheck<v8::Float64Array, 8>(buffer, 8, 127);
v8::Handle<v8::DataView> dv = v8::DataView::New(buffer, 1, 1023);
CheckInternalFieldsAreZero<v8::ArrayBufferView>(dv);
CHECK_EQ(1, static_cast<int>(dv->ByteOffset()));
CHECK_EQ(1023, static_cast<int>(dv->ByteLength()));
ScopedArrayBufferContents contents(buffer->Externalize());
buffer->Neuter();
CHECK_EQ(0, static_cast<int>(buffer->ByteLength()));
CheckIsNeutered(u8a);
CheckIsNeutered(u8c);
CheckIsNeutered(i8a);
CheckIsNeutered(u16a);
CheckIsNeutered(i16a);
CheckIsNeutered(u32a);
CheckIsNeutered(i32a);
CheckIsNeutered(f32a);
CheckIsNeutered(f64a);
CheckDataViewIsNeutered(dv);
}
THREADED_TEST(ArrayBuffer_NeuteringScript) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
CompileRun(
"var ab = new ArrayBuffer(1024);"
"var u8a = new Uint8Array(ab, 1, 1023);"
"var u8c = new Uint8ClampedArray(ab, 1, 1023);"
"var i8a = new Int8Array(ab, 1, 1023);"
"var u16a = new Uint16Array(ab, 2, 511);"
"var i16a = new Int16Array(ab, 2, 511);"
"var u32a = new Uint32Array(ab, 4, 255);"
"var i32a = new Int32Array(ab, 4, 255);"
"var f32a = new Float32Array(ab, 4, 255);"
"var f64a = new Float64Array(ab, 8, 127);"
"var dv = new DataView(ab, 1, 1023);");
v8::Handle<v8::ArrayBuffer> ab =
Local<v8::ArrayBuffer>::Cast(CompileRun("ab"));
v8::Handle<v8::DataView> dv =
v8::Handle<v8::DataView>::Cast(CompileRun("dv"));
ScopedArrayBufferContents contents(ab->Externalize());
ab->Neuter();
CHECK_EQ(0, static_cast<int>(ab->ByteLength()));
CHECK_EQ(0, CompileRun("ab.byteLength")->Int32Value());
CheckIsTypedArrayVarNeutered("u8a");
CheckIsTypedArrayVarNeutered("u8c");
CheckIsTypedArrayVarNeutered("i8a");
CheckIsTypedArrayVarNeutered("u16a");
CheckIsTypedArrayVarNeutered("i16a");
CheckIsTypedArrayVarNeutered("u32a");
CheckIsTypedArrayVarNeutered("i32a");
CheckIsTypedArrayVarNeutered("f32a");
CheckIsTypedArrayVarNeutered("f64a");
CHECK(CompileRun("dv.byteLength == 0 && dv.byteOffset == 0")->IsTrue());
CheckDataViewIsNeutered(dv);
}
THREADED_TEST(HiddenProperties) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Local<v8::Object> obj = v8::Object::New();
v8::Local<v8::String> key = v8_str("api-test::hidden-key");
v8::Local<v8::String> empty = v8_str("");
v8::Local<v8::String> prop_name = v8_str("prop_name");
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
// Make sure delete of a non-existent hidden value works
CHECK(obj->DeleteHiddenValue(key));
CHECK(obj->SetHiddenValue(key, v8::Integer::New(1503)));
CHECK_EQ(1503, obj->GetHiddenValue(key)->Int32Value());
CHECK(obj->SetHiddenValue(key, v8::Integer::New(2002)));
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
// Make sure we do not find the hidden property.
CHECK(!obj->Has(empty));
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
CHECK(obj->Get(empty)->IsUndefined());
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
CHECK(obj->Set(empty, v8::Integer::New(2003)));
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
CHECK_EQ(2003, obj->Get(empty)->Int32Value());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
// Add another property and delete it afterwards to force the object in
// slow case.
CHECK(obj->Set(prop_name, v8::Integer::New(2008)));
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
CHECK_EQ(2008, obj->Get(prop_name)->Int32Value());
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
CHECK(obj->Delete(prop_name));
CHECK_EQ(2002, obj->GetHiddenValue(key)->Int32Value());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK(obj->SetHiddenValue(key, Handle<Value>()));
CHECK(obj->GetHiddenValue(key).IsEmpty());
CHECK(obj->SetHiddenValue(key, v8::Integer::New(2002)));
CHECK(obj->DeleteHiddenValue(key));
CHECK(obj->GetHiddenValue(key).IsEmpty());
}
THREADED_TEST(Regress97784) {
// Regression test for crbug.com/97784
// Messing with the Object.prototype should not have effect on
// hidden properties.
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Local<v8::Object> obj = v8::Object::New();
v8::Local<v8::String> key = v8_str("hidden");
CompileRun(
"set_called = false;"
"Object.defineProperty("
" Object.prototype,"
" 'hidden',"
" {get: function() { return 45; },"
" set: function() { set_called = true; }})");
CHECK(obj->GetHiddenValue(key).IsEmpty());
// Make sure that the getter and setter from Object.prototype is not invoked.
// If it did we would have full access to the hidden properties in
// the accessor.
CHECK(obj->SetHiddenValue(key, v8::Integer::New(42)));
ExpectFalse("set_called");
CHECK_EQ(42, obj->GetHiddenValue(key)->Int32Value());
}
static bool interceptor_for_hidden_properties_called;
static void InterceptorForHiddenProperties(
Local<String> name, const v8::PropertyCallbackInfo<v8::Value>& info) {
interceptor_for_hidden_properties_called = true;
}
THREADED_TEST(HiddenPropertiesWithInterceptors) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
interceptor_for_hidden_properties_called = false;
v8::Local<v8::String> key = v8_str("api-test::hidden-key");
// Associate an interceptor with an object and start setting hidden values.
Local<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
Local<v8::ObjectTemplate> instance_templ = fun_templ->InstanceTemplate();
instance_templ->SetNamedPropertyHandler(InterceptorForHiddenProperties);
Local<v8::Function> function = fun_templ->GetFunction();
Local<v8::Object> obj = function->NewInstance();
CHECK(obj->SetHiddenValue(key, v8::Integer::New(2302)));
CHECK_EQ(2302, obj->GetHiddenValue(key)->Int32Value());
CHECK(!interceptor_for_hidden_properties_called);
}
THREADED_TEST(External) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
int x = 3;
Local<v8::External> ext = v8::External::New(&x);
LocalContext env;
env->Global()->Set(v8_str("ext"), ext);
Local<Value> reext_obj = Script::Compile(v8_str("this.ext"))->Run();
v8::Handle<v8::External> reext = reext_obj.As<v8::External>();
int* ptr = static_cast<int*>(reext->Value());
CHECK_EQ(x, 3);
*ptr = 10;
CHECK_EQ(x, 10);
// Make sure unaligned pointers are wrapped properly.
char* data = i::StrDup("0123456789");
Local<v8::Value> zero = v8::External::New(&data[0]);
Local<v8::Value> one = v8::External::New(&data[1]);
Local<v8::Value> two = v8::External::New(&data[2]);
Local<v8::Value> three = v8::External::New(&data[3]);
char* char_ptr = reinterpret_cast<char*>(v8::External::Cast(*zero)->Value());
CHECK_EQ('0', *char_ptr);
char_ptr = reinterpret_cast<char*>(v8::External::Cast(*one)->Value());
CHECK_EQ('1', *char_ptr);
char_ptr = reinterpret_cast<char*>(v8::External::Cast(*two)->Value());
CHECK_EQ('2', *char_ptr);
char_ptr = reinterpret_cast<char*>(v8::External::Cast(*three)->Value());
CHECK_EQ('3', *char_ptr);
i::DeleteArray(data);
}
THREADED_TEST(GlobalHandle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Persistent<String> global;
{
v8::HandleScope scope(isolate);
global.Reset(isolate, v8_str("str"));
}
{
v8::HandleScope scope(isolate);
CHECK_EQ(v8::Local<String>::New(isolate, global)->Length(), 3);
}
global.Dispose();
global.Clear();
{
v8::HandleScope scope(isolate);
global.Reset(isolate, v8_str("str"));
}
{
v8::HandleScope scope(isolate);
CHECK_EQ(v8::Local<String>::New(isolate, global)->Length(), 3);
}
global.Dispose();
}
THREADED_TEST(ResettingGlobalHandle) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Persistent<String> global;
{
v8::HandleScope scope(isolate);
global.Reset(isolate, v8_str("str"));
}
v8::internal::GlobalHandles* global_handles =
reinterpret_cast<v8::internal::Isolate*>(isolate)->global_handles();
int initial_handle_count = global_handles->global_handles_count();
{
v8::HandleScope scope(isolate);
CHECK_EQ(v8::Local<String>::New(isolate, global)->Length(), 3);
}
{
v8::HandleScope scope(isolate);
global.Reset(isolate, v8_str("longer"));
}
CHECK_EQ(global_handles->global_handles_count(), initial_handle_count);
{
v8::HandleScope scope(isolate);
CHECK_EQ(v8::Local<String>::New(isolate, global)->Length(), 6);
}
global.Dispose(isolate);
CHECK_EQ(global_handles->global_handles_count(), initial_handle_count - 1);
}
THREADED_TEST(ResettingGlobalHandleToEmpty) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Persistent<String> global;
{
v8::HandleScope scope(isolate);
global.Reset(isolate, v8_str("str"));
}
v8::internal::GlobalHandles* global_handles =
reinterpret_cast<v8::internal::Isolate*>(isolate)->global_handles();
int initial_handle_count = global_handles->global_handles_count();
{
v8::HandleScope scope(isolate);
CHECK_EQ(v8::Local<String>::New(isolate, global)->Length(), 3);
}
{
v8::HandleScope scope(isolate);
Local<String> empty;
global.Reset(isolate, empty);
}
CHECK(global.IsEmpty());
CHECK_EQ(global_handles->global_handles_count(), initial_handle_count - 1);
}
THREADED_TEST(ClearAndLeakGlobal) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::internal::GlobalHandles* global_handles = NULL;
int initial_handle_count = 0;
v8::Persistent<String> global;
{
v8::HandleScope scope(isolate);
Local<String> str = v8_str("str");
global_handles =
reinterpret_cast<v8::internal::Isolate*>(isolate)->global_handles();
initial_handle_count = global_handles->global_handles_count();
global.Reset(isolate, str);
}
CHECK_EQ(global_handles->global_handles_count(), initial_handle_count + 1);
String* str = global.ClearAndLeak();
CHECK(global.IsEmpty());
CHECK_EQ(global_handles->global_handles_count(), initial_handle_count + 1);
global_handles->Destroy(reinterpret_cast<i::Object**>(str));
CHECK_EQ(global_handles->global_handles_count(), initial_handle_count);
}
THREADED_TEST(GlobalHandleUpcast) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Local<String> local = v8::Local<String>::New(v8_str("str"));
v8::Persistent<String> global_string(isolate, local);
#ifdef V8_USE_UNSAFE_HANDLES
v8::Persistent<Value> global_value =
v8::Persistent<Value>::Cast(global_string);
#else
v8::Persistent<Value>& global_value =
v8::Persistent<Value>::Cast(global_string);
#endif
CHECK(v8::Local<v8::Value>::New(isolate, global_value)->IsString());
CHECK(global_string == v8::Persistent<String>::Cast(global_value));
global_string.Dispose();
}
THREADED_TEST(LocalHandle) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<String> local = v8::Local<String>::New(v8_str("str"));
CHECK_EQ(local->Length(), 3);
local = v8::Local<String>::New(v8::Isolate::GetCurrent(), v8_str("str"));
CHECK_EQ(local->Length(), 3);
}
class WeakCallCounter {
public:
explicit WeakCallCounter(int id) : id_(id), number_of_weak_calls_(0) { }
int id() { return id_; }
void increment() { number_of_weak_calls_++; }
int NumberOfWeakCalls() { return number_of_weak_calls_; }
private:
int id_;
int number_of_weak_calls_;
};
static void WeakPointerCallback(v8::Isolate* isolate,
Persistent<Value>* handle,
WeakCallCounter* counter) {
CHECK_EQ(1234, counter->id());
counter->increment();
handle->Dispose(isolate);
}
static UniqueId MakeUniqueId(const Persistent<Value>& p) {
return UniqueId(reinterpret_cast<uintptr_t>(*v8::Utils::OpenPersistent(p)));
}
THREADED_TEST(ApiObjectGroups) {
LocalContext env;
v8::Isolate* iso = env->GetIsolate();
HandleScope scope(iso);
Persistent<Value> g1s1;
Persistent<Value> g1s2;
Persistent<Value> g1c1;
Persistent<Value> g2s1;
Persistent<Value> g2s2;
Persistent<Value> g2c1;
WeakCallCounter counter(1234);
{
HandleScope scope(iso);
g1s1.Reset(iso, Object::New());
g1s2.Reset(iso, Object::New());
g1c1.Reset(iso, Object::New());
g1s1.MakeWeak(&counter, &WeakPointerCallback);
g1s2.MakeWeak(&counter, &WeakPointerCallback);
g1c1.MakeWeak(&counter, &WeakPointerCallback);
g2s1.Reset(iso, Object::New());
g2s2.Reset(iso, Object::New());
g2c1.Reset(iso, Object::New());
g2s1.MakeWeak(&counter, &WeakPointerCallback);
g2s2.MakeWeak(&counter, &WeakPointerCallback);
g2c1.MakeWeak(&counter, &WeakPointerCallback);
}
Persistent<Value> root(iso, g1s1); // make a root.
// Connect group 1 and 2, make a cycle.
{
HandleScope scope(iso);
CHECK(Local<Object>::New(iso, g1s2.As<Object>())->
Set(0, Local<Value>::New(iso, g2s2)));
CHECK(Local<Object>::New(iso, g2s1.As<Object>())->
Set(0, Local<Value>::New(iso, g1s1)));
}
{
UniqueId id1 = MakeUniqueId(g1s1);
UniqueId id2 = MakeUniqueId(g2s2);
iso->SetObjectGroupId(g1s1, id1);
iso->SetObjectGroupId(g1s2, id1);
iso->SetReferenceFromGroup(id1, g1c1);
iso->SetObjectGroupId(g2s1, id2);
iso->SetObjectGroupId(g2s2, id2);
iso->SetReferenceFromGroup(id2, g2c1);
}
// Do a single full GC, ensure incremental marking is stopped.
v8::internal::Heap* heap = reinterpret_cast<v8::internal::Isolate*>(
iso)->heap();
heap->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
// All object should be alive.
CHECK_EQ(0, counter.NumberOfWeakCalls());
// Weaken the root.
root.MakeWeak(&counter, &WeakPointerCallback);
// But make children strong roots---all the objects (except for children)
// should be collectable now.
g1c1.ClearWeak(iso);
g2c1.ClearWeak(iso);
// Groups are deleted, rebuild groups.
{
UniqueId id1 = MakeUniqueId(g1s1);
UniqueId id2 = MakeUniqueId(g2s2);
iso->SetObjectGroupId(g1s1, id1);
iso->SetObjectGroupId(g1s2, id1);
iso->SetReferenceFromGroup(id1, g1c1);
iso->SetObjectGroupId(g2s1, id2);
iso->SetObjectGroupId(g2s2, id2);
iso->SetReferenceFromGroup(id2, g2c1);
}
heap->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
// All objects should be gone. 5 global handles in total.
CHECK_EQ(5, counter.NumberOfWeakCalls());
// And now make children weak again and collect them.
g1c1.MakeWeak(&counter, &WeakPointerCallback);
g2c1.MakeWeak(&counter, &WeakPointerCallback);
heap->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
CHECK_EQ(7, counter.NumberOfWeakCalls());
}
THREADED_TEST(ApiObjectGroupsCycle) {
LocalContext env;
v8::Isolate* iso = env->GetIsolate();
HandleScope scope(iso);
WeakCallCounter counter(1234);
Persistent<Value> g1s1;
Persistent<Value> g1s2;
Persistent<Value> g2s1;
Persistent<Value> g2s2;
Persistent<Value> g3s1;
Persistent<Value> g3s2;
Persistent<Value> g4s1;
Persistent<Value> g4s2;
{
HandleScope scope(iso);
g1s1.Reset(iso, Object::New());
g1s2.Reset(iso, Object::New());
g1s1.MakeWeak(&counter, &WeakPointerCallback);
g1s2.MakeWeak(&counter, &WeakPointerCallback);
CHECK(g1s1.IsWeak(iso));
CHECK(g1s2.IsWeak(iso));
g2s1.Reset(iso, Object::New());
g2s2.Reset(iso, Object::New());
g2s1.MakeWeak(&counter, &WeakPointerCallback);
g2s2.MakeWeak(&counter, &WeakPointerCallback);
CHECK(g2s1.IsWeak(iso));
CHECK(g2s2.IsWeak(iso));
g3s1.Reset(iso, Object::New());
g3s2.Reset(iso, Object::New());
g3s1.MakeWeak(&counter, &WeakPointerCallback);
g3s2.MakeWeak(&counter, &WeakPointerCallback);
CHECK(g3s1.IsWeak(iso));
CHECK(g3s2.IsWeak(iso));
g4s1.Reset(iso, Object::New());
g4s2.Reset(iso, Object::New());
g4s1.MakeWeak(&counter, &WeakPointerCallback);
g4s2.MakeWeak(&counter, &WeakPointerCallback);
CHECK(g4s1.IsWeak(iso));
CHECK(g4s2.IsWeak(iso));
}
Persistent<Value> root(iso, g1s1); // make a root.
// Connect groups. We're building the following cycle:
// G1: { g1s1, g2s1 }, g1s1 implicitly references g2s1, ditto for other
// groups.
{
UniqueId id1 = MakeUniqueId(g1s1);
UniqueId id2 = MakeUniqueId(g2s1);
UniqueId id3 = MakeUniqueId(g3s1);
UniqueId id4 = MakeUniqueId(g4s1);
iso->SetObjectGroupId(g1s1, id1);
iso->SetObjectGroupId(g1s2, id1);
iso->SetReferenceFromGroup(id1, g2s1);
iso->SetObjectGroupId(g2s1, id2);
iso->SetObjectGroupId(g2s2, id2);
iso->SetReferenceFromGroup(id2, g3s1);
iso->SetObjectGroupId(g3s1, id3);
iso->SetObjectGroupId(g3s2, id3);
iso->SetReferenceFromGroup(id3, g4s1);
iso->SetObjectGroupId(g4s1, id4);
iso->SetObjectGroupId(g4s2, id4);
iso->SetReferenceFromGroup(id4, g1s1);
}
// Do a single full GC
v8::internal::Heap* heap = reinterpret_cast<v8::internal::Isolate*>(
iso)->heap();
heap->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
// All object should be alive.
CHECK_EQ(0, counter.NumberOfWeakCalls());
// Weaken the root.
root.MakeWeak(&counter, &WeakPointerCallback);
// Groups are deleted, rebuild groups.
{
UniqueId id1 = MakeUniqueId(g1s1);
UniqueId id2 = MakeUniqueId(g2s1);
UniqueId id3 = MakeUniqueId(g3s1);
UniqueId id4 = MakeUniqueId(g4s1);
iso->SetObjectGroupId(g1s1, id1);
iso->SetObjectGroupId(g1s2, id1);
iso->SetReferenceFromGroup(id1, g2s1);
iso->SetObjectGroupId(g2s1, id2);
iso->SetObjectGroupId(g2s2, id2);
iso->SetReferenceFromGroup(id2, g3s1);
iso->SetObjectGroupId(g3s1, id3);
iso->SetObjectGroupId(g3s2, id3);
iso->SetReferenceFromGroup(id3, g4s1);
iso->SetObjectGroupId(g4s1, id4);
iso->SetObjectGroupId(g4s2, id4);
iso->SetReferenceFromGroup(id4, g1s1);
}
heap->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
// All objects should be gone. 9 global handles in total.
CHECK_EQ(9, counter.NumberOfWeakCalls());
}
// TODO(mstarzinger): This should be a THREADED_TEST but causes failures
// on the buildbots, so was made non-threaded for the time being.
TEST(ApiObjectGroupsCycleForScavenger) {
i::FLAG_stress_compaction = false;
i::FLAG_gc_global = false;
LocalContext env;
v8::Isolate* iso = env->GetIsolate();
HandleScope scope(iso);
WeakCallCounter counter(1234);
Persistent<Value> g1s1;
Persistent<Value> g1s2;
Persistent<Value> g2s1;
Persistent<Value> g2s2;
Persistent<Value> g3s1;
Persistent<Value> g3s2;
{
HandleScope scope(iso);
g1s1.Reset(iso, Object::New());
g1s2.Reset(iso, Object::New());
g1s1.MakeWeak(&counter, &WeakPointerCallback);
g1s2.MakeWeak(&counter, &WeakPointerCallback);
g2s1.Reset(iso, Object::New());
g2s2.Reset(iso, Object::New());
g2s1.MakeWeak(&counter, &WeakPointerCallback);
g2s2.MakeWeak(&counter, &WeakPointerCallback);
g3s1.Reset(iso, Object::New());
g3s2.Reset(iso, Object::New());
g3s1.MakeWeak(&counter, &WeakPointerCallback);
g3s2.MakeWeak(&counter, &WeakPointerCallback);
}
// Make a root.
Persistent<Value> root(iso, g1s1);
root.MarkPartiallyDependent(iso);
// Connect groups. We're building the following cycle:
// G1: { g1s1, g2s1 }, g1s1 implicitly references g2s1, ditto for other
// groups.
{
HandleScope handle_scope(iso);
g1s1.MarkPartiallyDependent(iso);
g1s2.MarkPartiallyDependent(iso);
g2s1.MarkPartiallyDependent(iso);
g2s2.MarkPartiallyDependent(iso);
g3s1.MarkPartiallyDependent(iso);
g3s2.MarkPartiallyDependent(iso);
iso->SetObjectGroupId(g1s1, UniqueId(1));
iso->SetObjectGroupId(g1s2, UniqueId(1));
Local<Object>::New(iso, g1s1.As<Object>())->Set(
v8_str("x"), Local<Value>::New(iso, g2s1));
iso->SetObjectGroupId(g2s1, UniqueId(2));
iso->SetObjectGroupId(g2s2, UniqueId(2));
Local<Object>::New(iso, g2s1.As<Object>())->Set(
v8_str("x"), Local<Value>::New(iso, g3s1));
iso->SetObjectGroupId(g3s1, UniqueId(3));
iso->SetObjectGroupId(g3s2, UniqueId(3));
Local<Object>::New(iso, g3s1.As<Object>())->Set(
v8_str("x"), Local<Value>::New(iso, g1s1));
}
v8::internal::Heap* heap = reinterpret_cast<v8::internal::Isolate*>(
iso)->heap();
heap->CollectGarbage(i::NEW_SPACE);
// All objects should be alive.
CHECK_EQ(0, counter.NumberOfWeakCalls());
// Weaken the root.
root.MakeWeak(&counter, &WeakPointerCallback);
root.MarkPartiallyDependent(iso);
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// Groups are deleted, rebuild groups.
{
HandleScope handle_scope(iso);
g1s1.MarkPartiallyDependent(isolate);
g1s2.MarkPartiallyDependent(isolate);
g2s1.MarkPartiallyDependent(isolate);
g2s2.MarkPartiallyDependent(isolate);
g3s1.MarkPartiallyDependent(isolate);
g3s2.MarkPartiallyDependent(isolate);
iso->SetObjectGroupId(g1s1, UniqueId(1));
iso->SetObjectGroupId(g1s2, UniqueId(1));
Local<Object>::New(iso, g1s1.As<Object>())->Set(
v8_str("x"), Local<Value>::New(iso, g2s1));
iso->SetObjectGroupId(g2s1, UniqueId(2));
iso->SetObjectGroupId(g2s2, UniqueId(2));
Local<Object>::New(iso, g2s1.As<Object>())->Set(
v8_str("x"), Local<Value>::New(iso, g3s1));
iso->SetObjectGroupId(g3s1, UniqueId(3));
iso->SetObjectGroupId(g3s2, UniqueId(3));
Local<Object>::New(iso, g3s1.As<Object>())->Set(
v8_str("x"), Local<Value>::New(iso, g1s1));
}
heap->CollectGarbage(i::NEW_SPACE);
// All objects should be gone. 7 global handles in total.
CHECK_EQ(7, counter.NumberOfWeakCalls());
}
THREADED_TEST(ScriptException) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<Script> script = Script::Compile(v8_str("throw 'panama!';"));
v8::TryCatch try_catch;
Local<Value> result = script->Run();
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ(*exception_value, "panama!");
}
TEST(TryCatchCustomException) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::TryCatch try_catch;
CompileRun("function CustomError() { this.a = 'b'; }"
"(function f() { throw new CustomError(); })();");
CHECK(try_catch.HasCaught());
CHECK(try_catch.Exception()->ToObject()->
Get(v8_str("a"))->Equals(v8_str("b")));
}
bool message_received;
static void check_message_0(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK_EQ(5.76, data->NumberValue());
CHECK_EQ(6.75, message->GetScriptResourceName()->NumberValue());
CHECK_EQ(7.56, message->GetScriptData()->NumberValue());
CHECK(!message->IsSharedCrossOrigin());
message_received = true;
}
THREADED_TEST(MessageHandler0) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
CHECK(!message_received);
v8::V8::AddMessageListener(check_message_0, v8_num(5.76));
LocalContext context;
v8::ScriptOrigin origin =
v8::ScriptOrigin(v8_str("6.75"));
v8::Handle<v8::Script> script = Script::Compile(v8_str("throw 'error'"),
&origin);
script->SetData(v8_str("7.56"));
script->Run();
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_0);
}
static void check_message_1(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK(data->IsNumber());
CHECK_EQ(1337, data->Int32Value());
CHECK(!message->IsSharedCrossOrigin());
message_received = true;
}
TEST(MessageHandler1) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
CHECK(!message_received);
v8::V8::AddMessageListener(check_message_1);
LocalContext context;
CompileRun("throw 1337;");
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_1);
}
static void check_message_2(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
LocalContext context;
CHECK(data->IsObject());
v8::Local<v8::Value> hidden_property =
v8::Object::Cast(*data)->GetHiddenValue(v8_str("hidden key"));
CHECK(v8_str("hidden value")->Equals(hidden_property));
CHECK(!message->IsSharedCrossOrigin());
message_received = true;
}
TEST(MessageHandler2) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
CHECK(!message_received);
v8::V8::AddMessageListener(check_message_2);
LocalContext context;
v8::Local<v8::Value> error = v8::Exception::Error(v8_str("custom error"));
v8::Object::Cast(*error)->SetHiddenValue(v8_str("hidden key"),
v8_str("hidden value"));
context->Global()->Set(v8_str("error"), error);
CompileRun("throw error;");
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_2);
}
static void check_message_3(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK(message->IsSharedCrossOrigin());
CHECK_EQ(6.75, message->GetScriptResourceName()->NumberValue());
message_received = true;
}
TEST(MessageHandler3) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
CHECK(!message_received);
v8::V8::AddMessageListener(check_message_3);
LocalContext context;
v8::ScriptOrigin origin =
v8::ScriptOrigin(v8_str("6.75"),
v8::Integer::New(1),
v8::Integer::New(2),
v8::True());
v8::Handle<v8::Script> script = Script::Compile(v8_str("throw 'error'"),
&origin);
script->Run();
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_3);
}
static void check_message_4(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK(!message->IsSharedCrossOrigin());
CHECK_EQ(6.75, message->GetScriptResourceName()->NumberValue());
message_received = true;
}
TEST(MessageHandler4) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
CHECK(!message_received);
v8::V8::AddMessageListener(check_message_4);
LocalContext context;
v8::ScriptOrigin origin =
v8::ScriptOrigin(v8_str("6.75"),
v8::Integer::New(1),
v8::Integer::New(2),
v8::False());
v8::Handle<v8::Script> script = Script::Compile(v8_str("throw 'error'"),
&origin);
script->Run();
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_4);
}
static void check_message_5a(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK(message->IsSharedCrossOrigin());
CHECK_EQ(6.75, message->GetScriptResourceName()->NumberValue());
message_received = true;
}
static void check_message_5b(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK(!message->IsSharedCrossOrigin());
CHECK_EQ(6.75, message->GetScriptResourceName()->NumberValue());
message_received = true;
}
TEST(MessageHandler5) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
CHECK(!message_received);
v8::V8::AddMessageListener(check_message_5a);
LocalContext context;
v8::ScriptOrigin origin =
v8::ScriptOrigin(v8_str("6.75"),
v8::Integer::New(1),
v8::Integer::New(2),
v8::True());
v8::Handle<v8::Script> script = Script::Compile(v8_str("throw 'error'"),
&origin);
script->Run();
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_5a);
message_received = false;
v8::V8::AddMessageListener(check_message_5b);
origin =
v8::ScriptOrigin(v8_str("6.75"),
v8::Integer::New(1),
v8::Integer::New(2),
v8::False());
script = Script::Compile(v8_str("throw 'error'"),
&origin);
script->Run();
CHECK(message_received);
// clear out the message listener
v8::V8::RemoveMessageListeners(check_message_5b);
}
THREADED_TEST(GetSetProperty) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
context->Global()->Set(v8_str("foo"), v8_num(14));
context->Global()->Set(v8_str("12"), v8_num(92));
context->Global()->Set(v8::Integer::New(16), v8_num(32));
context->Global()->Set(v8_num(13), v8_num(56));
Local<Value> foo = Script::Compile(v8_str("this.foo"))->Run();
CHECK_EQ(14, foo->Int32Value());
Local<Value> twelve = Script::Compile(v8_str("this[12]"))->Run();
CHECK_EQ(92, twelve->Int32Value());
Local<Value> sixteen = Script::Compile(v8_str("this[16]"))->Run();
CHECK_EQ(32, sixteen->Int32Value());
Local<Value> thirteen = Script::Compile(v8_str("this[13]"))->Run();
CHECK_EQ(56, thirteen->Int32Value());
CHECK_EQ(92, context->Global()->Get(v8::Integer::New(12))->Int32Value());
CHECK_EQ(92, context->Global()->Get(v8_str("12"))->Int32Value());
CHECK_EQ(92, context->Global()->Get(v8_num(12))->Int32Value());
CHECK_EQ(32, context->Global()->Get(v8::Integer::New(16))->Int32Value());
CHECK_EQ(32, context->Global()->Get(v8_str("16"))->Int32Value());
CHECK_EQ(32, context->Global()->Get(v8_num(16))->Int32Value());
CHECK_EQ(56, context->Global()->Get(v8::Integer::New(13))->Int32Value());
CHECK_EQ(56, context->Global()->Get(v8_str("13"))->Int32Value());
CHECK_EQ(56, context->Global()->Get(v8_num(13))->Int32Value());
}
THREADED_TEST(PropertyAttributes) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// none
Local<String> prop = v8_str("none");
context->Global()->Set(prop, v8_num(7));
CHECK_EQ(v8::None, context->Global()->GetPropertyAttributes(prop));
// read-only
prop = v8_str("read_only");
context->Global()->Set(prop, v8_num(7), v8::ReadOnly);
CHECK_EQ(7, context->Global()->Get(prop)->Int32Value());
CHECK_EQ(v8::ReadOnly, context->Global()->GetPropertyAttributes(prop));
Script::Compile(v8_str("read_only = 9"))->Run();
CHECK_EQ(7, context->Global()->Get(prop)->Int32Value());
context->Global()->Set(prop, v8_num(10));
CHECK_EQ(7, context->Global()->Get(prop)->Int32Value());
// dont-delete
prop = v8_str("dont_delete");
context->Global()->Set(prop, v8_num(13), v8::DontDelete);
CHECK_EQ(13, context->Global()->Get(prop)->Int32Value());
Script::Compile(v8_str("delete dont_delete"))->Run();
CHECK_EQ(13, context->Global()->Get(prop)->Int32Value());
CHECK_EQ(v8::DontDelete, context->Global()->GetPropertyAttributes(prop));
// dont-enum
prop = v8_str("dont_enum");
context->Global()->Set(prop, v8_num(28), v8::DontEnum);
CHECK_EQ(v8::DontEnum, context->Global()->GetPropertyAttributes(prop));
// absent
prop = v8_str("absent");
CHECK_EQ(v8::None, context->Global()->GetPropertyAttributes(prop));
Local<Value> fake_prop = v8_num(1);
CHECK_EQ(v8::None, context->Global()->GetPropertyAttributes(fake_prop));
// exception
TryCatch try_catch;
Local<Value> exception =
CompileRun("({ toString: function() { throw 'exception';} })");
CHECK_EQ(v8::None, context->Global()->GetPropertyAttributes(exception));
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ("exception", *exception_value);
try_catch.Reset();
}
THREADED_TEST(Array) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<v8::Array> array = v8::Array::New();
CHECK_EQ(0, array->Length());
CHECK(array->Get(0)->IsUndefined());
CHECK(!array->Has(0));
CHECK(array->Get(100)->IsUndefined());
CHECK(!array->Has(100));
array->Set(2, v8_num(7));
CHECK_EQ(3, array->Length());
CHECK(!array->Has(0));
CHECK(!array->Has(1));
CHECK(array->Has(2));
CHECK_EQ(7, array->Get(2)->Int32Value());
Local<Value> obj = Script::Compile(v8_str("[1, 2, 3]"))->Run();
Local<v8::Array> arr = obj.As<v8::Array>();
CHECK_EQ(3, arr->Length());
CHECK_EQ(1, arr->Get(0)->Int32Value());
CHECK_EQ(2, arr->Get(1)->Int32Value());
CHECK_EQ(3, arr->Get(2)->Int32Value());
array = v8::Array::New(27);
CHECK_EQ(27, array->Length());
array = v8::Array::New(-27);
CHECK_EQ(0, array->Length());
}
void HandleF(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
ApiTestFuzzer::Fuzz();
Local<v8::Array> result = v8::Array::New(args.Length());
for (int i = 0; i < args.Length(); i++)
result->Set(i, args[i]);
args.GetReturnValue().Set(scope.Close(result));
}
THREADED_TEST(Vector) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> global = ObjectTemplate::New();
global->Set(v8_str("f"), v8::FunctionTemplate::New(HandleF));
LocalContext context(0, global);
const char* fun = "f()";
Local<v8::Array> a0 = CompileRun(fun).As<v8::Array>();
CHECK_EQ(0, a0->Length());
const char* fun2 = "f(11)";
Local<v8::Array> a1 = CompileRun(fun2).As<v8::Array>();
CHECK_EQ(1, a1->Length());
CHECK_EQ(11, a1->Get(0)->Int32Value());
const char* fun3 = "f(12, 13)";
Local<v8::Array> a2 = CompileRun(fun3).As<v8::Array>();
CHECK_EQ(2, a2->Length());
CHECK_EQ(12, a2->Get(0)->Int32Value());
CHECK_EQ(13, a2->Get(1)->Int32Value());
const char* fun4 = "f(14, 15, 16)";
Local<v8::Array> a3 = CompileRun(fun4).As<v8::Array>();
CHECK_EQ(3, a3->Length());
CHECK_EQ(14, a3->Get(0)->Int32Value());
CHECK_EQ(15, a3->Get(1)->Int32Value());
CHECK_EQ(16, a3->Get(2)->Int32Value());
const char* fun5 = "f(17, 18, 19, 20)";
Local<v8::Array> a4 = CompileRun(fun5).As<v8::Array>();
CHECK_EQ(4, a4->Length());
CHECK_EQ(17, a4->Get(0)->Int32Value());
CHECK_EQ(18, a4->Get(1)->Int32Value());
CHECK_EQ(19, a4->Get(2)->Int32Value());
CHECK_EQ(20, a4->Get(3)->Int32Value());
}
THREADED_TEST(FunctionCall) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
CompileRun(
"function Foo() {"
" var result = [];"
" for (var i = 0; i < arguments.length; i++) {"
" result.push(arguments[i]);"
" }"
" return result;"
"}");
Local<Function> Foo =
Local<Function>::Cast(context->Global()->Get(v8_str("Foo")));
v8::Handle<Value>* args0 = NULL;
Local<v8::Array> a0 = Local<v8::Array>::Cast(Foo->Call(Foo, 0, args0));
CHECK_EQ(0, a0->Length());
v8::Handle<Value> args1[] = { v8_num(1.1) };
Local<v8::Array> a1 = Local<v8::Array>::Cast(Foo->Call(Foo, 1, args1));
CHECK_EQ(1, a1->Length());
CHECK_EQ(1.1, a1->Get(v8::Integer::New(0))->NumberValue());
v8::Handle<Value> args2[] = { v8_num(2.2),
v8_num(3.3) };
Local<v8::Array> a2 = Local<v8::Array>::Cast(Foo->Call(Foo, 2, args2));
CHECK_EQ(2, a2->Length());
CHECK_EQ(2.2, a2->Get(v8::Integer::New(0))->NumberValue());
CHECK_EQ(3.3, a2->Get(v8::Integer::New(1))->NumberValue());
v8::Handle<Value> args3[] = { v8_num(4.4),
v8_num(5.5),
v8_num(6.6) };
Local<v8::Array> a3 = Local<v8::Array>::Cast(Foo->Call(Foo, 3, args3));
CHECK_EQ(3, a3->Length());
CHECK_EQ(4.4, a3->Get(v8::Integer::New(0))->NumberValue());
CHECK_EQ(5.5, a3->Get(v8::Integer::New(1))->NumberValue());
CHECK_EQ(6.6, a3->Get(v8::Integer::New(2))->NumberValue());
v8::Handle<Value> args4[] = { v8_num(7.7),
v8_num(8.8),
v8_num(9.9),
v8_num(10.11) };
Local<v8::Array> a4 = Local<v8::Array>::Cast(Foo->Call(Foo, 4, args4));
CHECK_EQ(4, a4->Length());
CHECK_EQ(7.7, a4->Get(v8::Integer::New(0))->NumberValue());
CHECK_EQ(8.8, a4->Get(v8::Integer::New(1))->NumberValue());
CHECK_EQ(9.9, a4->Get(v8::Integer::New(2))->NumberValue());
CHECK_EQ(10.11, a4->Get(v8::Integer::New(3))->NumberValue());
}
static const char* js_code_causing_out_of_memory =
"var a = new Array(); while(true) a.push(a);";
// These tests run for a long time and prevent us from running tests
// that come after them so they cannot run in parallel.
TEST(OutOfMemory) {
// It's not possible to read a snapshot into a heap with different dimensions.
if (i::Snapshot::IsEnabled()) return;
// Set heap limits.
static const int K = 1024;
v8::ResourceConstraints constraints;
constraints.set_max_young_space_size(256 * K);
constraints.set_max_old_space_size(5 * K * K);
v8::SetResourceConstraints(&constraints);
// Execute a script that causes out of memory.
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::V8::IgnoreOutOfMemoryException();
Local<Script> script =
Script::Compile(String::New(js_code_causing_out_of_memory));
Local<Value> result = script->Run();
// Check for out of memory state.
CHECK(result.IsEmpty());
CHECK(context->HasOutOfMemoryException());
}
void ProvokeOutOfMemory(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<Script> script =
Script::Compile(String::New(js_code_causing_out_of_memory));
Local<Value> result = script->Run();
// Check for out of memory state.
CHECK(result.IsEmpty());
CHECK(context->HasOutOfMemoryException());
args.GetReturnValue().Set(result);
}
TEST(OutOfMemoryNested) {
// It's not possible to read a snapshot into a heap with different dimensions.
if (i::Snapshot::IsEnabled()) return;
// Set heap limits.
static const int K = 1024;
v8::ResourceConstraints constraints;
constraints.set_max_young_space_size(256 * K);
constraints.set_max_old_space_size(5 * K * K);
v8::SetResourceConstraints(&constraints);
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("ProvokeOutOfMemory"),
v8::FunctionTemplate::New(ProvokeOutOfMemory));
LocalContext context(0, templ);
v8::V8::IgnoreOutOfMemoryException();
Local<Value> result = CompileRun(
"var thrown = false;"
"try {"
" ProvokeOutOfMemory();"
"} catch (e) {"
" thrown = true;"
"}");
// Check for out of memory state.
CHECK(result.IsEmpty());
CHECK(context->HasOutOfMemoryException());
}
TEST(HugeConsStringOutOfMemory) {
// It's not possible to read a snapshot into a heap with different dimensions.
if (i::Snapshot::IsEnabled()) return;
// Set heap limits.
static const int K = 1024;
v8::ResourceConstraints constraints;
constraints.set_max_young_space_size(256 * K);
constraints.set_max_old_space_size(4 * K * K);
v8::SetResourceConstraints(&constraints);
// Execute a script that causes out of memory.
v8::V8::IgnoreOutOfMemoryException();
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// Build huge string. This should fail with out of memory exception.
Local<Value> result = CompileRun(
"var str = Array.prototype.join.call({length: 513}, \"A\").toUpperCase();"
"for (var i = 0; i < 22; i++) { str = str + str; }");
// Check for out of memory state.
CHECK(result.IsEmpty());
CHECK(context->HasOutOfMemoryException());
}
THREADED_TEST(ConstructCall) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
CompileRun(
"function Foo() {"
" var result = [];"
" for (var i = 0; i < arguments.length; i++) {"
" result.push(arguments[i]);"
" }"
" return result;"
"}");
Local<Function> Foo =
Local<Function>::Cast(context->Global()->Get(v8_str("Foo")));
v8::Handle<Value>* args0 = NULL;
Local<v8::Array> a0 = Local<v8::Array>::Cast(Foo->NewInstance(0, args0));
CHECK_EQ(0, a0->Length());
v8::Handle<Value> args1[] = { v8_num(1.1) };
Local<v8::Array> a1 = Local<v8::Array>::Cast(Foo->NewInstance(1, args1));
CHECK_EQ(1, a1->Length());
CHECK_EQ(1.1, a1->Get(v8::Integer::New(0))->NumberValue());
v8::Handle<Value> args2[] = { v8_num(2.2),
v8_num(3.3) };
Local<v8::Array> a2 = Local<v8::Array>::Cast(Foo->NewInstance(2, args2));
CHECK_EQ(2, a2->Length());
CHECK_EQ(2.2, a2->Get(v8::Integer::New(0))->NumberValue());
CHECK_EQ(3.3, a2->Get(v8::Integer::New(1))->NumberValue());
v8::Handle<Value> args3[] = { v8_num(4.4),
v8_num(5.5),
v8_num(6.6) };
Local<v8::Array> a3 = Local<v8::Array>::Cast(Foo->NewInstance(3, args3));
CHECK_EQ(3, a3->Length());
CHECK_EQ(4.4, a3->Get(v8::Integer::New(0))->NumberValue());
CHECK_EQ(5.5, a3->Get(v8::Integer::New(1))->NumberValue());
CHECK_EQ(6.6, a3->Get(v8::Integer::New(2))->NumberValue());
v8::Handle<Value> args4[] = { v8_num(7.7),
v8_num(8.8),
v8_num(9.9),
v8_num(10.11) };
Local<v8::Array> a4 = Local<v8::Array>::Cast(Foo->NewInstance(4, args4));
CHECK_EQ(4, a4->Length());
CHECK_EQ(7.7, a4->Get(v8::Integer::New(0))->NumberValue());
CHECK_EQ(8.8, a4->Get(v8::Integer::New(1))->NumberValue());
CHECK_EQ(9.9, a4->Get(v8::Integer::New(2))->NumberValue());
CHECK_EQ(10.11, a4->Get(v8::Integer::New(3))->NumberValue());
}
static void CheckUncle(v8::TryCatch* try_catch) {
CHECK(try_catch->HasCaught());
String::Utf8Value str_value(try_catch->Exception());
CHECK_EQ(*str_value, "uncle?");
try_catch->Reset();
}
THREADED_TEST(ConversionNumber) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// Very large number.
CompileRun("var obj = Math.pow(2,32) * 1237;");
Local<Value> obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(5312874545152.0, obj->ToNumber()->Value());
CHECK_EQ(0, obj->ToInt32()->Value());
CHECK(0u == obj->ToUint32()->Value()); // NOLINT - no CHECK_EQ for unsigned.
// Large number.
CompileRun("var obj = -1234567890123;");
obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(-1234567890123.0, obj->ToNumber()->Value());
CHECK_EQ(-1912276171, obj->ToInt32()->Value());
CHECK(2382691125u == obj->ToUint32()->Value()); // NOLINT
// Small positive integer.
CompileRun("var obj = 42;");
obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(42.0, obj->ToNumber()->Value());
CHECK_EQ(42, obj->ToInt32()->Value());
CHECK(42u == obj->ToUint32()->Value()); // NOLINT
// Negative integer.
CompileRun("var obj = -37;");
obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(-37.0, obj->ToNumber()->Value());
CHECK_EQ(-37, obj->ToInt32()->Value());
CHECK(4294967259u == obj->ToUint32()->Value()); // NOLINT
// Positive non-int32 integer.
CompileRun("var obj = 0x81234567;");
obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(2166572391.0, obj->ToNumber()->Value());
CHECK_EQ(-2128394905, obj->ToInt32()->Value());
CHECK(2166572391u == obj->ToUint32()->Value()); // NOLINT
// Fraction.
CompileRun("var obj = 42.3;");
obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(42.3, obj->ToNumber()->Value());
CHECK_EQ(42, obj->ToInt32()->Value());
CHECK(42u == obj->ToUint32()->Value()); // NOLINT
// Large negative fraction.
CompileRun("var obj = -5726623061.75;");
obj = env->Global()->Get(v8_str("obj"));
CHECK_EQ(-5726623061.75, obj->ToNumber()->Value());
CHECK_EQ(-1431655765, obj->ToInt32()->Value());
CHECK(2863311531u == obj->ToUint32()->Value()); // NOLINT
}
THREADED_TEST(isNumberType) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// Very large number.
CompileRun("var obj = Math.pow(2,32) * 1237;");
Local<Value> obj = env->Global()->Get(v8_str("obj"));
CHECK(!obj->IsInt32());
CHECK(!obj->IsUint32());
// Large negative number.
CompileRun("var obj = -1234567890123;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(!obj->IsInt32());
CHECK(!obj->IsUint32());
// Small positive integer.
CompileRun("var obj = 42;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(obj->IsInt32());
CHECK(obj->IsUint32());
// Negative integer.
CompileRun("var obj = -37;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(obj->IsInt32());
CHECK(!obj->IsUint32());
// Positive non-int32 integer.
CompileRun("var obj = 0x81234567;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(!obj->IsInt32());
CHECK(obj->IsUint32());
// Fraction.
CompileRun("var obj = 42.3;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(!obj->IsInt32());
CHECK(!obj->IsUint32());
// Large negative fraction.
CompileRun("var obj = -5726623061.75;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(!obj->IsInt32());
CHECK(!obj->IsUint32());
// Positive zero
CompileRun("var obj = 0.0;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(obj->IsInt32());
CHECK(obj->IsUint32());
// Positive zero
CompileRun("var obj = -0.0;");
obj = env->Global()->Get(v8_str("obj"));
CHECK(!obj->IsInt32());
CHECK(!obj->IsUint32());
}
THREADED_TEST(ConversionException) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
CompileRun(
"function TestClass() { };"
"TestClass.prototype.toString = function () { throw 'uncle?'; };"
"var obj = new TestClass();");
Local<Value> obj = env->Global()->Get(v8_str("obj"));
v8::TryCatch try_catch;
Local<Value> to_string_result = obj->ToString();
CHECK(to_string_result.IsEmpty());
CheckUncle(&try_catch);
Local<Value> to_number_result = obj->ToNumber();
CHECK(to_number_result.IsEmpty());
CheckUncle(&try_catch);
Local<Value> to_integer_result = obj->ToInteger();
CHECK(to_integer_result.IsEmpty());
CheckUncle(&try_catch);
Local<Value> to_uint32_result = obj->ToUint32();
CHECK(to_uint32_result.IsEmpty());
CheckUncle(&try_catch);
Local<Value> to_int32_result = obj->ToInt32();
CHECK(to_int32_result.IsEmpty());
CheckUncle(&try_catch);
Local<Value> to_object_result = v8::Undefined()->ToObject();
CHECK(to_object_result.IsEmpty());
CHECK(try_catch.HasCaught());
try_catch.Reset();
int32_t int32_value = obj->Int32Value();
CHECK_EQ(0, int32_value);
CheckUncle(&try_catch);
uint32_t uint32_value = obj->Uint32Value();
CHECK_EQ(0, uint32_value);
CheckUncle(&try_catch);
double number_value = obj->NumberValue();
CHECK_NE(0, std::isnan(number_value));
CheckUncle(&try_catch);
int64_t integer_value = obj->IntegerValue();
CHECK_EQ(0.0, static_cast<double>(integer_value));
CheckUncle(&try_catch);
}
void ThrowFromC(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
v8::ThrowException(v8_str("konto"));
}
void CCatcher(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() < 1) {
args.GetReturnValue().Set(false);
return;
}
v8::HandleScope scope(args.GetIsolate());
v8::TryCatch try_catch;
Local<Value> result = v8::Script::Compile(args[0]->ToString())->Run();
CHECK(!try_catch.HasCaught() || result.IsEmpty());
args.GetReturnValue().Set(try_catch.HasCaught());
}
THREADED_TEST(APICatch) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("ThrowFromC"),
v8::FunctionTemplate::New(ThrowFromC));
LocalContext context(0, templ);
CompileRun(
"var thrown = false;"
"try {"
" ThrowFromC();"
"} catch (e) {"
" thrown = true;"
"}");
Local<Value> thrown = context->Global()->Get(v8_str("thrown"));
CHECK(thrown->BooleanValue());
}
THREADED_TEST(APIThrowTryCatch) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("ThrowFromC"),
v8::FunctionTemplate::New(ThrowFromC));
LocalContext context(0, templ);
v8::TryCatch try_catch;
CompileRun("ThrowFromC();");
CHECK(try_catch.HasCaught());
}
// Test that a try-finally block doesn't shadow a try-catch block
// when setting up an external handler.
//
// BUG(271): Some of the exception propagation does not work on the
// ARM simulator because the simulator separates the C++ stack and the
// JS stack. This test therefore fails on the simulator. The test is
// not threaded to allow the threading tests to run on the simulator.
TEST(TryCatchInTryFinally) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("CCatcher"),
v8::FunctionTemplate::New(CCatcher));
LocalContext context(0, templ);
Local<Value> result = CompileRun("try {"
" try {"
" CCatcher('throw 7;');"
" } finally {"
" }"
"} catch (e) {"
"}");
CHECK(result->IsTrue());
}
static void check_reference_error_message(
v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
const char* reference_error = "Uncaught ReferenceError: asdf is not defined";
CHECK(message->Get()->Equals(v8_str(reference_error)));
}
static void Fail(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CHECK(false);
}
// Test that overwritten methods are not invoked on uncaught exception
// formatting. However, they are invoked when performing normal error
// string conversions.
TEST(APIThrowMessageOverwrittenToString) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::V8::AddMessageListener(check_reference_error_message);
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("fail"), v8::FunctionTemplate::New(Fail));
LocalContext context(NULL, templ);
CompileRun("asdf;");
CompileRun("var limit = {};"
"limit.valueOf = fail;"
"Error.stackTraceLimit = limit;");
CompileRun("asdf");
CompileRun("Array.prototype.pop = fail;");
CompileRun("Object.prototype.hasOwnProperty = fail;");
CompileRun("Object.prototype.toString = function f() { return 'Yikes'; }");
CompileRun("Number.prototype.toString = function f() { return 'Yikes'; }");
CompileRun("String.prototype.toString = function f() { return 'Yikes'; }");
CompileRun("ReferenceError.prototype.toString ="
" function() { return 'Whoops' }");
CompileRun("asdf;");
CompileRun("ReferenceError.prototype.constructor.name = void 0;");
CompileRun("asdf;");
CompileRun("ReferenceError.prototype.constructor = void 0;");
CompileRun("asdf;");
CompileRun("ReferenceError.prototype.__proto__ = new Object();");
CompileRun("asdf;");
CompileRun("ReferenceError.prototype = new Object();");
CompileRun("asdf;");
v8::Handle<Value> string = CompileRun("try { asdf; } catch(e) { e + ''; }");
CHECK(string->Equals(v8_str("Whoops")));
CompileRun("ReferenceError.prototype.constructor = new Object();"
"ReferenceError.prototype.constructor.name = 1;"
"Number.prototype.toString = function() { return 'Whoops'; };"
"ReferenceError.prototype.toString = Object.prototype.toString;");
CompileRun("asdf;");
v8::V8::RemoveMessageListeners(check_reference_error_message);
}
static void check_custom_error_tostring(
v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
const char* uncaught_error = "Uncaught MyError toString";
CHECK(message->Get()->Equals(v8_str(uncaught_error)));
}
TEST(CustomErrorToString) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::V8::AddMessageListener(check_custom_error_tostring);
CompileRun(
"function MyError(name, message) { "
" this.name = name; "
" this.message = message; "
"} "
"MyError.prototype = Object.create(Error.prototype); "
"MyError.prototype.toString = function() { "
" return 'MyError toString'; "
"}; "
"throw new MyError('my name', 'my message'); ");
v8::V8::RemoveMessageListeners(check_custom_error_tostring);
}
static void check_custom_error_message(
v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
const char* uncaught_error = "Uncaught MyError: my message";
printf("%s\n", *v8::String::Utf8Value(message->Get()));
CHECK(message->Get()->Equals(v8_str(uncaught_error)));
}
TEST(CustomErrorMessage) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::V8::AddMessageListener(check_custom_error_message);
// Handlebars.
CompileRun(
"function MyError(msg) { "
" this.name = 'MyError'; "
" this.message = msg; "
"} "
"MyError.prototype = new Error(); "
"throw new MyError('my message'); ");
// Closure.
CompileRun(
"function MyError(msg) { "
" this.name = 'MyError'; "
" this.message = msg; "
"} "
"inherits = function(childCtor, parentCtor) { "
" function tempCtor() {}; "
" tempCtor.prototype = parentCtor.prototype; "
" childCtor.superClass_ = parentCtor.prototype; "
" childCtor.prototype = new tempCtor(); "
" childCtor.prototype.constructor = childCtor; "
"}; "
"inherits(MyError, Error); "
"throw new MyError('my message'); ");
// Object.create.
CompileRun(
"function MyError(msg) { "
" this.name = 'MyError'; "
" this.message = msg; "
"} "
"MyError.prototype = Object.create(Error.prototype); "
"throw new MyError('my message'); ");
v8::V8::RemoveMessageListeners(check_custom_error_message);
}
static void receive_message(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
message->Get();
message_received = true;
}
TEST(APIThrowMessage) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::V8::AddMessageListener(receive_message);
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("ThrowFromC"),
v8::FunctionTemplate::New(ThrowFromC));
LocalContext context(0, templ);
CompileRun("ThrowFromC();");
CHECK(message_received);
v8::V8::RemoveMessageListeners(receive_message);
}
TEST(APIThrowMessageAndVerboseTryCatch) {
message_received = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::V8::AddMessageListener(receive_message);
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("ThrowFromC"),
v8::FunctionTemplate::New(ThrowFromC));
LocalContext context(0, templ);
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
Local<Value> result = CompileRun("ThrowFromC();");
CHECK(try_catch.HasCaught());
CHECK(result.IsEmpty());
CHECK(message_received);
v8::V8::RemoveMessageListeners(receive_message);
}
TEST(APIStackOverflowAndVerboseTryCatch) {
message_received = false;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::V8::AddMessageListener(receive_message);
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
Local<Value> result = CompileRun("function foo() { foo(); } foo();");
CHECK(try_catch.HasCaught());
CHECK(result.IsEmpty());
CHECK(message_received);
v8::V8::RemoveMessageListeners(receive_message);
}
THREADED_TEST(ExternalScriptException) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("ThrowFromC"),
v8::FunctionTemplate::New(ThrowFromC));
LocalContext context(0, templ);
v8::TryCatch try_catch;
Local<Script> script
= Script::Compile(v8_str("ThrowFromC(); throw 'panama';"));
Local<Value> result = script->Run();
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ("konto", *exception_value);
}
void CThrowCountDown(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(4, args.Length());
int count = args[0]->Int32Value();
int cInterval = args[2]->Int32Value();
if (count == 0) {
v8::ThrowException(v8_str("FromC"));
return;
} else {
Local<v8::Object> global = Context::GetCurrent()->Global();
Local<Value> fun = global->Get(v8_str("JSThrowCountDown"));
v8::Handle<Value> argv[] = { v8_num(count - 1),
args[1],
args[2],
args[3] };
if (count % cInterval == 0) {
v8::TryCatch try_catch;
Local<Value> result = fun.As<Function>()->Call(global, 4, argv);
int expected = args[3]->Int32Value();
if (try_catch.HasCaught()) {
CHECK_EQ(expected, count);
CHECK(result.IsEmpty());
CHECK(!i::Isolate::Current()->has_scheduled_exception());
} else {
CHECK_NE(expected, count);
}
args.GetReturnValue().Set(result);
return;
} else {
args.GetReturnValue().Set(fun.As<Function>()->Call(global, 4, argv));
return;
}
}
}
void JSCheck(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(3, args.Length());
bool equality = args[0]->BooleanValue();
int count = args[1]->Int32Value();
int expected = args[2]->Int32Value();
if (equality) {
CHECK_EQ(count, expected);
} else {
CHECK_NE(count, expected);
}
}
THREADED_TEST(EvalInTryFinally) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
CompileRun("(function() {"
" try {"
" eval('asldkf (*&^&*^');"
" } finally {"
" return;"
" }"
"})()");
CHECK(!try_catch.HasCaught());
}
// This test works by making a stack of alternating JavaScript and C
// activations. These activations set up exception handlers with regular
// intervals, one interval for C activations and another for JavaScript
// activations. When enough activations have been created an exception is
// thrown and we check that the right activation catches the exception and that
// no other activations do. The right activation is always the topmost one with
// a handler, regardless of whether it is in JavaScript or C.
//
// The notation used to describe a test case looks like this:
//
// *JS[4] *C[3] @JS[2] C[1] JS[0]
//
// Each entry is an activation, either JS or C. The index is the count at that
// level. Stars identify activations with exception handlers, the @ identifies
// the exception handler that should catch the exception.
//
// BUG(271): Some of the exception propagation does not work on the
// ARM simulator because the simulator separates the C++ stack and the
// JS stack. This test therefore fails on the simulator. The test is
// not threaded to allow the threading tests to run on the simulator.
TEST(ExceptionOrder) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("check"), v8::FunctionTemplate::New(JSCheck));
templ->Set(v8_str("CThrowCountDown"),
v8::FunctionTemplate::New(CThrowCountDown));
LocalContext context(0, templ);
CompileRun(
"function JSThrowCountDown(count, jsInterval, cInterval, expected) {"
" if (count == 0) throw 'FromJS';"
" if (count % jsInterval == 0) {"
" try {"
" var value = CThrowCountDown(count - 1,"
" jsInterval,"
" cInterval,"
" expected);"
" check(false, count, expected);"
" return value;"
" } catch (e) {"
" check(true, count, expected);"
" }"
" } else {"
" return CThrowCountDown(count - 1, jsInterval, cInterval, expected);"
" }"
"}");
Local<Function> fun =
Local<Function>::Cast(context->Global()->Get(v8_str("JSThrowCountDown")));
const int argc = 4;
// count jsInterval cInterval expected
// *JS[4] *C[3] @JS[2] C[1] JS[0]
v8::Handle<Value> a0[argc] = { v8_num(4), v8_num(2), v8_num(3), v8_num(2) };
fun->Call(fun, argc, a0);
// JS[5] *C[4] JS[3] @C[2] JS[1] C[0]
v8::Handle<Value> a1[argc] = { v8_num(5), v8_num(6), v8_num(1), v8_num(2) };
fun->Call(fun, argc, a1);
// JS[6] @C[5] JS[4] C[3] JS[2] C[1] JS[0]
v8::Handle<Value> a2[argc] = { v8_num(6), v8_num(7), v8_num(5), v8_num(5) };
fun->Call(fun, argc, a2);
// @JS[6] C[5] JS[4] C[3] JS[2] C[1] JS[0]
v8::Handle<Value> a3[argc] = { v8_num(6), v8_num(6), v8_num(7), v8_num(6) };
fun->Call(fun, argc, a3);
// JS[6] *C[5] @JS[4] C[3] JS[2] C[1] JS[0]
v8::Handle<Value> a4[argc] = { v8_num(6), v8_num(4), v8_num(5), v8_num(4) };
fun->Call(fun, argc, a4);
// JS[6] C[5] *JS[4] @C[3] JS[2] C[1] JS[0]
v8::Handle<Value> a5[argc] = { v8_num(6), v8_num(4), v8_num(3), v8_num(3) };
fun->Call(fun, argc, a5);
}
void ThrowValue(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(1, args.Length());
v8::ThrowException(args[0]);
}
THREADED_TEST(ThrowValues) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("Throw"), v8::FunctionTemplate::New(ThrowValue));
LocalContext context(0, templ);
v8::Handle<v8::Array> result = v8::Handle<v8::Array>::Cast(CompileRun(
"function Run(obj) {"
" try {"
" Throw(obj);"
" } catch (e) {"
" return e;"
" }"
" return 'no exception';"
"}"
"[Run('str'), Run(1), Run(0), Run(null), Run(void 0)];"));
CHECK_EQ(5, result->Length());
CHECK(result->Get(v8::Integer::New(0))->IsString());
CHECK(result->Get(v8::Integer::New(1))->IsNumber());
CHECK_EQ(1, result->Get(v8::Integer::New(1))->Int32Value());
CHECK(result->Get(v8::Integer::New(2))->IsNumber());
CHECK_EQ(0, result->Get(v8::Integer::New(2))->Int32Value());
CHECK(result->Get(v8::Integer::New(3))->IsNull());
CHECK(result->Get(v8::Integer::New(4))->IsUndefined());
}
THREADED_TEST(CatchZero) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
CHECK(!try_catch.HasCaught());
Script::Compile(v8_str("throw 10"))->Run();
CHECK(try_catch.HasCaught());
CHECK_EQ(10, try_catch.Exception()->Int32Value());
try_catch.Reset();
CHECK(!try_catch.HasCaught());
Script::Compile(v8_str("throw 0"))->Run();
CHECK(try_catch.HasCaught());
CHECK_EQ(0, try_catch.Exception()->Int32Value());
}
THREADED_TEST(CatchExceptionFromWith) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
CHECK(!try_catch.HasCaught());
Script::Compile(v8_str("var o = {}; with (o) { throw 42; }"))->Run();
CHECK(try_catch.HasCaught());
}
THREADED_TEST(TryCatchAndFinallyHidingException) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
CHECK(!try_catch.HasCaught());
CompileRun("function f(k) { try { this[k]; } finally { return 0; } };");
CompileRun("f({toString: function() { throw 42; }});");
CHECK(!try_catch.HasCaught());
}
void WithTryCatch(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::TryCatch try_catch;
}
THREADED_TEST(TryCatchAndFinally) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
context->Global()->Set(
v8_str("native_with_try_catch"),
v8::FunctionTemplate::New(WithTryCatch)->GetFunction());
v8::TryCatch try_catch;
CHECK(!try_catch.HasCaught());
CompileRun(
"try {\n"
" throw new Error('a');\n"
"} finally {\n"
" native_with_try_catch();\n"
"}\n");
CHECK(try_catch.HasCaught());
}
static void TryCatchNestedHelper(int depth) {
if (depth > 0) {
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
TryCatchNestedHelper(depth - 1);
CHECK(try_catch.HasCaught());
try_catch.ReThrow();
} else {
v8::ThrowException(v8_str("back"));
}
}
TEST(TryCatchNested) {
v8::V8::Initialize();
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
TryCatchNestedHelper(5);
CHECK(try_catch.HasCaught());
CHECK_EQ(0, strcmp(*v8::String::Utf8Value(try_catch.Exception()), "back"));
}
void TryCatchMixedNestingCheck(v8::TryCatch* try_catch) {
CHECK(try_catch->HasCaught());
Handle<Message> message = try_catch->Message();
Handle<Value> resource = message->GetScriptResourceName();
CHECK_EQ(0, strcmp(*v8::String::Utf8Value(resource), "inner"));
CHECK_EQ(0, strcmp(*v8::String::Utf8Value(message->Get()),
"Uncaught Error: a"));
CHECK_EQ(1, message->GetLineNumber());
CHECK_EQ(6, message->GetStartColumn());
}
void TryCatchMixedNestingHelper(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
v8::TryCatch try_catch;
CompileRunWithOrigin("throw new Error('a');\n", "inner", 0, 0);
CHECK(try_catch.HasCaught());
TryCatchMixedNestingCheck(&try_catch);
try_catch.ReThrow();
}
// This test ensures that an outer TryCatch in the following situation:
// C++/TryCatch -> JS -> C++/TryCatch -> JS w/ SyntaxError
// does not clobber the Message object generated for the inner TryCatch.
// This exercises the ability of TryCatch.ReThrow() to restore the
// inner pending Message before throwing the exception again.
TEST(TryCatchMixedNesting) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::V8::Initialize();
v8::TryCatch try_catch;
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("TryCatchMixedNestingHelper"),
v8::FunctionTemplate::New(TryCatchMixedNestingHelper));
LocalContext context(0, templ);
CompileRunWithOrigin("TryCatchMixedNestingHelper();\n", "outer", 1, 1);
TryCatchMixedNestingCheck(&try_catch);
}
THREADED_TEST(Equality) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope scope(context->GetIsolate());
// Check that equality works at all before relying on CHECK_EQ
CHECK(v8_str("a")->Equals(v8_str("a")));
CHECK(!v8_str("a")->Equals(v8_str("b")));
CHECK_EQ(v8_str("a"), v8_str("a"));
CHECK_NE(v8_str("a"), v8_str("b"));
CHECK_EQ(v8_num(1), v8_num(1));
CHECK_EQ(v8_num(1.00), v8_num(1));
CHECK_NE(v8_num(1), v8_num(2));
// Assume String is not internalized.
CHECK(v8_str("a")->StrictEquals(v8_str("a")));
CHECK(!v8_str("a")->StrictEquals(v8_str("b")));
CHECK(!v8_str("5")->StrictEquals(v8_num(5)));
CHECK(v8_num(1)->StrictEquals(v8_num(1)));
CHECK(!v8_num(1)->StrictEquals(v8_num(2)));
CHECK(v8_num(0)->StrictEquals(v8_num(-0)));
Local<Value> not_a_number = v8_num(i::OS::nan_value());
CHECK(!not_a_number->StrictEquals(not_a_number));
CHECK(v8::False()->StrictEquals(v8::False()));
CHECK(!v8::False()->StrictEquals(v8::Undefined()));
v8::Handle<v8::Object> obj = v8::Object::New();
v8::Persistent<v8::Object> alias(isolate, obj);
CHECK(v8::Local<v8::Object>::New(isolate, alias)->StrictEquals(obj));
alias.Dispose(isolate);
}
THREADED_TEST(MultiRun) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<Script> script = Script::Compile(v8_str("x"));
for (int i = 0; i < 10; i++)
script->Run();
}
static void GetXValue(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(info.Data(), v8_str("donut"));
CHECK_EQ(name, v8_str("x"));
info.GetReturnValue().Set(name);
}
THREADED_TEST(SimplePropertyRead) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut"));
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> script = Script::Compile(v8_str("obj.x"));
for (int i = 0; i < 10; i++) {
Local<Value> result = script->Run();
CHECK_EQ(result, v8_str("x"));
}
}
THREADED_TEST(DefinePropertyOnAPIAccessor) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut"));
context->Global()->Set(v8_str("obj"), templ->NewInstance());
// Uses getOwnPropertyDescriptor to check the configurable status
Local<Script> script_desc
= Script::Compile(v8_str("var prop = Object.getOwnPropertyDescriptor( "
"obj, 'x');"
"prop.configurable;"));
Local<Value> result = script_desc->Run();
CHECK_EQ(result->BooleanValue(), true);
// Redefine get - but still configurable
Local<Script> script_define
= Script::Compile(v8_str("var desc = { get: function(){return 42; },"
" configurable: true };"
"Object.defineProperty(obj, 'x', desc);"
"obj.x"));
result = script_define->Run();
CHECK_EQ(result, v8_num(42));
// Check that the accessor is still configurable
result = script_desc->Run();
CHECK_EQ(result->BooleanValue(), true);
// Redefine to a non-configurable
script_define
= Script::Compile(v8_str("var desc = { get: function(){return 43; },"
" configurable: false };"
"Object.defineProperty(obj, 'x', desc);"
"obj.x"));
result = script_define->Run();
CHECK_EQ(result, v8_num(43));
result = script_desc->Run();
CHECK_EQ(result->BooleanValue(), false);
// Make sure that it is not possible to redefine again
v8::TryCatch try_catch;
result = script_define->Run();
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ(*exception_value, "TypeError: Cannot redefine property: x");
}
THREADED_TEST(DefinePropertyOnDefineGetterSetter) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut"));
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> script_desc = Script::Compile(v8_str("var prop ="
"Object.getOwnPropertyDescriptor( "
"obj, 'x');"
"prop.configurable;"));
Local<Value> result = script_desc->Run();
CHECK_EQ(result->BooleanValue(), true);
Local<Script> script_define =
Script::Compile(v8_str("var desc = {get: function(){return 42; },"
" configurable: true };"
"Object.defineProperty(obj, 'x', desc);"
"obj.x"));
result = script_define->Run();
CHECK_EQ(result, v8_num(42));
result = script_desc->Run();
CHECK_EQ(result->BooleanValue(), true);
script_define =
Script::Compile(v8_str("var desc = {get: function(){return 43; },"
" configurable: false };"
"Object.defineProperty(obj, 'x', desc);"
"obj.x"));
result = script_define->Run();
CHECK_EQ(result, v8_num(43));
result = script_desc->Run();
CHECK_EQ(result->BooleanValue(), false);
v8::TryCatch try_catch;
result = script_define->Run();
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ(*exception_value, "TypeError: Cannot redefine property: x");
}
static v8::Handle<v8::Object> GetGlobalProperty(LocalContext* context,
char const* name) {
return v8::Handle<v8::Object>::Cast((*context)->Global()->Get(v8_str(name)));
}
THREADED_TEST(DefineAPIAccessorOnObject) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
LocalContext context;
context->Global()->Set(v8_str("obj1"), templ->NewInstance());
CompileRun("var obj2 = {};");
CHECK(CompileRun("obj1.x")->IsUndefined());
CHECK(CompileRun("obj2.x")->IsUndefined());
CHECK(GetGlobalProperty(&context, "obj1")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
ExpectString("obj1.x", "x");
CHECK(CompileRun("obj2.x")->IsUndefined());
CHECK(GetGlobalProperty(&context, "obj2")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
ExpectString("obj1.x", "x");
ExpectString("obj2.x", "x");
ExpectTrue("Object.getOwnPropertyDescriptor(obj1, 'x').configurable");
ExpectTrue("Object.getOwnPropertyDescriptor(obj2, 'x').configurable");
CompileRun("Object.defineProperty(obj1, 'x',"
"{ get: function() { return 'y'; }, configurable: true })");
ExpectString("obj1.x", "y");
ExpectString("obj2.x", "x");
CompileRun("Object.defineProperty(obj2, 'x',"
"{ get: function() { return 'y'; }, configurable: true })");
ExpectString("obj1.x", "y");
ExpectString("obj2.x", "y");
ExpectTrue("Object.getOwnPropertyDescriptor(obj1, 'x').configurable");
ExpectTrue("Object.getOwnPropertyDescriptor(obj2, 'x').configurable");
CHECK(GetGlobalProperty(&context, "obj1")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
CHECK(GetGlobalProperty(&context, "obj2")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
ExpectString("obj1.x", "x");
ExpectString("obj2.x", "x");
ExpectTrue("Object.getOwnPropertyDescriptor(obj1, 'x').configurable");
ExpectTrue("Object.getOwnPropertyDescriptor(obj2, 'x').configurable");
// Define getters/setters, but now make them not configurable.
CompileRun("Object.defineProperty(obj1, 'x',"
"{ get: function() { return 'z'; }, configurable: false })");
CompileRun("Object.defineProperty(obj2, 'x',"
"{ get: function() { return 'z'; }, configurable: false })");
ExpectTrue("!Object.getOwnPropertyDescriptor(obj1, 'x').configurable");
ExpectTrue("!Object.getOwnPropertyDescriptor(obj2, 'x').configurable");
ExpectString("obj1.x", "z");
ExpectString("obj2.x", "z");
CHECK(!GetGlobalProperty(&context, "obj1")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
CHECK(!GetGlobalProperty(&context, "obj2")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
ExpectString("obj1.x", "z");
ExpectString("obj2.x", "z");
}
THREADED_TEST(DontDeleteAPIAccessorsCannotBeOverriden) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
LocalContext context;
context->Global()->Set(v8_str("obj1"), templ->NewInstance());
CompileRun("var obj2 = {};");
CHECK(GetGlobalProperty(&context, "obj1")->SetAccessor(
v8_str("x"),
GetXValue, NULL,
v8_str("donut"), v8::DEFAULT, v8::DontDelete));
CHECK(GetGlobalProperty(&context, "obj2")->SetAccessor(
v8_str("x"),
GetXValue, NULL,
v8_str("donut"), v8::DEFAULT, v8::DontDelete));
ExpectString("obj1.x", "x");
ExpectString("obj2.x", "x");
ExpectTrue("!Object.getOwnPropertyDescriptor(obj1, 'x').configurable");
ExpectTrue("!Object.getOwnPropertyDescriptor(obj2, 'x').configurable");
CHECK(!GetGlobalProperty(&context, "obj1")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
CHECK(!GetGlobalProperty(&context, "obj2")->
SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("donut")));
{
v8::TryCatch try_catch;
CompileRun("Object.defineProperty(obj1, 'x',"
"{get: function() { return 'func'; }})");
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ(*exception_value, "TypeError: Cannot redefine property: x");
}
{
v8::TryCatch try_catch;
CompileRun("Object.defineProperty(obj2, 'x',"
"{get: function() { return 'func'; }})");
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Exception());
CHECK_EQ(*exception_value, "TypeError: Cannot redefine property: x");
}
}
static void Get239Value(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(info.Data(), v8_str("donut"));
CHECK_EQ(name, v8_str("239"));
info.GetReturnValue().Set(name);
}
THREADED_TEST(ElementAPIAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
LocalContext context;
context->Global()->Set(v8_str("obj1"), templ->NewInstance());
CompileRun("var obj2 = {};");
CHECK(GetGlobalProperty(&context, "obj1")->SetAccessor(
v8_str("239"),
Get239Value, NULL,
v8_str("donut")));
CHECK(GetGlobalProperty(&context, "obj2")->SetAccessor(
v8_str("239"),
Get239Value, NULL,
v8_str("donut")));
ExpectString("obj1[239]", "239");
ExpectString("obj2[239]", "239");
ExpectString("obj1['239']", "239");
ExpectString("obj2['239']", "239");
}
v8::Persistent<Value> xValue;
static void SetXValue(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<void>& info) {
CHECK_EQ(value, v8_num(4));
CHECK_EQ(info.Data(), v8_str("donut"));
CHECK_EQ(name, v8_str("x"));
CHECK(xValue.IsEmpty());
xValue.Reset(info.GetIsolate(), value);
}
THREADED_TEST(SimplePropertyWrite) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"), GetXValue, SetXValue, v8_str("donut"));
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> script = Script::Compile(v8_str("obj.x = 4"));
for (int i = 0; i < 10; i++) {
CHECK(xValue.IsEmpty());
script->Run();
CHECK_EQ(v8_num(4), Local<Value>::New(v8::Isolate::GetCurrent(), xValue));
xValue.Dispose(context->GetIsolate());
xValue.Clear();
}
}
THREADED_TEST(SetterOnly) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"), NULL, SetXValue, v8_str("donut"));
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> script = Script::Compile(v8_str("obj.x = 4; obj.x"));
for (int i = 0; i < 10; i++) {
CHECK(xValue.IsEmpty());
script->Run();
CHECK_EQ(v8_num(4), Local<Value>::New(v8::Isolate::GetCurrent(), xValue));
xValue.Dispose(context->GetIsolate());
xValue.Clear();
}
}
THREADED_TEST(NoAccessors) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"),
static_cast<v8::AccessorGetterCallback>(NULL),
NULL,
v8_str("donut"));
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> script = Script::Compile(v8_str("obj.x = 4; obj.x"));
for (int i = 0; i < 10; i++) {
script->Run();
}
}
static void XPropertyGetter(Local<String> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK(info.Data()->IsUndefined());
info.GetReturnValue().Set(property);
}
THREADED_TEST(NamedInterceptorPropertyRead) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(XPropertyGetter);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> script = Script::Compile(v8_str("obj.x"));
for (int i = 0; i < 10; i++) {
Local<Value> result = script->Run();
CHECK_EQ(result, v8_str("x"));
}
}
THREADED_TEST(NamedInterceptorDictionaryIC) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(XPropertyGetter);
LocalContext context;
// Create an object with a named interceptor.
context->Global()->Set(v8_str("interceptor_obj"), templ->NewInstance());
Local<Script> script = Script::Compile(v8_str("interceptor_obj.x"));
for (int i = 0; i < 10; i++) {
Local<Value> result = script->Run();
CHECK_EQ(result, v8_str("x"));
}
// Create a slow case object and a function accessing a property in
// that slow case object (with dictionary probing in generated
// code). Then force object with a named interceptor into slow-case,
// pass it to the function, and check that the interceptor is called
// instead of accessing the local property.
Local<Value> result =
CompileRun("function get_x(o) { return o.x; };"
"var obj = { x : 42, y : 0 };"
"delete obj.y;"
"for (var i = 0; i < 10; i++) get_x(obj);"
"interceptor_obj.x = 42;"
"interceptor_obj.y = 10;"
"delete interceptor_obj.y;"
"get_x(interceptor_obj)");
CHECK_EQ(result, v8_str("x"));
}
THREADED_TEST(NamedInterceptorDictionaryICMultipleContext) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(XPropertyGetter);
// Create an object with a named interceptor.
v8::Local<v8::Object> object = templ->NewInstance();
context1->Global()->Set(v8_str("interceptor_obj"), object);
// Force the object into the slow case.
CompileRun("interceptor_obj.y = 0;"
"delete interceptor_obj.y;");
context1->Exit();
{
// Introduce the object into a different context.
// Repeat named loads to exercise ICs.
LocalContext context2;
context2->Global()->Set(v8_str("interceptor_obj"), object);
Local<Value> result =
CompileRun("function get_x(o) { return o.x; }"
"interceptor_obj.x = 42;"
"for (var i=0; i != 10; i++) {"
" get_x(interceptor_obj);"
"}"
"get_x(interceptor_obj)");
// Check that the interceptor was actually invoked.
CHECK_EQ(result, v8_str("x"));
}
// Return to the original context and force some object to the slow case
// to cause the NormalizedMapCache to verify.
context1->Enter();
CompileRun("var obj = { x : 0 }; delete obj.x;");
context1->Exit();
}
static void SetXOnPrototypeGetter(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
// Set x on the prototype object and do not handle the get request.
v8::Handle<v8::Value> proto = info.Holder()->GetPrototype();
proto.As<v8::Object>()->Set(v8_str("x"), v8::Integer::New(23));
}
// This is a regression test for http://crbug.com/20104. Map
// transitions should not interfere with post interceptor lookup.
THREADED_TEST(NamedInterceptorMapTransitionRead) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<v8::FunctionTemplate> function_template = v8::FunctionTemplate::New();
Local<v8::ObjectTemplate> instance_template
= function_template->InstanceTemplate();
instance_template->SetNamedPropertyHandler(SetXOnPrototypeGetter);
LocalContext context;
context->Global()->Set(v8_str("F"), function_template->GetFunction());
// Create an instance of F and introduce a map transition for x.
CompileRun("var o = new F(); o.x = 23;");
// Create an instance of F and invoke the getter. The result should be 23.
Local<Value> result = CompileRun("o = new F(); o.x");
CHECK_EQ(result->Int32Value(), 23);
}
static void IndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (index == 37) {
info.GetReturnValue().Set(v8_num(625));
}
}
static void IndexedPropertySetter(
uint32_t index,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (index == 39) {
info.GetReturnValue().Set(value);
}
}
THREADED_TEST(IndexedInterceptorWithIndexedAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IndexedPropertyGetter,
IndexedPropertySetter);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> getter_script = Script::Compile(v8_str(
"obj.__defineGetter__(\"3\", function(){return 5;});obj[3];"));
Local<Script> setter_script = Script::Compile(v8_str(
"obj.__defineSetter__(\"17\", function(val){this.foo = val;});"
"obj[17] = 23;"
"obj.foo;"));
Local<Script> interceptor_setter_script = Script::Compile(v8_str(
"obj.__defineSetter__(\"39\", function(val){this.foo = \"hit\";});"
"obj[39] = 47;"
"obj.foo;")); // This setter should not run, due to the interceptor.
Local<Script> interceptor_getter_script = Script::Compile(v8_str(
"obj[37];"));
Local<Value> result = getter_script->Run();
CHECK_EQ(v8_num(5), result);
result = setter_script->Run();
CHECK_EQ(v8_num(23), result);
result = interceptor_setter_script->Run();
CHECK_EQ(v8_num(23), result);
result = interceptor_getter_script->Run();
CHECK_EQ(v8_num(625), result);
}
static void UnboxedDoubleIndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (index < 25) {
info.GetReturnValue().Set(v8_num(index));
}
}
static void UnboxedDoubleIndexedPropertySetter(
uint32_t index,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (index < 25) {
info.GetReturnValue().Set(v8_num(index));
}
}
void UnboxedDoubleIndexedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
// Force the list of returned keys to be stored in a FastDoubleArray.
Local<Script> indexed_property_names_script = Script::Compile(v8_str(
"keys = new Array(); keys[125000] = 1;"
"for(i = 0; i < 80000; i++) { keys[i] = i; };"
"keys.length = 25; keys;"));
Local<Value> result = indexed_property_names_script->Run();
info.GetReturnValue().Set(Local<v8::Array>::Cast(result));
}
// Make sure that the the interceptor code in the runtime properly handles
// merging property name lists for double-array-backed arrays.
THREADED_TEST(IndexedInterceptorUnboxedDoubleWithIndexedAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(UnboxedDoubleIndexedPropertyGetter,
UnboxedDoubleIndexedPropertySetter,
0,
0,
UnboxedDoubleIndexedPropertyEnumerator);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
// When obj is created, force it to be Stored in a FastDoubleArray.
Local<Script> create_unboxed_double_script = Script::Compile(v8_str(
"obj[125000] = 1; for(i = 0; i < 80000; i+=2) { obj[i] = i; } "
"key_count = 0; "
"for (x in obj) {key_count++;};"
"obj;"));
Local<Value> result = create_unboxed_double_script->Run();
CHECK(result->ToObject()->HasRealIndexedProperty(2000));
Local<Script> key_count_check = Script::Compile(v8_str(
"key_count;"));
result = key_count_check->Run();
CHECK_EQ(v8_num(40013), result);
}
void NonStrictArgsIndexedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
// Force the list of returned keys to be stored in a Arguments object.
Local<Script> indexed_property_names_script = Script::Compile(v8_str(
"function f(w,x) {"
" return arguments;"
"}"
"keys = f(0, 1, 2, 3);"
"keys;"));
Local<Object> result =
Local<Object>::Cast(indexed_property_names_script->Run());
// Have to populate the handle manually, as it's not Cast-able.
i::Handle<i::JSObject> o =
v8::Utils::OpenHandle<Object, i::JSObject>(result);
i::Handle<i::JSArray> array(reinterpret_cast<i::JSArray*>(*o));
info.GetReturnValue().Set(v8::Utils::ToLocal(array));
}
static void NonStrictIndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (index < 4) {
info.GetReturnValue().Set(v8_num(index));
}
}
// Make sure that the the interceptor code in the runtime properly handles
// merging property name lists for non-string arguments arrays.
THREADED_TEST(IndexedInterceptorNonStrictArgsWithIndexedAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(NonStrictIndexedPropertyGetter,
0,
0,
0,
NonStrictArgsIndexedPropertyEnumerator);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
Local<Script> create_args_script =
Script::Compile(v8_str(
"var key_count = 0;"
"for (x in obj) {key_count++;} key_count;"));
Local<Value> result = create_args_script->Run();
CHECK_EQ(v8_num(4), result);
}
static void IdentityIndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(index);
}
THREADED_TEST(IndexedInterceptorWithGetOwnPropertyDescriptor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
// Check fast object case.
const char* fast_case_code =
"Object.getOwnPropertyDescriptor(obj, 0).value.toString()";
ExpectString(fast_case_code, "0");
// Check slow case.
const char* slow_case_code =
"obj.x = 1; delete obj.x;"
"Object.getOwnPropertyDescriptor(obj, 1).value.toString()";
ExpectString(slow_case_code, "1");
}
THREADED_TEST(IndexedInterceptorWithNoSetter) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
const char* code =
"try {"
" obj[0] = 239;"
" for (var i = 0; i < 100; i++) {"
" var v = obj[0];"
" if (v != 0) throw 'Wrong value ' + v + ' at iteration ' + i;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorWithAccessorCheck) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
obj->TurnOnAccessCheck();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"try {"
" for (var i = 0; i < 100; i++) {"
" var v = obj[0];"
" if (v != undefined) throw 'Wrong value ' + v + ' at iteration ' + i;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorWithAccessorCheckSwitchedOn) {
i::FLAG_allow_natives_syntax = true;
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"try {"
" for (var i = 0; i < 100; i++) {"
" var expected = i;"
" if (i == 5) {"
" %EnableAccessChecks(obj);"
" expected = undefined;"
" }"
" var v = obj[i];"
" if (v != expected) throw 'Wrong value ' + v + ' at iteration ' + i;"
" if (i == 5) %DisableAccessChecks(obj);"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorWithDifferentIndices) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"try {"
" for (var i = 0; i < 100; i++) {"
" var v = obj[i];"
" if (v != i) throw 'Wrong value ' + v + ' at iteration ' + i;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorWithNegativeIndices) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"try {"
" for (var i = 0; i < 100; i++) {"
" var expected = i;"
" var key = i;"
" if (i == 25) {"
" key = -1;"
" expected = undefined;"
" }"
" if (i == 50) {"
" /* probe minimal Smi number on 32-bit platforms */"
" key = -(1 << 30);"
" expected = undefined;"
" }"
" if (i == 75) {"
" /* probe minimal Smi number on 64-bit platforms */"
" key = 1 << 31;"
" expected = undefined;"
" }"
" var v = obj[key];"
" if (v != expected) throw 'Wrong value ' + v + ' at iteration ' + i;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorWithNotSmiLookup) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"try {"
" for (var i = 0; i < 100; i++) {"
" var expected = i;"
" var key = i;"
" if (i == 50) {"
" key = 'foobar';"
" expected = undefined;"
" }"
" var v = obj[key];"
" if (v != expected) throw 'Wrong value ' + v + ' at iteration ' + i;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorGoingMegamorphic) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"var original = obj;"
"try {"
" for (var i = 0; i < 100; i++) {"
" var expected = i;"
" if (i == 50) {"
" obj = {50: 'foobar'};"
" expected = 'foobar';"
" }"
" var v = obj[i];"
" if (v != expected) throw 'Wrong value ' + v + ' at iteration ' + i;"
" if (i == 50) obj = original;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorReceiverTurningSmi) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"var original = obj;"
"try {"
" for (var i = 0; i < 100; i++) {"
" var expected = i;"
" if (i == 5) {"
" obj = 239;"
" expected = undefined;"
" }"
" var v = obj[i];"
" if (v != expected) throw 'Wrong value ' + v + ' at iteration ' + i;"
" if (i == 5) obj = original;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(IndexedInterceptorOnProto) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(IdentityIndexedPropertyGetter);
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
const char* code =
"var o = {__proto__: obj};"
"try {"
" for (var i = 0; i < 100; i++) {"
" var v = o[i];"
" if (v != i) throw 'Wrong value ' + v + ' at iteration ' + i;"
" }"
" 'PASSED'"
"} catch(e) {"
" e"
"}";
ExpectString(code, "PASSED");
}
THREADED_TEST(MultiContexts) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("dummy"), v8::FunctionTemplate::New(DummyCallHandler));
Local<String> password = v8_str("Password");
// Create an environment
LocalContext context0(0, templ);
context0->SetSecurityToken(password);
v8::Handle<v8::Object> global0 = context0->Global();
global0->Set(v8_str("custom"), v8_num(1234));
CHECK_EQ(1234, global0->Get(v8_str("custom"))->Int32Value());
// Create an independent environment
LocalContext context1(0, templ);
context1->SetSecurityToken(password);
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("custom"), v8_num(1234));
CHECK_NE(global0, global1);
CHECK_EQ(1234, global0->Get(v8_str("custom"))->Int32Value());
CHECK_EQ(1234, global1->Get(v8_str("custom"))->Int32Value());
// Now create a new context with the old global
LocalContext context2(0, templ, global1);
context2->SetSecurityToken(password);
v8::Handle<v8::Object> global2 = context2->Global();
CHECK_EQ(global1, global2);
CHECK_EQ(0, global1->Get(v8_str("custom"))->Int32Value());
CHECK_EQ(0, global2->Get(v8_str("custom"))->Int32Value());
}
THREADED_TEST(FunctionPrototypeAcrossContexts) {
// Make sure that functions created by cloning boilerplates cannot
// communicate through their __proto__ field.
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext env0;
v8::Handle<v8::Object> global0 =
env0->Global();
v8::Handle<v8::Object> object0 =
global0->Get(v8_str("Object")).As<v8::Object>();
v8::Handle<v8::Object> tostring0 =
object0->Get(v8_str("toString")).As<v8::Object>();
v8::Handle<v8::Object> proto0 =
tostring0->Get(v8_str("__proto__")).As<v8::Object>();
proto0->Set(v8_str("custom"), v8_num(1234));
LocalContext env1;
v8::Handle<v8::Object> global1 =
env1->Global();
v8::Handle<v8::Object> object1 =
global1->Get(v8_str("Object")).As<v8::Object>();
v8::Handle<v8::Object> tostring1 =
object1->Get(v8_str("toString")).As<v8::Object>();
v8::Handle<v8::Object> proto1 =
tostring1->Get(v8_str("__proto__")).As<v8::Object>();
CHECK(!proto1->Has(v8_str("custom")));
}
THREADED_TEST(Regress892105) {
// Make sure that object and array literals created by cloning
// boilerplates cannot communicate through their __proto__
// field. This is rather difficult to check, but we try to add stuff
// to Object.prototype and Array.prototype and create a new
// environment. This should succeed.
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<String> source = v8_str("Object.prototype.obj = 1234;"
"Array.prototype.arr = 4567;"
"8901");
LocalContext env0;
Local<Script> script0 = Script::Compile(source);
CHECK_EQ(8901.0, script0->Run()->NumberValue());
LocalContext env1;
Local<Script> script1 = Script::Compile(source);
CHECK_EQ(8901.0, script1->Run()->NumberValue());
}
THREADED_TEST(UndetectableObject) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> desc = v8::FunctionTemplate::New();
desc->InstanceTemplate()->MarkAsUndetectable(); // undetectable
Local<v8::Object> obj = desc->GetFunction()->NewInstance();
env->Global()->Set(v8_str("undetectable"), obj);
ExpectString("undetectable.toString()", "[object Object]");
ExpectString("typeof undetectable", "undefined");
ExpectString("typeof(undetectable)", "undefined");
ExpectBoolean("typeof undetectable == 'undefined'", true);
ExpectBoolean("typeof undetectable == 'object'", false);
ExpectBoolean("if (undetectable) { true; } else { false; }", false);
ExpectBoolean("!undetectable", true);
ExpectObject("true&&undetectable", obj);
ExpectBoolean("false&&undetectable", false);
ExpectBoolean("true||undetectable", true);
ExpectObject("false||undetectable", obj);
ExpectObject("undetectable&&true", obj);
ExpectObject("undetectable&&false", obj);
ExpectBoolean("undetectable||true", true);
ExpectBoolean("undetectable||false", false);
ExpectBoolean("undetectable==null", true);
ExpectBoolean("null==undetectable", true);
ExpectBoolean("undetectable==undefined", true);
ExpectBoolean("undefined==undetectable", true);
ExpectBoolean("undetectable==undetectable", true);
ExpectBoolean("undetectable===null", false);
ExpectBoolean("null===undetectable", false);
ExpectBoolean("undetectable===undefined", false);
ExpectBoolean("undefined===undetectable", false);
ExpectBoolean("undetectable===undetectable", true);
}
THREADED_TEST(VoidLiteral) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> desc = v8::FunctionTemplate::New();
desc->InstanceTemplate()->MarkAsUndetectable(); // undetectable
Local<v8::Object> obj = desc->GetFunction()->NewInstance();
env->Global()->Set(v8_str("undetectable"), obj);
ExpectBoolean("undefined == void 0", true);
ExpectBoolean("undetectable == void 0", true);
ExpectBoolean("null == void 0", true);
ExpectBoolean("undefined === void 0", true);
ExpectBoolean("undetectable === void 0", false);
ExpectBoolean("null === void 0", false);
ExpectBoolean("void 0 == undefined", true);
ExpectBoolean("void 0 == undetectable", true);
ExpectBoolean("void 0 == null", true);
ExpectBoolean("void 0 === undefined", true);
ExpectBoolean("void 0 === undetectable", false);
ExpectBoolean("void 0 === null", false);
ExpectString("(function() {"
" try {"
" return x === void 0;"
" } catch(e) {"
" return e.toString();"
" }"
"})()",
"ReferenceError: x is not defined");
ExpectString("(function() {"
" try {"
" return void 0 === x;"
" } catch(e) {"
" return e.toString();"
" }"
"})()",
"ReferenceError: x is not defined");
}
THREADED_TEST(ExtensibleOnUndetectable) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> desc = v8::FunctionTemplate::New();
desc->InstanceTemplate()->MarkAsUndetectable(); // undetectable
Local<v8::Object> obj = desc->GetFunction()->NewInstance();
env->Global()->Set(v8_str("undetectable"), obj);
Local<String> source = v8_str("undetectable.x = 42;"
"undetectable.x");
Local<Script> script = Script::Compile(source);
CHECK_EQ(v8::Integer::New(42), script->Run());
ExpectBoolean("Object.isExtensible(undetectable)", true);
source = v8_str("Object.preventExtensions(undetectable);");
script = Script::Compile(source);
script->Run();
ExpectBoolean("Object.isExtensible(undetectable)", false);
source = v8_str("undetectable.y = 2000;");
script = Script::Compile(source);
script->Run();
ExpectBoolean("undetectable.y == undefined", true);
}
THREADED_TEST(UndetectableString) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> obj = String::NewUndetectable("foo");
env->Global()->Set(v8_str("undetectable"), obj);
ExpectString("undetectable", "foo");
ExpectString("typeof undetectable", "undefined");
ExpectString("typeof(undetectable)", "undefined");
ExpectBoolean("typeof undetectable == 'undefined'", true);
ExpectBoolean("typeof undetectable == 'string'", false);
ExpectBoolean("if (undetectable) { true; } else { false; }", false);
ExpectBoolean("!undetectable", true);
ExpectObject("true&&undetectable", obj);
ExpectBoolean("false&&undetectable", false);
ExpectBoolean("true||undetectable", true);
ExpectObject("false||undetectable", obj);
ExpectObject("undetectable&&true", obj);
ExpectObject("undetectable&&false", obj);
ExpectBoolean("undetectable||true", true);
ExpectBoolean("undetectable||false", false);
ExpectBoolean("undetectable==null", true);
ExpectBoolean("null==undetectable", true);
ExpectBoolean("undetectable==undefined", true);
ExpectBoolean("undefined==undetectable", true);
ExpectBoolean("undetectable==undetectable", true);
ExpectBoolean("undetectable===null", false);
ExpectBoolean("null===undetectable", false);
ExpectBoolean("undetectable===undefined", false);
ExpectBoolean("undefined===undetectable", false);
ExpectBoolean("undetectable===undetectable", true);
}
TEST(UndetectableOptimized) {
i::FLAG_allow_natives_syntax = true;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<String> obj = String::NewUndetectable("foo");
env->Global()->Set(v8_str("undetectable"), obj);
env->Global()->Set(v8_str("detectable"), v8_str("bar"));
ExpectString(
"function testBranch() {"
" if (!%_IsUndetectableObject(undetectable)) throw 1;"
" if (%_IsUndetectableObject(detectable)) throw 2;"
"}\n"
"function testBool() {"
" var b1 = !%_IsUndetectableObject(undetectable);"
" var b2 = %_IsUndetectableObject(detectable);"
" if (b1) throw 3;"
" if (b2) throw 4;"
" return b1 == b2;"
"}\n"
"%OptimizeFunctionOnNextCall(testBranch);"
"%OptimizeFunctionOnNextCall(testBool);"
"for (var i = 0; i < 10; i++) {"
" testBranch();"
" testBool();"
"}\n"
"\"PASS\"",
"PASS");
}
template <typename T> static void USE(T) { }
// This test is not intended to be run, just type checked.
static inline void PersistentHandles(v8::Isolate* isolate) {
USE(PersistentHandles);
Local<String> str = v8_str("foo");
v8::Persistent<String> p_str(isolate, str);
p_str.Dispose();
Local<Script> scr = Script::Compile(v8_str(""));
v8::Persistent<Script> p_scr(isolate, scr);
p_scr.Dispose();
Local<ObjectTemplate> templ = ObjectTemplate::New();
v8::Persistent<ObjectTemplate> p_templ(isolate, templ);
p_templ.Dispose();
}
static void HandleLogDelegator(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
}
THREADED_TEST(GlobalObjectTemplate) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
Local<ObjectTemplate> global_template = ObjectTemplate::New();
global_template->Set(v8_str("JSNI_Log"),
v8::FunctionTemplate::New(HandleLogDelegator));
v8::Local<Context> context = Context::New(isolate, 0, global_template);
Context::Scope context_scope(context);
Script::Compile(v8_str("JSNI_Log('LOG')"))->Run();
}
static const char* kSimpleExtensionSource =
"function Foo() {"
" return 4;"
"}";
THREADED_TEST(SimpleExtensions) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("simpletest", kSimpleExtensionSource));
const char* extension_names[] = { "simpletest" };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("Foo()"))->Run();
CHECK_EQ(result, v8::Integer::New(4));
}
THREADED_TEST(NullExtensions) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("nulltest", NULL));
const char* extension_names[] = { "nulltest" };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("1+3"))->Run();
CHECK_EQ(result, v8::Integer::New(4));
}
static const char* kEmbeddedExtensionSource =
"function Ret54321(){return 54321;}~~@@$"
"$%% THIS IS A SERIES OF NON-NULL-TERMINATED STRINGS.";
static const int kEmbeddedExtensionSourceValidLen = 34;
THREADED_TEST(ExtensionMissingSourceLength) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("srclentest_fail",
kEmbeddedExtensionSource));
const char* extension_names[] = { "srclentest_fail" };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
CHECK_EQ(0, *context);
}
THREADED_TEST(ExtensionWithSourceLength) {
for (int source_len = kEmbeddedExtensionSourceValidLen - 1;
source_len <= kEmbeddedExtensionSourceValidLen + 1; ++source_len) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
i::ScopedVector<char> extension_name(32);
i::OS::SNPrintF(extension_name, "ext #%d", source_len);
v8::RegisterExtension(new Extension(extension_name.start(),
kEmbeddedExtensionSource, 0, 0,
source_len));
const char* extension_names[1] = { extension_name.start() };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
if (source_len == kEmbeddedExtensionSourceValidLen) {
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("Ret54321()"))->Run();
CHECK_EQ(v8::Integer::New(54321), result);
} else {
// Anything but exactly the right length should fail to compile.
CHECK_EQ(0, *context);
}
}
}
static const char* kEvalExtensionSource1 =
"function UseEval1() {"
" var x = 42;"
" return eval('x');"
"}";
static const char* kEvalExtensionSource2 =
"(function() {"
" var x = 42;"
" function e() {"
" return eval('x');"
" }"
" this.UseEval2 = e;"
"})()";
THREADED_TEST(UseEvalFromExtension) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("evaltest1", kEvalExtensionSource1));
v8::RegisterExtension(new Extension("evaltest2", kEvalExtensionSource2));
const char* extension_names[] = { "evaltest1", "evaltest2" };
v8::ExtensionConfiguration extensions(2, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("UseEval1()"))->Run();
CHECK_EQ(result, v8::Integer::New(42));
result = Script::Compile(v8_str("UseEval2()"))->Run();
CHECK_EQ(result, v8::Integer::New(42));
}
static const char* kWithExtensionSource1 =
"function UseWith1() {"
" var x = 42;"
" with({x:87}) { return x; }"
"}";
static const char* kWithExtensionSource2 =
"(function() {"
" var x = 42;"
" function e() {"
" with ({x:87}) { return x; }"
" }"
" this.UseWith2 = e;"
"})()";
THREADED_TEST(UseWithFromExtension) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("withtest1", kWithExtensionSource1));
v8::RegisterExtension(new Extension("withtest2", kWithExtensionSource2));
const char* extension_names[] = { "withtest1", "withtest2" };
v8::ExtensionConfiguration extensions(2, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("UseWith1()"))->Run();
CHECK_EQ(result, v8::Integer::New(87));
result = Script::Compile(v8_str("UseWith2()"))->Run();
CHECK_EQ(result, v8::Integer::New(87));
}
THREADED_TEST(AutoExtensions) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
Extension* extension = new Extension("autotest", kSimpleExtensionSource);
extension->set_auto_enable(true);
v8::RegisterExtension(extension);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent());
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("Foo()"))->Run();
CHECK_EQ(result, v8::Integer::New(4));
}
static const char* kSyntaxErrorInExtensionSource =
"[";
// Test that a syntax error in an extension does not cause a fatal
// error but results in an empty context.
THREADED_TEST(SyntaxErrorExtensions) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("syntaxerror",
kSyntaxErrorInExtensionSource));
const char* extension_names[] = { "syntaxerror" };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
CHECK(context.IsEmpty());
}
static const char* kExceptionInExtensionSource =
"throw 42";
// Test that an exception when installing an extension does not cause
// a fatal error but results in an empty context.
THREADED_TEST(ExceptionExtensions) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("exception",
kExceptionInExtensionSource));
const char* extension_names[] = { "exception" };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
CHECK(context.IsEmpty());
}
static const char* kNativeCallInExtensionSource =
"function call_runtime_last_index_of(x) {"
" return %StringLastIndexOf(x, 'bob', 10);"
"}";
static const char* kNativeCallTest =
"call_runtime_last_index_of('bobbobboellebobboellebobbob');";
// Test that a native runtime calls are supported in extensions.
THREADED_TEST(NativeCallInExtensions) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::RegisterExtension(new Extension("nativecall",
kNativeCallInExtensionSource));
const char* extension_names[] = { "nativecall" };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str(kNativeCallTest))->Run();
CHECK_EQ(result, v8::Integer::New(3));
}
class NativeFunctionExtension : public Extension {
public:
NativeFunctionExtension(const char* name,
const char* source,
v8::FunctionCallback fun = &Echo)
: Extension(name, source),
function_(fun) { }
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
return v8::FunctionTemplate::New(function_);
}
static void Echo(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() >= 1) args.GetReturnValue().Set(args[0]);
}
private:
v8::FunctionCallback function_;
};
THREADED_TEST(NativeFunctionDeclaration) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
const char* name = "nativedecl";
v8::RegisterExtension(new NativeFunctionExtension(name,
"native function foo();"));
const char* extension_names[] = { name };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope lock(context);
v8::Handle<Value> result = Script::Compile(v8_str("foo(42);"))->Run();
CHECK_EQ(result, v8::Integer::New(42));
}
THREADED_TEST(NativeFunctionDeclarationError) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
const char* name = "nativedeclerr";
// Syntax error in extension code.
v8::RegisterExtension(new NativeFunctionExtension(name,
"native\nfunction foo();"));
const char* extension_names[] = { name };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
CHECK(context.IsEmpty());
}
THREADED_TEST(NativeFunctionDeclarationErrorEscape) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
const char* name = "nativedeclerresc";
// Syntax error in extension code - escape code in "native" means that
// it's not treated as a keyword.
v8::RegisterExtension(new NativeFunctionExtension(
name,
"nativ\\u0065 function foo();"));
const char* extension_names[] = { name };
v8::ExtensionConfiguration extensions(1, extension_names);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
CHECK(context.IsEmpty());
}
static void CheckDependencies(const char* name, const char* expected) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::ExtensionConfiguration config(1, &name);
LocalContext context(&config);
CHECK_EQ(String::New(expected), context->Global()->Get(v8_str("loaded")));
}
/*
* Configuration:
*
* /-- B <--\
* A <- -- D <-- E
* \-- C <--/
*/
THREADED_TEST(ExtensionDependency) {
static const char* kEDeps[] = { "D" };
v8::RegisterExtension(new Extension("E", "this.loaded += 'E';", 1, kEDeps));
static const char* kDDeps[] = { "B", "C" };
v8::RegisterExtension(new Extension("D", "this.loaded += 'D';", 2, kDDeps));
static const char* kBCDeps[] = { "A" };
v8::RegisterExtension(new Extension("B", "this.loaded += 'B';", 1, kBCDeps));
v8::RegisterExtension(new Extension("C", "this.loaded += 'C';", 1, kBCDeps));
v8::RegisterExtension(new Extension("A", "this.loaded += 'A';"));
CheckDependencies("A", "undefinedA");
CheckDependencies("B", "undefinedAB");
CheckDependencies("C", "undefinedAC");
CheckDependencies("D", "undefinedABCD");
CheckDependencies("E", "undefinedABCDE");
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
static const char* exts[2] = { "C", "E" };
v8::ExtensionConfiguration config(2, exts);
LocalContext context(&config);
CHECK_EQ(v8_str("undefinedACBDE"), context->Global()->Get(v8_str("loaded")));
}
static const char* kExtensionTestScript =
"native function A();"
"native function B();"
"native function C();"
"function Foo(i) {"
" if (i == 0) return A();"
" if (i == 1) return B();"
" if (i == 2) return C();"
"}";
static void CallFun(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
if (args.IsConstructCall()) {
args.This()->Set(v8_str("data"), args.Data());
args.GetReturnValue().SetNull();
return;
}
args.GetReturnValue().Set(args.Data());
}
class FunctionExtension : public Extension {
public:
FunctionExtension() : Extension("functiontest", kExtensionTestScript) { }
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<String> name);
};
static int lookup_count = 0;
v8::Handle<v8::FunctionTemplate> FunctionExtension::GetNativeFunction(
v8::Handle<String> name) {
lookup_count++;
if (name->Equals(v8_str("A"))) {
return v8::FunctionTemplate::New(CallFun, v8::Integer::New(8));
} else if (name->Equals(v8_str("B"))) {
return v8::FunctionTemplate::New(CallFun, v8::Integer::New(7));
} else if (name->Equals(v8_str("C"))) {
return v8::FunctionTemplate::New(CallFun, v8::Integer::New(6));
} else {
return v8::Handle<v8::FunctionTemplate>();
}
}
THREADED_TEST(FunctionLookup) {
v8::RegisterExtension(new FunctionExtension());
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
static const char* exts[1] = { "functiontest" };
v8::ExtensionConfiguration config(1, exts);
LocalContext context(&config);
CHECK_EQ(3, lookup_count);
CHECK_EQ(v8::Integer::New(8), Script::Compile(v8_str("Foo(0)"))->Run());
CHECK_EQ(v8::Integer::New(7), Script::Compile(v8_str("Foo(1)"))->Run());
CHECK_EQ(v8::Integer::New(6), Script::Compile(v8_str("Foo(2)"))->Run());
}
THREADED_TEST(NativeFunctionConstructCall) {
v8::RegisterExtension(new FunctionExtension());
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
static const char* exts[1] = { "functiontest" };
v8::ExtensionConfiguration config(1, exts);
LocalContext context(&config);
for (int i = 0; i < 10; i++) {
// Run a few times to ensure that allocation of objects doesn't
// change behavior of a constructor function.
CHECK_EQ(v8::Integer::New(8),
Script::Compile(v8_str("(new A()).data"))->Run());
CHECK_EQ(v8::Integer::New(7),
Script::Compile(v8_str("(new B()).data"))->Run());
CHECK_EQ(v8::Integer::New(6),
Script::Compile(v8_str("(new C()).data"))->Run());
}
}
static const char* last_location;
static const char* last_message;
void StoringErrorCallback(const char* location, const char* message) {
if (last_location == NULL) {
last_location = location;
last_message = message;
}
}
// ErrorReporting creates a circular extensions configuration and
// tests that the fatal error handler gets called. This renders V8
// unusable and therefore this test cannot be run in parallel.
TEST(ErrorReporting) {
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
static const char* aDeps[] = { "B" };
v8::RegisterExtension(new Extension("A", "", 1, aDeps));
static const char* bDeps[] = { "A" };
v8::RegisterExtension(new Extension("B", "", 1, bDeps));
last_location = NULL;
v8::ExtensionConfiguration config(1, bDeps);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &config);
CHECK(context.IsEmpty());
CHECK_NE(last_location, NULL);
}
static const char* js_code_causing_huge_string_flattening =
"var str = 'X';"
"for (var i = 0; i < 30; i++) {"
" str = str + str;"
"}"
"str.match(/X/);";
void OOMCallback(const char* location, const char* message) {
exit(0);
}
TEST(RegexpOutOfMemory) {
// Execute a script that causes out of memory when flattening a string.
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::V8::SetFatalErrorHandler(OOMCallback);
LocalContext context;
Local<Script> script =
Script::Compile(String::New(js_code_causing_huge_string_flattening));
last_location = NULL;
script->Run();
CHECK(false); // Should not return.
}
static void MissingScriptInfoMessageListener(v8::Handle<v8::Message> message,
v8::Handle<Value> data) {
CHECK(message->GetScriptResourceName()->IsUndefined());
CHECK_EQ(v8::Undefined(), message->GetScriptResourceName());
message->GetLineNumber();
message->GetSourceLine();
}
THREADED_TEST(ErrorWithMissingScriptInfo) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::V8::AddMessageListener(MissingScriptInfoMessageListener);
Script::Compile(v8_str("throw Error()"))->Run();
v8::V8::RemoveMessageListeners(MissingScriptInfoMessageListener);
}
int global_index = 0;
class Snorkel {
public:
Snorkel() { index_ = global_index++; }
int index_;
};
class Whammy {
public:
explicit Whammy(v8::Isolate* isolate) : cursor_(0), isolate_(isolate) { }
~Whammy() { script_.Dispose(isolate_); }
v8::Handle<Script> getScript() {
if (script_.IsEmpty()) script_.Reset(isolate_, v8_compile("({}).blammo"));
return Local<Script>::New(isolate_, script_);
}
public:
static const int kObjectCount = 256;
int cursor_;
v8::Isolate* isolate_;
v8::Persistent<v8::Object> objects_[kObjectCount];
v8::Persistent<Script> script_;
};
static void HandleWeakReference(v8::Isolate* isolate,
v8::Persistent<v8::Value>* obj,
Snorkel* snorkel) {
delete snorkel;
obj->ClearWeak(isolate);
}
void WhammyPropertyGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
Whammy* whammy =
static_cast<Whammy*>(v8::Handle<v8::External>::Cast(info.Data())->Value());
v8::Persistent<v8::Object>& prev = whammy->objects_[whammy->cursor_];
v8::Handle<v8::Object> obj = v8::Object::New();
if (!prev.IsEmpty()) {
v8::Local<v8::Object>::New(info.GetIsolate(), prev)
->Set(v8_str("next"), obj);
prev.MakeWeak<Value, Snorkel>(new Snorkel(), &HandleWeakReference);
whammy->objects_[whammy->cursor_].Clear();
}
whammy->objects_[whammy->cursor_].Reset(info.GetIsolate(), obj);
whammy->cursor_ = (whammy->cursor_ + 1) % Whammy::kObjectCount;
info.GetReturnValue().Set(whammy->getScript()->Run());
}
THREADED_TEST(WeakReference) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ= v8::ObjectTemplate::New();
Whammy* whammy = new Whammy(v8::Isolate::GetCurrent());
templ->SetNamedPropertyHandler(WhammyPropertyGetter,
0, 0, 0, 0,
v8::External::New(whammy));
const char* extension_list[] = { "v8/gc" };
v8::ExtensionConfiguration extensions(1, extension_list);
v8::Handle<Context> context =
Context::New(v8::Isolate::GetCurrent(), &extensions);
Context::Scope context_scope(context);
v8::Handle<v8::Object> interceptor = templ->NewInstance();
context->Global()->Set(v8_str("whammy"), interceptor);
const char* code =
"var last;"
"for (var i = 0; i < 10000; i++) {"
" var obj = whammy.length;"
" if (last) last.next = obj;"
" last = obj;"
"}"
"gc();"
"4";
v8::Handle<Value> result = CompileRun(code);
CHECK_EQ(4.0, result->NumberValue());
delete whammy;
}
static void DisposeAndSetFlag(v8::Isolate* isolate,
v8::Persistent<v8::Object>* obj,
bool* data) {
obj->Dispose(isolate);
*(data) = true;
}
THREADED_TEST(IndependentWeakHandle) {
v8::Isolate* iso = v8::Isolate::GetCurrent();
v8::HandleScope scope(iso);
v8::Handle<Context> context = Context::New(iso);
Context::Scope context_scope(context);
v8::Persistent<v8::Object> object_a, object_b;
{
v8::HandleScope handle_scope(iso);
object_a.Reset(iso, v8::Object::New());
object_b.Reset(iso, v8::Object::New());
}
bool object_a_disposed = false;
bool object_b_disposed = false;
object_a.MakeWeak(&object_a_disposed, &DisposeAndSetFlag);
object_b.MakeWeak(&object_b_disposed, &DisposeAndSetFlag);
CHECK(!object_b.IsIndependent(iso));
object_a.MarkIndependent(iso);
object_b.MarkIndependent(iso);
CHECK(object_b.IsIndependent(iso));
HEAP->PerformScavenge();
CHECK(object_a_disposed);
CHECK(object_b_disposed);
}
static void InvokeScavenge() {
HEAP->PerformScavenge();
}
static void InvokeMarkSweep() {
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
static void ForceScavenge(v8::Isolate* isolate,
v8::Persistent<v8::Object>* obj,
bool* data) {
obj->Dispose(isolate);
*(data) = true;
InvokeScavenge();
}
static void ForceMarkSweep(v8::Isolate* isolate,
v8::Persistent<v8::Object>* obj,
bool* data) {
obj->Dispose(isolate);
*(data) = true;
InvokeMarkSweep();
}
THREADED_TEST(GCFromWeakCallbacks) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Handle<Context> context = Context::New(isolate);
Context::Scope context_scope(context);
static const int kNumberOfGCTypes = 2;
typedef v8::WeakReferenceCallbacks<v8::Object, bool>::Revivable Callback;
Callback gc_forcing_callback[kNumberOfGCTypes] =
{&ForceScavenge, &ForceMarkSweep};
typedef void (*GCInvoker)();
GCInvoker invoke_gc[kNumberOfGCTypes] = {&InvokeScavenge, &InvokeMarkSweep};
for (int outer_gc = 0; outer_gc < kNumberOfGCTypes; outer_gc++) {
for (int inner_gc = 0; inner_gc < kNumberOfGCTypes; inner_gc++) {
v8::Persistent<v8::Object> object;
{
v8::HandleScope handle_scope(isolate);
object.Reset(isolate, v8::Object::New());
}
bool disposed = false;
object.MakeWeak(&disposed, gc_forcing_callback[inner_gc]);
object.MarkIndependent(isolate);
invoke_gc[outer_gc]();
CHECK(disposed);
}
}
}
static void RevivingCallback(v8::Isolate* isolate,
v8::Persistent<v8::Object>* obj,
bool* data) {
obj->ClearWeak(isolate);
*(data) = true;
}
THREADED_TEST(IndependentHandleRevival) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Handle<Context> context = Context::New(isolate);
Context::Scope context_scope(context);
v8::Persistent<v8::Object> object;
{
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> o = v8::Object::New();
object.Reset(isolate, o);
o->Set(v8_str("x"), v8::Integer::New(1));
v8::Local<String> y_str = v8_str("y");
o->Set(y_str, y_str);
}
bool revived = false;
object.MakeWeak(&revived, &RevivingCallback);
object.MarkIndependent(isolate);
HEAP->PerformScavenge();
CHECK(revived);
HEAP->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
{
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> o = v8::Local<v8::Object>::New(isolate, object);
v8::Local<String> y_str = v8_str("y");
CHECK_EQ(v8::Integer::New(1), o->Get(v8_str("x")));
CHECK(o->Get(y_str)->Equals(y_str));
}
}
v8::Handle<Function> args_fun;
static void ArgumentsTestCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CHECK_EQ(args_fun, args.Callee());
CHECK_EQ(3, args.Length());
CHECK_EQ(v8::Integer::New(1), args[0]);
CHECK_EQ(v8::Integer::New(2), args[1]);
CHECK_EQ(v8::Integer::New(3), args[2]);
CHECK_EQ(v8::Undefined(), args[3]);
v8::HandleScope scope(args.GetIsolate());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
THREADED_TEST(Arguments) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> global = ObjectTemplate::New();
global->Set(v8_str("f"), v8::FunctionTemplate::New(ArgumentsTestCallback));
LocalContext context(NULL, global);
args_fun = context->Global()->Get(v8_str("f")).As<Function>();
v8_compile("f(1, 2, 3)")->Run();
}
static void NoBlockGetterX(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>&) {
}
static void NoBlockGetterI(uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>&) {
}
static void PDeleter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Boolean>& info) {
if (!name->Equals(v8_str("foo"))) {
return; // not intercepted
}
info.GetReturnValue().Set(false); // intercepted, don't delete the property
}
static void IDeleter(uint32_t index,
const v8::PropertyCallbackInfo<v8::Boolean>& info) {
if (index != 2) {
return; // not intercepted
}
info.GetReturnValue().Set(false); // intercepted, don't delete the property
}
THREADED_TEST(Deleter) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj = ObjectTemplate::New();
obj->SetNamedPropertyHandler(NoBlockGetterX, NULL, NULL, PDeleter, NULL);
obj->SetIndexedPropertyHandler(NoBlockGetterI, NULL, NULL, IDeleter, NULL);
LocalContext context;
context->Global()->Set(v8_str("k"), obj->NewInstance());
CompileRun(
"k.foo = 'foo';"
"k.bar = 'bar';"
"k[2] = 2;"
"k[4] = 4;");
CHECK(v8_compile("delete k.foo")->Run()->IsFalse());
CHECK(v8_compile("delete k.bar")->Run()->IsTrue());
CHECK_EQ(v8_compile("k.foo")->Run(), v8_str("foo"));
CHECK(v8_compile("k.bar")->Run()->IsUndefined());
CHECK(v8_compile("delete k[2]")->Run()->IsFalse());
CHECK(v8_compile("delete k[4]")->Run()->IsTrue());
CHECK_EQ(v8_compile("k[2]")->Run(), v8_num(2));
CHECK(v8_compile("k[4]")->Run()->IsUndefined());
}
static void GetK(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (name->Equals(v8_str("foo")) ||
name->Equals(v8_str("bar")) ||
name->Equals(v8_str("baz"))) {
info.GetReturnValue().SetUndefined();
}
}
static void IndexedGetK(uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (index == 0 || index == 1) info.GetReturnValue().SetUndefined();
}
static void NamedEnum(const v8::PropertyCallbackInfo<v8::Array>& info) {
ApiTestFuzzer::Fuzz();
v8::Handle<v8::Array> result = v8::Array::New(3);
result->Set(v8::Integer::New(0), v8_str("foo"));
result->Set(v8::Integer::New(1), v8_str("bar"));
result->Set(v8::Integer::New(2), v8_str("baz"));
info.GetReturnValue().Set(result);
}
static void IndexedEnum(const v8::PropertyCallbackInfo<v8::Array>& info) {
ApiTestFuzzer::Fuzz();
v8::Handle<v8::Array> result = v8::Array::New(2);
result->Set(v8::Integer::New(0), v8_str("0"));
result->Set(v8::Integer::New(1), v8_str("1"));
info.GetReturnValue().Set(result);
}
THREADED_TEST(Enumerators) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj = ObjectTemplate::New();
obj->SetNamedPropertyHandler(GetK, NULL, NULL, NULL, NamedEnum);
obj->SetIndexedPropertyHandler(IndexedGetK, NULL, NULL, NULL, IndexedEnum);
LocalContext context;
context->Global()->Set(v8_str("k"), obj->NewInstance());
v8::Handle<v8::Array> result = v8::Handle<v8::Array>::Cast(CompileRun(
"k[10] = 0;"
"k.a = 0;"
"k[5] = 0;"
"k.b = 0;"
"k[4294967295] = 0;"
"k.c = 0;"
"k[4294967296] = 0;"
"k.d = 0;"
"k[140000] = 0;"
"k.e = 0;"
"k[30000000000] = 0;"
"k.f = 0;"
"var result = [];"
"for (var prop in k) {"
" result.push(prop);"
"}"
"result"));
// Check that we get all the property names returned including the
// ones from the enumerators in the right order: indexed properties
// in numerical order, indexed interceptor properties, named
// properties in insertion order, named interceptor properties.
// This order is not mandated by the spec, so this test is just
// documenting our behavior.
CHECK_EQ(17, result->Length());
// Indexed properties in numerical order.
CHECK_EQ(v8_str("5"), result->Get(v8::Integer::New(0)));
CHECK_EQ(v8_str("10"), result->Get(v8::Integer::New(1)));
CHECK_EQ(v8_str("140000"), result->Get(v8::Integer::New(2)));
CHECK_EQ(v8_str("4294967295"), result->Get(v8::Integer::New(3)));
// Indexed interceptor properties in the order they are returned
// from the enumerator interceptor.
CHECK_EQ(v8_str("0"), result->Get(v8::Integer::New(4)));
CHECK_EQ(v8_str("1"), result->Get(v8::Integer::New(5)));
// Named properties in insertion order.
CHECK_EQ(v8_str("a"), result->Get(v8::Integer::New(6)));
CHECK_EQ(v8_str("b"), result->Get(v8::Integer::New(7)));
CHECK_EQ(v8_str("c"), result->Get(v8::Integer::New(8)));
CHECK_EQ(v8_str("4294967296"), result->Get(v8::Integer::New(9)));
CHECK_EQ(v8_str("d"), result->Get(v8::Integer::New(10)));
CHECK_EQ(v8_str("e"), result->Get(v8::Integer::New(11)));
CHECK_EQ(v8_str("30000000000"), result->Get(v8::Integer::New(12)));
CHECK_EQ(v8_str("f"), result->Get(v8::Integer::New(13)));
// Named interceptor properties.
CHECK_EQ(v8_str("foo"), result->Get(v8::Integer::New(14)));
CHECK_EQ(v8_str("bar"), result->Get(v8::Integer::New(15)));
CHECK_EQ(v8_str("baz"), result->Get(v8::Integer::New(16)));
}
int p_getter_count;
int p_getter_count2;
static void PGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
p_getter_count++;
v8::Handle<v8::Object> global = Context::GetCurrent()->Global();
CHECK_EQ(info.Holder(), global->Get(v8_str("o1")));
if (name->Equals(v8_str("p1"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o1")));
} else if (name->Equals(v8_str("p2"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o2")));
} else if (name->Equals(v8_str("p3"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o3")));
} else if (name->Equals(v8_str("p4"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o4")));
}
}
static void RunHolderTest(v8::Handle<v8::ObjectTemplate> obj) {
ApiTestFuzzer::Fuzz();
LocalContext context;
context->Global()->Set(v8_str("o1"), obj->NewInstance());
CompileRun(
"o1.__proto__ = { };"
"var o2 = { __proto__: o1 };"
"var o3 = { __proto__: o2 };"
"var o4 = { __proto__: o3 };"
"for (var i = 0; i < 10; i++) o4.p4;"
"for (var i = 0; i < 10; i++) o3.p3;"
"for (var i = 0; i < 10; i++) o2.p2;"
"for (var i = 0; i < 10; i++) o1.p1;");
}
static void PGetter2(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
p_getter_count2++;
v8::Handle<v8::Object> global = Context::GetCurrent()->Global();
CHECK_EQ(info.Holder(), global->Get(v8_str("o1")));
if (name->Equals(v8_str("p1"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o1")));
} else if (name->Equals(v8_str("p2"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o2")));
} else if (name->Equals(v8_str("p3"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o3")));
} else if (name->Equals(v8_str("p4"))) {
CHECK_EQ(info.This(), global->Get(v8_str("o4")));
}
}
THREADED_TEST(GetterHolders) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj = ObjectTemplate::New();
obj->SetAccessor(v8_str("p1"), PGetter);
obj->SetAccessor(v8_str("p2"), PGetter);
obj->SetAccessor(v8_str("p3"), PGetter);
obj->SetAccessor(v8_str("p4"), PGetter);
p_getter_count = 0;
RunHolderTest(obj);
CHECK_EQ(40, p_getter_count);
}
THREADED_TEST(PreInterceptorHolders) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj = ObjectTemplate::New();
obj->SetNamedPropertyHandler(PGetter2);
p_getter_count2 = 0;
RunHolderTest(obj);
CHECK_EQ(40, p_getter_count2);
}
THREADED_TEST(ObjectInstantiation) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("t"), PGetter2);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
for (int i = 0; i < 100; i++) {
v8::HandleScope inner_scope(v8::Isolate::GetCurrent());
v8::Handle<v8::Object> obj = templ->NewInstance();
CHECK_NE(obj, context->Global()->Get(v8_str("o")));
context->Global()->Set(v8_str("o2"), obj);
v8::Handle<Value> value =
Script::Compile(v8_str("o.__proto__ === o2.__proto__"))->Run();
CHECK_EQ(v8::True(), value);
context->Global()->Set(v8_str("o"), obj);
}
}
static int StrCmp16(uint16_t* a, uint16_t* b) {
while (true) {
if (*a == 0 && *b == 0) return 0;
if (*a != *b) return 0 + *a - *b;
a++;
b++;
}
}
static int StrNCmp16(uint16_t* a, uint16_t* b, int n) {
while (true) {
if (n-- == 0) return 0;
if (*a == 0 && *b == 0) return 0;
if (*a != *b) return 0 + *a - *b;
a++;
b++;
}
}
int GetUtf8Length(Handle<String> str) {
int len = str->Utf8Length();
if (len < 0) {
i::Handle<i::String> istr(v8::Utils::OpenHandle(*str));
i::FlattenString(istr);
len = str->Utf8Length();
}
return len;
}
THREADED_TEST(StringWrite) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<String> str = v8_str("abcde");
// abc<Icelandic eth><Unicode snowman>.
v8::Handle<String> str2 = v8_str("abc\303\260\342\230\203");
v8::Handle<String> str3 = v8::String::New("abc\0def", 7);
const int kStride = 4; // Must match stride in for loops in JS below.
CompileRun(
"var left = '';"
"for (var i = 0; i < 0xd800; i += 4) {"
" left = left + String.fromCharCode(i);"
"}");
CompileRun(
"var right = '';"
"for (var i = 0; i < 0xd800; i += 4) {"
" right = String.fromCharCode(i) + right;"
"}");
v8::Handle<v8::Object> global = Context::GetCurrent()->Global();
Handle<String> left_tree = global->Get(v8_str("left")).As<String>();
Handle<String> right_tree = global->Get(v8_str("right")).As<String>();
CHECK_EQ(5, str2->Length());
CHECK_EQ(0xd800 / kStride, left_tree->Length());
CHECK_EQ(0xd800 / kStride, right_tree->Length());
char buf[100];
char utf8buf[0xd800 * 3];
uint16_t wbuf[100];
int len;
int charlen;
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, sizeof(utf8buf), &charlen);
CHECK_EQ(9, len);
CHECK_EQ(5, charlen);
CHECK_EQ(0, strcmp(utf8buf, "abc\303\260\342\230\203"));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 8, &charlen);
CHECK_EQ(8, len);
CHECK_EQ(5, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\303\260\342\230\203\1", 9));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 7, &charlen);
CHECK_EQ(5, len);
CHECK_EQ(4, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\303\260\1", 5));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 6, &charlen);
CHECK_EQ(5, len);
CHECK_EQ(4, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\303\260\1", 5));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 5, &charlen);
CHECK_EQ(5, len);
CHECK_EQ(4, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\303\260\1", 5));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 4, &charlen);
CHECK_EQ(3, len);
CHECK_EQ(3, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\1", 4));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 3, &charlen);
CHECK_EQ(3, len);
CHECK_EQ(3, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\1", 4));
memset(utf8buf, 0x1, 1000);
len = str2->WriteUtf8(utf8buf, 2, &charlen);
CHECK_EQ(2, len);
CHECK_EQ(2, charlen);
CHECK_EQ(0, strncmp(utf8buf, "ab\1", 3));
memset(utf8buf, 0x1, sizeof(utf8buf));
len = GetUtf8Length(left_tree);
int utf8_expected =
(0x80 + (0x800 - 0x80) * 2 + (0xd800 - 0x800) * 3) / kStride;
CHECK_EQ(utf8_expected, len);
len = left_tree->WriteUtf8(utf8buf, utf8_expected, &charlen);
CHECK_EQ(utf8_expected, len);
CHECK_EQ(0xd800 / kStride, charlen);
CHECK_EQ(0xed, static_cast<unsigned char>(utf8buf[utf8_expected - 3]));
CHECK_EQ(0x9f, static_cast<unsigned char>(utf8buf[utf8_expected - 2]));
CHECK_EQ(0xc0 - kStride,
static_cast<unsigned char>(utf8buf[utf8_expected - 1]));
CHECK_EQ(1, utf8buf[utf8_expected]);
memset(utf8buf, 0x1, sizeof(utf8buf));
len = GetUtf8Length(right_tree);
CHECK_EQ(utf8_expected, len);
len = right_tree->WriteUtf8(utf8buf, utf8_expected, &charlen);
CHECK_EQ(utf8_expected, len);
CHECK_EQ(0xd800 / kStride, charlen);
CHECK_EQ(0xed, static_cast<unsigned char>(utf8buf[0]));
CHECK_EQ(0x9f, static_cast<unsigned char>(utf8buf[1]));
CHECK_EQ(0xc0 - kStride, static_cast<unsigned char>(utf8buf[2]));
CHECK_EQ(1, utf8buf[utf8_expected]);
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf));
CHECK_EQ(5, len);
len = str->Write(wbuf);
CHECK_EQ(5, len);
CHECK_EQ(0, strcmp("abcde", buf));
uint16_t answer1[] = {'a', 'b', 'c', 'd', 'e', '\0'};
CHECK_EQ(0, StrCmp16(answer1, wbuf));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 0, 4);
CHECK_EQ(4, len);
len = str->Write(wbuf, 0, 4);
CHECK_EQ(4, len);
CHECK_EQ(0, strncmp("abcd\1", buf, 5));
uint16_t answer2[] = {'a', 'b', 'c', 'd', 0x101};
CHECK_EQ(0, StrNCmp16(answer2, wbuf, 5));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 0, 5);
CHECK_EQ(5, len);
len = str->Write(wbuf, 0, 5);
CHECK_EQ(5, len);
CHECK_EQ(0, strncmp("abcde\1", buf, 6));
uint16_t answer3[] = {'a', 'b', 'c', 'd', 'e', 0x101};
CHECK_EQ(0, StrNCmp16(answer3, wbuf, 6));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 0, 6);
CHECK_EQ(5, len);
len = str->Write(wbuf, 0, 6);
CHECK_EQ(5, len);
CHECK_EQ(0, strcmp("abcde", buf));
uint16_t answer4[] = {'a', 'b', 'c', 'd', 'e', '\0'};
CHECK_EQ(0, StrCmp16(answer4, wbuf));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 4, -1);
CHECK_EQ(1, len);
len = str->Write(wbuf, 4, -1);
CHECK_EQ(1, len);
CHECK_EQ(0, strcmp("e", buf));
uint16_t answer5[] = {'e', '\0'};
CHECK_EQ(0, StrCmp16(answer5, wbuf));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 4, 6);
CHECK_EQ(1, len);
len = str->Write(wbuf, 4, 6);
CHECK_EQ(1, len);
CHECK_EQ(0, strcmp("e", buf));
CHECK_EQ(0, StrCmp16(answer5, wbuf));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 4, 1);
CHECK_EQ(1, len);
len = str->Write(wbuf, 4, 1);
CHECK_EQ(1, len);
CHECK_EQ(0, strncmp("e\1", buf, 2));
uint16_t answer6[] = {'e', 0x101};
CHECK_EQ(0, StrNCmp16(answer6, wbuf, 2));
memset(buf, 0x1, sizeof(buf));
memset(wbuf, 0x1, sizeof(wbuf));
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf), 3, 1);
CHECK_EQ(1, len);
len = str->Write(wbuf, 3, 1);
CHECK_EQ(1, len);
CHECK_EQ(0, strncmp("d\1", buf, 2));
uint16_t answer7[] = {'d', 0x101};
CHECK_EQ(0, StrNCmp16(answer7, wbuf, 2));
memset(wbuf, 0x1, sizeof(wbuf));
wbuf[5] = 'X';
len = str->Write(wbuf, 0, 6, String::NO_NULL_TERMINATION);
CHECK_EQ(5, len);
CHECK_EQ('X', wbuf[5]);
uint16_t answer8a[] = {'a', 'b', 'c', 'd', 'e'};
uint16_t answer8b[] = {'a', 'b', 'c', 'd', 'e', '\0'};
CHECK_EQ(0, StrNCmp16(answer8a, wbuf, 5));
CHECK_NE(0, StrCmp16(answer8b, wbuf));
wbuf[5] = '\0';
CHECK_EQ(0, StrCmp16(answer8b, wbuf));
memset(buf, 0x1, sizeof(buf));
buf[5] = 'X';
len = str->WriteOneByte(reinterpret_cast<uint8_t*>(buf),
0,
6,
String::NO_NULL_TERMINATION);
CHECK_EQ(5, len);
CHECK_EQ('X', buf[5]);
CHECK_EQ(0, strncmp("abcde", buf, 5));
CHECK_NE(0, strcmp("abcde", buf));
buf[5] = '\0';
CHECK_EQ(0, strcmp("abcde", buf));
memset(utf8buf, 0x1, sizeof(utf8buf));
utf8buf[8] = 'X';
len = str2->WriteUtf8(utf8buf, sizeof(utf8buf), &charlen,
String::NO_NULL_TERMINATION);
CHECK_EQ(8, len);
CHECK_EQ('X', utf8buf[8]);
CHECK_EQ(5, charlen);
CHECK_EQ(0, strncmp(utf8buf, "abc\303\260\342\230\203", 8));
CHECK_NE(0, strcmp(utf8buf, "abc\303\260\342\230\203"));
utf8buf[8] = '\0';
CHECK_EQ(0, strcmp(utf8buf, "abc\303\260\342\230\203"));
memset(utf8buf, 0x1, sizeof(utf8buf));
utf8buf[5] = 'X';
len = str->WriteUtf8(utf8buf, sizeof(utf8buf), &charlen,
String::NO_NULL_TERMINATION);
CHECK_EQ(5, len);
CHECK_EQ('X', utf8buf[5]); // Test that the sixth character is untouched.
CHECK_EQ(5, charlen);
utf8buf[5] = '\0';
CHECK_EQ(0, strcmp(utf8buf, "abcde"));
memset(buf, 0x1, sizeof(buf));
len = str3->WriteOneByte(reinterpret_cast<uint8_t*>(buf));
CHECK_EQ(7, len);
CHECK_EQ(0, strcmp("abc", buf));
CHECK_EQ(0, buf[3]);
CHECK_EQ(0, strcmp("def", buf + 4));
CHECK_EQ(0, str->WriteOneByte(NULL, 0, 0, String::NO_NULL_TERMINATION));
CHECK_EQ(0, str->WriteUtf8(NULL, 0, 0, String::NO_NULL_TERMINATION));
CHECK_EQ(0, str->Write(NULL, 0, 0, String::NO_NULL_TERMINATION));
}
static void Utf16Helper(
LocalContext& context,
const char* name,
const char* lengths_name,
int len) {
Local<v8::Array> a =
Local<v8::Array>::Cast(context->Global()->Get(v8_str(name)));
Local<v8::Array> alens =
Local<v8::Array>::Cast(context->Global()->Get(v8_str(lengths_name)));
for (int i = 0; i < len; i++) {
Local<v8::String> string =
Local<v8::String>::Cast(a->Get(i));
Local<v8::Number> expected_len =
Local<v8::Number>::Cast(alens->Get(i));
int length = GetUtf8Length(string);
CHECK_EQ(static_cast<int>(expected_len->Value()), length);
}
}
static uint16_t StringGet(Handle<String> str, int index) {
i::Handle<i::String> istring =
v8::Utils::OpenHandle(String::Cast(*str));
return istring->Get(index);
}
static void WriteUtf8Helper(
LocalContext& context,
const char* name,
const char* lengths_name,
int len) {
Local<v8::Array> b =
Local<v8::Array>::Cast(context->Global()->Get(v8_str(name)));
Local<v8::Array> alens =
Local<v8::Array>::Cast(context->Global()->Get(v8_str(lengths_name)));
char buffer[1000];
char buffer2[1000];
for (int i = 0; i < len; i++) {
Local<v8::String> string =
Local<v8::String>::Cast(b->Get(i));
Local<v8::Number> expected_len =
Local<v8::Number>::Cast(alens->Get(i));
int utf8_length = static_cast<int>(expected_len->Value());
for (int j = utf8_length + 1; j >= 0; j--) {
memset(reinterpret_cast<void*>(&buffer), 42, sizeof(buffer));
memset(reinterpret_cast<void*>(&buffer2), 42, sizeof(buffer2));
int nchars;
int utf8_written =
string->WriteUtf8(buffer, j, &nchars, String::NO_OPTIONS);
int utf8_written2 =
string->WriteUtf8(buffer2, j, &nchars, String::NO_NULL_TERMINATION);
CHECK_GE(utf8_length + 1, utf8_written);
CHECK_GE(utf8_length, utf8_written2);
for (int k = 0; k < utf8_written2; k++) {
CHECK_EQ(buffer[k], buffer2[k]);
}
CHECK(nchars * 3 >= utf8_written - 1);
CHECK(nchars <= utf8_written);
if (j == utf8_length + 1) {
CHECK_EQ(utf8_written2, utf8_length);
CHECK_EQ(utf8_written2 + 1, utf8_written);
}
CHECK_EQ(buffer[utf8_written], 42);
if (j > utf8_length) {
if (utf8_written != 0) CHECK_EQ(buffer[utf8_written - 1], 0);
if (utf8_written > 1) CHECK_NE(buffer[utf8_written - 2], 42);
Handle<String> roundtrip = v8_str(buffer);
CHECK(roundtrip->Equals(string));
} else {
if (utf8_written != 0) CHECK_NE(buffer[utf8_written - 1], 42);
}
if (utf8_written2 != 0) CHECK_NE(buffer[utf8_written - 1], 42);
if (nchars >= 2) {
uint16_t trail = StringGet(string, nchars - 1);
uint16_t lead = StringGet(string, nchars - 2);
if (((lead & 0xfc00) == 0xd800) &&
((trail & 0xfc00) == 0xdc00)) {
unsigned char u1 = buffer2[utf8_written2 - 4];
unsigned char u2 = buffer2[utf8_written2 - 3];
unsigned char u3 = buffer2[utf8_written2 - 2];
unsigned char u4 = buffer2[utf8_written2 - 1];
CHECK_EQ((u1 & 0xf8), 0xf0);
CHECK_EQ((u2 & 0xc0), 0x80);
CHECK_EQ((u3 & 0xc0), 0x80);
CHECK_EQ((u4 & 0xc0), 0x80);
uint32_t c = 0x10000 + ((lead & 0x3ff) << 10) + (trail & 0x3ff);
CHECK_EQ((u4 & 0x3f), (c & 0x3f));
CHECK_EQ((u3 & 0x3f), ((c >> 6) & 0x3f));
CHECK_EQ((u2 & 0x3f), ((c >> 12) & 0x3f));
CHECK_EQ((u1 & 0x3), c >> 18);
}
}
}
}
}
THREADED_TEST(Utf16) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
CompileRun(
"var pad = '01234567890123456789';"
"var p = [];"
"var plens = [20, 3, 3];"
"p.push('01234567890123456789');"
"var lead = 0xd800;"
"var trail = 0xdc00;"
"p.push(String.fromCharCode(0xd800));"
"p.push(String.fromCharCode(0xdc00));"
"var a = [];"
"var b = [];"
"var c = [];"
"var alens = [];"
"for (var i = 0; i < 3; i++) {"
" p[1] = String.fromCharCode(lead++);"
" for (var j = 0; j < 3; j++) {"
" p[2] = String.fromCharCode(trail++);"
" a.push(p[i] + p[j]);"
" b.push(p[i] + p[j]);"
" c.push(p[i] + p[j]);"
" alens.push(plens[i] + plens[j]);"
" }"
"}"
"alens[5] -= 2;" // Here the surrogate pairs match up.
"var a2 = [];"
"var b2 = [];"
"var c2 = [];"
"var a2lens = [];"
"for (var m = 0; m < 9; m++) {"
" for (var n = 0; n < 9; n++) {"
" a2.push(a[m] + a[n]);"
" b2.push(b[m] + b[n]);"
" var newc = 'x' + c[m] + c[n] + 'y';"
" c2.push(newc.substring(1, newc.length - 1));"
" var utf = alens[m] + alens[n];" // And here.
// The 'n's that start with 0xdc.. are 6-8
// The 'm's that end with 0xd8.. are 1, 4 and 7
" if ((m % 3) == 1 && n >= 6) utf -= 2;"
" a2lens.push(utf);"
" }"
"}");
Utf16Helper(context, "a", "alens", 9);
Utf16Helper(context, "a2", "a2lens", 81);
WriteUtf8Helper(context, "b", "alens", 9);
WriteUtf8Helper(context, "b2", "a2lens", 81);
WriteUtf8Helper(context, "c2", "a2lens", 81);
}
static bool SameSymbol(Handle<String> s1, Handle<String> s2) {
i::Handle<i::String> is1(v8::Utils::OpenHandle(*s1));
i::Handle<i::String> is2(v8::Utils::OpenHandle(*s2));
return *is1 == *is2;
}
static void SameSymbolHelper(const char* a, const char* b) {
Handle<String> symbol1 = v8::String::NewSymbol(a);
Handle<String> symbol2 = v8::String::NewSymbol(b);
CHECK(SameSymbol(symbol1, symbol2));
}
THREADED_TEST(Utf16Symbol) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Handle<String> symbol1 = v8::String::NewSymbol("abc");
Handle<String> symbol2 = v8::String::NewSymbol("abc");
CHECK(SameSymbol(symbol1, symbol2));
SameSymbolHelper("\360\220\220\205", // 4 byte encoding.
"\355\240\201\355\260\205"); // 2 3-byte surrogates.
SameSymbolHelper("\355\240\201\355\260\206", // 2 3-byte surrogates.
"\360\220\220\206"); // 4 byte encoding.
SameSymbolHelper("x\360\220\220\205", // 4 byte encoding.
"x\355\240\201\355\260\205"); // 2 3-byte surrogates.
SameSymbolHelper("x\355\240\201\355\260\206", // 2 3-byte surrogates.
"x\360\220\220\206"); // 4 byte encoding.
CompileRun(
"var sym0 = 'benedictus';"
"var sym0b = 'S\303\270ren';"
"var sym1 = '\355\240\201\355\260\207';"
"var sym2 = '\360\220\220\210';"
"var sym3 = 'x\355\240\201\355\260\207';"
"var sym4 = 'x\360\220\220\210';"
"if (sym1.length != 2) throw sym1;"
"if (sym1.charCodeAt(1) != 0xdc07) throw sym1.charCodeAt(1);"
"if (sym2.length != 2) throw sym2;"
"if (sym2.charCodeAt(1) != 0xdc08) throw sym2.charCodeAt(2);"
"if (sym3.length != 3) throw sym3;"
"if (sym3.charCodeAt(2) != 0xdc07) throw sym1.charCodeAt(2);"
"if (sym4.length != 3) throw sym4;"
"if (sym4.charCodeAt(2) != 0xdc08) throw sym2.charCodeAt(2);");
Handle<String> sym0 = v8::String::NewSymbol("benedictus");
Handle<String> sym0b = v8::String::NewSymbol("S\303\270ren");
Handle<String> sym1 = v8::String::NewSymbol("\355\240\201\355\260\207");
Handle<String> sym2 = v8::String::NewSymbol("\360\220\220\210");
Handle<String> sym3 = v8::String::NewSymbol("x\355\240\201\355\260\207");
Handle<String> sym4 = v8::String::NewSymbol("x\360\220\220\210");
v8::Local<v8::Object> global = context->Global();
Local<Value> s0 = global->Get(v8_str("sym0"));
Local<Value> s0b = global->Get(v8_str("sym0b"));
Local<Value> s1 = global->Get(v8_str("sym1"));
Local<Value> s2 = global->Get(v8_str("sym2"));
Local<Value> s3 = global->Get(v8_str("sym3"));
Local<Value> s4 = global->Get(v8_str("sym4"));
CHECK(SameSymbol(sym0, Handle<String>::Cast(s0)));
CHECK(SameSymbol(sym0b, Handle<String>::Cast(s0b)));
CHECK(SameSymbol(sym1, Handle<String>::Cast(s1)));
CHECK(SameSymbol(sym2, Handle<String>::Cast(s2)));
CHECK(SameSymbol(sym3, Handle<String>::Cast(s3)));
CHECK(SameSymbol(sym4, Handle<String>::Cast(s4)));
}
THREADED_TEST(ToArrayIndex) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<String> str = v8_str("42");
v8::Handle<v8::Uint32> index = str->ToArrayIndex();
CHECK(!index.IsEmpty());
CHECK_EQ(42.0, index->Uint32Value());
str = v8_str("42asdf");
index = str->ToArrayIndex();
CHECK(index.IsEmpty());
str = v8_str("-42");
index = str->ToArrayIndex();
CHECK(index.IsEmpty());
str = v8_str("4294967295");
index = str->ToArrayIndex();
CHECK(!index.IsEmpty());
CHECK_EQ(4294967295.0, index->Uint32Value());
v8::Handle<v8::Number> num = v8::Number::New(1);
index = num->ToArrayIndex();
CHECK(!index.IsEmpty());
CHECK_EQ(1.0, index->Uint32Value());
num = v8::Number::New(-1);
index = num->ToArrayIndex();
CHECK(index.IsEmpty());
v8::Handle<v8::Object> obj = v8::Object::New();
index = obj->ToArrayIndex();
CHECK(index.IsEmpty());
}
THREADED_TEST(ErrorConstruction) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<String> foo = v8_str("foo");
v8::Handle<String> message = v8_str("message");
v8::Handle<Value> range_error = v8::Exception::RangeError(foo);
CHECK(range_error->IsObject());
CHECK(range_error.As<v8::Object>()->Get(message)->Equals(foo));
v8::Handle<Value> reference_error = v8::Exception::ReferenceError(foo);
CHECK(reference_error->IsObject());
CHECK(reference_error.As<v8::Object>()->Get(message)->Equals(foo));
v8::Handle<Value> syntax_error = v8::Exception::SyntaxError(foo);
CHECK(syntax_error->IsObject());
CHECK(syntax_error.As<v8::Object>()->Get(message)->Equals(foo));
v8::Handle<Value> type_error = v8::Exception::TypeError(foo);
CHECK(type_error->IsObject());
CHECK(type_error.As<v8::Object>()->Get(message)->Equals(foo));
v8::Handle<Value> error = v8::Exception::Error(foo);
CHECK(error->IsObject());
CHECK(error.As<v8::Object>()->Get(message)->Equals(foo));
}
static void YGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(v8_num(10));
}
static void YSetter(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<void>& info) {
if (info.This()->Has(name)) {
info.This()->Delete(name);
}
info.This()->Set(name, value);
}
THREADED_TEST(DeleteAccessor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj = ObjectTemplate::New();
obj->SetAccessor(v8_str("y"), YGetter, YSetter);
LocalContext context;
v8::Handle<v8::Object> holder = obj->NewInstance();
context->Global()->Set(v8_str("holder"), holder);
v8::Handle<Value> result = CompileRun(
"holder.y = 11; holder.y = 12; holder.y");
CHECK_EQ(12, result->Uint32Value());
}
THREADED_TEST(TypeSwitch) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> templ1 = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> templ2 = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> templ3 = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> templs[3] = { templ1, templ2, templ3 };
v8::Handle<v8::TypeSwitch> type_switch = v8::TypeSwitch::New(3, templs);
LocalContext context;
v8::Handle<v8::Object> obj0 = v8::Object::New();
v8::Handle<v8::Object> obj1 = templ1->GetFunction()->NewInstance();
v8::Handle<v8::Object> obj2 = templ2->GetFunction()->NewInstance();
v8::Handle<v8::Object> obj3 = templ3->GetFunction()->NewInstance();
for (int i = 0; i < 10; i++) {
CHECK_EQ(0, type_switch->match(obj0));
CHECK_EQ(1, type_switch->match(obj1));
CHECK_EQ(2, type_switch->match(obj2));
CHECK_EQ(3, type_switch->match(obj3));
CHECK_EQ(3, type_switch->match(obj3));
CHECK_EQ(2, type_switch->match(obj2));
CHECK_EQ(1, type_switch->match(obj1));
CHECK_EQ(0, type_switch->match(obj0));
}
}
// For use within the TestSecurityHandler() test.
static bool g_security_callback_result = false;
static bool NamedSecurityTestCallback(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
// Always allow read access.
if (type == v8::ACCESS_GET)
return true;
// Sometimes allow other access.
return g_security_callback_result;
}
static bool IndexedSecurityTestCallback(Local<v8::Object> global,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
// Always allow read access.
if (type == v8::ACCESS_GET)
return true;
// Sometimes allow other access.
return g_security_callback_result;
}
static int trouble_nesting = 0;
static void TroubleCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
trouble_nesting++;
// Call a JS function that throws an uncaught exception.
Local<v8::Object> arg_this = Context::GetCurrent()->Global();
Local<Value> trouble_callee = (trouble_nesting == 3) ?
arg_this->Get(v8_str("trouble_callee")) :
arg_this->Get(v8_str("trouble_caller"));
CHECK(trouble_callee->IsFunction());
args.GetReturnValue().Set(
Function::Cast(*trouble_callee)->Call(arg_this, 0, NULL));
}
static int report_count = 0;
static void ApiUncaughtExceptionTestListener(v8::Handle<v8::Message>,
v8::Handle<Value>) {
report_count++;
}
// Counts uncaught exceptions, but other tests running in parallel
// also have uncaught exceptions.
TEST(ApiUncaughtException) {
report_count = 0;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::V8::AddMessageListener(ApiUncaughtExceptionTestListener);
Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(TroubleCallback);
v8::Local<v8::Object> global = env->Global();
global->Set(v8_str("trouble"), fun->GetFunction());
Script::Compile(v8_str("function trouble_callee() {"
" var x = null;"
" return x.foo;"
"};"
"function trouble_caller() {"
" trouble();"
"};"))->Run();
Local<Value> trouble = global->Get(v8_str("trouble"));
CHECK(trouble->IsFunction());
Local<Value> trouble_callee = global->Get(v8_str("trouble_callee"));
CHECK(trouble_callee->IsFunction());
Local<Value> trouble_caller = global->Get(v8_str("trouble_caller"));
CHECK(trouble_caller->IsFunction());
Function::Cast(*trouble_caller)->Call(global, 0, NULL);
CHECK_EQ(1, report_count);
v8::V8::RemoveMessageListeners(ApiUncaughtExceptionTestListener);
}
static const char* script_resource_name = "ExceptionInNativeScript.js";
static void ExceptionInNativeScriptTestListener(v8::Handle<v8::Message> message,
v8::Handle<Value>) {
v8::Handle<v8::Value> name_val = message->GetScriptResourceName();
CHECK(!name_val.IsEmpty() && name_val->IsString());
v8::String::Utf8Value name(message->GetScriptResourceName());
CHECK_EQ(script_resource_name, *name);
CHECK_EQ(3, message->GetLineNumber());
v8::String::Utf8Value source_line(message->GetSourceLine());
CHECK_EQ(" new o.foo();", *source_line);
}
TEST(ExceptionInNativeScript) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::V8::AddMessageListener(ExceptionInNativeScriptTestListener);
Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(TroubleCallback);
v8::Local<v8::Object> global = env->Global();
global->Set(v8_str("trouble"), fun->GetFunction());
Script::Compile(v8_str("function trouble() {\n"
" var o = {};\n"
" new o.foo();\n"
"};"), v8::String::New(script_resource_name))->Run();
Local<Value> trouble = global->Get(v8_str("trouble"));
CHECK(trouble->IsFunction());
Function::Cast(*trouble)->Call(global, 0, NULL);
v8::V8::RemoveMessageListeners(ExceptionInNativeScriptTestListener);
}
TEST(CompilationErrorUsingTryCatchHandler) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::TryCatch try_catch;
Script::Compile(v8_str("This doesn't &*&@#$&*^ compile."));
CHECK_NE(NULL, *try_catch.Exception());
CHECK(try_catch.HasCaught());
}
TEST(TryCatchFinallyUsingTryCatchHandler) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::TryCatch try_catch;
Script::Compile(v8_str("try { throw ''; } catch (e) {}"))->Run();
CHECK(!try_catch.HasCaught());
Script::Compile(v8_str("try { throw ''; } finally {}"))->Run();
CHECK(try_catch.HasCaught());
try_catch.Reset();
Script::Compile(v8_str("(function() {"
"try { throw ''; } finally { return; }"
"})()"))->Run();
CHECK(!try_catch.HasCaught());
Script::Compile(v8_str("(function()"
" { try { throw ''; } finally { throw 0; }"
"})()"))->Run();
CHECK(try_catch.HasCaught());
}
// SecurityHandler can't be run twice
TEST(SecurityHandler) {
v8::HandleScope scope0(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedSecurityTestCallback,
IndexedSecurityTestCallback);
// Create an environment
v8::Handle<Context> context0 =
Context::New(v8::Isolate::GetCurrent(), NULL, global_template);
context0->Enter();
v8::Handle<v8::Object> global0 = context0->Global();
v8::Handle<Script> script0 = v8_compile("foo = 111");
script0->Run();
global0->Set(v8_str("0"), v8_num(999));
v8::Handle<Value> foo0 = global0->Get(v8_str("foo"));
CHECK_EQ(111, foo0->Int32Value());
v8::Handle<Value> z0 = global0->Get(v8_str("0"));
CHECK_EQ(999, z0->Int32Value());
// Create another environment, should fail security checks.
v8::HandleScope scope1(v8::Isolate::GetCurrent());
v8::Handle<Context> context1 =
Context::New(v8::Isolate::GetCurrent(), NULL, global_template);
context1->Enter();
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("othercontext"), global0);
// This set will fail the security check.
v8::Handle<Script> script1 =
v8_compile("othercontext.foo = 222; othercontext[0] = 888;");
script1->Run();
// This read will pass the security check.
v8::Handle<Value> foo1 = global0->Get(v8_str("foo"));
CHECK_EQ(111, foo1->Int32Value());
// This read will pass the security check.
v8::Handle<Value> z1 = global0->Get(v8_str("0"));
CHECK_EQ(999, z1->Int32Value());
// Create another environment, should pass security checks.
{ g_security_callback_result = true; // allow security handler to pass.
v8::HandleScope scope2(v8::Isolate::GetCurrent());
LocalContext context2;
v8::Handle<v8::Object> global2 = context2->Global();
global2->Set(v8_str("othercontext"), global0);
v8::Handle<Script> script2 =
v8_compile("othercontext.foo = 333; othercontext[0] = 888;");
script2->Run();
v8::Handle<Value> foo2 = global0->Get(v8_str("foo"));
CHECK_EQ(333, foo2->Int32Value());
v8::Handle<Value> z2 = global0->Get(v8_str("0"));
CHECK_EQ(888, z2->Int32Value());
}
context1->Exit();
context0->Exit();
}
THREADED_TEST(SecurityChecks) {
LocalContext env1;
v8::HandleScope handle_scope(env1->GetIsolate());
v8::Handle<Context> env2 = Context::New(env1->GetIsolate());
Local<Value> foo = v8_str("foo");
Local<Value> bar = v8_str("bar");
// Set to the same domain.
env1->SetSecurityToken(foo);
// Create a function in env1.
Script::Compile(v8_str("spy=function(){return spy;}"))->Run();
Local<Value> spy = env1->Global()->Get(v8_str("spy"));
CHECK(spy->IsFunction());
// Create another function accessing global objects.
Script::Compile(v8_str("spy2=function(){return new this.Array();}"))->Run();
Local<Value> spy2 = env1->Global()->Get(v8_str("spy2"));
CHECK(spy2->IsFunction());
// Switch to env2 in the same domain and invoke spy on env2.
{
env2->SetSecurityToken(foo);
// Enter env2
Context::Scope scope_env2(env2);
Local<Value> result = Function::Cast(*spy)->Call(env2->Global(), 0, NULL);
CHECK(result->IsFunction());
}
{
env2->SetSecurityToken(bar);
Context::Scope scope_env2(env2);
// Call cross_domain_call, it should throw an exception
v8::TryCatch try_catch;
Function::Cast(*spy2)->Call(env2->Global(), 0, NULL);
CHECK(try_catch.HasCaught());
}
}
// Regression test case for issue 1183439.
THREADED_TEST(SecurityChecksForPrototypeChain) {
LocalContext current;
v8::HandleScope scope(current->GetIsolate());
v8::Handle<Context> other = Context::New(current->GetIsolate());
// Change context to be able to get to the Object function in the
// other context without hitting the security checks.
v8::Local<Value> other_object;
{ Context::Scope scope(other);
other_object = other->Global()->Get(v8_str("Object"));
other->Global()->Set(v8_num(42), v8_num(87));
}
current->Global()->Set(v8_str("other"), other->Global());
CHECK(v8_compile("other")->Run()->Equals(other->Global()));
// Make sure the security check fails here and we get an undefined
// result instead of getting the Object function. Repeat in a loop
// to make sure to exercise the IC code.
v8::Local<Script> access_other0 = v8_compile("other.Object");
v8::Local<Script> access_other1 = v8_compile("other[42]");
for (int i = 0; i < 5; i++) {
CHECK(!access_other0->Run()->Equals(other_object));
CHECK(access_other0->Run()->IsUndefined());
CHECK(!access_other1->Run()->Equals(v8_num(87)));
CHECK(access_other1->Run()->IsUndefined());
}
// Create an object that has 'other' in its prototype chain and make
// sure we cannot access the Object function indirectly through
// that. Repeat in a loop to make sure to exercise the IC code.
v8_compile("function F() { };"
"F.prototype = other;"
"var f = new F();")->Run();
v8::Local<Script> access_f0 = v8_compile("f.Object");
v8::Local<Script> access_f1 = v8_compile("f[42]");
for (int j = 0; j < 5; j++) {
CHECK(!access_f0->Run()->Equals(other_object));
CHECK(access_f0->Run()->IsUndefined());
CHECK(!access_f1->Run()->Equals(v8_num(87)));
CHECK(access_f1->Run()->IsUndefined());
}
// Now it gets hairy: Set the prototype for the other global object
// to be the current global object. The prototype chain for 'f' now
// goes through 'other' but ends up in the current global object.
{ Context::Scope scope(other);
other->Global()->Set(v8_str("__proto__"), current->Global());
}
// Set a named and an index property on the current global
// object. To force the lookup to go through the other global object,
// the properties must not exist in the other global object.
current->Global()->Set(v8_str("foo"), v8_num(100));
current->Global()->Set(v8_num(99), v8_num(101));
// Try to read the properties from f and make sure that the access
// gets stopped by the security checks on the other global object.
Local<Script> access_f2 = v8_compile("f.foo");
Local<Script> access_f3 = v8_compile("f[99]");
for (int k = 0; k < 5; k++) {
CHECK(!access_f2->Run()->Equals(v8_num(100)));
CHECK(access_f2->Run()->IsUndefined());
CHECK(!access_f3->Run()->Equals(v8_num(101)));
CHECK(access_f3->Run()->IsUndefined());
}
}
THREADED_TEST(CrossDomainDelete) {
LocalContext env1;
v8::HandleScope handle_scope(env1->GetIsolate());
v8::Handle<Context> env2 = Context::New(env1->GetIsolate());
Local<Value> foo = v8_str("foo");
Local<Value> bar = v8_str("bar");
// Set to the same domain.
env1->SetSecurityToken(foo);
env2->SetSecurityToken(foo);
env1->Global()->Set(v8_str("prop"), v8_num(3));
env2->Global()->Set(v8_str("env1"), env1->Global());
// Change env2 to a different domain and delete env1.prop.
env2->SetSecurityToken(bar);
{
Context::Scope scope_env2(env2);
Local<Value> result =
Script::Compile(v8_str("delete env1.prop"))->Run();
CHECK(result->IsFalse());
}
// Check that env1.prop still exists.
Local<Value> v = env1->Global()->Get(v8_str("prop"));
CHECK(v->IsNumber());
CHECK_EQ(3, v->Int32Value());
}
THREADED_TEST(CrossDomainIsPropertyEnumerable) {
LocalContext env1;
v8::HandleScope handle_scope(env1->GetIsolate());
v8::Handle<Context> env2 = Context::New(env1->GetIsolate());
Local<Value> foo = v8_str("foo");
Local<Value> bar = v8_str("bar");
// Set to the same domain.
env1->SetSecurityToken(foo);
env2->SetSecurityToken(foo);
env1->Global()->Set(v8_str("prop"), v8_num(3));
env2->Global()->Set(v8_str("env1"), env1->Global());
// env1.prop is enumerable in env2.
Local<String> test = v8_str("propertyIsEnumerable.call(env1, 'prop')");
{
Context::Scope scope_env2(env2);
Local<Value> result = Script::Compile(test)->Run();
CHECK(result->IsTrue());
}
// Change env2 to a different domain and test again.
env2->SetSecurityToken(bar);
{
Context::Scope scope_env2(env2);
Local<Value> result = Script::Compile(test)->Run();
CHECK(result->IsFalse());
}
}
THREADED_TEST(CrossDomainForIn) {
LocalContext env1;
v8::HandleScope handle_scope(env1->GetIsolate());
v8::Handle<Context> env2 = Context::New(env1->GetIsolate());
Local<Value> foo = v8_str("foo");
Local<Value> bar = v8_str("bar");
// Set to the same domain.
env1->SetSecurityToken(foo);
env2->SetSecurityToken(foo);
env1->Global()->Set(v8_str("prop"), v8_num(3));
env2->Global()->Set(v8_str("env1"), env1->Global());
// Change env2 to a different domain and set env1's global object
// as the __proto__ of an object in env2 and enumerate properties
// in for-in. It shouldn't enumerate properties on env1's global
// object.
env2->SetSecurityToken(bar);
{
Context::Scope scope_env2(env2);
Local<Value> result =
CompileRun("(function(){var obj = {'__proto__':env1};"
"for (var p in obj)"
" if (p == 'prop') return false;"
"return true;})()");
CHECK(result->IsTrue());
}
}
TEST(ContextDetachGlobal) {
LocalContext env1;
v8::HandleScope handle_scope(env1->GetIsolate());
v8::Handle<Context> env2 = Context::New(env1->GetIsolate());
Local<v8::Object> global1 = env1->Global();
Local<Value> foo = v8_str("foo");
// Set to the same domain.
env1->SetSecurityToken(foo);
env2->SetSecurityToken(foo);
// Enter env2
env2->Enter();
// Create a function in env2 and add a reference to it in env1.
Local<v8::Object> global2 = env2->Global();
global2->Set(v8_str("prop"), v8::Integer::New(1));
CompileRun("function getProp() {return prop;}");
env1->Global()->Set(v8_str("getProp"),
global2->Get(v8_str("getProp")));
// Detach env2's global, and reuse the global object of env2
env2->Exit();
env2->DetachGlobal();
// env2 has a new global object.
CHECK(!env2->Global()->Equals(global2));
v8::Handle<Context> env3 = Context::New(env1->GetIsolate(),
0,
v8::Handle<v8::ObjectTemplate>(),
global2);
env3->SetSecurityToken(v8_str("bar"));
env3->Enter();
Local<v8::Object> global3 = env3->Global();
CHECK_EQ(global2, global3);
CHECK(global3->Get(v8_str("prop"))->IsUndefined());
CHECK(global3->Get(v8_str("getProp"))->IsUndefined());
global3->Set(v8_str("prop"), v8::Integer::New(-1));
global3->Set(v8_str("prop2"), v8::Integer::New(2));
env3->Exit();
// Call getProp in env1, and it should return the value 1
{
Local<Value> get_prop = global1->Get(v8_str("getProp"));
CHECK(get_prop->IsFunction());
v8::TryCatch try_catch;
Local<Value> r = Function::Cast(*get_prop)->Call(global1, 0, NULL);
CHECK(!try_catch.HasCaught());
CHECK_EQ(1, r->Int32Value());
}
// Check that env3 is not accessible from env1
{
Local<Value> r = global3->Get(v8_str("prop2"));
CHECK(r->IsUndefined());
}
}
TEST(DetachAndReattachGlobal) {
LocalContext env1;
v8::HandleScope scope(env1->GetIsolate());
// Create second environment.
v8::Handle<Context> env2 = Context::New(env1->GetIsolate());
Local<Value> foo = v8_str("foo");
// Set same security token for env1 and env2.
env1->SetSecurityToken(foo);
env2->SetSecurityToken(foo);
// Create a property on the global object in env2.
{
v8::Context::Scope scope(env2);
env2->Global()->Set(v8_str("p"), v8::Integer::New(42));
}
// Create a reference to env2 global from env1 global.
env1->Global()->Set(v8_str("other"), env2->Global());
// Check that we have access to other.p in env2 from env1.
Local<Value> result = CompileRun("other.p");
CHECK(result->IsInt32());
CHECK_EQ(42, result->Int32Value());
// Hold on to global from env2 and detach global from env2.
Local<v8::Object> global2 = env2->Global();
env2->DetachGlobal();
// Check that the global has been detached. No other.p property can
// be found.
result = CompileRun("other.p");
CHECK(result->IsUndefined());
// Reuse global2 for env3.
v8::Handle<Context> env3 = Context::New(env1->GetIsolate(),
0,
v8::Handle<v8::ObjectTemplate>(),
global2);
CHECK_EQ(global2, env3->Global());
// Start by using the same security token for env3 as for env1 and env2.
env3->SetSecurityToken(foo);
// Create a property on the global object in env3.
{
v8::Context::Scope scope(env3);
env3->Global()->Set(v8_str("p"), v8::Integer::New(24));
}
// Check that other.p is now the property in env3 and that we have access.
result = CompileRun("other.p");
CHECK(result->IsInt32());
CHECK_EQ(24, result->Int32Value());
// Change security token for env3 to something different from env1 and env2.
env3->SetSecurityToken(v8_str("bar"));
// Check that we do not have access to other.p in env1. |other| is now
// the global object for env3 which has a different security token,
// so access should be blocked.
result = CompileRun("other.p");
CHECK(result->IsUndefined());
// Detach the global for env3 and reattach it to env2.
env3->DetachGlobal();
env2->ReattachGlobal(global2);
// Check that we have access to other.p again in env1. |other| is now
// the global object for env2 which has the same security token as env1.
result = CompileRun("other.p");
CHECK(result->IsInt32());
CHECK_EQ(42, result->Int32Value());
}
static bool allowed_access_type[v8::ACCESS_KEYS + 1] = { false };
static bool NamedAccessBlocker(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
return Context::GetCurrent()->Global()->Equals(global) ||
allowed_access_type[type];
}
static bool IndexedAccessBlocker(Local<v8::Object> global,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
return Context::GetCurrent()->Global()->Equals(global) ||
allowed_access_type[type];
}
static int g_echo_value = -1;
static void EchoGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8_num(g_echo_value));
}
static void EchoSetter(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<void>&) {
if (value->IsNumber())
g_echo_value = value->Int32Value();
}
static void UnreachableGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CHECK(false); // This function should not be called..
}
static void UnreachableSetter(Local<String>,
Local<Value>,
const v8::PropertyCallbackInfo<void>&) {
CHECK(false); // This function should nto be called.
}
TEST(AccessControl) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedAccessBlocker,
IndexedAccessBlocker);
// Add an accessor accessible by cross-domain JS code.
global_template->SetAccessor(
v8_str("accessible_prop"),
EchoGetter, EchoSetter,
v8::Handle<Value>(),
v8::AccessControl(v8::ALL_CAN_READ | v8::ALL_CAN_WRITE));
// Add an accessor that is not accessible by cross-domain JS code.
global_template->SetAccessor(v8_str("blocked_prop"),
UnreachableGetter, UnreachableSetter,
v8::Handle<Value>(),
v8::DEFAULT);
// Create an environment
v8::Local<Context> context0 = Context::New(isolate, NULL, global_template);
context0->Enter();
v8::Handle<v8::Object> global0 = context0->Global();
// Define a property with JS getter and setter.
CompileRun(
"function getter() { return 'getter'; };\n"
"function setter() { return 'setter'; }\n"
"Object.defineProperty(this, 'js_accessor_p', {get:getter, set:setter})");
Local<Value> getter = global0->Get(v8_str("getter"));
Local<Value> setter = global0->Get(v8_str("setter"));
// And define normal element.
global0->Set(239, v8_str("239"));
// Define an element with JS getter and setter.
CompileRun(
"function el_getter() { return 'el_getter'; };\n"
"function el_setter() { return 'el_setter'; };\n"
"Object.defineProperty(this, '42', {get: el_getter, set: el_setter});");
Local<Value> el_getter = global0->Get(v8_str("el_getter"));
Local<Value> el_setter = global0->Get(v8_str("el_setter"));
v8::HandleScope scope1(isolate);
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("other"), global0);
// Access blocked property.
CompileRun("other.blocked_prop = 1");
ExpectUndefined("other.blocked_prop");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'blocked_prop')");
ExpectFalse("propertyIsEnumerable.call(other, 'blocked_prop')");
// Enable ACCESS_HAS
allowed_access_type[v8::ACCESS_HAS] = true;
ExpectUndefined("other.blocked_prop");
// ... and now we can get the descriptor...
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'blocked_prop').value");
// ... and enumerate the property.
ExpectTrue("propertyIsEnumerable.call(other, 'blocked_prop')");
allowed_access_type[v8::ACCESS_HAS] = false;
// Access blocked element.
CompileRun("other[239] = 1");
ExpectUndefined("other[239]");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '239')");
ExpectFalse("propertyIsEnumerable.call(other, '239')");
// Enable ACCESS_HAS
allowed_access_type[v8::ACCESS_HAS] = true;
ExpectUndefined("other[239]");
// ... and now we can get the descriptor...
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '239').value");
// ... and enumerate the property.
ExpectTrue("propertyIsEnumerable.call(other, '239')");
allowed_access_type[v8::ACCESS_HAS] = false;
// Access a property with JS accessor.
CompileRun("other.js_accessor_p = 2");
ExpectUndefined("other.js_accessor_p");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p')");
// Enable ACCESS_HAS.
allowed_access_type[v8::ACCESS_HAS] = true;
ExpectUndefined("other.js_accessor_p");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').get");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').set");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').value");
allowed_access_type[v8::ACCESS_HAS] = false;
// Enable both ACCESS_HAS and ACCESS_GET.
allowed_access_type[v8::ACCESS_HAS] = true;
allowed_access_type[v8::ACCESS_GET] = true;
ExpectString("other.js_accessor_p", "getter");
ExpectObject(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').get", getter);
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').set");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').value");
allowed_access_type[v8::ACCESS_GET] = false;
allowed_access_type[v8::ACCESS_HAS] = false;
// Enable both ACCESS_HAS and ACCESS_SET.
allowed_access_type[v8::ACCESS_HAS] = true;
allowed_access_type[v8::ACCESS_SET] = true;
ExpectUndefined("other.js_accessor_p");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').get");
ExpectObject(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').set", setter);
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').value");
allowed_access_type[v8::ACCESS_SET] = false;
allowed_access_type[v8::ACCESS_HAS] = false;
// Enable both ACCESS_HAS, ACCESS_GET and ACCESS_SET.
allowed_access_type[v8::ACCESS_HAS] = true;
allowed_access_type[v8::ACCESS_GET] = true;
allowed_access_type[v8::ACCESS_SET] = true;
ExpectString("other.js_accessor_p", "getter");
ExpectObject(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').get", getter);
ExpectObject(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').set", setter);
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'js_accessor_p').value");
allowed_access_type[v8::ACCESS_SET] = false;
allowed_access_type[v8::ACCESS_GET] = false;
allowed_access_type[v8::ACCESS_HAS] = false;
// Access an element with JS accessor.
CompileRun("other[42] = 2");
ExpectUndefined("other[42]");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42')");
// Enable ACCESS_HAS.
allowed_access_type[v8::ACCESS_HAS] = true;
ExpectUndefined("other[42]");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').get");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').set");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').value");
allowed_access_type[v8::ACCESS_HAS] = false;
// Enable both ACCESS_HAS and ACCESS_GET.
allowed_access_type[v8::ACCESS_HAS] = true;
allowed_access_type[v8::ACCESS_GET] = true;
ExpectString("other[42]", "el_getter");
ExpectObject("Object.getOwnPropertyDescriptor(other, '42').get", el_getter);
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').set");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').value");
allowed_access_type[v8::ACCESS_GET] = false;
allowed_access_type[v8::ACCESS_HAS] = false;
// Enable both ACCESS_HAS and ACCESS_SET.
allowed_access_type[v8::ACCESS_HAS] = true;
allowed_access_type[v8::ACCESS_SET] = true;
ExpectUndefined("other[42]");
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').get");
ExpectObject("Object.getOwnPropertyDescriptor(other, '42').set", el_setter);
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').value");
allowed_access_type[v8::ACCESS_SET] = false;
allowed_access_type[v8::ACCESS_HAS] = false;
// Enable both ACCESS_HAS, ACCESS_GET and ACCESS_SET.
allowed_access_type[v8::ACCESS_HAS] = true;
allowed_access_type[v8::ACCESS_GET] = true;
allowed_access_type[v8::ACCESS_SET] = true;
ExpectString("other[42]", "el_getter");
ExpectObject("Object.getOwnPropertyDescriptor(other, '42').get", el_getter);
ExpectObject("Object.getOwnPropertyDescriptor(other, '42').set", el_setter);
ExpectUndefined("Object.getOwnPropertyDescriptor(other, '42').value");
allowed_access_type[v8::ACCESS_SET] = false;
allowed_access_type[v8::ACCESS_GET] = false;
allowed_access_type[v8::ACCESS_HAS] = false;
v8::Handle<Value> value;
// Access accessible property
value = CompileRun("other.accessible_prop = 3");
CHECK(value->IsNumber());
CHECK_EQ(3, value->Int32Value());
CHECK_EQ(3, g_echo_value);
value = CompileRun("other.accessible_prop");
CHECK(value->IsNumber());
CHECK_EQ(3, value->Int32Value());
value = CompileRun(
"Object.getOwnPropertyDescriptor(other, 'accessible_prop').value");
CHECK(value->IsNumber());
CHECK_EQ(3, value->Int32Value());
value = CompileRun("propertyIsEnumerable.call(other, 'accessible_prop')");
CHECK(value->IsTrue());
// Enumeration doesn't enumerate accessors from inaccessible objects in
// the prototype chain even if the accessors are in themselves accessible.
value =
CompileRun("(function(){var obj = {'__proto__':other};"
"for (var p in obj)"
" if (p == 'accessible_prop' || p == 'blocked_prop') {"
" return false;"
" }"
"return true;})()");
CHECK(value->IsTrue());
context1->Exit();
context0->Exit();
}
TEST(AccessControlES5) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedAccessBlocker,
IndexedAccessBlocker);
// Add accessible accessor.
global_template->SetAccessor(
v8_str("accessible_prop"),
EchoGetter, EchoSetter,
v8::Handle<Value>(),
v8::AccessControl(v8::ALL_CAN_READ | v8::ALL_CAN_WRITE));
// Add an accessor that is not accessible by cross-domain JS code.
global_template->SetAccessor(v8_str("blocked_prop"),
UnreachableGetter, UnreachableSetter,
v8::Handle<Value>(),
v8::DEFAULT);
// Create an environment
v8::Local<Context> context0 = Context::New(isolate, NULL, global_template);
context0->Enter();
v8::Handle<v8::Object> global0 = context0->Global();
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("other"), global0);
// Regression test for issue 1154.
ExpectTrue("Object.keys(other).indexOf('blocked_prop') == -1");
ExpectUndefined("other.blocked_prop");
// Regression test for issue 1027.
CompileRun("Object.defineProperty(\n"
" other, 'blocked_prop', {configurable: false})");
ExpectUndefined("other.blocked_prop");
ExpectUndefined(
"Object.getOwnPropertyDescriptor(other, 'blocked_prop')");
// Regression test for issue 1171.
ExpectTrue("Object.isExtensible(other)");
CompileRun("Object.preventExtensions(other)");
ExpectTrue("Object.isExtensible(other)");
// Object.seal and Object.freeze.
CompileRun("Object.freeze(other)");
ExpectTrue("Object.isExtensible(other)");
CompileRun("Object.seal(other)");
ExpectTrue("Object.isExtensible(other)");
// Regression test for issue 1250.
// Make sure that we can set the accessible accessors value using normal
// assignment.
CompileRun("other.accessible_prop = 42");
CHECK_EQ(42, g_echo_value);
v8::Handle<Value> value;
// We follow Safari in ignoring assignments to host object accessors.
CompileRun("Object.defineProperty(other, 'accessible_prop', {value: -1})");
value = CompileRun("other.accessible_prop == 42");
CHECK(value->IsTrue());
}
static bool GetOwnPropertyNamesNamedBlocker(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
return false;
}
static bool GetOwnPropertyNamesIndexedBlocker(Local<v8::Object> global,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
return false;
}
THREADED_TEST(AccessControlGetOwnPropertyNames) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::ObjectTemplate> obj_template = v8::ObjectTemplate::New();
obj_template->Set(v8_str("x"), v8::Integer::New(42));
obj_template->SetAccessCheckCallbacks(GetOwnPropertyNamesNamedBlocker,
GetOwnPropertyNamesIndexedBlocker);
// Create an environment
v8::Local<Context> context0 = Context::New(isolate, NULL, obj_template);
context0->Enter();
v8::Handle<v8::Object> global0 = context0->Global();
v8::HandleScope scope1(v8::Isolate::GetCurrent());
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("other"), global0);
global1->Set(v8_str("object"), obj_template->NewInstance());
v8::Handle<Value> value;
// Attempt to get the property names of the other global object and
// of an object that requires access checks. Accessing the other
// global object should be blocked by access checks on the global
// proxy object. Accessing the object that requires access checks
// is blocked by the access checks on the object itself.
value = CompileRun("Object.getOwnPropertyNames(other).length == 0");
CHECK(value->IsTrue());
value = CompileRun("Object.getOwnPropertyNames(object).length == 0");
CHECK(value->IsTrue());
context1->Exit();
context0->Exit();
}
static void IndexedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
v8::Handle<v8::Array> result = v8::Array::New(2);
result->Set(0, v8::Integer::New(7));
result->Set(1, v8::Object::New());
info.GetReturnValue().Set(result);
}
static void NamedPropertyEnumerator(
const v8::PropertyCallbackInfo<v8::Array>& info) {
v8::Handle<v8::Array> result = v8::Array::New(2);
result->Set(0, v8_str("x"));
result->Set(1, v8::Object::New());
info.GetReturnValue().Set(result);
}
THREADED_TEST(GetOwnPropertyNamesWithInterceptor) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> obj_template = v8::ObjectTemplate::New();
obj_template->Set(v8_str("7"), v8::Integer::New(7));
obj_template->Set(v8_str("x"), v8::Integer::New(42));
obj_template->SetIndexedPropertyHandler(NULL, NULL, NULL, NULL,
IndexedPropertyEnumerator);
obj_template->SetNamedPropertyHandler(NULL, NULL, NULL, NULL,
NamedPropertyEnumerator);
LocalContext context;
v8::Handle<v8::Object> global = context->Global();
global->Set(v8_str("object"), obj_template->NewInstance());
v8::Handle<v8::Value> result =
CompileRun("Object.getOwnPropertyNames(object)");
CHECK(result->IsArray());
v8::Handle<v8::Array> result_array = v8::Handle<v8::Array>::Cast(result);
CHECK_EQ(3, result_array->Length());
CHECK(result_array->Get(0)->IsString());
CHECK(result_array->Get(1)->IsString());
CHECK(result_array->Get(2)->IsString());
CHECK_EQ(v8_str("7"), result_array->Get(0));
CHECK_EQ(v8_str("[object Object]"), result_array->Get(1));
CHECK_EQ(v8_str("x"), result_array->Get(2));
}
static void ConstTenGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8_num(10));
}
THREADED_TEST(CrossDomainAccessors) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New();
v8::Handle<v8::ObjectTemplate> global_template =
func_template->InstanceTemplate();
v8::Handle<v8::ObjectTemplate> proto_template =
func_template->PrototypeTemplate();
// Add an accessor to proto that's accessible by cross-domain JS code.
proto_template->SetAccessor(v8_str("accessible"),
ConstTenGetter, 0,
v8::Handle<Value>(),
v8::ALL_CAN_READ);
// Add an accessor that is not accessible by cross-domain JS code.
global_template->SetAccessor(v8_str("unreachable"),
UnreachableGetter, 0,
v8::Handle<Value>(),
v8::DEFAULT);
v8::Local<Context> context0 = Context::New(isolate, NULL, global_template);
context0->Enter();
Local<v8::Object> global = context0->Global();
// Add a normal property that shadows 'accessible'
global->Set(v8_str("accessible"), v8_num(11));
// Enter a new context.
v8::HandleScope scope1(v8::Isolate::GetCurrent());
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("other"), global);
// Should return 10, instead of 11
v8::Handle<Value> value = v8_compile("other.accessible")->Run();
CHECK(value->IsNumber());
CHECK_EQ(10, value->Int32Value());
value = v8_compile("other.unreachable")->Run();
CHECK(value->IsUndefined());
context1->Exit();
context0->Exit();
}
static int named_access_count = 0;
static int indexed_access_count = 0;
static bool NamedAccessCounter(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
named_access_count++;
return true;
}
static bool IndexedAccessCounter(Local<v8::Object> global,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
indexed_access_count++;
return true;
}
// This one is too easily disturbed by other tests.
TEST(AccessControlIC) {
named_access_count = 0;
indexed_access_count = 0;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
// Create an environment.
v8::Local<Context> context0 = Context::New(isolate);
context0->Enter();
// Create an object that requires access-check functions to be
// called for cross-domain access.
v8::Handle<v8::ObjectTemplate> object_template = v8::ObjectTemplate::New();
object_template->SetAccessCheckCallbacks(NamedAccessCounter,
IndexedAccessCounter);
Local<v8::Object> object = object_template->NewInstance();
v8::HandleScope scope1(isolate);
// Create another environment.
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
// Make easy access to the object from the other environment.
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("obj"), object);
v8::Handle<Value> value;
// Check that the named access-control function is called every time.
CompileRun("function testProp(obj) {"
" for (var i = 0; i < 10; i++) obj.prop = 1;"
" for (var j = 0; j < 10; j++) obj.prop;"
" return obj.prop"
"}");
value = CompileRun("testProp(obj)");
CHECK(value->IsNumber());
CHECK_EQ(1, value->Int32Value());
CHECK_EQ(21, named_access_count);
// Check that the named access-control function is called every time.
CompileRun("var p = 'prop';"
"function testKeyed(obj) {"
" for (var i = 0; i < 10; i++) obj[p] = 1;"
" for (var j = 0; j < 10; j++) obj[p];"
" return obj[p];"
"}");
// Use obj which requires access checks. No inline caching is used
// in that case.
value = CompileRun("testKeyed(obj)");
CHECK(value->IsNumber());
CHECK_EQ(1, value->Int32Value());
CHECK_EQ(42, named_access_count);
// Force the inline caches into generic state and try again.
CompileRun("testKeyed({ a: 0 })");
CompileRun("testKeyed({ b: 0 })");
value = CompileRun("testKeyed(obj)");
CHECK(value->IsNumber());
CHECK_EQ(1, value->Int32Value());
CHECK_EQ(63, named_access_count);
// Check that the indexed access-control function is called every time.
CompileRun("function testIndexed(obj) {"
" for (var i = 0; i < 10; i++) obj[0] = 1;"
" for (var j = 0; j < 10; j++) obj[0];"
" return obj[0]"
"}");
value = CompileRun("testIndexed(obj)");
CHECK(value->IsNumber());
CHECK_EQ(1, value->Int32Value());
CHECK_EQ(21, indexed_access_count);
// Force the inline caches into generic state.
CompileRun("testIndexed(new Array(1))");
// Test that the indexed access check is called.
value = CompileRun("testIndexed(obj)");
CHECK(value->IsNumber());
CHECK_EQ(1, value->Int32Value());
CHECK_EQ(42, indexed_access_count);
// Check that the named access check is called when invoking
// functions on an object that requires access checks.
CompileRun("obj.f = function() {}");
CompileRun("function testCallNormal(obj) {"
" for (var i = 0; i < 10; i++) obj.f();"
"}");
CompileRun("testCallNormal(obj)");
CHECK_EQ(74, named_access_count);
// Force obj into slow case.
value = CompileRun("delete obj.prop");
CHECK(value->BooleanValue());
// Force inline caches into dictionary probing mode.
CompileRun("var o = { x: 0 }; delete o.x; testProp(o);");
// Test that the named access check is called.
value = CompileRun("testProp(obj);");
CHECK(value->IsNumber());
CHECK_EQ(1, value->Int32Value());
CHECK_EQ(96, named_access_count);
// Force the call inline cache into dictionary probing mode.
CompileRun("o.f = function() {}; testCallNormal(o)");
// Test that the named access check is still called for each
// invocation of the function.
value = CompileRun("testCallNormal(obj)");
CHECK_EQ(106, named_access_count);
context1->Exit();
context0->Exit();
}
static bool NamedAccessFlatten(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
char buf[100];
int len;
CHECK(name->IsString());
memset(buf, 0x1, sizeof(buf));
len = name.As<String>()->WriteOneByte(reinterpret_cast<uint8_t*>(buf));
CHECK_EQ(4, len);
uint16_t buf2[100];
memset(buf, 0x1, sizeof(buf));
len = name.As<String>()->Write(buf2);
CHECK_EQ(4, len);
return true;
}
static bool IndexedAccessFlatten(Local<v8::Object> global,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
return true;
}
// Regression test. In access checks, operations that may cause
// garbage collection are not allowed. It used to be the case that
// using the Write operation on a string could cause a garbage
// collection due to flattening of the string. This is no longer the
// case.
THREADED_TEST(AccessControlFlatten) {
named_access_count = 0;
indexed_access_count = 0;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
// Create an environment.
v8::Local<Context> context0 = Context::New(isolate);
context0->Enter();
// Create an object that requires access-check functions to be
// called for cross-domain access.
v8::Handle<v8::ObjectTemplate> object_template = v8::ObjectTemplate::New();
object_template->SetAccessCheckCallbacks(NamedAccessFlatten,
IndexedAccessFlatten);
Local<v8::Object> object = object_template->NewInstance();
v8::HandleScope scope1(isolate);
// Create another environment.
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
// Make easy access to the object from the other environment.
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("obj"), object);
v8::Handle<Value> value;
value = v8_compile("var p = 'as' + 'df';")->Run();
value = v8_compile("obj[p];")->Run();
context1->Exit();
context0->Exit();
}
static void AccessControlNamedGetter(
Local<String>,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(42);
}
static void AccessControlNamedSetter(
Local<String>,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(value);
}
static void AccessControlIndexedGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8_num(42));
}
static void AccessControlIndexedSetter(
uint32_t,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(value);
}
THREADED_TEST(AccessControlInterceptorIC) {
named_access_count = 0;
indexed_access_count = 0;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
// Create an environment.
v8::Local<Context> context0 = Context::New(isolate);
context0->Enter();
// Create an object that requires access-check functions to be
// called for cross-domain access. The object also has interceptors
// interceptor.
v8::Handle<v8::ObjectTemplate> object_template = v8::ObjectTemplate::New();
object_template->SetAccessCheckCallbacks(NamedAccessCounter,
IndexedAccessCounter);
object_template->SetNamedPropertyHandler(AccessControlNamedGetter,
AccessControlNamedSetter);
object_template->SetIndexedPropertyHandler(AccessControlIndexedGetter,
AccessControlIndexedSetter);
Local<v8::Object> object = object_template->NewInstance();
v8::HandleScope scope1(isolate);
// Create another environment.
v8::Local<Context> context1 = Context::New(isolate);
context1->Enter();
// Make easy access to the object from the other environment.
v8::Handle<v8::Object> global1 = context1->Global();
global1->Set(v8_str("obj"), object);
v8::Handle<Value> value;
// Check that the named access-control function is called every time
// eventhough there is an interceptor on the object.
value = v8_compile("for (var i = 0; i < 10; i++) obj.x = 1;")->Run();
value = v8_compile("for (var i = 0; i < 10; i++) obj.x;"
"obj.x")->Run();
CHECK(value->IsNumber());
CHECK_EQ(42, value->Int32Value());
CHECK_EQ(21, named_access_count);
value = v8_compile("var p = 'x';")->Run();
value = v8_compile("for (var i = 0; i < 10; i++) obj[p] = 1;")->Run();
value = v8_compile("for (var i = 0; i < 10; i++) obj[p];"
"obj[p]")->Run();
CHECK(value->IsNumber());
CHECK_EQ(42, value->Int32Value());
CHECK_EQ(42, named_access_count);
// Check that the indexed access-control function is called every
// time eventhough there is an interceptor on the object.
value = v8_compile("for (var i = 0; i < 10; i++) obj[0] = 1;")->Run();
value = v8_compile("for (var i = 0; i < 10; i++) obj[0];"
"obj[0]")->Run();
CHECK(value->IsNumber());
CHECK_EQ(42, value->Int32Value());
CHECK_EQ(21, indexed_access_count);
context1->Exit();
context0->Exit();
}
THREADED_TEST(Version) {
v8::V8::GetVersion();
}
static void InstanceFunctionCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(v8_num(12));
}
THREADED_TEST(InstanceProperties) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
Local<ObjectTemplate> instance = t->InstanceTemplate();
instance->Set(v8_str("x"), v8_num(42));
instance->Set(v8_str("f"),
v8::FunctionTemplate::New(InstanceFunctionCallback));
Local<Value> o = t->GetFunction()->NewInstance();
context->Global()->Set(v8_str("i"), o);
Local<Value> value = Script::Compile(v8_str("i.x"))->Run();
CHECK_EQ(42, value->Int32Value());
value = Script::Compile(v8_str("i.f()"))->Run();
CHECK_EQ(12, value->Int32Value());
}
static void GlobalObjectInstancePropertiesGet(
Local<String> key,
const v8::PropertyCallbackInfo<v8::Value>&) {
ApiTestFuzzer::Fuzz();
}
THREADED_TEST(GlobalObjectInstanceProperties) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
Local<Value> global_object;
Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
t->InstanceTemplate()->SetNamedPropertyHandler(
GlobalObjectInstancePropertiesGet);
Local<ObjectTemplate> instance_template = t->InstanceTemplate();
instance_template->Set(v8_str("x"), v8_num(42));
instance_template->Set(v8_str("f"),
v8::FunctionTemplate::New(InstanceFunctionCallback));
// The script to check how Crankshaft compiles missing global function
// invocations. function g is not defined and should throw on call.
const char* script =
"function wrapper(call) {"
" var x = 0, y = 1;"
" for (var i = 0; i < 1000; i++) {"
" x += i * 100;"
" y += i * 100;"
" }"
" if (call) g();"
"}"
"for (var i = 0; i < 17; i++) wrapper(false);"
"var thrown = 0;"
"try { wrapper(true); } catch (e) { thrown = 1; };"
"thrown";
{
LocalContext env(NULL, instance_template);
// Hold on to the global object so it can be used again in another
// environment initialization.
global_object = env->Global();
Local<Value> value = Script::Compile(v8_str("x"))->Run();
CHECK_EQ(42, value->Int32Value());
value = Script::Compile(v8_str("f()"))->Run();
CHECK_EQ(12, value->Int32Value());
value = Script::Compile(v8_str(script))->Run();
CHECK_EQ(1, value->Int32Value());
}
{
// Create new environment reusing the global object.
LocalContext env(NULL, instance_template, global_object);
Local<Value> value = Script::Compile(v8_str("x"))->Run();
CHECK_EQ(42, value->Int32Value());
value = Script::Compile(v8_str("f()"))->Run();
CHECK_EQ(12, value->Int32Value());
value = Script::Compile(v8_str(script))->Run();
CHECK_EQ(1, value->Int32Value());
}
}
THREADED_TEST(CallKnownGlobalReceiver) {
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
Local<Value> global_object;
Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
Local<ObjectTemplate> instance_template = t->InstanceTemplate();
// The script to check that we leave global object not
// global object proxy on stack when we deoptimize from inside
// arguments evaluation.
// To provoke error we need to both force deoptimization
// from arguments evaluation and to force CallIC to take
// CallIC_Miss code path that can't cope with global proxy.
const char* script =
"function bar(x, y) { try { } finally { } }"
"function baz(x) { try { } finally { } }"
"function bom(x) { try { } finally { } }"
"function foo(x) { bar([x], bom(2)); }"
"for (var i = 0; i < 10000; i++) foo(1);"
"foo";
Local<Value> foo;
{
LocalContext env(NULL, instance_template);
// Hold on to the global object so it can be used again in another
// environment initialization.
global_object = env->Global();
foo = Script::Compile(v8_str(script))->Run();
}
{
// Create new environment reusing the global object.
LocalContext env(NULL, instance_template, global_object);
env->Global()->Set(v8_str("foo"), foo);
Script::Compile(v8_str("foo()"))->Run();
}
}
static void ShadowFunctionCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(v8_num(42));
}
static int shadow_y;
static int shadow_y_setter_call_count;
static int shadow_y_getter_call_count;
static void ShadowYSetter(Local<String>,
Local<Value>,
const v8::PropertyCallbackInfo<void>&) {
shadow_y_setter_call_count++;
shadow_y = 42;
}
static void ShadowYGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
shadow_y_getter_call_count++;
info.GetReturnValue().Set(v8_num(shadow_y));
}
static void ShadowIndexedGet(uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>&) {
}
static void ShadowNamedGet(Local<String> key,
const v8::PropertyCallbackInfo<v8::Value>&) {
}
THREADED_TEST(ShadowObject) {
shadow_y = shadow_y_setter_call_count = shadow_y_getter_call_count = 0;
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> global_template = v8::ObjectTemplate::New();
LocalContext context(NULL, global_template);
Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
t->InstanceTemplate()->SetNamedPropertyHandler(ShadowNamedGet);
t->InstanceTemplate()->SetIndexedPropertyHandler(ShadowIndexedGet);
Local<ObjectTemplate> proto = t->PrototypeTemplate();
Local<ObjectTemplate> instance = t->InstanceTemplate();
proto->Set(v8_str("f"),
v8::FunctionTemplate::New(ShadowFunctionCallback, Local<Value>()));
proto->Set(v8_str("x"), v8_num(12));
instance->SetAccessor(v8_str("y"), ShadowYGetter, ShadowYSetter);
Local<Value> o = t->GetFunction()->NewInstance();
context->Global()->Set(v8_str("__proto__"), o);
Local<Value> value =
Script::Compile(v8_str("this.propertyIsEnumerable(0)"))->Run();
CHECK(value->IsBoolean());
CHECK(!value->BooleanValue());
value = Script::Compile(v8_str("x"))->Run();
CHECK_EQ(12, value->Int32Value());
value = Script::Compile(v8_str("f()"))->Run();
CHECK_EQ(42, value->Int32Value());
Script::Compile(v8_str("y = 43"))->Run();
CHECK_EQ(1, shadow_y_setter_call_count);
value = Script::Compile(v8_str("y"))->Run();
CHECK_EQ(1, shadow_y_getter_call_count);
CHECK_EQ(42, value->Int32Value());
}
THREADED_TEST(HiddenPrototype) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New();
t0->InstanceTemplate()->Set(v8_str("x"), v8_num(0));
Local<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
t1->SetHiddenPrototype(true);
t1->InstanceTemplate()->Set(v8_str("y"), v8_num(1));
Local<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New();
t2->SetHiddenPrototype(true);
t2->InstanceTemplate()->Set(v8_str("z"), v8_num(2));
Local<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New();
t3->InstanceTemplate()->Set(v8_str("u"), v8_num(3));
Local<v8::Object> o0 = t0->GetFunction()->NewInstance();
Local<v8::Object> o1 = t1->GetFunction()->NewInstance();
Local<v8::Object> o2 = t2->GetFunction()->NewInstance();
Local<v8::Object> o3 = t3->GetFunction()->NewInstance();
// Setting the prototype on an object skips hidden prototypes.
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
o0->Set(v8_str("__proto__"), o1);
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK_EQ(1, o0->Get(v8_str("y"))->Int32Value());
o0->Set(v8_str("__proto__"), o2);
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK_EQ(1, o0->Get(v8_str("y"))->Int32Value());
CHECK_EQ(2, o0->Get(v8_str("z"))->Int32Value());
o0->Set(v8_str("__proto__"), o3);
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK_EQ(1, o0->Get(v8_str("y"))->Int32Value());
CHECK_EQ(2, o0->Get(v8_str("z"))->Int32Value());
CHECK_EQ(3, o0->Get(v8_str("u"))->Int32Value());
// Getting the prototype of o0 should get the first visible one
// which is o3. Therefore, z should not be defined on the prototype
// object.
Local<Value> proto = o0->Get(v8_str("__proto__"));
CHECK(proto->IsObject());
CHECK(proto.As<v8::Object>()->Get(v8_str("z"))->IsUndefined());
}
THREADED_TEST(HiddenPrototypeSet) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> ot = v8::FunctionTemplate::New();
Local<v8::FunctionTemplate> ht = v8::FunctionTemplate::New();
ht->SetHiddenPrototype(true);
Local<v8::FunctionTemplate> pt = v8::FunctionTemplate::New();
ht->InstanceTemplate()->Set(v8_str("x"), v8_num(0));
Local<v8::Object> o = ot->GetFunction()->NewInstance();
Local<v8::Object> h = ht->GetFunction()->NewInstance();
Local<v8::Object> p = pt->GetFunction()->NewInstance();
o->Set(v8_str("__proto__"), h);
h->Set(v8_str("__proto__"), p);
// Setting a property that exists on the hidden prototype goes there.
o->Set(v8_str("x"), v8_num(7));
CHECK_EQ(7, o->Get(v8_str("x"))->Int32Value());
CHECK_EQ(7, h->Get(v8_str("x"))->Int32Value());
CHECK(p->Get(v8_str("x"))->IsUndefined());
// Setting a new property should not be forwarded to the hidden prototype.
o->Set(v8_str("y"), v8_num(6));
CHECK_EQ(6, o->Get(v8_str("y"))->Int32Value());
CHECK(h->Get(v8_str("y"))->IsUndefined());
CHECK(p->Get(v8_str("y"))->IsUndefined());
// Setting a property that only exists on a prototype of the hidden prototype
// is treated normally again.
p->Set(v8_str("z"), v8_num(8));
CHECK_EQ(8, o->Get(v8_str("z"))->Int32Value());
CHECK_EQ(8, h->Get(v8_str("z"))->Int32Value());
CHECK_EQ(8, p->Get(v8_str("z"))->Int32Value());
o->Set(v8_str("z"), v8_num(9));
CHECK_EQ(9, o->Get(v8_str("z"))->Int32Value());
CHECK_EQ(8, h->Get(v8_str("z"))->Int32Value());
CHECK_EQ(8, p->Get(v8_str("z"))->Int32Value());
}
// Regression test for issue 2457.
THREADED_TEST(HiddenPrototypeIdentityHash) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Handle<FunctionTemplate> t = FunctionTemplate::New();
t->SetHiddenPrototype(true);
t->InstanceTemplate()->Set(v8_str("foo"), v8_num(75));
Handle<Object> p = t->GetFunction()->NewInstance();
Handle<Object> o = Object::New();
o->SetPrototype(p);
int hash = o->GetIdentityHash();
USE(hash);
o->Set(v8_str("foo"), v8_num(42));
ASSERT_EQ(hash, o->GetIdentityHash());
}
THREADED_TEST(SetPrototype) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New();
t0->InstanceTemplate()->Set(v8_str("x"), v8_num(0));
Local<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
t1->SetHiddenPrototype(true);
t1->InstanceTemplate()->Set(v8_str("y"), v8_num(1));
Local<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New();
t2->SetHiddenPrototype(true);
t2->InstanceTemplate()->Set(v8_str("z"), v8_num(2));
Local<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New();
t3->InstanceTemplate()->Set(v8_str("u"), v8_num(3));
Local<v8::Object> o0 = t0->GetFunction()->NewInstance();
Local<v8::Object> o1 = t1->GetFunction()->NewInstance();
Local<v8::Object> o2 = t2->GetFunction()->NewInstance();
Local<v8::Object> o3 = t3->GetFunction()->NewInstance();
// Setting the prototype on an object does not skip hidden prototypes.
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK(o0->SetPrototype(o1));
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK_EQ(1, o0->Get(v8_str("y"))->Int32Value());
CHECK(o1->SetPrototype(o2));
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK_EQ(1, o0->Get(v8_str("y"))->Int32Value());
CHECK_EQ(2, o0->Get(v8_str("z"))->Int32Value());
CHECK(o2->SetPrototype(o3));
CHECK_EQ(0, o0->Get(v8_str("x"))->Int32Value());
CHECK_EQ(1, o0->Get(v8_str("y"))->Int32Value());
CHECK_EQ(2, o0->Get(v8_str("z"))->Int32Value());
CHECK_EQ(3, o0->Get(v8_str("u"))->Int32Value());
// Getting the prototype of o0 should get the first visible one
// which is o3. Therefore, z should not be defined on the prototype
// object.
Local<Value> proto = o0->Get(v8_str("__proto__"));
CHECK(proto->IsObject());
CHECK_EQ(proto.As<v8::Object>(), o3);
// However, Object::GetPrototype ignores hidden prototype.
Local<Value> proto0 = o0->GetPrototype();
CHECK(proto0->IsObject());
CHECK_EQ(proto0.As<v8::Object>(), o1);
Local<Value> proto1 = o1->GetPrototype();
CHECK(proto1->IsObject());
CHECK_EQ(proto1.As<v8::Object>(), o2);
Local<Value> proto2 = o2->GetPrototype();
CHECK(proto2->IsObject());
CHECK_EQ(proto2.As<v8::Object>(), o3);
}
// Getting property names of an object with a prototype chain that
// triggers dictionary elements in GetLocalPropertyNames() shouldn't
// crash the runtime.
THREADED_TEST(Regress91517) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
t1->SetHiddenPrototype(true);
t1->InstanceTemplate()->Set(v8_str("foo"), v8_num(1));
Local<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New();
t2->SetHiddenPrototype(true);
t2->InstanceTemplate()->Set(v8_str("fuz1"), v8_num(2));
t2->InstanceTemplate()->Set(v8_str("objects"), v8::Object::New());
t2->InstanceTemplate()->Set(v8_str("fuz2"), v8_num(2));
Local<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New();
t3->SetHiddenPrototype(true);
t3->InstanceTemplate()->Set(v8_str("boo"), v8_num(3));
Local<v8::FunctionTemplate> t4 = v8::FunctionTemplate::New();
t4->InstanceTemplate()->Set(v8_str("baz"), v8_num(4));
// Force dictionary-based properties.
i::ScopedVector<char> name_buf(1024);
for (int i = 1; i <= 1000; i++) {
i::OS::SNPrintF(name_buf, "sdf%d", i);
t2->InstanceTemplate()->Set(v8_str(name_buf.start()), v8_num(2));
}
Local<v8::Object> o1 = t1->GetFunction()->NewInstance();
Local<v8::Object> o2 = t2->GetFunction()->NewInstance();
Local<v8::Object> o3 = t3->GetFunction()->NewInstance();
Local<v8::Object> o4 = t4->GetFunction()->NewInstance();
// Create prototype chain of hidden prototypes.
CHECK(o4->SetPrototype(o3));
CHECK(o3->SetPrototype(o2));
CHECK(o2->SetPrototype(o1));
// Call the runtime version of GetLocalPropertyNames() on the natively
// created object through JavaScript.
context->Global()->Set(v8_str("obj"), o4);
CompileRun("var names = %GetLocalPropertyNames(obj, true);");
ExpectInt32("names.length", 1006);
ExpectTrue("names.indexOf(\"baz\") >= 0");
ExpectTrue("names.indexOf(\"boo\") >= 0");
ExpectTrue("names.indexOf(\"foo\") >= 0");
ExpectTrue("names.indexOf(\"fuz1\") >= 0");
ExpectTrue("names.indexOf(\"fuz2\") >= 0");
ExpectFalse("names[1005] == undefined");
}
THREADED_TEST(FunctionReadOnlyPrototype) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
t1->PrototypeTemplate()->Set(v8_str("x"), v8::Integer::New(42));
t1->ReadOnlyPrototype();
context->Global()->Set(v8_str("func1"), t1->GetFunction());
// Configured value of ReadOnly flag.
CHECK(CompileRun(
"(function() {"
" descriptor = Object.getOwnPropertyDescriptor(func1, 'prototype');"
" return (descriptor['writable'] == false);"
"})()")->BooleanValue());
CHECK_EQ(42, CompileRun("func1.prototype.x")->Int32Value());
CHECK_EQ(42,
CompileRun("func1.prototype = {}; func1.prototype.x")->Int32Value());
Local<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New();
t2->PrototypeTemplate()->Set(v8_str("x"), v8::Integer::New(42));
context->Global()->Set(v8_str("func2"), t2->GetFunction());
// Default value of ReadOnly flag.
CHECK(CompileRun(
"(function() {"
" descriptor = Object.getOwnPropertyDescriptor(func2, 'prototype');"
" return (descriptor['writable'] == true);"
"})()")->BooleanValue());
CHECK_EQ(42, CompileRun("func2.prototype.x")->Int32Value());
}
THREADED_TEST(SetPrototypeThrows) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
Local<v8::Object> o0 = t->GetFunction()->NewInstance();
Local<v8::Object> o1 = t->GetFunction()->NewInstance();
CHECK(o0->SetPrototype(o1));
// If setting the prototype leads to the cycle, SetPrototype should
// return false and keep VM in sane state.
v8::TryCatch try_catch;
CHECK(!o1->SetPrototype(o0));
CHECK(!try_catch.HasCaught());
ASSERT(!i::Isolate::Current()->has_pending_exception());
CHECK_EQ(42, CompileRun("function f() { return 42; }; f()")->Int32Value());
}
THREADED_TEST(GetterSetterExceptions) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
CompileRun(
"function Foo() { };"
"function Throw() { throw 5; };"
"var x = { };"
"x.__defineSetter__('set', Throw);"
"x.__defineGetter__('get', Throw);");
Local<v8::Object> x =
Local<v8::Object>::Cast(context->Global()->Get(v8_str("x")));
v8::TryCatch try_catch;
x->Set(v8_str("set"), v8::Integer::New(8));
x->Get(v8_str("get"));
x->Set(v8_str("set"), v8::Integer::New(8));
x->Get(v8_str("get"));
x->Set(v8_str("set"), v8::Integer::New(8));
x->Get(v8_str("get"));
x->Set(v8_str("set"), v8::Integer::New(8));
x->Get(v8_str("get"));
}
THREADED_TEST(Constructor) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->SetClassName(v8_str("Fun"));
Local<Function> cons = templ->GetFunction();
context->Global()->Set(v8_str("Fun"), cons);
Local<v8::Object> inst = cons->NewInstance();
i::Handle<i::JSObject> obj(v8::Utils::OpenHandle(*inst));
CHECK(obj->IsJSObject());
Local<Value> value = CompileRun("(new Fun()).constructor === Fun");
CHECK(value->BooleanValue());
}
static void ConstructorCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
Local<Object> This;
if (args.IsConstructCall()) {
Local<Object> Holder = args.Holder();
This = Object::New();
Local<Value> proto = Holder->GetPrototype();
if (proto->IsObject()) {
This->SetPrototype(proto);
}
} else {
This = args.This();
}
This->Set(v8_str("a"), args[0]);
args.GetReturnValue().Set(This);
}
static void FakeConstructorCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(args[0]);
}
THREADED_TEST(ConstructorForObject) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
{ Local<ObjectTemplate> instance_template = ObjectTemplate::New();
instance_template->SetCallAsFunctionHandler(ConstructorCallback);
Local<Object> instance = instance_template->NewInstance();
context->Global()->Set(v8_str("obj"), instance);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
// Call the Object's constructor with a 32-bit signed integer.
value = CompileRun("(function() { var o = new obj(28); return o.a; })()");
CHECK(!try_catch.HasCaught());
CHECK(value->IsInt32());
CHECK_EQ(28, value->Int32Value());
Local<Value> args1[] = { v8_num(28) };
Local<Value> value_obj1 = instance->CallAsConstructor(1, args1);
CHECK(value_obj1->IsObject());
Local<Object> object1 = Local<Object>::Cast(value_obj1);
value = object1->Get(v8_str("a"));
CHECK(value->IsInt32());
CHECK(!try_catch.HasCaught());
CHECK_EQ(28, value->Int32Value());
// Call the Object's constructor with a String.
value = CompileRun(
"(function() { var o = new obj('tipli'); return o.a; })()");
CHECK(!try_catch.HasCaught());
CHECK(value->IsString());
String::Utf8Value string_value1(value->ToString());
CHECK_EQ("tipli", *string_value1);
Local<Value> args2[] = { v8_str("tipli") };
Local<Value> value_obj2 = instance->CallAsConstructor(1, args2);
CHECK(value_obj2->IsObject());
Local<Object> object2 = Local<Object>::Cast(value_obj2);
value = object2->Get(v8_str("a"));
CHECK(!try_catch.HasCaught());
CHECK(value->IsString());
String::Utf8Value string_value2(value->ToString());
CHECK_EQ("tipli", *string_value2);
// Call the Object's constructor with a Boolean.
value = CompileRun("(function() { var o = new obj(true); return o.a; })()");
CHECK(!try_catch.HasCaught());
CHECK(value->IsBoolean());
CHECK_EQ(true, value->BooleanValue());
Handle<Value> args3[] = { v8::True() };
Local<Value> value_obj3 = instance->CallAsConstructor(1, args3);
CHECK(value_obj3->IsObject());
Local<Object> object3 = Local<Object>::Cast(value_obj3);
value = object3->Get(v8_str("a"));
CHECK(!try_catch.HasCaught());
CHECK(value->IsBoolean());
CHECK_EQ(true, value->BooleanValue());
// Call the Object's constructor with undefined.
Handle<Value> args4[] = { v8::Undefined() };
Local<Value> value_obj4 = instance->CallAsConstructor(1, args4);
CHECK(value_obj4->IsObject());
Local<Object> object4 = Local<Object>::Cast(value_obj4);
value = object4->Get(v8_str("a"));
CHECK(!try_catch.HasCaught());
CHECK(value->IsUndefined());
// Call the Object's constructor with null.
Handle<Value> args5[] = { v8::Null() };
Local<Value> value_obj5 = instance->CallAsConstructor(1, args5);
CHECK(value_obj5->IsObject());
Local<Object> object5 = Local<Object>::Cast(value_obj5);
value = object5->Get(v8_str("a"));
CHECK(!try_catch.HasCaught());
CHECK(value->IsNull());
}
// Check exception handling when there is no constructor set for the Object.
{ Local<ObjectTemplate> instance_template = ObjectTemplate::New();
Local<Object> instance = instance_template->NewInstance();
context->Global()->Set(v8_str("obj2"), instance);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
value = CompileRun("new obj2(28)");
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value1(try_catch.Exception());
CHECK_EQ("TypeError: object is not a function", *exception_value1);
try_catch.Reset();
Local<Value> args[] = { v8_num(29) };
value = instance->CallAsConstructor(1, args);
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value2(try_catch.Exception());
CHECK_EQ("TypeError: #<Object> is not a function", *exception_value2);
try_catch.Reset();
}
// Check the case when constructor throws exception.
{ Local<ObjectTemplate> instance_template = ObjectTemplate::New();
instance_template->SetCallAsFunctionHandler(ThrowValue);
Local<Object> instance = instance_template->NewInstance();
context->Global()->Set(v8_str("obj3"), instance);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
value = CompileRun("new obj3(22)");
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value1(try_catch.Exception());
CHECK_EQ("22", *exception_value1);
try_catch.Reset();
Local<Value> args[] = { v8_num(23) };
value = instance->CallAsConstructor(1, args);
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value2(try_catch.Exception());
CHECK_EQ("23", *exception_value2);
try_catch.Reset();
}
// Check whether constructor returns with an object or non-object.
{ Local<FunctionTemplate> function_template =
FunctionTemplate::New(FakeConstructorCallback);
Local<Function> function = function_template->GetFunction();
Local<Object> instance1 = function;
context->Global()->Set(v8_str("obj4"), instance1);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
CHECK(instance1->IsObject());
CHECK(instance1->IsFunction());
value = CompileRun("new obj4(28)");
CHECK(!try_catch.HasCaught());
CHECK(value->IsObject());
Local<Value> args1[] = { v8_num(28) };
value = instance1->CallAsConstructor(1, args1);
CHECK(!try_catch.HasCaught());
CHECK(value->IsObject());
Local<ObjectTemplate> instance_template = ObjectTemplate::New();
instance_template->SetCallAsFunctionHandler(FakeConstructorCallback);
Local<Object> instance2 = instance_template->NewInstance();
context->Global()->Set(v8_str("obj5"), instance2);
CHECK(!try_catch.HasCaught());
CHECK(instance2->IsObject());
CHECK(!instance2->IsFunction());
value = CompileRun("new obj5(28)");
CHECK(!try_catch.HasCaught());
CHECK(!value->IsObject());
Local<Value> args2[] = { v8_num(28) };
value = instance2->CallAsConstructor(1, args2);
CHECK(!try_catch.HasCaught());
CHECK(!value->IsObject());
}
}
THREADED_TEST(FunctionDescriptorException) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->SetClassName(v8_str("Fun"));
Local<Function> cons = templ->GetFunction();
context->Global()->Set(v8_str("Fun"), cons);
Local<Value> value = CompileRun(
"function test() {"
" try {"
" (new Fun()).blah()"
" } catch (e) {"
" var str = String(e);"
" if (str.indexOf('TypeError') == -1) return 1;"
" if (str.indexOf('[object Fun]') != -1) return 2;"
" if (str.indexOf('#<Fun>') == -1) return 3;"
" return 0;"
" }"
" return 4;"
"}"
"test();");
CHECK_EQ(0, value->Int32Value());
}
THREADED_TEST(EvalAliasedDynamic) {
LocalContext current;
v8::HandleScope scope(current->GetIsolate());
// Tests where aliased eval can only be resolved dynamically.
Local<Script> script =
Script::Compile(v8_str("function f(x) { "
" var foo = 2;"
" with (x) { return eval('foo'); }"
"}"
"foo = 0;"
"result1 = f(new Object());"
"result2 = f(this);"
"var x = new Object();"
"x.eval = function(x) { return 1; };"
"result3 = f(x);"));
script->Run();
CHECK_EQ(2, current->Global()->Get(v8_str("result1"))->Int32Value());
CHECK_EQ(0, current->Global()->Get(v8_str("result2"))->Int32Value());
CHECK_EQ(1, current->Global()->Get(v8_str("result3"))->Int32Value());
v8::TryCatch try_catch;
script =
Script::Compile(v8_str("function f(x) { "
" var bar = 2;"
" with (x) { return eval('bar'); }"
"}"
"result4 = f(this)"));
script->Run();
CHECK(!try_catch.HasCaught());
CHECK_EQ(2, current->Global()->Get(v8_str("result4"))->Int32Value());
try_catch.Reset();
}
THREADED_TEST(CrossEval) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext other;
LocalContext current;
Local<String> token = v8_str("<security token>");
other->SetSecurityToken(token);
current->SetSecurityToken(token);
// Set up reference from current to other.
current->Global()->Set(v8_str("other"), other->Global());
// Check that new variables are introduced in other context.
Local<Script> script =
Script::Compile(v8_str("other.eval('var foo = 1234')"));
script->Run();
Local<Value> foo = other->Global()->Get(v8_str("foo"));
CHECK_EQ(1234, foo->Int32Value());
CHECK(!current->Global()->Has(v8_str("foo")));
// Check that writing to non-existing properties introduces them in
// the other context.
script =
Script::Compile(v8_str("other.eval('na = 1234')"));
script->Run();
CHECK_EQ(1234, other->Global()->Get(v8_str("na"))->Int32Value());
CHECK(!current->Global()->Has(v8_str("na")));
// Check that global variables in current context are not visible in other
// context.
v8::TryCatch try_catch;
script =
Script::Compile(v8_str("var bar = 42; other.eval('bar');"));
Local<Value> result = script->Run();
CHECK(try_catch.HasCaught());
try_catch.Reset();
// Check that local variables in current context are not visible in other
// context.
script =
Script::Compile(v8_str("(function() { "
" var baz = 87;"
" return other.eval('baz');"
"})();"));
result = script->Run();
CHECK(try_catch.HasCaught());
try_catch.Reset();
// Check that global variables in the other environment are visible
// when evaluting code.
other->Global()->Set(v8_str("bis"), v8_num(1234));
script = Script::Compile(v8_str("other.eval('bis')"));
CHECK_EQ(1234, script->Run()->Int32Value());
CHECK(!try_catch.HasCaught());
// Check that the 'this' pointer points to the global object evaluating
// code.
other->Global()->Set(v8_str("t"), other->Global());
script = Script::Compile(v8_str("other.eval('this == t')"));
result = script->Run();
CHECK(result->IsTrue());
CHECK(!try_catch.HasCaught());
// Check that variables introduced in with-statement are not visible in
// other context.
script =
Script::Compile(v8_str("with({x:2}){other.eval('x')}"));
result = script->Run();
CHECK(try_catch.HasCaught());
try_catch.Reset();
// Check that you cannot use 'eval.call' with another object than the
// current global object.
script =
Script::Compile(v8_str("other.y = 1; eval.call(other, 'y')"));
result = script->Run();
CHECK(try_catch.HasCaught());
}
// Test that calling eval in a context which has been detached from
// its global throws an exception. This behavior is consistent with
// other JavaScript implementations.
THREADED_TEST(EvalInDetachedGlobal) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Local<Context> context0 = Context::New(isolate);
v8::Local<Context> context1 = Context::New(isolate);
// Set up function in context0 that uses eval from context0.
context0->Enter();
v8::Handle<v8::Value> fun =
CompileRun("var x = 42;"
"(function() {"
" var e = eval;"
" return function(s) { return e(s); }"
"})()");
context0->Exit();
// Put the function into context1 and call it before and after
// detaching the global. Before detaching, the call succeeds and
// after detaching and exception is thrown.
context1->Enter();
context1->Global()->Set(v8_str("fun"), fun);
v8::Handle<v8::Value> x_value = CompileRun("fun('x')");
CHECK_EQ(42, x_value->Int32Value());
context0->DetachGlobal();
v8::TryCatch catcher;
x_value = CompileRun("fun('x')");
CHECK(x_value.IsEmpty());
CHECK(catcher.HasCaught());
context1->Exit();
}
THREADED_TEST(CrossLazyLoad) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext other;
LocalContext current;
Local<String> token = v8_str("<security token>");
other->SetSecurityToken(token);
current->SetSecurityToken(token);
// Set up reference from current to other.
current->Global()->Set(v8_str("other"), other->Global());
// Trigger lazy loading in other context.
Local<Script> script =
Script::Compile(v8_str("other.eval('new Date(42)')"));
Local<Value> value = script->Run();
CHECK_EQ(42.0, value->NumberValue());
}
static void call_as_function(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
if (args.IsConstructCall()) {
if (args[0]->IsInt32()) {
args.GetReturnValue().Set(v8_num(-args[0]->Int32Value()));
return;
}
}
args.GetReturnValue().Set(args[0]);
}
// Test that a call handler can be set for objects which will allow
// non-function objects created through the API to be called as
// functions.
THREADED_TEST(CallAsFunction) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
{ Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
Local<ObjectTemplate> instance_template = t->InstanceTemplate();
instance_template->SetCallAsFunctionHandler(call_as_function);
Local<v8::Object> instance = t->GetFunction()->NewInstance();
context->Global()->Set(v8_str("obj"), instance);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
value = CompileRun("obj(42)");
CHECK(!try_catch.HasCaught());
CHECK_EQ(42, value->Int32Value());
value = CompileRun("(function(o){return o(49)})(obj)");
CHECK(!try_catch.HasCaught());
CHECK_EQ(49, value->Int32Value());
// test special case of call as function
value = CompileRun("[obj]['0'](45)");
CHECK(!try_catch.HasCaught());
CHECK_EQ(45, value->Int32Value());
value = CompileRun("obj.call = Function.prototype.call;"
"obj.call(null, 87)");
CHECK(!try_catch.HasCaught());
CHECK_EQ(87, value->Int32Value());
// Regression tests for bug #1116356: Calling call through call/apply
// must work for non-function receivers.
const char* apply_99 = "Function.prototype.call.apply(obj, [this, 99])";
value = CompileRun(apply_99);
CHECK(!try_catch.HasCaught());
CHECK_EQ(99, value->Int32Value());
const char* call_17 = "Function.prototype.call.call(obj, this, 17)";
value = CompileRun(call_17);
CHECK(!try_catch.HasCaught());
CHECK_EQ(17, value->Int32Value());
// Check that the call-as-function handler can be called through
// new.
value = CompileRun("new obj(43)");
CHECK(!try_catch.HasCaught());
CHECK_EQ(-43, value->Int32Value());
// Check that the call-as-function handler can be called through
// the API.
v8::Handle<Value> args[] = { v8_num(28) };
value = instance->CallAsFunction(instance, 1, args);
CHECK(!try_catch.HasCaught());
CHECK_EQ(28, value->Int32Value());
}
{ Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
Local<ObjectTemplate> instance_template(t->InstanceTemplate());
USE(instance_template);
Local<v8::Object> instance = t->GetFunction()->NewInstance();
context->Global()->Set(v8_str("obj2"), instance);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
// Call an object without call-as-function handler through the JS
value = CompileRun("obj2(28)");
CHECK(value.IsEmpty());
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value1(try_catch.Exception());
CHECK_EQ("TypeError: Property 'obj2' of object #<Object> is not a function",
*exception_value1);
try_catch.Reset();
// Call an object without call-as-function handler through the API
value = CompileRun("obj2(28)");
v8::Handle<Value> args[] = { v8_num(28) };
value = instance->CallAsFunction(instance, 1, args);
CHECK(value.IsEmpty());
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value2(try_catch.Exception());
CHECK_EQ("TypeError: [object Object] is not a function", *exception_value2);
try_catch.Reset();
}
{ Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
Local<ObjectTemplate> instance_template = t->InstanceTemplate();
instance_template->SetCallAsFunctionHandler(ThrowValue);
Local<v8::Object> instance = t->GetFunction()->NewInstance();
context->Global()->Set(v8_str("obj3"), instance);
v8::TryCatch try_catch;
Local<Value> value;
CHECK(!try_catch.HasCaught());
// Catch the exception which is thrown by call-as-function handler
value = CompileRun("obj3(22)");
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value1(try_catch.Exception());
CHECK_EQ("22", *exception_value1);
try_catch.Reset();
v8::Handle<Value> args[] = { v8_num(23) };
value = instance->CallAsFunction(instance, 1, args);
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value2(try_catch.Exception());
CHECK_EQ("23", *exception_value2);
try_catch.Reset();
}
}
// Check whether a non-function object is callable.
THREADED_TEST(CallableObject) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
{ Local<ObjectTemplate> instance_template = ObjectTemplate::New();
instance_template->SetCallAsFunctionHandler(call_as_function);
Local<Object> instance = instance_template->NewInstance();
v8::TryCatch try_catch;
CHECK(instance->IsCallable());
CHECK(!try_catch.HasCaught());
}
{ Local<ObjectTemplate> instance_template = ObjectTemplate::New();
Local<Object> instance = instance_template->NewInstance();
v8::TryCatch try_catch;
CHECK(!instance->IsCallable());
CHECK(!try_catch.HasCaught());
}
{ Local<FunctionTemplate> function_template =
FunctionTemplate::New(call_as_function);
Local<Function> function = function_template->GetFunction();
Local<Object> instance = function;
v8::TryCatch try_catch;
CHECK(instance->IsCallable());
CHECK(!try_catch.HasCaught());
}
{ Local<FunctionTemplate> function_template = FunctionTemplate::New();
Local<Function> function = function_template->GetFunction();
Local<Object> instance = function;
v8::TryCatch try_catch;
CHECK(instance->IsCallable());
CHECK(!try_catch.HasCaught());
}
}
static int CountHandles() {
return v8::HandleScope::NumberOfHandles();
}
static int Recurse(int depth, int iterations) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
if (depth == 0) return CountHandles();
for (int i = 0; i < iterations; i++) {
Local<v8::Number> n(v8::Integer::New(42));
}
return Recurse(depth - 1, iterations);
}
THREADED_TEST(HandleIteration) {
static const int kIterations = 500;
static const int kNesting = 200;
CHECK_EQ(0, CountHandles());
{
v8::HandleScope scope1(v8::Isolate::GetCurrent());
CHECK_EQ(0, CountHandles());
for (int i = 0; i < kIterations; i++) {
Local<v8::Number> n(v8::Integer::New(42));
CHECK_EQ(i + 1, CountHandles());
}
CHECK_EQ(kIterations, CountHandles());
{
v8::HandleScope scope2(v8::Isolate::GetCurrent());
for (int j = 0; j < kIterations; j++) {
Local<v8::Number> n(v8::Integer::New(42));
CHECK_EQ(j + 1 + kIterations, CountHandles());
}
}
CHECK_EQ(kIterations, CountHandles());
}
CHECK_EQ(0, CountHandles());
CHECK_EQ(kNesting * kIterations, Recurse(kNesting, kIterations));
}
static void InterceptorHasOwnPropertyGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
}
THREADED_TEST(InterceptorHasOwnProperty) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
Local<v8::ObjectTemplate> instance_templ = fun_templ->InstanceTemplate();
instance_templ->SetNamedPropertyHandler(InterceptorHasOwnPropertyGetter);
Local<Function> function = fun_templ->GetFunction();
context->Global()->Set(v8_str("constructor"), function);
v8::Handle<Value> value = CompileRun(
"var o = new constructor();"
"o.hasOwnProperty('ostehaps');");
CHECK_EQ(false, value->BooleanValue());
value = CompileRun(
"o.ostehaps = 42;"
"o.hasOwnProperty('ostehaps');");
CHECK_EQ(true, value->BooleanValue());
value = CompileRun(
"var p = new constructor();"
"p.hasOwnProperty('ostehaps');");
CHECK_EQ(false, value->BooleanValue());
}
static void InterceptorHasOwnPropertyGetterGC(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
THREADED_TEST(InterceptorHasOwnPropertyCausingGC) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
Local<v8::ObjectTemplate> instance_templ = fun_templ->InstanceTemplate();
instance_templ->SetNamedPropertyHandler(InterceptorHasOwnPropertyGetterGC);
Local<Function> function = fun_templ->GetFunction();
context->Global()->Set(v8_str("constructor"), function);
// Let's first make some stuff so we can be sure to get a good GC.
CompileRun(
"function makestr(size) {"
" switch (size) {"
" case 1: return 'f';"
" case 2: return 'fo';"
" case 3: return 'foo';"
" }"
" return makestr(size >> 1) + makestr((size + 1) >> 1);"
"}"
"var x = makestr(12345);"
"x = makestr(31415);"
"x = makestr(23456);");
v8::Handle<Value> value = CompileRun(
"var o = new constructor();"
"o.__proto__ = new String(x);"
"o.hasOwnProperty('ostehaps');");
CHECK_EQ(false, value->BooleanValue());
}
typedef void (*NamedPropertyGetter)(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Value>& info);
static void CheckInterceptorLoadIC(NamedPropertyGetter getter,
const char* source,
int expected) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(getter, 0, 0, 0, 0, v8_str("data"));
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(source);
CHECK_EQ(expected, value->Int32Value());
}
static void InterceptorLoadICGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
CHECK_EQ(isolate, info.GetIsolate());
CHECK_EQ(v8_str("data"), info.Data());
CHECK_EQ(v8_str("x"), name);
info.GetReturnValue().Set(v8::Integer::New(42));
}
// This test should hit the load IC for the interceptor case.
THREADED_TEST(InterceptorLoadIC) {
CheckInterceptorLoadIC(InterceptorLoadICGetter,
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = o.x;"
"}",
42);
}
// Below go several tests which verify that JITing for various
// configurations of interceptor and explicit fields works fine
// (those cases are special cased to get better performance).
static void InterceptorLoadXICGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(
v8_str("x")->Equals(name) ?
v8::Handle<v8::Value>(v8::Integer::New(42)) :
v8::Handle<v8::Value>());
}
THREADED_TEST(InterceptorLoadICWithFieldOnHolder) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"var result = 0;"
"o.y = 239;"
"for (var i = 0; i < 1000; i++) {"
" result = o.y;"
"}",
239);
}
THREADED_TEST(InterceptorLoadICWithSubstitutedProto) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"var result = 0;"
"o.__proto__ = { 'y': 239 };"
"for (var i = 0; i < 1000; i++) {"
" result = o.y + o.x;"
"}",
239 + 42);
}
THREADED_TEST(InterceptorLoadICWithPropertyOnProto) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"var result = 0;"
"o.__proto__.y = 239;"
"for (var i = 0; i < 1000; i++) {"
" result = o.y + o.x;"
"}",
239 + 42);
}
THREADED_TEST(InterceptorLoadICUndefined) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = (o.y == undefined) ? 239 : 42;"
"}",
239);
}
THREADED_TEST(InterceptorLoadICWithOverride) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"fst = new Object(); fst.__proto__ = o;"
"snd = new Object(); snd.__proto__ = fst;"
"var result1 = 0;"
"for (var i = 0; i < 1000; i++) {"
" result1 = snd.x;"
"}"
"fst.x = 239;"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = snd.x;"
"}"
"result + result1",
239 + 42);
}
// Test the case when we stored field into
// a stub, but interceptor produced value on its own.
THREADED_TEST(InterceptorLoadICFieldNotNeeded) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"proto = new Object();"
"o.__proto__ = proto;"
"proto.x = 239;"
"for (var i = 0; i < 1000; i++) {"
" o.x;"
// Now it should be ICed and keep a reference to x defined on proto
"}"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result += o.x;"
"}"
"result;",
42 * 1000);
}
// Test the case when we stored field into
// a stub, but it got invalidated later on.
THREADED_TEST(InterceptorLoadICInvalidatedField) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"proto1 = new Object();"
"proto2 = new Object();"
"o.__proto__ = proto1;"
"proto1.__proto__ = proto2;"
"proto2.y = 239;"
"for (var i = 0; i < 1000; i++) {"
" o.y;"
// Now it should be ICed and keep a reference to y defined on proto2
"}"
"proto1.y = 42;"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result += o.y;"
"}"
"result;",
42 * 1000);
}
static int interceptor_load_not_handled_calls = 0;
static void InterceptorLoadNotHandled(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
++interceptor_load_not_handled_calls;
}
// Test how post-interceptor lookups are done in the non-cacheable
// case: the interceptor should not be invoked during this lookup.
THREADED_TEST(InterceptorLoadICPostInterceptor) {
interceptor_load_not_handled_calls = 0;
CheckInterceptorLoadIC(InterceptorLoadNotHandled,
"receiver = new Object();"
"receiver.__proto__ = o;"
"proto = new Object();"
"/* Make proto a slow-case object. */"
"for (var i = 0; i < 1000; i++) {"
" proto[\"xxxxxxxx\" + i] = [];"
"}"
"proto.x = 17;"
"o.__proto__ = proto;"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result += receiver.x;"
"}"
"result;",
17 * 1000);
CHECK_EQ(1000, interceptor_load_not_handled_calls);
}
// Test the case when we stored field into
// a stub, but it got invalidated later on due to override on
// global object which is between interceptor and fields' holders.
THREADED_TEST(InterceptorLoadICInvalidatedFieldViaGlobal) {
CheckInterceptorLoadIC(InterceptorLoadXICGetter,
"o.__proto__ = this;" // set a global to be a proto of o.
"this.__proto__.y = 239;"
"for (var i = 0; i < 10; i++) {"
" if (o.y != 239) throw 'oops: ' + o.y;"
// Now it should be ICed and keep a reference to y defined on field_holder.
"}"
"this.y = 42;" // Assign on a global.
"var result = 0;"
"for (var i = 0; i < 10; i++) {"
" result += o.y;"
"}"
"result;",
42 * 10);
}
static void SetOnThis(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<void>& info) {
info.This()->ForceSet(name, value);
}
THREADED_TEST(InterceptorLoadICWithCallbackOnHolder) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorLoadXICGetter);
templ->SetAccessor(v8_str("y"), Return239Callback);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
// Check the case when receiver and interceptor's holder
// are the same objects.
v8::Handle<Value> value = CompileRun(
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result = o.y;"
"}");
CHECK_EQ(239, value->Int32Value());
// Check the case when interceptor's holder is in proto chain
// of receiver.
value = CompileRun(
"r = { __proto__: o };"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result = r.y;"
"}");
CHECK_EQ(239, value->Int32Value());
}
THREADED_TEST(InterceptorLoadICWithCallbackOnProto) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(InterceptorLoadXICGetter);
v8::Handle<v8::ObjectTemplate> templ_p = ObjectTemplate::New();
templ_p->SetAccessor(v8_str("y"), Return239Callback);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
context->Global()->Set(v8_str("p"), templ_p->NewInstance());
// Check the case when receiver and interceptor's holder
// are the same objects.
v8::Handle<Value> value = CompileRun(
"o.__proto__ = p;"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result = o.x + o.y;"
"}");
CHECK_EQ(239 + 42, value->Int32Value());
// Check the case when interceptor's holder is in proto chain
// of receiver.
value = CompileRun(
"r = { __proto__: o };"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result = r.x + r.y;"
"}");
CHECK_EQ(239 + 42, value->Int32Value());
}
THREADED_TEST(InterceptorLoadICForCallbackWithOverride) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorLoadXICGetter);
templ->SetAccessor(v8_str("y"), Return239Callback);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"fst = new Object(); fst.__proto__ = o;"
"snd = new Object(); snd.__proto__ = fst;"
"var result1 = 0;"
"for (var i = 0; i < 7; i++) {"
" result1 = snd.x;"
"}"
"fst.x = 239;"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result = snd.x;"
"}"
"result + result1");
CHECK_EQ(239 + 42, value->Int32Value());
}
// Test the case when we stored callback into
// a stub, but interceptor produced value on its own.
THREADED_TEST(InterceptorLoadICCallbackNotNeeded) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(InterceptorLoadXICGetter);
v8::Handle<v8::ObjectTemplate> templ_p = ObjectTemplate::New();
templ_p->SetAccessor(v8_str("y"), Return239Callback);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
context->Global()->Set(v8_str("p"), templ_p->NewInstance());
v8::Handle<Value> value = CompileRun(
"o.__proto__ = p;"
"for (var i = 0; i < 7; i++) {"
" o.x;"
// Now it should be ICed and keep a reference to x defined on p
"}"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result += o.x;"
"}"
"result");
CHECK_EQ(42 * 7, value->Int32Value());
}
// Test the case when we stored callback into
// a stub, but it got invalidated later on.
THREADED_TEST(InterceptorLoadICInvalidatedCallback) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(InterceptorLoadXICGetter);
v8::Handle<v8::ObjectTemplate> templ_p = ObjectTemplate::New();
templ_p->SetAccessor(v8_str("y"), Return239Callback, SetOnThis);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
context->Global()->Set(v8_str("p"), templ_p->NewInstance());
v8::Handle<Value> value = CompileRun(
"inbetween = new Object();"
"o.__proto__ = inbetween;"
"inbetween.__proto__ = p;"
"for (var i = 0; i < 10; i++) {"
" o.y;"
// Now it should be ICed and keep a reference to y defined on p
"}"
"inbetween.y = 42;"
"var result = 0;"
"for (var i = 0; i < 10; i++) {"
" result += o.y;"
"}"
"result");
CHECK_EQ(42 * 10, value->Int32Value());
}
// Test the case when we stored callback into
// a stub, but it got invalidated later on due to override on
// global object which is between interceptor and callbacks' holders.
THREADED_TEST(InterceptorLoadICInvalidatedCallbackViaGlobal) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(InterceptorLoadXICGetter);
v8::Handle<v8::ObjectTemplate> templ_p = ObjectTemplate::New();
templ_p->SetAccessor(v8_str("y"), Return239Callback, SetOnThis);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
context->Global()->Set(v8_str("p"), templ_p->NewInstance());
v8::Handle<Value> value = CompileRun(
"o.__proto__ = this;"
"this.__proto__ = p;"
"for (var i = 0; i < 10; i++) {"
" if (o.y != 239) throw 'oops: ' + o.y;"
// Now it should be ICed and keep a reference to y defined on p
"}"
"this.y = 42;"
"var result = 0;"
"for (var i = 0; i < 10; i++) {"
" result += o.y;"
"}"
"result");
CHECK_EQ(42 * 10, value->Int32Value());
}
static void InterceptorLoadICGetter0(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK(v8_str("x")->Equals(name));
info.GetReturnValue().Set(v8::Integer::New(0));
}
THREADED_TEST(InterceptorReturningZero) {
CheckInterceptorLoadIC(InterceptorLoadICGetter0,
"o.x == undefined ? 1 : 0",
0);
}
static void InterceptorStoreICSetter(
Local<String> key,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CHECK(v8_str("x")->Equals(key));
CHECK_EQ(42, value->Int32Value());
info.GetReturnValue().Set(value);
}
// This test should hit the store IC for the interceptor case.
THREADED_TEST(InterceptorStoreIC) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorLoadICGetter,
InterceptorStoreICSetter,
0, 0, 0, v8_str("data"));
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
CompileRun(
"for (var i = 0; i < 1000; i++) {"
" o.x = 42;"
"}");
}
THREADED_TEST(InterceptorStoreICWithNoSetter) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorLoadXICGetter);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"for (var i = 0; i < 1000; i++) {"
" o.y = 239;"
"}"
"42 + o.y");
CHECK_EQ(239 + 42, value->Int32Value());
}
v8::Handle<Value> call_ic_function;
v8::Handle<Value> call_ic_function2;
v8::Handle<Value> call_ic_function3;
static void InterceptorCallICGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK(v8_str("x")->Equals(name));
info.GetReturnValue().Set(call_ic_function);
}
// This test should hit the call IC for the interceptor case.
THREADED_TEST(InterceptorCallIC) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorCallICGetter);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
call_ic_function =
v8_compile("function f(x) { return x + 1; }; f")->Run();
v8::Handle<Value> value = CompileRun(
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = o.x(41);"
"}");
CHECK_EQ(42, value->Int32Value());
}
// This test checks that if interceptor doesn't provide
// a value, we can fetch regular value.
THREADED_TEST(InterceptorCallICSeesOthers) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"o.x = function f(x) { return x + 1; };"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result = o.x(41);"
"}");
CHECK_EQ(42, value->Int32Value());
}
static v8::Handle<Value> call_ic_function4;
static void InterceptorCallICGetter4(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CHECK(v8_str("x")->Equals(name));
info.GetReturnValue().Set(call_ic_function4);
}
// This test checks that if interceptor provides a function,
// even if we cached shadowed variant, interceptor's function
// is invoked
THREADED_TEST(InterceptorCallICCacheableNotNeeded) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorCallICGetter4);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
call_ic_function4 =
v8_compile("function f(x) { return x - 1; }; f")->Run();
v8::Handle<Value> value = CompileRun(
"Object.getPrototypeOf(o).x = function(x) { return x + 1; };"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = o.x(42);"
"}");
CHECK_EQ(41, value->Int32Value());
}
// Test the case when we stored cacheable lookup into
// a stub, but it got invalidated later on
THREADED_TEST(InterceptorCallICInvalidatedCacheable) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"proto1 = new Object();"
"proto2 = new Object();"
"o.__proto__ = proto1;"
"proto1.__proto__ = proto2;"
"proto2.y = function(x) { return x + 1; };"
// Invoke it many times to compile a stub
"for (var i = 0; i < 7; i++) {"
" o.y(42);"
"}"
"proto1.y = function(x) { return x - 1; };"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result += o.y(42);"
"}");
CHECK_EQ(41 * 7, value->Int32Value());
}
// This test checks that if interceptor doesn't provide a function,
// cached constant function is used
THREADED_TEST(InterceptorCallICConstantFunctionUsed) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"function inc(x) { return x + 1; };"
"inc(1);"
"o.x = inc;"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = o.x(42);"
"}");
CHECK_EQ(43, value->Int32Value());
}
static v8::Handle<Value> call_ic_function5;
static void InterceptorCallICGetter5(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (v8_str("x")->Equals(name))
info.GetReturnValue().Set(call_ic_function5);
}
// This test checks that if interceptor provides a function,
// even if we cached constant function, interceptor's function
// is invoked
THREADED_TEST(InterceptorCallICConstantFunctionNotNeeded) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorCallICGetter5);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
call_ic_function5 =
v8_compile("function f(x) { return x - 1; }; f")->Run();
v8::Handle<Value> value = CompileRun(
"function inc(x) { return x + 1; };"
"inc(1);"
"o.x = inc;"
"var result = 0;"
"for (var i = 0; i < 1000; i++) {"
" result = o.x(42);"
"}");
CHECK_EQ(41, value->Int32Value());
}
static v8::Handle<Value> call_ic_function6;
static void InterceptorCallICGetter6(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (v8_str("x")->Equals(name))
info.GetReturnValue().Set(call_ic_function6);
}
// Same test as above, except the code is wrapped in a function
// to test the optimized compiler.
THREADED_TEST(InterceptorCallICConstantFunctionNotNeededWrapped) {
i::FLAG_allow_natives_syntax = true;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorCallICGetter6);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
call_ic_function6 =
v8_compile("function f(x) { return x - 1; }; f")->Run();
v8::Handle<Value> value = CompileRun(
"function inc(x) { return x + 1; };"
"inc(1);"
"o.x = inc;"
"function test() {"
" var result = 0;"
" for (var i = 0; i < 1000; i++) {"
" result = o.x(42);"
" }"
" return result;"
"};"
"test();"
"test();"
"test();"
"%OptimizeFunctionOnNextCall(test);"
"test()");
CHECK_EQ(41, value->Int32Value());
}
// Test the case when we stored constant function into
// a stub, but it got invalidated later on
THREADED_TEST(InterceptorCallICInvalidatedConstantFunction) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"function inc(x) { return x + 1; };"
"inc(1);"
"proto1 = new Object();"
"proto2 = new Object();"
"o.__proto__ = proto1;"
"proto1.__proto__ = proto2;"
"proto2.y = inc;"
// Invoke it many times to compile a stub
"for (var i = 0; i < 7; i++) {"
" o.y(42);"
"}"
"proto1.y = function(x) { return x - 1; };"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result += o.y(42);"
"}");
CHECK_EQ(41 * 7, value->Int32Value());
}
// Test the case when we stored constant function into
// a stub, but it got invalidated later on due to override on
// global object which is between interceptor and constant function' holders.
THREADED_TEST(InterceptorCallICInvalidatedConstantFunctionViaGlobal) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
v8::Handle<Value> value = CompileRun(
"function inc(x) { return x + 1; };"
"inc(1);"
"o.__proto__ = this;"
"this.__proto__.y = inc;"
// Invoke it many times to compile a stub
"for (var i = 0; i < 7; i++) {"
" if (o.y(42) != 43) throw 'oops: ' + o.y(42);"
"}"
"this.y = function(x) { return x - 1; };"
"var result = 0;"
"for (var i = 0; i < 7; i++) {"
" result += o.y(42);"
"}");
CHECK_EQ(41 * 7, value->Int32Value());
}
// Test the case when actual function to call sits on global object.
THREADED_TEST(InterceptorCallICCachedFromGlobal) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
v8::Handle<Value> value = CompileRun(
"try {"
" o.__proto__ = this;"
" for (var i = 0; i < 10; i++) {"
" var v = o.parseFloat('239');"
" if (v != 239) throw v;"
// Now it should be ICed and keep a reference to parseFloat.
" }"
" var result = 0;"
" for (var i = 0; i < 10; i++) {"
" result += o.parseFloat('239');"
" }"
" result"
"} catch(e) {"
" e"
"};");
CHECK_EQ(239 * 10, value->Int32Value());
}
static void InterceptorCallICFastApi(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(info, FUNCTION_ADDR(InterceptorCallICFastApi));
int* call_count =
reinterpret_cast<int*>(v8::External::Cast(*info.Data())->Value());
++(*call_count);
if ((*call_count) % 20 == 0) {
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
}
static void FastApiCallback_TrivialSignature(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(args, FUNCTION_ADDR(FastApiCallback_TrivialSignature));
v8::Isolate* isolate = v8::Isolate::GetCurrent();
CHECK_EQ(isolate, args.GetIsolate());
CHECK_EQ(args.This(), args.Holder());
CHECK(args.Data()->Equals(v8_str("method_data")));
args.GetReturnValue().Set(args[0]->Int32Value() + 1);
}
static void FastApiCallback_SimpleSignature(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CheckReturnValue(args, FUNCTION_ADDR(FastApiCallback_SimpleSignature));
v8::Isolate* isolate = v8::Isolate::GetCurrent();
CHECK_EQ(isolate, args.GetIsolate());
CHECK_EQ(args.This()->GetPrototype(), args.Holder());
CHECK(args.Data()->Equals(v8_str("method_data")));
// Note, we're using HasRealNamedProperty instead of Has to avoid
// invoking the interceptor again.
CHECK(args.Holder()->HasRealNamedProperty(v8_str("foo")));
args.GetReturnValue().Set(args[0]->Int32Value() + 1);
}
// Helper to maximize the odds of object moving.
static void GenerateSomeGarbage() {
CompileRun(
"var garbage;"
"for (var i = 0; i < 1000; i++) {"
" garbage = [1/i, \"garbage\" + i, garbage, {foo: garbage}];"
"}"
"garbage = undefined;");
}
void DirectApiCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
static int count = 0;
if (count++ % 3 == 0) {
HEAP->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
// This should move the stub
GenerateSomeGarbage(); // This should ensure the old stub memory is flushed
}
}
THREADED_TEST(CallICFastApi_DirectCall_GCMoveStub) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::ObjectTemplate> nativeobject_templ = v8::ObjectTemplate::New();
nativeobject_templ->Set("callback",
v8::FunctionTemplate::New(DirectApiCallback));
v8::Local<v8::Object> nativeobject_obj = nativeobject_templ->NewInstance();
context->Global()->Set(v8_str("nativeobject"), nativeobject_obj);
// call the api function multiple times to ensure direct call stub creation.
CompileRun(
"function f() {"
" for (var i = 1; i <= 30; i++) {"
" nativeobject.callback();"
" }"
"}"
"f();");
}
void ThrowingDirectApiCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::ThrowException(v8_str("g"));
}
THREADED_TEST(CallICFastApi_DirectCall_Throw) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::ObjectTemplate> nativeobject_templ = v8::ObjectTemplate::New();
nativeobject_templ->Set("callback",
v8::FunctionTemplate::New(ThrowingDirectApiCallback));
v8::Local<v8::Object> nativeobject_obj = nativeobject_templ->NewInstance();
context->Global()->Set(v8_str("nativeobject"), nativeobject_obj);
// call the api function multiple times to ensure direct call stub creation.
v8::Handle<Value> result = CompileRun(
"var result = '';"
"function f() {"
" for (var i = 1; i <= 5; i++) {"
" try { nativeobject.callback(); } catch (e) { result += e; }"
" }"
"}"
"f(); result;");
CHECK_EQ(v8_str("ggggg"), result);
}
static Handle<Value> DoDirectGetter() {
if (++p_getter_count % 3 == 0) {
HEAP->CollectAllGarbage(i::Heap::kAbortIncrementalMarkingMask);
GenerateSomeGarbage();
}
return v8_str("Direct Getter Result");
}
static void DirectGetterCallback(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CheckReturnValue(info, FUNCTION_ADDR(DirectGetterCallback));
info.GetReturnValue().Set(DoDirectGetter());
}
template<typename Accessor>
static void LoadICFastApi_DirectCall_GCMoveStub(Accessor accessor) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::ObjectTemplate> obj = v8::ObjectTemplate::New();
obj->SetAccessor(v8_str("p1"), accessor);
context->Global()->Set(v8_str("o1"), obj->NewInstance());
p_getter_count = 0;
v8::Handle<v8::Value> result = CompileRun(
"function f() {"
" for (var i = 0; i < 30; i++) o1.p1;"
" return o1.p1"
"}"
"f();");
CHECK_EQ(v8_str("Direct Getter Result"), result);
CHECK_EQ(31, p_getter_count);
}
THREADED_PROFILED_TEST(LoadICFastApi_DirectCall_GCMoveStub) {
LoadICFastApi_DirectCall_GCMoveStub(DirectGetterCallback);
}
void ThrowingDirectGetterCallback(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
v8::ThrowException(v8_str("g"));
}
THREADED_TEST(LoadICFastApi_DirectCall_Throw) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::ObjectTemplate> obj = v8::ObjectTemplate::New();
obj->SetAccessor(v8_str("p1"), ThrowingDirectGetterCallback);
context->Global()->Set(v8_str("o1"), obj->NewInstance());
v8::Handle<Value> result = CompileRun(
"var result = '';"
"for (var i = 0; i < 5; i++) {"
" try { o1.p1; } catch (e) { result += e; }"
"}"
"result;");
CHECK_EQ(v8_str("ggggg"), result);
}
THREADED_PROFILED_TEST(InterceptorCallICFastApi_TrivialSignature) {
int interceptor_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_TrivialSignature,
v8_str("method_data"),
v8::Handle<v8::Signature>());
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
v8::Handle<v8::ObjectTemplate> templ = fun_templ->InstanceTemplate();
templ->SetNamedPropertyHandler(InterceptorCallICFastApi,
NULL, NULL, NULL, NULL,
v8::External::New(&interceptor_call_count));
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"var result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = o.method(41);"
"}");
CHECK_EQ(42, context->Global()->Get(v8_str("result"))->Int32Value());
CHECK_EQ(100, interceptor_call_count);
}
THREADED_PROFILED_TEST(InterceptorCallICFastApi_SimpleSignature) {
int interceptor_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ = fun_templ->InstanceTemplate();
templ->SetNamedPropertyHandler(InterceptorCallICFastApi,
NULL, NULL, NULL, NULL,
v8::External::New(&interceptor_call_count));
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
"}");
CHECK_EQ(42, context->Global()->Get(v8_str("result"))->Int32Value());
CHECK_EQ(100, interceptor_call_count);
}
THREADED_PROFILED_TEST(InterceptorCallICFastApi_SimpleSignature_Miss1) {
int interceptor_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ = fun_templ->InstanceTemplate();
templ->SetNamedPropertyHandler(InterceptorCallICFastApi,
NULL, NULL, NULL, NULL,
v8::External::New(&interceptor_call_count));
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" receiver = {method: function(x) { return x - 1 }};"
" }"
"}");
CHECK_EQ(40, context->Global()->Get(v8_str("result"))->Int32Value());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
CHECK_GE(interceptor_call_count, 50);
}
THREADED_PROFILED_TEST(InterceptorCallICFastApi_SimpleSignature_Miss2) {
int interceptor_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ = fun_templ->InstanceTemplate();
templ->SetNamedPropertyHandler(InterceptorCallICFastApi,
NULL, NULL, NULL, NULL,
v8::External::New(&interceptor_call_count));
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" o.method = function(x) { return x - 1 };"
" }"
"}");
CHECK_EQ(40, context->Global()->Get(v8_str("result"))->Int32Value());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
CHECK_GE(interceptor_call_count, 50);
}
THREADED_PROFILED_TEST(InterceptorCallICFastApi_SimpleSignature_Miss3) {
int interceptor_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ = fun_templ->InstanceTemplate();
templ->SetNamedPropertyHandler(InterceptorCallICFastApi,
NULL, NULL, NULL, NULL,
v8::External::New(&interceptor_call_count));
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
v8::TryCatch try_catch;
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" receiver = 333;"
" }"
"}");
CHECK(try_catch.HasCaught());
CHECK_EQ(v8_str("TypeError: Object 333 has no method 'method'"),
try_catch.Exception()->ToString());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
CHECK_GE(interceptor_call_count, 50);
}
THREADED_PROFILED_TEST(InterceptorCallICFastApi_SimpleSignature_TypeError) {
int interceptor_call_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ = fun_templ->InstanceTemplate();
templ->SetNamedPropertyHandler(InterceptorCallICFastApi,
NULL, NULL, NULL, NULL,
v8::External::New(&interceptor_call_count));
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
v8::TryCatch try_catch;
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" receiver = {method: receiver.method};"
" }"
"}");
CHECK(try_catch.HasCaught());
CHECK_EQ(v8_str("TypeError: Illegal invocation"),
try_catch.Exception()->ToString());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
CHECK_GE(interceptor_call_count, 50);
}
THREADED_PROFILED_TEST(CallICFastApi_TrivialSignature) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_TrivialSignature,
v8_str("method_data"),
v8::Handle<v8::Signature>());
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
v8::Handle<v8::ObjectTemplate> templ(fun_templ->InstanceTemplate());
USE(templ);
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"var result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = o.method(41);"
"}");
CHECK_EQ(42, context->Global()->Get(v8_str("result"))->Int32Value());
}
THREADED_PROFILED_TEST(CallICFastApi_SimpleSignature) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ(fun_templ->InstanceTemplate());
CHECK(!templ.IsEmpty());
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
"}");
CHECK_EQ(42, context->Global()->Get(v8_str("result"))->Int32Value());
}
THREADED_PROFILED_TEST(CallICFastApi_SimpleSignature_Miss1) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ(fun_templ->InstanceTemplate());
CHECK(!templ.IsEmpty());
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" receiver = {method: function(x) { return x - 1 }};"
" }"
"}");
CHECK_EQ(40, context->Global()->Get(v8_str("result"))->Int32Value());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
}
THREADED_PROFILED_TEST(CallICFastApi_SimpleSignature_Miss2) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ(fun_templ->InstanceTemplate());
CHECK(!templ.IsEmpty());
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
v8::TryCatch try_catch;
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" receiver = 333;"
" }"
"}");
CHECK(try_catch.HasCaught());
CHECK_EQ(v8_str("TypeError: Object 333 has no method 'method'"),
try_catch.Exception()->ToString());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
}
THREADED_PROFILED_TEST(CallICFastApi_SimpleSignature_TypeError) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New();
v8::Handle<v8::FunctionTemplate> method_templ =
v8::FunctionTemplate::New(FastApiCallback_SimpleSignature,
v8_str("method_data"),
v8::Signature::New(fun_templ));
v8::Handle<v8::ObjectTemplate> proto_templ = fun_templ->PrototypeTemplate();
proto_templ->Set(v8_str("method"), method_templ);
fun_templ->SetHiddenPrototype(true);
v8::Handle<v8::ObjectTemplate> templ(fun_templ->InstanceTemplate());
CHECK(!templ.IsEmpty());
LocalContext context;
v8::Handle<v8::Function> fun = fun_templ->GetFunction();
GenerateSomeGarbage();
context->Global()->Set(v8_str("o"), fun->NewInstance());
v8::TryCatch try_catch;
CompileRun(
"o.foo = 17;"
"var receiver = {};"
"receiver.__proto__ = o;"
"var result = 0;"
"var saved_result = 0;"
"for (var i = 0; i < 100; i++) {"
" result = receiver.method(41);"
" if (i == 50) {"
" saved_result = result;"
" receiver = Object.create(receiver);"
" }"
"}");
CHECK(try_catch.HasCaught());
CHECK_EQ(v8_str("TypeError: Illegal invocation"),
try_catch.Exception()->ToString());
CHECK_EQ(42, context->Global()->Get(v8_str("saved_result"))->Int32Value());
}
v8::Handle<Value> keyed_call_ic_function;
static void InterceptorKeyedCallICGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (v8_str("x")->Equals(name)) {
info.GetReturnValue().Set(keyed_call_ic_function);
}
}
// Test the case when we stored cacheable lookup into
// a stub, but the function name changed (to another cacheable function).
THREADED_TEST(InterceptorKeyedCallICKeyChange1) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
CompileRun(
"proto = new Object();"
"proto.y = function(x) { return x + 1; };"
"proto.z = function(x) { return x - 1; };"
"o.__proto__ = proto;"
"var result = 0;"
"var method = 'y';"
"for (var i = 0; i < 10; i++) {"
" if (i == 5) { method = 'z'; };"
" result += o[method](41);"
"}");
CHECK_EQ(42*5 + 40*5, context->Global()->Get(v8_str("result"))->Int32Value());
}
// Test the case when we stored cacheable lookup into
// a stub, but the function name changed (and the new function is present
// both before and after the interceptor in the prototype chain).
THREADED_TEST(InterceptorKeyedCallICKeyChange2) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorKeyedCallICGetter);
LocalContext context;
context->Global()->Set(v8_str("proto1"), templ->NewInstance());
keyed_call_ic_function =
v8_compile("function f(x) { return x - 1; }; f")->Run();
CompileRun(
"o = new Object();"
"proto2 = new Object();"
"o.y = function(x) { return x + 1; };"
"proto2.y = function(x) { return x + 2; };"
"o.__proto__ = proto1;"
"proto1.__proto__ = proto2;"
"var result = 0;"
"var method = 'x';"
"for (var i = 0; i < 10; i++) {"
" if (i == 5) { method = 'y'; };"
" result += o[method](41);"
"}");
CHECK_EQ(42*5 + 40*5, context->Global()->Get(v8_str("result"))->Int32Value());
}
// Same as InterceptorKeyedCallICKeyChange1 only the cacheable function sit
// on the global object.
THREADED_TEST(InterceptorKeyedCallICKeyChangeOnGlobal) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ->NewInstance());
CompileRun(
"function inc(x) { return x + 1; };"
"inc(1);"
"function dec(x) { return x - 1; };"
"dec(1);"
"o.__proto__ = this;"
"this.__proto__.x = inc;"
"this.__proto__.y = dec;"
"var result = 0;"
"var method = 'x';"
"for (var i = 0; i < 10; i++) {"
" if (i == 5) { method = 'y'; };"
" result += o[method](41);"
"}");
CHECK_EQ(42*5 + 40*5, context->Global()->Get(v8_str("result"))->Int32Value());
}
// Test the case when actual function to call sits on global object.
THREADED_TEST(InterceptorKeyedCallICFromGlobal) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
CompileRun(
"function len(x) { return x.length; };"
"o.__proto__ = this;"
"var m = 'parseFloat';"
"var result = 0;"
"for (var i = 0; i < 10; i++) {"
" if (i == 5) {"
" m = 'len';"
" saved_result = result;"
" };"
" result = o[m]('239');"
"}");
CHECK_EQ(3, context->Global()->Get(v8_str("result"))->Int32Value());
CHECK_EQ(239, context->Global()->Get(v8_str("saved_result"))->Int32Value());
}
// Test the map transition before the interceptor.
THREADED_TEST(InterceptorKeyedCallICMapChangeBefore) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("proto"), templ_o->NewInstance());
CompileRun(
"var o = new Object();"
"o.__proto__ = proto;"
"o.method = function(x) { return x + 1; };"
"var m = 'method';"
"var result = 0;"
"for (var i = 0; i < 10; i++) {"
" if (i == 5) { o.method = function(x) { return x - 1; }; };"
" result += o[m](41);"
"}");
CHECK_EQ(42*5 + 40*5, context->Global()->Get(v8_str("result"))->Int32Value());
}
// Test the map transition after the interceptor.
THREADED_TEST(InterceptorKeyedCallICMapChangeAfter) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ_o = ObjectTemplate::New();
templ_o->SetNamedPropertyHandler(NoBlockGetterX);
LocalContext context;
context->Global()->Set(v8_str("o"), templ_o->NewInstance());
CompileRun(
"var proto = new Object();"
"o.__proto__ = proto;"
"proto.method = function(x) { return x + 1; };"
"var m = 'method';"
"var result = 0;"
"for (var i = 0; i < 10; i++) {"
" if (i == 5) { proto.method = function(x) { return x - 1; }; };"
" result += o[m](41);"
"}");
CHECK_EQ(42*5 + 40*5, context->Global()->Get(v8_str("result"))->Int32Value());
}
static int interceptor_call_count = 0;
static void InterceptorICRefErrorGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (v8_str("x")->Equals(name) && interceptor_call_count++ < 20) {
info.GetReturnValue().Set(call_ic_function2);
}
}
// This test should hit load and call ICs for the interceptor case.
// Once in a while, the interceptor will reply that a property was not
// found in which case we should get a reference error.
THREADED_TEST(InterceptorICReferenceErrors) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorICRefErrorGetter);
LocalContext context(0, templ, v8::Handle<Value>());
call_ic_function2 = v8_compile("function h(x) { return x; }; h")->Run();
v8::Handle<Value> value = CompileRun(
"function f() {"
" for (var i = 0; i < 1000; i++) {"
" try { x; } catch(e) { return true; }"
" }"
" return false;"
"};"
"f();");
CHECK_EQ(true, value->BooleanValue());
interceptor_call_count = 0;
value = CompileRun(
"function g() {"
" for (var i = 0; i < 1000; i++) {"
" try { x(42); } catch(e) { return true; }"
" }"
" return false;"
"};"
"g();");
CHECK_EQ(true, value->BooleanValue());
}
static int interceptor_ic_exception_get_count = 0;
static void InterceptorICExceptionGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (v8_str("x")->Equals(name) && ++interceptor_ic_exception_get_count < 20) {
info.GetReturnValue().Set(call_ic_function3);
}
if (interceptor_ic_exception_get_count == 20) {
v8::ThrowException(v8_num(42));
return;
}
}
// Test interceptor load/call IC where the interceptor throws an
// exception once in a while.
THREADED_TEST(InterceptorICGetterExceptions) {
interceptor_ic_exception_get_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(InterceptorICExceptionGetter);
LocalContext context(0, templ, v8::Handle<Value>());
call_ic_function3 = v8_compile("function h(x) { return x; }; h")->Run();
v8::Handle<Value> value = CompileRun(
"function f() {"
" for (var i = 0; i < 100; i++) {"
" try { x; } catch(e) { return true; }"
" }"
" return false;"
"};"
"f();");
CHECK_EQ(true, value->BooleanValue());
interceptor_ic_exception_get_count = 0;
value = CompileRun(
"function f() {"
" for (var i = 0; i < 100; i++) {"
" try { x(42); } catch(e) { return true; }"
" }"
" return false;"
"};"
"f();");
CHECK_EQ(true, value->BooleanValue());
}
static int interceptor_ic_exception_set_count = 0;
static void InterceptorICExceptionSetter(
Local<String> key,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
if (++interceptor_ic_exception_set_count > 20) {
v8::ThrowException(v8_num(42));
}
}
// Test interceptor store IC where the interceptor throws an exception
// once in a while.
THREADED_TEST(InterceptorICSetterExceptions) {
interceptor_ic_exception_set_count = 0;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(0, InterceptorICExceptionSetter);
LocalContext context(0, templ, v8::Handle<Value>());
v8::Handle<Value> value = CompileRun(
"function f() {"
" for (var i = 0; i < 100; i++) {"
" try { x = 42; } catch(e) { return true; }"
" }"
" return false;"
"};"
"f();");
CHECK_EQ(true, value->BooleanValue());
}
// Test that we ignore null interceptors.
THREADED_TEST(NullNamedInterceptor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(
static_cast<v8::NamedPropertyGetterCallback>(0));
LocalContext context;
templ->Set("x", v8_num(42));
v8::Handle<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
v8::Handle<Value> value = CompileRun("obj.x");
CHECK(value->IsInt32());
CHECK_EQ(42, value->Int32Value());
}
// Test that we ignore null interceptors.
THREADED_TEST(NullIndexedInterceptor) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(
static_cast<v8::IndexedPropertyGetterCallback>(0));
LocalContext context;
templ->Set("42", v8_num(42));
v8::Handle<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
v8::Handle<Value> value = CompileRun("obj[42]");
CHECK(value->IsInt32());
CHECK_EQ(42, value->Int32Value());
}
THREADED_TEST(NamedPropertyHandlerGetterAttributes) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->InstanceTemplate()->SetNamedPropertyHandler(InterceptorLoadXICGetter);
LocalContext env;
env->Global()->Set(v8_str("obj"),
templ->GetFunction()->NewInstance());
ExpectTrue("obj.x === 42");
ExpectTrue("!obj.propertyIsEnumerable('x')");
}
static void ThrowingGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
ThrowException(Handle<Value>());
info.GetReturnValue().SetUndefined();
}
THREADED_TEST(VariousGetPropertiesAndThrowingCallbacks) {
LocalContext context;
HandleScope scope(context->GetIsolate());
Local<FunctionTemplate> templ = FunctionTemplate::New();
Local<ObjectTemplate> instance_templ = templ->InstanceTemplate();
instance_templ->SetAccessor(v8_str("f"), ThrowingGetter);
Local<Object> instance = templ->GetFunction()->NewInstance();
Local<Object> another = Object::New();
another->SetPrototype(instance);
Local<Object> with_js_getter = CompileRun(
"o = {};\n"
"o.__defineGetter__('f', function() { throw undefined; });\n"
"o\n").As<Object>();
CHECK(!with_js_getter.IsEmpty());
TryCatch try_catch;
Local<Value> result = instance->GetRealNamedProperty(v8_str("f"));
CHECK(try_catch.HasCaught());
try_catch.Reset();
CHECK(result.IsEmpty());
result = another->GetRealNamedProperty(v8_str("f"));
CHECK(try_catch.HasCaught());
try_catch.Reset();
CHECK(result.IsEmpty());
result = another->GetRealNamedPropertyInPrototypeChain(v8_str("f"));
CHECK(try_catch.HasCaught());
try_catch.Reset();
CHECK(result.IsEmpty());
result = another->Get(v8_str("f"));
CHECK(try_catch.HasCaught());
try_catch.Reset();
CHECK(result.IsEmpty());
result = with_js_getter->GetRealNamedProperty(v8_str("f"));
CHECK(try_catch.HasCaught());
try_catch.Reset();
CHECK(result.IsEmpty());
result = with_js_getter->Get(v8_str("f"));
CHECK(try_catch.HasCaught());
try_catch.Reset();
CHECK(result.IsEmpty());
}
static void ThrowingCallbackWithTryCatch(
const v8::FunctionCallbackInfo<v8::Value>& args) {
TryCatch try_catch;
// Verboseness is important: it triggers message delivery which can call into
// external code.
try_catch.SetVerbose(true);
CompileRun("throw 'from JS';");
CHECK(try_catch.HasCaught());
CHECK(!i::Isolate::Current()->has_pending_exception());
CHECK(!i::Isolate::Current()->has_scheduled_exception());
}
static int call_depth;
static void WithTryCatch(Handle<Message> message, Handle<Value> data) {
TryCatch try_catch;
}
static void ThrowFromJS(Handle<Message> message, Handle<Value> data) {
if (--call_depth) CompileRun("throw 'ThrowInJS';");
}
static void ThrowViaApi(Handle<Message> message, Handle<Value> data) {
if (--call_depth) ThrowException(v8_str("ThrowViaApi"));
}
static void WebKitLike(Handle<Message> message, Handle<Value> data) {
Handle<String> errorMessageString = message->Get();
CHECK(!errorMessageString.IsEmpty());
message->GetStackTrace();
message->GetScriptResourceName();
}
THREADED_TEST(ExceptionsDoNotPropagatePastTryCatch) {
LocalContext context;
HandleScope scope(context->GetIsolate());
Local<Function> func =
FunctionTemplate::New(ThrowingCallbackWithTryCatch)->GetFunction();
context->Global()->Set(v8_str("func"), func);
MessageCallback callbacks[] =
{ NULL, WebKitLike, ThrowViaApi, ThrowFromJS, WithTryCatch };
for (unsigned i = 0; i < sizeof(callbacks)/sizeof(callbacks[0]); i++) {
MessageCallback callback = callbacks[i];
if (callback != NULL) {
V8::AddMessageListener(callback);
}
// Some small number to control number of times message handler should
// throw an exception.
call_depth = 5;
ExpectFalse(
"var thrown = false;\n"
"try { func(); } catch(e) { thrown = true; }\n"
"thrown\n");
if (callback != NULL) {
V8::RemoveMessageListeners(callback);
}
}
}
static void ParentGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(v8_num(1));
}
static void ChildGetter(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
info.GetReturnValue().Set(v8_num(42));
}
THREADED_TEST(Overriding) {
i::FLAG_es5_readonly = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// Parent template.
Local<v8::FunctionTemplate> parent_templ = v8::FunctionTemplate::New();
Local<ObjectTemplate> parent_instance_templ =
parent_templ->InstanceTemplate();
parent_instance_templ->SetAccessor(v8_str("f"), ParentGetter);
// Template that inherits from the parent template.
Local<v8::FunctionTemplate> child_templ = v8::FunctionTemplate::New();
Local<ObjectTemplate> child_instance_templ =
child_templ->InstanceTemplate();
child_templ->Inherit(parent_templ);
// Override 'f'. The child version of 'f' should get called for child
// instances.
child_instance_templ->SetAccessor(v8_str("f"), ChildGetter);
// Add 'g' twice. The 'g' added last should get called for instances.
child_instance_templ->SetAccessor(v8_str("g"), ParentGetter);
child_instance_templ->SetAccessor(v8_str("g"), ChildGetter);
// Add 'h' as an accessor to the proto template with ReadOnly attributes
// so 'h' can be shadowed on the instance object.
Local<ObjectTemplate> child_proto_templ = child_templ->PrototypeTemplate();
child_proto_templ->SetAccessor(v8_str("h"), ParentGetter, 0,
v8::Handle<Value>(), v8::DEFAULT, v8::ReadOnly);
// Add 'i' as an accessor to the instance template with ReadOnly attributes
// but the attribute does not have effect because it is duplicated with
// NULL setter.
child_instance_templ->SetAccessor(v8_str("i"), ChildGetter, 0,
v8::Handle<Value>(), v8::DEFAULT, v8::ReadOnly);
// Instantiate the child template.
Local<v8::Object> instance = child_templ->GetFunction()->NewInstance();
// Check that the child function overrides the parent one.
context->Global()->Set(v8_str("o"), instance);
Local<Value> value = v8_compile("o.f")->Run();
// Check that the 'g' that was added last is hit.
CHECK_EQ(42, value->Int32Value());
value = v8_compile("o.g")->Run();
CHECK_EQ(42, value->Int32Value());
// Check that 'h' cannot be shadowed.
value = v8_compile("o.h = 3; o.h")->Run();
CHECK_EQ(1, value->Int32Value());
// Check that 'i' cannot be shadowed or changed.
value = v8_compile("o.i = 3; o.i")->Run();
CHECK_EQ(42, value->Int32Value());
}
static void IsConstructHandler(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(args.IsConstructCall());
}
THREADED_TEST(IsConstructCall) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
// Function template with call handler.
Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->SetCallHandler(IsConstructHandler);
LocalContext context;
context->Global()->Set(v8_str("f"), templ->GetFunction());
Local<Value> value = v8_compile("f()")->Run();
CHECK(!value->BooleanValue());
value = v8_compile("new f()")->Run();
CHECK(value->BooleanValue());
}
THREADED_TEST(ObjectProtoToString) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
templ->SetClassName(v8_str("MyClass"));
LocalContext context;
Local<String> customized_tostring = v8_str("customized toString");
// Replace Object.prototype.toString
v8_compile("Object.prototype.toString = function() {"
" return 'customized toString';"
"}")->Run();
// Normal ToString call should call replaced Object.prototype.toString
Local<v8::Object> instance = templ->GetFunction()->NewInstance();
Local<String> value = instance->ToString();
CHECK(value->IsString() && value->Equals(customized_tostring));
// ObjectProtoToString should not call replace toString function.
value = instance->ObjectProtoToString();
CHECK(value->IsString() && value->Equals(v8_str("[object MyClass]")));
// Check global
value = context->Global()->ObjectProtoToString();
CHECK(value->IsString() && value->Equals(v8_str("[object global]")));
// Check ordinary object
Local<Value> object = v8_compile("new Object()")->Run();
value = object.As<v8::Object>()->ObjectProtoToString();
CHECK(value->IsString() && value->Equals(v8_str("[object Object]")));
}
THREADED_TEST(ObjectGetConstructorName) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8_compile("function Parent() {};"
"function Child() {};"
"Child.prototype = new Parent();"
"var outer = { inner: function() { } };"
"var p = new Parent();"
"var c = new Child();"
"var x = new outer.inner();")->Run();
Local<v8::Value> p = context->Global()->Get(v8_str("p"));
CHECK(p->IsObject() && p->ToObject()->GetConstructorName()->Equals(
v8_str("Parent")));
Local<v8::Value> c = context->Global()->Get(v8_str("c"));
CHECK(c->IsObject() && c->ToObject()->GetConstructorName()->Equals(
v8_str("Child")));
Local<v8::Value> x = context->Global()->Get(v8_str("x"));
CHECK(x->IsObject() && x->ToObject()->GetConstructorName()->Equals(
v8_str("outer.inner")));
}
bool ApiTestFuzzer::fuzzing_ = false;
i::Semaphore* ApiTestFuzzer::all_tests_done_=
i::OS::CreateSemaphore(0);
int ApiTestFuzzer::active_tests_;
int ApiTestFuzzer::tests_being_run_;
int ApiTestFuzzer::current_;
// We are in a callback and want to switch to another thread (if we
// are currently running the thread fuzzing test).
void ApiTestFuzzer::Fuzz() {
if (!fuzzing_) return;
ApiTestFuzzer* test = RegisterThreadedTest::nth(current_)->fuzzer_;
test->ContextSwitch();
}
// Let the next thread go. Since it is also waiting on the V8 lock it may
// not start immediately.
bool ApiTestFuzzer::NextThread() {
int test_position = GetNextTestNumber();
const char* test_name = RegisterThreadedTest::nth(current_)->name();
if (test_position == current_) {
if (kLogThreading)
printf("Stay with %s\n", test_name);
return false;
}
if (kLogThreading) {
printf("Switch from %s to %s\n",
test_name,
RegisterThreadedTest::nth(test_position)->name());
}
current_ = test_position;
RegisterThreadedTest::nth(current_)->fuzzer_->gate_->Signal();
return true;
}
void ApiTestFuzzer::Run() {
// When it is our turn...
gate_->Wait();
{
// ... get the V8 lock and start running the test.
v8::Locker locker(CcTest::default_isolate());
CallTest();
}
// This test finished.
active_ = false;
active_tests_--;
// If it was the last then signal that fact.
if (active_tests_ == 0) {
all_tests_done_->Signal();
} else {
// Otherwise select a new test and start that.
NextThread();
}
}
static unsigned linear_congruential_generator;
void ApiTestFuzzer::SetUp(PartOfTest part) {
linear_congruential_generator = i::FLAG_testing_prng_seed;
fuzzing_ = true;
int count = RegisterThreadedTest::count();
int start = count * part / (LAST_PART + 1);
int end = (count * (part + 1) / (LAST_PART + 1)) - 1;
active_tests_ = tests_being_run_ = end - start + 1;
for (int i = 0; i < tests_being_run_; i++) {
RegisterThreadedTest::nth(i)->fuzzer_ = new ApiTestFuzzer(i + start);
}
for (int i = 0; i < active_tests_; i++) {
RegisterThreadedTest::nth(i)->fuzzer_->Start();
}
}
static void CallTestNumber(int test_number) {
(RegisterThreadedTest::nth(test_number)->callback())();
}
void ApiTestFuzzer::RunAllTests() {
// Set off the first test.
current_ = -1;
NextThread();
// Wait till they are all done.
all_tests_done_->Wait();
}
int ApiTestFuzzer::GetNextTestNumber() {
int next_test;
do {
next_test = (linear_congruential_generator >> 16) % tests_being_run_;
linear_congruential_generator *= 1664525u;
linear_congruential_generator += 1013904223u;
} while (!RegisterThreadedTest::nth(next_test)->fuzzer_->active_);
return next_test;
}
void ApiTestFuzzer::ContextSwitch() {
// If the new thread is the same as the current thread there is nothing to do.
if (NextThread()) {
// Now it can start.
v8::Unlocker unlocker(CcTest::default_isolate());
// Wait till someone starts us again.
gate_->Wait();
// And we're off.
}
}
void ApiTestFuzzer::TearDown() {
fuzzing_ = false;
for (int i = 0; i < RegisterThreadedTest::count(); i++) {
ApiTestFuzzer *fuzzer = RegisterThreadedTest::nth(i)->fuzzer_;
if (fuzzer != NULL) fuzzer->Join();
}
}
// Lets not be needlessly self-referential.
TEST(Threading1) {
// TODO(mstarzinger): Disabled in GC stress mode for now, we should find the
// correct timeout for this an re-enable this test again
if (i::FLAG_stress_compaction) return;
ApiTestFuzzer::SetUp(ApiTestFuzzer::FIRST_PART);
ApiTestFuzzer::RunAllTests();
ApiTestFuzzer::TearDown();
}
TEST(Threading2) {
ApiTestFuzzer::SetUp(ApiTestFuzzer::SECOND_PART);
ApiTestFuzzer::RunAllTests();
ApiTestFuzzer::TearDown();
}
TEST(Threading3) {
ApiTestFuzzer::SetUp(ApiTestFuzzer::THIRD_PART);
ApiTestFuzzer::RunAllTests();
ApiTestFuzzer::TearDown();
}
TEST(Threading4) {
ApiTestFuzzer::SetUp(ApiTestFuzzer::FOURTH_PART);
ApiTestFuzzer::RunAllTests();
ApiTestFuzzer::TearDown();
}
void ApiTestFuzzer::CallTest() {
if (kLogThreading)
printf("Start test %d\n", test_number_);
CallTestNumber(test_number_);
if (kLogThreading)
printf("End test %d\n", test_number_);
}
static void ThrowInJS(const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(v8::Locker::IsLocked(CcTest::default_isolate()));
ApiTestFuzzer::Fuzz();
v8::Unlocker unlocker(CcTest::default_isolate());
const char* code = "throw 7;";
{
v8::Locker nested_locker(CcTest::default_isolate());
v8::HandleScope scope(args.GetIsolate());
v8::Handle<Value> exception;
{ v8::TryCatch try_catch;
v8::Handle<Value> value = CompileRun(code);
CHECK(value.IsEmpty());
CHECK(try_catch.HasCaught());
// Make sure to wrap the exception in a new handle because
// the handle returned from the TryCatch is destroyed
// when the TryCatch is destroyed.
exception = Local<Value>::New(try_catch.Exception());
}
v8::ThrowException(exception);
}
}
static void ThrowInJSNoCatch(const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(v8::Locker::IsLocked(CcTest::default_isolate()));
ApiTestFuzzer::Fuzz();
v8::Unlocker unlocker(CcTest::default_isolate());
const char* code = "throw 7;";
{
v8::Locker nested_locker(CcTest::default_isolate());
v8::HandleScope scope(args.GetIsolate());
v8::Handle<Value> value = CompileRun(code);
CHECK(value.IsEmpty());
args.GetReturnValue().Set(v8_str("foo"));
}
}
// These are locking tests that don't need to be run again
// as part of the locking aggregation tests.
TEST(NestedLockers) {
v8::Locker locker(CcTest::default_isolate());
CHECK(v8::Locker::IsLocked(CcTest::default_isolate()));
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> fun_templ = v8::FunctionTemplate::New(ThrowInJS);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("throw_in_js"), fun);
Local<Script> script = v8_compile("(function () {"
" try {"
" throw_in_js();"
" return 42;"
" } catch (e) {"
" return e * 13;"
" }"
"})();");
CHECK_EQ(91, script->Run()->Int32Value());
}
// These are locking tests that don't need to be run again
// as part of the locking aggregation tests.
TEST(NestedLockersNoTryCatch) {
v8::Locker locker(CcTest::default_isolate());
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(ThrowInJSNoCatch);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("throw_in_js"), fun);
Local<Script> script = v8_compile("(function () {"
" try {"
" throw_in_js();"
" return 42;"
" } catch (e) {"
" return e * 13;"
" }"
"})();");
CHECK_EQ(91, script->Run()->Int32Value());
}
THREADED_TEST(RecursiveLocking) {
v8::Locker locker(CcTest::default_isolate());
{
v8::Locker locker2(CcTest::default_isolate());
CHECK(v8::Locker::IsLocked(CcTest::default_isolate()));
}
}
static void UnlockForAMoment(const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
v8::Unlocker unlocker(CcTest::default_isolate());
}
THREADED_TEST(LockUnlockLock) {
{
v8::Locker locker(CcTest::default_isolate());
v8::HandleScope scope(CcTest::default_isolate());
LocalContext env;
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(UnlockForAMoment);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("unlock_for_a_moment"), fun);
Local<Script> script = v8_compile("(function () {"
" unlock_for_a_moment();"
" return 42;"
"})();");
CHECK_EQ(42, script->Run()->Int32Value());
}
{
v8::Locker locker(CcTest::default_isolate());
v8::HandleScope scope(CcTest::default_isolate());
LocalContext env;
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(UnlockForAMoment);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("unlock_for_a_moment"), fun);
Local<Script> script = v8_compile("(function () {"
" unlock_for_a_moment();"
" return 42;"
"})();");
CHECK_EQ(42, script->Run()->Int32Value());
}
}
static int GetGlobalObjectsCount() {
i::Isolate::Current()->heap()->EnsureHeapIsIterable();
int count = 0;
i::HeapIterator it(HEAP);
for (i::HeapObject* object = it.next(); object != NULL; object = it.next())
if (object->IsJSGlobalObject()) count++;
return count;
}
static void CheckSurvivingGlobalObjectsCount(int expected) {
// We need to collect all garbage twice to be sure that everything
// has been collected. This is because inline caches are cleared in
// the first garbage collection but some of the maps have already
// been marked at that point. Therefore some of the maps are not
// collected until the second garbage collection.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
HEAP->CollectAllGarbage(i::Heap::kMakeHeapIterableMask);
int count = GetGlobalObjectsCount();
#ifdef DEBUG
if (count != expected) HEAP->TracePathToGlobal();
#endif
CHECK_EQ(expected, count);
}
TEST(DontLeakGlobalObjects) {
// Regression test for issues 1139850 and 1174891.
v8::V8::Initialize();
for (int i = 0; i < 5; i++) {
{ v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
}
v8::V8::ContextDisposedNotification();
CheckSurvivingGlobalObjectsCount(0);
{ v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
v8_compile("Date")->Run();
}
v8::V8::ContextDisposedNotification();
CheckSurvivingGlobalObjectsCount(0);
{ v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
v8_compile("/aaa/")->Run();
}
v8::V8::ContextDisposedNotification();
CheckSurvivingGlobalObjectsCount(0);
{ v8::HandleScope scope(v8::Isolate::GetCurrent());
const char* extension_list[] = { "v8/gc" };
v8::ExtensionConfiguration extensions(1, extension_list);
LocalContext context(&extensions);
v8_compile("gc();")->Run();
}
v8::V8::ContextDisposedNotification();
CheckSurvivingGlobalObjectsCount(0);
}
}
v8::Persistent<v8::Object> some_object;
v8::Persistent<v8::Object> bad_handle;
void NewPersistentHandleCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value>* handle,
void*) {
v8::HandleScope scope(isolate);
bad_handle.Reset(isolate, some_object);
handle->Dispose(isolate);
}
THREADED_TEST(NewPersistentHandleFromWeakCallback) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::Persistent<v8::Object> handle1, handle2;
{
v8::HandleScope scope(isolate);
some_object.Reset(isolate, v8::Object::New());
handle1.Reset(isolate, v8::Object::New());
handle2.Reset(isolate, v8::Object::New());
}
// Note: order is implementation dependent alas: currently
// global handle nodes are processed by PostGarbageCollectionProcessing
// in reverse allocation order, so if second allocated handle is deleted,
// weak callback of the first handle would be able to 'reallocate' it.
handle1.MakeWeak<v8::Value, void>(NULL, NewPersistentHandleCallback);
handle2.Dispose(isolate);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
v8::Persistent<v8::Object> to_be_disposed;
void DisposeAndForceGcCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value>* handle,
void*) {
to_be_disposed.Dispose(isolate);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
handle->Dispose(isolate);
}
THREADED_TEST(DoNotUseDeletedNodesInSecondLevelGc) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::Persistent<v8::Object> handle1, handle2;
{
v8::HandleScope scope(isolate);
handle1.Reset(isolate, v8::Object::New());
handle2.Reset(isolate, v8::Object::New());
}
handle1.MakeWeak<v8::Value, void>(NULL, DisposeAndForceGcCallback);
to_be_disposed.Reset(isolate, handle2);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
void DisposingCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value>* handle,
void*) {
handle->Dispose(isolate);
}
void HandleCreatingCallback(v8::Isolate* isolate,
v8::Persistent<v8::Value>* handle,
void*) {
v8::HandleScope scope(isolate);
v8::Persistent<v8::Object>(isolate, v8::Object::New());
handle->Dispose(isolate);
}
THREADED_TEST(NoGlobalHandlesOrphaningDueToWeakCallback) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::Persistent<v8::Object> handle1, handle2, handle3;
{
v8::HandleScope scope(isolate);
handle3.Reset(isolate, v8::Object::New());
handle2.Reset(isolate, v8::Object::New());
handle1.Reset(isolate, v8::Object::New());
}
handle2.MakeWeak<v8::Value, void>(NULL, DisposingCallback);
handle3.MakeWeak<v8::Value, void>(NULL, HandleCreatingCallback);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
THREADED_TEST(CheckForCrossContextObjectLiterals) {
v8::V8::Initialize();
const int nof = 2;
const char* sources[nof] = {
"try { [ 2, 3, 4 ].forEach(5); } catch(e) { e.toString(); }",
"Object()"
};
for (int i = 0; i < nof; i++) {
const char* source = sources[i];
{ v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
CompileRun(source);
}
{ v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
CompileRun(source);
}
}
}
static v8::Handle<Value> NestedScope(v8::Local<Context> env) {
v8::HandleScope inner(env->GetIsolate());
env->Enter();
v8::Handle<Value> three = v8_num(3);
v8::Handle<Value> value = inner.Close(three);
env->Exit();
return value;
}
THREADED_TEST(NestedHandleScopeAndContexts) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope outer(isolate);
v8::Local<Context> env = Context::New(isolate);
env->Enter();
v8::Handle<Value> value = NestedScope(env);
v8::Handle<String> str(value->ToString());
CHECK(!str.IsEmpty());
env->Exit();
}
static bool MatchPointers(void* key1, void* key2) {
return key1 == key2;
}
struct SymbolInfo {
size_t id;
size_t size;
std::string name;
};
class SetFunctionEntryHookTest {
public:
SetFunctionEntryHookTest() {
CHECK(instance_ == NULL);
instance_ = this;
}
~SetFunctionEntryHookTest() {
CHECK(instance_ == this);
instance_ = NULL;
}
void Reset() {
symbols_.clear();
symbol_locations_.clear();
invocations_.clear();
}
void RunTest();
void OnJitEvent(const v8::JitCodeEvent* event);
static void JitEvent(const v8::JitCodeEvent* event) {
CHECK(instance_ != NULL);
instance_->OnJitEvent(event);
}
void OnEntryHook(uintptr_t function,
uintptr_t return_addr_location);
static void EntryHook(uintptr_t function,
uintptr_t return_addr_location) {
CHECK(instance_ != NULL);
instance_->OnEntryHook(function, return_addr_location);
}
static void RuntimeCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(instance_ != NULL);
args.GetReturnValue().Set(v8_num(42));
}
void RunLoopInNewEnv(v8::Isolate* isolate);
// Records addr as location of symbol.
void InsertSymbolAt(i::Address addr, SymbolInfo* symbol);
// Finds the symbol containing addr
SymbolInfo* FindSymbolForAddr(i::Address addr);
// Returns the number of invocations where the caller name contains
// \p caller_name and the function name contains \p function_name.
int CountInvocations(const char* caller_name,
const char* function_name);
i::Handle<i::JSFunction> foo_func_;
i::Handle<i::JSFunction> bar_func_;
typedef std::map<size_t, SymbolInfo> SymbolMap;
typedef std::map<i::Address, SymbolInfo*> SymbolLocationMap;
typedef std::map<std::pair<SymbolInfo*, SymbolInfo*>, int> InvocationMap;
SymbolMap symbols_;
SymbolLocationMap symbol_locations_;
InvocationMap invocations_;
static SetFunctionEntryHookTest* instance_;
};
SetFunctionEntryHookTest* SetFunctionEntryHookTest::instance_ = NULL;
// Returns true if addr is in the range [start, start+len).
static bool Overlaps(i::Address start, size_t len, i::Address addr) {
if (start <= addr && start + len > addr)
return true;
return false;
}
void SetFunctionEntryHookTest::InsertSymbolAt(i::Address addr,
SymbolInfo* symbol) {
// Insert the symbol at the new location.
SymbolLocationMap::iterator it =
symbol_locations_.insert(std::make_pair(addr, symbol)).first;
// Now erase symbols to the left and right that overlap this one.
while (it != symbol_locations_.begin()) {
SymbolLocationMap::iterator left = it;
--left;
if (!Overlaps(left->first, left->second->size, addr))
break;
symbol_locations_.erase(left);
}
// Now erase symbols to the left and right that overlap this one.
while (true) {
SymbolLocationMap::iterator right = it;
++right;
if (right == symbol_locations_.end())
break;
if (!Overlaps(addr, symbol->size, right->first))
break;
symbol_locations_.erase(right);
}
}
void SetFunctionEntryHookTest::OnJitEvent(const v8::JitCodeEvent* event) {
switch (event->type) {
case v8::JitCodeEvent::CODE_ADDED: {
CHECK(event->code_start != NULL);
CHECK_NE(0, static_cast<int>(event->code_len));
CHECK(event->name.str != NULL);
size_t symbol_id = symbols_.size();
// Record the new symbol.
SymbolInfo& info = symbols_[symbol_id];
info.id = symbol_id;
info.size = event->code_len;
info.name.assign(event->name.str, event->name.str + event->name.len);
// And record it's location.
InsertSymbolAt(reinterpret_cast<i::Address>(event->code_start), &info);
}
break;
case v8::JitCodeEvent::CODE_MOVED: {
// We would like to never see code move that we haven't seen before,
// but the code creation event does not happen until the line endings
// have been calculated (this is so that we can report the line in the
// script at which the function source is found, see
// Compiler::RecordFunctionCompilation) and the line endings
// calculations can cause a GC, which can move the newly created code
// before its existence can be logged.
SymbolLocationMap::iterator it(
symbol_locations_.find(
reinterpret_cast<i::Address>(event->code_start)));
if (it != symbol_locations_.end()) {
// Found a symbol at this location, move it.
SymbolInfo* info = it->second;
symbol_locations_.erase(it);
InsertSymbolAt(reinterpret_cast<i::Address>(event->new_code_start),
info);
}
}
default:
break;
}
}
void SetFunctionEntryHookTest::OnEntryHook(
uintptr_t function, uintptr_t return_addr_location) {
// Get the function's code object.
i::Code* function_code = i::Code::GetCodeFromTargetAddress(
reinterpret_cast<i::Address>(function));
CHECK(function_code != NULL);
// Then try and look up the caller's code object.
i::Address caller = *reinterpret_cast<i::Address*>(return_addr_location);
// Count the invocation.
SymbolInfo* caller_symbol = FindSymbolForAddr(caller);
SymbolInfo* function_symbol =
FindSymbolForAddr(reinterpret_cast<i::Address>(function));
++invocations_[std::make_pair(caller_symbol, function_symbol)];
if (!bar_func_.is_null() && function_code == bar_func_->code()) {
// Check that we have a symbol for the "bar" function at the right location.
SymbolLocationMap::iterator it(
symbol_locations_.find(function_code->instruction_start()));
CHECK(it != symbol_locations_.end());
}
if (!foo_func_.is_null() && function_code == foo_func_->code()) {
// Check that we have a symbol for "foo" at the right location.
SymbolLocationMap::iterator it(
symbol_locations_.find(function_code->instruction_start()));
CHECK(it != symbol_locations_.end());
}
}
SymbolInfo* SetFunctionEntryHookTest::FindSymbolForAddr(i::Address addr) {
SymbolLocationMap::iterator it(symbol_locations_.lower_bound(addr));
// Do we have a direct hit on a symbol?
if (it != symbol_locations_.end()) {
if (it->first == addr)
return it->second;
}
// If not a direct hit, it'll have to be the previous symbol.
if (it == symbol_locations_.begin())
return NULL;
--it;
size_t offs = addr - it->first;
if (offs < it->second->size)
return it->second;
return NULL;
}
int SetFunctionEntryHookTest::CountInvocations(
const char* caller_name, const char* function_name) {
InvocationMap::iterator it(invocations_.begin());
int invocations = 0;
for (; it != invocations_.end(); ++it) {
SymbolInfo* caller = it->first.first;
SymbolInfo* function = it->first.second;
// Filter out non-matching functions.
if (function_name != NULL) {
if (function->name.find(function_name) == std::string::npos)
continue;
}
// Filter out non-matching callers.
if (caller_name != NULL) {
if (caller == NULL)
continue;
if (caller->name.find(caller_name) == std::string::npos)
continue;
}
// It matches add the invocation count to the tally.
invocations += it->second;
}
return invocations;
}
void SetFunctionEntryHookTest::RunLoopInNewEnv(v8::Isolate* isolate) {
v8::HandleScope outer(isolate);
v8::Local<Context> env = Context::New(isolate);
env->Enter();
Local<ObjectTemplate> t = ObjectTemplate::New();
t->Set(v8_str("asdf"), v8::FunctionTemplate::New(RuntimeCallback));
env->Global()->Set(v8_str("obj"), t->NewInstance());
const char* script =
"function bar() {\n"
" var sum = 0;\n"
" for (i = 0; i < 100; ++i)\n"
" sum = foo(i);\n"
" return sum;\n"
"}\n"
"function foo(i) { return i * i; }\n"
"// Invoke on the runtime function.\n"
"obj.asdf()";
CompileRun(script);
bar_func_ = i::Handle<i::JSFunction>::cast(
v8::Utils::OpenHandle(*env->Global()->Get(v8_str("bar"))));
ASSERT(!bar_func_.is_null());
foo_func_ =
i::Handle<i::JSFunction>::cast(
v8::Utils::OpenHandle(*env->Global()->Get(v8_str("foo"))));
ASSERT(!foo_func_.is_null());
v8::Handle<v8::Value> value = CompileRun("bar();");
CHECK(value->IsNumber());
CHECK_EQ(9801.0, v8::Number::Cast(*value)->Value());
// Test the optimized codegen path.
value = CompileRun("%OptimizeFunctionOnNextCall(foo);"
"bar();");
CHECK(value->IsNumber());
CHECK_EQ(9801.0, v8::Number::Cast(*value)->Value());
env->Exit();
}
void SetFunctionEntryHookTest::RunTest() {
// Work in a new isolate throughout.
v8::Isolate* isolate = v8::Isolate::New();
// Test setting the entry hook on the new isolate.
CHECK(v8::V8::SetFunctionEntryHook(isolate, EntryHook));
// Replacing the hook, once set should fail.
CHECK_EQ(false, v8::V8::SetFunctionEntryHook(isolate, EntryHook));
{
v8::Isolate::Scope scope(isolate);
v8::V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault, JitEvent);
RunLoopInNewEnv(isolate);
// Check the exepected invocation counts.
CHECK_EQ(2, CountInvocations(NULL, "bar"));
CHECK_EQ(200, CountInvocations("bar", "foo"));
CHECK_EQ(200, CountInvocations(NULL, "foo"));
// Verify that we have an entry hook on some specific stubs.
CHECK_NE(0, CountInvocations(NULL, "CEntryStub"));
CHECK_NE(0, CountInvocations(NULL, "JSEntryStub"));
CHECK_NE(0, CountInvocations(NULL, "JSEntryTrampoline"));
}
isolate->Dispose();
Reset();
// Make sure a second isolate is unaffected by the previous entry hook.
isolate = v8::Isolate::New();
{
v8::Isolate::Scope scope(isolate);
// Reset the entry count to zero and set the entry hook.
RunLoopInNewEnv(isolate);
// We should record no invocations in this isolate.
CHECK_EQ(0, static_cast<int>(invocations_.size()));
}
// Since the isolate has been used, we shouldn't be able to set an entry
// hook anymore.
CHECK_EQ(false, v8::V8::SetFunctionEntryHook(isolate, EntryHook));
isolate->Dispose();
}
TEST(SetFunctionEntryHook) {
// FunctionEntryHook does not work well with experimental natives.
// Experimental natives are compiled during snapshot deserialization.
// This test breaks because InstallGetter (function from snapshot that
// only gets called from experimental natives) is compiled with entry hooks.
i::FLAG_harmony_typed_arrays = false;
i::FLAG_harmony_array_buffer = false;
i::FLAG_allow_natives_syntax = true;
i::FLAG_use_inlining = false;
SetFunctionEntryHookTest test;
test.RunTest();
}
static i::HashMap* code_map = NULL;
static i::HashMap* jitcode_line_info = NULL;
static int saw_bar = 0;
static int move_events = 0;
static bool FunctionNameIs(const char* expected,
const v8::JitCodeEvent* event) {
// Log lines for functions are of the general form:
// "LazyCompile:<type><function_name>", where the type is one of
// "*", "~" or "".
static const char kPreamble[] = "LazyCompile:";
static size_t kPreambleLen = sizeof(kPreamble) - 1;
if (event->name.len < sizeof(kPreamble) - 1 ||
strncmp(kPreamble, event->name.str, kPreambleLen) != 0) {
return false;
}
const char* tail = event->name.str + kPreambleLen;
size_t tail_len = event->name.len - kPreambleLen;
size_t expected_len = strlen(expected);
if (tail_len > 1 && (*tail == '*' || *tail == '~')) {
--tail_len;
++tail;
}
// Check for tails like 'bar :1'.
if (tail_len > expected_len + 2 &&
tail[expected_len] == ' ' &&
tail[expected_len + 1] == ':' &&
tail[expected_len + 2] &&
!strncmp(tail, expected, expected_len)) {
return true;
}
if (tail_len != expected_len)
return false;
return strncmp(tail, expected, expected_len) == 0;
}
static void event_handler(const v8::JitCodeEvent* event) {
CHECK(event != NULL);
CHECK(code_map != NULL);
CHECK(jitcode_line_info != NULL);
class DummyJitCodeLineInfo {
};
switch (event->type) {
case v8::JitCodeEvent::CODE_ADDED: {
CHECK(event->code_start != NULL);
CHECK_NE(0, static_cast<int>(event->code_len));
CHECK(event->name.str != NULL);
i::HashMap::Entry* entry =
code_map->Lookup(event->code_start,
i::ComputePointerHash(event->code_start),
true);
entry->value = reinterpret_cast<void*>(event->code_len);
if (FunctionNameIs("bar", event)) {
++saw_bar;
}
}
break;
case v8::JitCodeEvent::CODE_MOVED: {
uint32_t hash = i::ComputePointerHash(event->code_start);
// We would like to never see code move that we haven't seen before,
// but the code creation event does not happen until the line endings
// have been calculated (this is so that we can report the line in the
// script at which the function source is found, see
// Compiler::RecordFunctionCompilation) and the line endings
// calculations can cause a GC, which can move the newly created code
// before its existence can be logged.
i::HashMap::Entry* entry =
code_map->Lookup(event->code_start, hash, false);
if (entry != NULL) {
++move_events;
CHECK_EQ(reinterpret_cast<void*>(event->code_len), entry->value);
code_map->Remove(event->code_start, hash);
entry = code_map->Lookup(event->new_code_start,
i::ComputePointerHash(event->new_code_start),
true);
CHECK(entry != NULL);
entry->value = reinterpret_cast<void*>(event->code_len);
}
}
break;
case v8::JitCodeEvent::CODE_REMOVED:
// Object/code removal events are currently not dispatched from the GC.
CHECK(false);
break;
// For CODE_START_LINE_INFO_RECORDING event, we will create one
// DummyJitCodeLineInfo data structure pointed by event->user_dat. We
// record it in jitcode_line_info.
case v8::JitCodeEvent::CODE_START_LINE_INFO_RECORDING: {
DummyJitCodeLineInfo* line_info = new DummyJitCodeLineInfo();
v8::JitCodeEvent* temp_event = const_cast<v8::JitCodeEvent*>(event);
temp_event->user_data = line_info;
i::HashMap::Entry* entry =
jitcode_line_info->Lookup(line_info,
i::ComputePointerHash(line_info),
true);
entry->value = reinterpret_cast<void*>(line_info);
}
break;
// For these two events, we will check whether the event->user_data
// data structure is created before during CODE_START_LINE_INFO_RECORDING
// event. And delete it in CODE_END_LINE_INFO_RECORDING event handling.
case v8::JitCodeEvent::CODE_END_LINE_INFO_RECORDING: {
CHECK(event->user_data != NULL);
uint32_t hash = i::ComputePointerHash(event->user_data);
i::HashMap::Entry* entry =
jitcode_line_info->Lookup(event->user_data, hash, false);
CHECK(entry != NULL);
delete reinterpret_cast<DummyJitCodeLineInfo*>(event->user_data);
}
break;
case v8::JitCodeEvent::CODE_ADD_LINE_POS_INFO: {
CHECK(event->user_data != NULL);
uint32_t hash = i::ComputePointerHash(event->user_data);
i::HashMap::Entry* entry =
jitcode_line_info->Lookup(event->user_data, hash, false);
CHECK(entry != NULL);
}
break;
default:
// Impossible event.
CHECK(false);
break;
}
}
TEST(SetJitCodeEventHandler) {
i::FLAG_stress_compaction = true;
i::FLAG_incremental_marking = false;
const char* script =
"function bar() {"
" var sum = 0;"
" for (i = 0; i < 100; ++i)"
" sum = foo(i);"
" return sum;"
"}"
"function foo(i) { return i * i; };"
"bar();";
// Run this test in a new isolate to make sure we don't
// have remnants of state from other code.
v8::Isolate* isolate = v8::Isolate::New();
isolate->Enter();
{
v8::HandleScope scope(isolate);
i::HashMap code(MatchPointers);
code_map = &code;
i::HashMap lineinfo(MatchPointers);
jitcode_line_info = &lineinfo;
saw_bar = 0;
move_events = 0;
V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault, event_handler);
// Generate new code objects sparsely distributed across several
// different fragmented code-space pages.
const int kIterations = 10;
for (int i = 0; i < kIterations; ++i) {
LocalContext env;
i::AlwaysAllocateScope always_allocate;
SimulateFullSpace(HEAP->code_space());
CompileRun(script);
// Keep a strong reference to the code object in the handle scope.
i::Handle<i::Code> bar_code(i::Handle<i::JSFunction>::cast(
v8::Utils::OpenHandle(*env->Global()->Get(v8_str("bar"))))->code());
i::Handle<i::Code> foo_code(i::Handle<i::JSFunction>::cast(
v8::Utils::OpenHandle(*env->Global()->Get(v8_str("foo"))))->code());
// Clear the compilation cache to get more wastage.
ISOLATE->compilation_cache()->Clear();
}
// Force code movement.
HEAP->CollectAllAvailableGarbage("TestSetJitCodeEventHandler");
V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault, NULL);
CHECK_LE(kIterations, saw_bar);
CHECK_LT(0, move_events);
code_map = NULL;
jitcode_line_info = NULL;
}
isolate->Exit();
isolate->Dispose();
// Do this in a new isolate.
isolate = v8::Isolate::New();
isolate->Enter();
// Verify that we get callbacks for existing code objects when we
// request enumeration of existing code.
{
v8::HandleScope scope(isolate);
LocalContext env;
CompileRun(script);
// Now get code through initial iteration.
i::HashMap code(MatchPointers);
code_map = &code;
i::HashMap lineinfo(MatchPointers);
jitcode_line_info = &lineinfo;
V8::SetJitCodeEventHandler(v8::kJitCodeEventEnumExisting, event_handler);
V8::SetJitCodeEventHandler(v8::kJitCodeEventDefault, NULL);
jitcode_line_info = NULL;
// We expect that we got some events. Note that if we could get code removal
// notifications, we could compare two collections, one created by listening
// from the time of creation of an isolate, and the other by subscribing
// with EnumExisting.
CHECK_LT(0, code.occupancy());
code_map = NULL;
}
isolate->Exit();
isolate->Dispose();
}
static int64_t cast(intptr_t x) { return static_cast<int64_t>(x); }
THREADED_TEST(ExternalAllocatedMemory) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope outer(isolate);
v8::Local<Context> env(Context::New(isolate));
CHECK(!env.IsEmpty());
const intptr_t kSize = 1024*1024;
int64_t baseline = cast(isolate->AdjustAmountOfExternalAllocatedMemory(0));
CHECK_EQ(baseline + cast(kSize),
cast(isolate->AdjustAmountOfExternalAllocatedMemory(kSize)));
CHECK_EQ(baseline,
cast(isolate->AdjustAmountOfExternalAllocatedMemory(-kSize)));
}
THREADED_TEST(DisposeEnteredContext) {
LocalContext outer;
v8::Isolate* isolate = outer->GetIsolate();
v8::Persistent<v8::Context> inner;
{
v8::HandleScope scope(isolate);
inner.Reset(isolate, v8::Context::New(isolate));
}
v8::HandleScope scope(isolate);
{
// Don't want a handle here, so do this unsafely
v8::Handle<v8::Context> inner_local =
v8::Utils::Convert<i::Object, v8::Context>(
v8::Utils::OpenPersistent(inner));
inner_local->Enter();
inner.Dispose();
inner.Clear();
inner_local->Exit();
}
}
// Regression test for issue 54, object templates with internal fields
// but no accessors or interceptors did not get their internal field
// count set on instances.
THREADED_TEST(Regress54) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope outer(isolate);
static v8::Persistent<v8::ObjectTemplate> templ;
if (templ.IsEmpty()) {
v8::HandleScope inner(isolate);
v8::Handle<v8::ObjectTemplate> local = v8::ObjectTemplate::New();
local->SetInternalFieldCount(1);
templ.Reset(isolate, inner.Close(local));
}
v8::Handle<v8::Object> result =
v8::Local<v8::ObjectTemplate>::New(isolate, templ)->NewInstance();
CHECK_EQ(1, result->InternalFieldCount());
}
// If part of the threaded tests, this test makes ThreadingTest fail
// on mac.
TEST(CatchStackOverflow) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(
"function f() {"
" return f();"
"}"
""
"f();"));
v8::Handle<v8::Value> result = script->Run();
CHECK(result.IsEmpty());
}
static void CheckTryCatchSourceInfo(v8::Handle<v8::Script> script,
const char* resource_name,
int line_offset) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::TryCatch try_catch;
v8::Handle<v8::Value> result = script->Run();
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
v8::Handle<v8::Message> message = try_catch.Message();
CHECK(!message.IsEmpty());
CHECK_EQ(10 + line_offset, message->GetLineNumber());
CHECK_EQ(91, message->GetStartPosition());
CHECK_EQ(92, message->GetEndPosition());
CHECK_EQ(2, message->GetStartColumn());
CHECK_EQ(3, message->GetEndColumn());
v8::String::Utf8Value line(message->GetSourceLine());
CHECK_EQ(" throw 'nirk';", *line);
v8::String::Utf8Value name(message->GetScriptResourceName());
CHECK_EQ(resource_name, *name);
}
THREADED_TEST(TryCatchSourceInfo) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::String> source = v8::String::New(
"function Foo() {\n"
" return Bar();\n"
"}\n"
"\n"
"function Bar() {\n"
" return Baz();\n"
"}\n"
"\n"
"function Baz() {\n"
" throw 'nirk';\n"
"}\n"
"\n"
"Foo();\n");
const char* resource_name;
v8::Handle<v8::Script> script;
resource_name = "test.js";
script = v8::Script::Compile(source, v8::String::New(resource_name));
CheckTryCatchSourceInfo(script, resource_name, 0);
resource_name = "test1.js";
v8::ScriptOrigin origin1(v8::String::New(resource_name));
script = v8::Script::Compile(source, &origin1);
CheckTryCatchSourceInfo(script, resource_name, 0);
resource_name = "test2.js";
v8::ScriptOrigin origin2(v8::String::New(resource_name), v8::Integer::New(7));
script = v8::Script::Compile(source, &origin2);
CheckTryCatchSourceInfo(script, resource_name, 7);
}
THREADED_TEST(CompilationCache) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::String> source0 = v8::String::New("1234");
v8::Handle<v8::String> source1 = v8::String::New("1234");
v8::Handle<v8::Script> script0 =
v8::Script::Compile(source0, v8::String::New("test.js"));
v8::Handle<v8::Script> script1 =
v8::Script::Compile(source1, v8::String::New("test.js"));
v8::Handle<v8::Script> script2 =
v8::Script::Compile(source0); // different origin
CHECK_EQ(1234, script0->Run()->Int32Value());
CHECK_EQ(1234, script1->Run()->Int32Value());
CHECK_EQ(1234, script2->Run()->Int32Value());
}
static void FunctionNameCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
args.GetReturnValue().Set(v8_num(42));
}
THREADED_TEST(CallbackFunctionName) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> t = ObjectTemplate::New();
t->Set(v8_str("asdf"), v8::FunctionTemplate::New(FunctionNameCallback));
context->Global()->Set(v8_str("obj"), t->NewInstance());
v8::Handle<v8::Value> value = CompileRun("obj.asdf.name");
CHECK(value->IsString());
v8::String::Utf8Value name(value);
CHECK_EQ("asdf", *name);
}
THREADED_TEST(DateAccess) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> date = v8::Date::New(1224744689038.0);
CHECK(date->IsDate());
CHECK_EQ(1224744689038.0, date.As<v8::Date>()->ValueOf());
}
void CheckProperties(v8::Handle<v8::Value> val, int elmc, const char* elmv[]) {
v8::Handle<v8::Object> obj = val.As<v8::Object>();
v8::Handle<v8::Array> props = obj->GetPropertyNames();
CHECK_EQ(elmc, props->Length());
for (int i = 0; i < elmc; i++) {
v8::String::Utf8Value elm(props->Get(v8::Integer::New(i)));
CHECK_EQ(elmv[i], *elm);
}
}
void CheckOwnProperties(v8::Handle<v8::Value> val,
int elmc,
const char* elmv[]) {
v8::Handle<v8::Object> obj = val.As<v8::Object>();
v8::Handle<v8::Array> props = obj->GetOwnPropertyNames();
CHECK_EQ(elmc, props->Length());
for (int i = 0; i < elmc; i++) {
v8::String::Utf8Value elm(props->Get(v8::Integer::New(i)));
CHECK_EQ(elmv[i], *elm);
}
}
THREADED_TEST(PropertyEnumeration) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> obj = v8::Script::Compile(v8::String::New(
"var result = [];"
"result[0] = {};"
"result[1] = {a: 1, b: 2};"
"result[2] = [1, 2, 3];"
"var proto = {x: 1, y: 2, z: 3};"
"var x = { __proto__: proto, w: 0, z: 1 };"
"result[3] = x;"
"result;"))->Run();
v8::Handle<v8::Array> elms = obj.As<v8::Array>();
CHECK_EQ(4, elms->Length());
int elmc0 = 0;
const char** elmv0 = NULL;
CheckProperties(elms->Get(v8::Integer::New(0)), elmc0, elmv0);
CheckOwnProperties(elms->Get(v8::Integer::New(0)), elmc0, elmv0);
int elmc1 = 2;
const char* elmv1[] = {"a", "b"};
CheckProperties(elms->Get(v8::Integer::New(1)), elmc1, elmv1);
CheckOwnProperties(elms->Get(v8::Integer::New(1)), elmc1, elmv1);
int elmc2 = 3;
const char* elmv2[] = {"0", "1", "2"};
CheckProperties(elms->Get(v8::Integer::New(2)), elmc2, elmv2);
CheckOwnProperties(elms->Get(v8::Integer::New(2)), elmc2, elmv2);
int elmc3 = 4;
const char* elmv3[] = {"w", "z", "x", "y"};
CheckProperties(elms->Get(v8::Integer::New(3)), elmc3, elmv3);
int elmc4 = 2;
const char* elmv4[] = {"w", "z"};
CheckOwnProperties(elms->Get(v8::Integer::New(3)), elmc4, elmv4);
}
THREADED_TEST(PropertyEnumeration2) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Value> obj = v8::Script::Compile(v8::String::New(
"var result = [];"
"result[0] = {};"
"result[1] = {a: 1, b: 2};"
"result[2] = [1, 2, 3];"
"var proto = {x: 1, y: 2, z: 3};"
"var x = { __proto__: proto, w: 0, z: 1 };"
"result[3] = x;"
"result;"))->Run();
v8::Handle<v8::Array> elms = obj.As<v8::Array>();
CHECK_EQ(4, elms->Length());
int elmc0 = 0;
const char** elmv0 = NULL;
CheckProperties(elms->Get(v8::Integer::New(0)), elmc0, elmv0);
v8::Handle<v8::Value> val = elms->Get(v8::Integer::New(0));
v8::Handle<v8::Array> props = val.As<v8::Object>()->GetPropertyNames();
CHECK_EQ(0, props->Length());
for (uint32_t i = 0; i < props->Length(); i++) {
printf("p[%d]\n", i);
}
}
static bool NamedSetAccessBlocker(Local<v8::Object> obj,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
return type != v8::ACCESS_SET;
}
static bool IndexedSetAccessBlocker(Local<v8::Object> obj,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
return type != v8::ACCESS_SET;
}
THREADED_TEST(DisableAccessChecksWhileConfiguring) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessCheckCallbacks(NamedSetAccessBlocker,
IndexedSetAccessBlocker);
templ->Set(v8_str("x"), v8::True());
Local<v8::Object> instance = templ->NewInstance();
context->Global()->Set(v8_str("obj"), instance);
Local<Value> value = CompileRun("obj.x");
CHECK(value->BooleanValue());
}
static bool NamedGetAccessBlocker(Local<v8::Object> obj,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
return false;
}
static bool IndexedGetAccessBlocker(Local<v8::Object> obj,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
return false;
}
THREADED_TEST(AccessChecksReenabledCorrectly) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessCheckCallbacks(NamedGetAccessBlocker,
IndexedGetAccessBlocker);
templ->Set(v8_str("a"), v8_str("a"));
// Add more than 8 (see kMaxFastProperties) properties
// so that the constructor will force copying map.
// Cannot sprintf, gcc complains unsafety.
char buf[4];
for (char i = '0'; i <= '9' ; i++) {
buf[0] = i;
for (char j = '0'; j <= '9'; j++) {
buf[1] = j;
for (char k = '0'; k <= '9'; k++) {
buf[2] = k;
buf[3] = 0;
templ->Set(v8_str(buf), v8::Number::New(k));
}
}
}
Local<v8::Object> instance_1 = templ->NewInstance();
context->Global()->Set(v8_str("obj_1"), instance_1);
Local<Value> value_1 = CompileRun("obj_1.a");
CHECK(value_1->IsUndefined());
Local<v8::Object> instance_2 = templ->NewInstance();
context->Global()->Set(v8_str("obj_2"), instance_2);
Local<Value> value_2 = CompileRun("obj_2.a");
CHECK(value_2->IsUndefined());
}
// This tests that access check information remains on the global
// object template when creating contexts.
THREADED_TEST(AccessControlRepeatedContextCreation) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedSetAccessBlocker,
IndexedSetAccessBlocker);
i::Handle<i::ObjectTemplateInfo> internal_template =
v8::Utils::OpenHandle(*global_template);
CHECK(!internal_template->constructor()->IsUndefined());
i::Handle<i::FunctionTemplateInfo> constructor(
i::FunctionTemplateInfo::cast(internal_template->constructor()));
CHECK(!constructor->access_check_info()->IsUndefined());
v8::Local<Context> context0(Context::New(isolate, NULL, global_template));
CHECK(!context0.IsEmpty());
CHECK(!constructor->access_check_info()->IsUndefined());
}
THREADED_TEST(TurnOnAccessCheck) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
// Create an environment with access check to the global object disabled by
// default.
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedGetAccessBlocker,
IndexedGetAccessBlocker,
v8::Handle<v8::Value>(),
false);
v8::Local<Context> context = Context::New(isolate, NULL, global_template);
Context::Scope context_scope(context);
// Set up a property and a number of functions.
context->Global()->Set(v8_str("a"), v8_num(1));
CompileRun("function f1() {return a;}"
"function f2() {return a;}"
"function g1() {return h();}"
"function g2() {return h();}"
"function h() {return 1;}");
Local<Function> f1 =
Local<Function>::Cast(context->Global()->Get(v8_str("f1")));
Local<Function> f2 =
Local<Function>::Cast(context->Global()->Get(v8_str("f2")));
Local<Function> g1 =
Local<Function>::Cast(context->Global()->Get(v8_str("g1")));
Local<Function> g2 =
Local<Function>::Cast(context->Global()->Get(v8_str("g2")));
Local<Function> h =
Local<Function>::Cast(context->Global()->Get(v8_str("h")));
// Get the global object.
v8::Handle<v8::Object> global = context->Global();
// Call f1 one time and f2 a number of times. This will ensure that f1 still
// uses the runtime system to retreive property a whereas f2 uses global load
// inline cache.
CHECK(f1->Call(global, 0, NULL)->Equals(v8_num(1)));
for (int i = 0; i < 4; i++) {
CHECK(f2->Call(global, 0, NULL)->Equals(v8_num(1)));
}
// Same for g1 and g2.
CHECK(g1->Call(global, 0, NULL)->Equals(v8_num(1)));
for (int i = 0; i < 4; i++) {
CHECK(g2->Call(global, 0, NULL)->Equals(v8_num(1)));
}
// Detach the global and turn on access check.
context->DetachGlobal();
context->Global()->TurnOnAccessCheck();
// Failing access check to property get results in undefined.
CHECK(f1->Call(global, 0, NULL)->IsUndefined());
CHECK(f2->Call(global, 0, NULL)->IsUndefined());
// Failing access check to function call results in exception.
CHECK(g1->Call(global, 0, NULL).IsEmpty());
CHECK(g2->Call(global, 0, NULL).IsEmpty());
// No failing access check when just returning a constant.
CHECK(h->Call(global, 0, NULL)->Equals(v8_num(1)));
}
static const char* kPropertyA = "a";
static const char* kPropertyH = "h";
static bool NamedGetAccessBlockAandH(Local<v8::Object> obj,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
if (!name->IsString()) return false;
i::Handle<i::String> name_handle =
v8::Utils::OpenHandle(String::Cast(*name));
return !name_handle->IsUtf8EqualTo(i::CStrVector(kPropertyA))
&& !name_handle->IsUtf8EqualTo(i::CStrVector(kPropertyH));
}
THREADED_TEST(TurnOnAccessCheckAndRecompile) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
// Create an environment with access check to the global object disabled by
// default. When the registered access checker will block access to properties
// a and h.
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedGetAccessBlockAandH,
IndexedGetAccessBlocker,
v8::Handle<v8::Value>(),
false);
v8::Local<Context> context = Context::New(isolate, NULL, global_template);
Context::Scope context_scope(context);
// Set up a property and a number of functions.
context->Global()->Set(v8_str("a"), v8_num(1));
static const char* source = "function f1() {return a;}"
"function f2() {return a;}"
"function g1() {return h();}"
"function g2() {return h();}"
"function h() {return 1;}";
CompileRun(source);
Local<Function> f1;
Local<Function> f2;
Local<Function> g1;
Local<Function> g2;
Local<Function> h;
f1 = Local<Function>::Cast(context->Global()->Get(v8_str("f1")));
f2 = Local<Function>::Cast(context->Global()->Get(v8_str("f2")));
g1 = Local<Function>::Cast(context->Global()->Get(v8_str("g1")));
g2 = Local<Function>::Cast(context->Global()->Get(v8_str("g2")));
h = Local<Function>::Cast(context->Global()->Get(v8_str("h")));
// Get the global object.
v8::Handle<v8::Object> global = context->Global();
// Call f1 one time and f2 a number of times. This will ensure that f1 still
// uses the runtime system to retreive property a whereas f2 uses global load
// inline cache.
CHECK(f1->Call(global, 0, NULL)->Equals(v8_num(1)));
for (int i = 0; i < 4; i++) {
CHECK(f2->Call(global, 0, NULL)->Equals(v8_num(1)));
}
// Same for g1 and g2.
CHECK(g1->Call(global, 0, NULL)->Equals(v8_num(1)));
for (int i = 0; i < 4; i++) {
CHECK(g2->Call(global, 0, NULL)->Equals(v8_num(1)));
}
// Detach the global and turn on access check now blocking access to property
// a and function h.
context->DetachGlobal();
context->Global()->TurnOnAccessCheck();
// Failing access check to property get results in undefined.
CHECK(f1->Call(global, 0, NULL)->IsUndefined());
CHECK(f2->Call(global, 0, NULL)->IsUndefined());
// Failing access check to function call results in exception.
CHECK(g1->Call(global, 0, NULL).IsEmpty());
CHECK(g2->Call(global, 0, NULL).IsEmpty());
// No failing access check when just returning a constant.
CHECK(h->Call(global, 0, NULL)->Equals(v8_num(1)));
// Now compile the source again. And get the newly compiled functions, except
// for h for which access is blocked.
CompileRun(source);
f1 = Local<Function>::Cast(context->Global()->Get(v8_str("f1")));
f2 = Local<Function>::Cast(context->Global()->Get(v8_str("f2")));
g1 = Local<Function>::Cast(context->Global()->Get(v8_str("g1")));
g2 = Local<Function>::Cast(context->Global()->Get(v8_str("g2")));
CHECK(context->Global()->Get(v8_str("h"))->IsUndefined());
// Failing access check to property get results in undefined.
CHECK(f1->Call(global, 0, NULL)->IsUndefined());
CHECK(f2->Call(global, 0, NULL)->IsUndefined());
// Failing access check to function call results in exception.
CHECK(g1->Call(global, 0, NULL).IsEmpty());
CHECK(g2->Call(global, 0, NULL).IsEmpty());
}
// This test verifies that pre-compilation (aka preparsing) can be called
// without initializing the whole VM. Thus we cannot run this test in a
// multi-threaded setup.
TEST(PreCompile) {
// TODO(155): This test would break without the initialization of V8. This is
// a workaround for now to make this test not fail.
v8::V8::Initialize();
const char* script = "function foo(a) { return a+1; }";
v8::ScriptData* sd =
v8::ScriptData::PreCompile(script, i::StrLength(script));
CHECK_NE(sd->Length(), 0);
CHECK_NE(sd->Data(), NULL);
CHECK(!sd->HasError());
delete sd;
}
TEST(PreCompileWithError) {
v8::V8::Initialize();
const char* script = "function foo(a) { return 1 * * 2; }";
v8::ScriptData* sd =
v8::ScriptData::PreCompile(script, i::StrLength(script));
CHECK(sd->HasError());
delete sd;
}
TEST(Regress31661) {
v8::V8::Initialize();
const char* script = " The Definintive Guide";
v8::ScriptData* sd =
v8::ScriptData::PreCompile(script, i::StrLength(script));
CHECK(sd->HasError());
delete sd;
}
// Tests that ScriptData can be serialized and deserialized.
TEST(PreCompileSerialization) {
v8::V8::Initialize();
const char* script = "function foo(a) { return a+1; }";
v8::ScriptData* sd =
v8::ScriptData::PreCompile(script, i::StrLength(script));
// Serialize.
int serialized_data_length = sd->Length();
char* serialized_data = i::NewArray<char>(serialized_data_length);
i::OS::MemCopy(serialized_data, sd->Data(), serialized_data_length);
// Deserialize.
v8::ScriptData* deserialized_sd =
v8::ScriptData::New(serialized_data, serialized_data_length);
// Verify that the original is the same as the deserialized.
CHECK_EQ(sd->Length(), deserialized_sd->Length());
CHECK_EQ(0, memcmp(sd->Data(), deserialized_sd->Data(), sd->Length()));
CHECK_EQ(sd->HasError(), deserialized_sd->HasError());
delete sd;
delete deserialized_sd;
}
// Attempts to deserialize bad data.
TEST(PreCompileDeserializationError) {
v8::V8::Initialize();
const char* data = "DONT CARE";
int invalid_size = 3;
v8::ScriptData* sd = v8::ScriptData::New(data, invalid_size);
CHECK_EQ(0, sd->Length());
delete sd;
}
// Attempts to deserialize bad data.
TEST(PreCompileInvalidPreparseDataError) {
v8::V8::Initialize();
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
const char* script = "function foo(){ return 5;}\n"
"function bar(){ return 6 + 7;} foo();";
v8::ScriptData* sd =
v8::ScriptData::PreCompile(script, i::StrLength(script));
CHECK(!sd->HasError());
// ScriptDataImpl private implementation details
const int kHeaderSize = i::PreparseDataConstants::kHeaderSize;
const int kFunctionEntrySize = i::FunctionEntry::kSize;
const int kFunctionEntryStartOffset = 0;
const int kFunctionEntryEndOffset = 1;
unsigned* sd_data =
reinterpret_cast<unsigned*>(const_cast<char*>(sd->Data()));
// Overwrite function bar's end position with 0.
sd_data[kHeaderSize + 1 * kFunctionEntrySize + kFunctionEntryEndOffset] = 0;
v8::TryCatch try_catch;
Local<String> source = String::New(script);
Local<Script> compiled_script = Script::New(source, NULL, sd);
CHECK(try_catch.HasCaught());
String::Utf8Value exception_value(try_catch.Message()->Get());
CHECK_EQ("Uncaught SyntaxError: Invalid preparser data for function bar",
*exception_value);
try_catch.Reset();
// Overwrite function bar's start position with 200. The function entry
// will not be found when searching for it by position and we should fall
// back on eager compilation.
sd = v8::ScriptData::PreCompile(script, i::StrLength(script));
sd_data = reinterpret_cast<unsigned*>(const_cast<char*>(sd->Data()));
sd_data[kHeaderSize + 1 * kFunctionEntrySize + kFunctionEntryStartOffset] =
200;
compiled_script = Script::New(source, NULL, sd);
CHECK(!try_catch.HasCaught());
delete sd;
}
// Verifies that the Handle<String> and const char* versions of the API produce
// the same results (at least for one trivial case).
TEST(PreCompileAPIVariationsAreSame) {
v8::V8::Initialize();
v8::HandleScope scope(v8::Isolate::GetCurrent());
const char* cstring = "function foo(a) { return a+1; }";
v8::ScriptData* sd_from_cstring =
v8::ScriptData::PreCompile(cstring, i::StrLength(cstring));
TestAsciiResource* resource = new TestAsciiResource(cstring);
v8::ScriptData* sd_from_external_string = v8::ScriptData::PreCompile(
v8::String::NewExternal(resource));
v8::ScriptData* sd_from_string = v8::ScriptData::PreCompile(
v8::String::New(cstring));
CHECK_EQ(sd_from_cstring->Length(), sd_from_external_string->Length());
CHECK_EQ(0, memcmp(sd_from_cstring->Data(),
sd_from_external_string->Data(),
sd_from_cstring->Length()));
CHECK_EQ(sd_from_cstring->Length(), sd_from_string->Length());
CHECK_EQ(0, memcmp(sd_from_cstring->Data(),
sd_from_string->Data(),
sd_from_cstring->Length()));
delete sd_from_cstring;
delete sd_from_external_string;
delete sd_from_string;
}
// This tests that we do not allow dictionary load/call inline caches
// to use functions that have not yet been compiled. The potential
// problem of loading a function that has not yet been compiled can
// arise because we share code between contexts via the compilation
// cache.
THREADED_TEST(DictionaryICLoadedFunction) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
// Test LoadIC.
for (int i = 0; i < 2; i++) {
LocalContext context;
context->Global()->Set(v8_str("tmp"), v8::True());
context->Global()->Delete(v8_str("tmp"));
CompileRun("for (var j = 0; j < 10; j++) new RegExp('');");
}
// Test CallIC.
for (int i = 0; i < 2; i++) {
LocalContext context;
context->Global()->Set(v8_str("tmp"), v8::True());
context->Global()->Delete(v8_str("tmp"));
CompileRun("for (var j = 0; j < 10; j++) RegExp('')");
}
}
// Test that cross-context new calls use the context of the callee to
// create the new JavaScript object.
THREADED_TEST(CrossContextNew) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Local<Context> context0 = Context::New(isolate);
v8::Local<Context> context1 = Context::New(isolate);
// Allow cross-domain access.
Local<String> token = v8_str("<security token>");
context0->SetSecurityToken(token);
context1->SetSecurityToken(token);
// Set an 'x' property on the Object prototype and define a
// constructor function in context0.
context0->Enter();
CompileRun("Object.prototype.x = 42; function C() {};");
context0->Exit();
// Call the constructor function from context0 and check that the
// result has the 'x' property.
context1->Enter();
context1->Global()->Set(v8_str("other"), context0->Global());
Local<Value> value = CompileRun("var instance = new other.C(); instance.x");
CHECK(value->IsInt32());
CHECK_EQ(42, value->Int32Value());
context1->Exit();
}
class RegExpInterruptTest {
public:
RegExpInterruptTest() : block_(NULL) {}
~RegExpInterruptTest() { delete block_; }
void RunTest() {
block_ = i::OS::CreateSemaphore(0);
gc_count_ = 0;
gc_during_regexp_ = 0;
regexp_success_ = false;
gc_success_ = false;
GCThread gc_thread(this);
gc_thread.Start();
v8::Locker::StartPreemption(1);
LongRunningRegExp();
{
v8::Unlocker unlock(CcTest::default_isolate());
gc_thread.Join();
}
v8::Locker::StopPreemption();
CHECK(regexp_success_);
CHECK(gc_success_);
}
private:
// Number of garbage collections required.
static const int kRequiredGCs = 5;
class GCThread : public i::Thread {
public:
explicit GCThread(RegExpInterruptTest* test)
: Thread("GCThread"), test_(test) {}
virtual void Run() {
test_->CollectGarbage();
}
private:
RegExpInterruptTest* test_;
};
void CollectGarbage() {
block_->Wait();
while (gc_during_regexp_ < kRequiredGCs) {
{
v8::Locker lock(CcTest::default_isolate());
// TODO(lrn): Perhaps create some garbage before collecting.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
gc_count_++;
}
i::OS::Sleep(1);
}
gc_success_ = true;
}
void LongRunningRegExp() {
block_->Signal(); // Enable garbage collection thread on next preemption.
int rounds = 0;
while (gc_during_regexp_ < kRequiredGCs) {
int gc_before = gc_count_;
{
// Match 15-30 "a"'s against 14 and a "b".
const char* c_source =
"/a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaa/"
".exec('aaaaaaaaaaaaaaab') === null";
Local<String> source = String::New(c_source);
Local<Script> script = Script::Compile(source);
Local<Value> result = script->Run();
if (!result->BooleanValue()) {
gc_during_regexp_ = kRequiredGCs; // Allow gc thread to exit.
return;
}
}
{
// Match 15-30 "a"'s against 15 and a "b".
const char* c_source =
"/a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaa/"
".exec('aaaaaaaaaaaaaaaab')[0] === 'aaaaaaaaaaaaaaaa'";
Local<String> source = String::New(c_source);
Local<Script> script = Script::Compile(source);
Local<Value> result = script->Run();
if (!result->BooleanValue()) {
gc_during_regexp_ = kRequiredGCs;
return;
}
}
int gc_after = gc_count_;
gc_during_regexp_ += gc_after - gc_before;
rounds++;
i::OS::Sleep(1);
}
regexp_success_ = true;
}
i::Semaphore* block_;
int gc_count_;
int gc_during_regexp_;
bool regexp_success_;
bool gc_success_;
};
// Test that a regular expression execution can be interrupted and
// survive a garbage collection.
TEST(RegExpInterruption) {
v8::Locker lock(CcTest::default_isolate());
v8::V8::Initialize();
v8::HandleScope scope(CcTest::default_isolate());
Local<Context> local_env;
{
LocalContext env;
local_env = env.local();
}
// Local context should still be live.
CHECK(!local_env.IsEmpty());
local_env->Enter();
// Should complete without problems.
RegExpInterruptTest().RunTest();
local_env->Exit();
}
class ApplyInterruptTest {
public:
ApplyInterruptTest() : block_(NULL) {}
~ApplyInterruptTest() { delete block_; }
void RunTest() {
block_ = i::OS::CreateSemaphore(0);
gc_count_ = 0;
gc_during_apply_ = 0;
apply_success_ = false;
gc_success_ = false;
GCThread gc_thread(this);
gc_thread.Start();
v8::Locker::StartPreemption(1);
LongRunningApply();
{
v8::Unlocker unlock(CcTest::default_isolate());
gc_thread.Join();
}
v8::Locker::StopPreemption();
CHECK(apply_success_);
CHECK(gc_success_);
}
private:
// Number of garbage collections required.
static const int kRequiredGCs = 2;
class GCThread : public i::Thread {
public:
explicit GCThread(ApplyInterruptTest* test)
: Thread("GCThread"), test_(test) {}
virtual void Run() {
test_->CollectGarbage();
}
private:
ApplyInterruptTest* test_;
};
void CollectGarbage() {
block_->Wait();
while (gc_during_apply_ < kRequiredGCs) {
{
v8::Locker lock(CcTest::default_isolate());
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
gc_count_++;
}
i::OS::Sleep(1);
}
gc_success_ = true;
}
void LongRunningApply() {
block_->Signal();
int rounds = 0;
while (gc_during_apply_ < kRequiredGCs) {
int gc_before = gc_count_;
{
const char* c_source =
"function do_very_little(bar) {"
" this.foo = bar;"
"}"
"for (var i = 0; i < 100000; i++) {"
" do_very_little.apply(this, ['bar']);"
"}";
Local<String> source = String::New(c_source);
Local<Script> script = Script::Compile(source);
Local<Value> result = script->Run();
// Check that no exception was thrown.
CHECK(!result.IsEmpty());
}
int gc_after = gc_count_;
gc_during_apply_ += gc_after - gc_before;
rounds++;
}
apply_success_ = true;
}
i::Semaphore* block_;
int gc_count_;
int gc_during_apply_;
bool apply_success_;
bool gc_success_;
};
// Test that nothing bad happens if we get a preemption just when we were
// about to do an apply().
TEST(ApplyInterruption) {
v8::Locker lock(CcTest::default_isolate());
v8::V8::Initialize();
v8::HandleScope scope(CcTest::default_isolate());
Local<Context> local_env;
{
LocalContext env;
local_env = env.local();
}
// Local context should still be live.
CHECK(!local_env.IsEmpty());
local_env->Enter();
// Should complete without problems.
ApplyInterruptTest().RunTest();
local_env->Exit();
}
// Verify that we can clone an object
TEST(ObjectClone) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* sample =
"var rv = {};" \
"rv.alpha = 'hello';" \
"rv.beta = 123;" \
"rv;";
// Create an object, verify basics.
Local<Value> val = CompileRun(sample);
CHECK(val->IsObject());
Local<v8::Object> obj = val.As<v8::Object>();
obj->Set(v8_str("gamma"), v8_str("cloneme"));
CHECK_EQ(v8_str("hello"), obj->Get(v8_str("alpha")));
CHECK_EQ(v8::Integer::New(123), obj->Get(v8_str("beta")));
CHECK_EQ(v8_str("cloneme"), obj->Get(v8_str("gamma")));
// Clone it.
Local<v8::Object> clone = obj->Clone();
CHECK_EQ(v8_str("hello"), clone->Get(v8_str("alpha")));
CHECK_EQ(v8::Integer::New(123), clone->Get(v8_str("beta")));
CHECK_EQ(v8_str("cloneme"), clone->Get(v8_str("gamma")));
// Set a property on the clone, verify each object.
clone->Set(v8_str("beta"), v8::Integer::New(456));
CHECK_EQ(v8::Integer::New(123), obj->Get(v8_str("beta")));
CHECK_EQ(v8::Integer::New(456), clone->Get(v8_str("beta")));
}
class AsciiVectorResource : public v8::String::ExternalAsciiStringResource {
public:
explicit AsciiVectorResource(i::Vector<const char> vector)
: data_(vector) {}
virtual ~AsciiVectorResource() {}
virtual size_t length() const { return data_.length(); }
virtual const char* data() const { return data_.start(); }
private:
i::Vector<const char> data_;
};
class UC16VectorResource : public v8::String::ExternalStringResource {
public:
explicit UC16VectorResource(i::Vector<const i::uc16> vector)
: data_(vector) {}
virtual ~UC16VectorResource() {}
virtual size_t length() const { return data_.length(); }
virtual const i::uc16* data() const { return data_.start(); }
private:
i::Vector<const i::uc16> data_;
};
static void MorphAString(i::String* string,
AsciiVectorResource* ascii_resource,
UC16VectorResource* uc16_resource) {
CHECK(i::StringShape(string).IsExternal());
if (string->IsOneByteRepresentation()) {
// Check old map is not internalized or long.
CHECK(string->map() == HEAP->external_ascii_string_map());
// Morph external string to be TwoByte string.
string->set_map(HEAP->external_string_map());
i::ExternalTwoByteString* morphed =
i::ExternalTwoByteString::cast(string);
morphed->set_resource(uc16_resource);
} else {
// Check old map is not internalized or long.
CHECK(string->map() == HEAP->external_string_map());
// Morph external string to be ASCII string.
string->set_map(HEAP->external_ascii_string_map());
i::ExternalAsciiString* morphed =
i::ExternalAsciiString::cast(string);
morphed->set_resource(ascii_resource);
}
}
// Test that we can still flatten a string if the components it is built up
// from have been turned into 16 bit strings in the mean time.
THREADED_TEST(MorphCompositeStringTest) {
char utf_buffer[129];
const char* c_string = "Now is the time for all good men"
" to come to the aid of the party";
uint16_t* two_byte_string = AsciiToTwoByteString(c_string);
{
LocalContext env;
i::Factory* factory = i::Isolate::Current()->factory();
v8::HandleScope scope(env->GetIsolate());
AsciiVectorResource ascii_resource(
i::Vector<const char>(c_string, i::StrLength(c_string)));
UC16VectorResource uc16_resource(
i::Vector<const uint16_t>(two_byte_string,
i::StrLength(c_string)));
Local<String> lhs(v8::Utils::ToLocal(
factory->NewExternalStringFromAscii(&ascii_resource)));
Local<String> rhs(v8::Utils::ToLocal(
factory->NewExternalStringFromAscii(&ascii_resource)));
env->Global()->Set(v8_str("lhs"), lhs);
env->Global()->Set(v8_str("rhs"), rhs);
CompileRun(
"var cons = lhs + rhs;"
"var slice = lhs.substring(1, lhs.length - 1);"
"var slice_on_cons = (lhs + rhs).substring(1, lhs.length *2 - 1);");
CHECK(lhs->IsOneByte());
CHECK(rhs->IsOneByte());
MorphAString(*v8::Utils::OpenHandle(*lhs), &ascii_resource, &uc16_resource);
MorphAString(*v8::Utils::OpenHandle(*rhs), &ascii_resource, &uc16_resource);
// This should UTF-8 without flattening, since everything is ASCII.
Handle<String> cons = v8_compile("cons")->Run().As<String>();
CHECK_EQ(128, cons->Utf8Length());
int nchars = -1;
CHECK_EQ(129, cons->WriteUtf8(utf_buffer, -1, &nchars));
CHECK_EQ(128, nchars);
CHECK_EQ(0, strcmp(
utf_buffer,
"Now is the time for all good men to come to the aid of the party"
"Now is the time for all good men to come to the aid of the party"));
// Now do some stuff to make sure the strings are flattened, etc.
CompileRun(
"/[^a-z]/.test(cons);"
"/[^a-z]/.test(slice);"
"/[^a-z]/.test(slice_on_cons);");
const char* expected_cons =
"Now is the time for all good men to come to the aid of the party"
"Now is the time for all good men to come to the aid of the party";
const char* expected_slice =
"ow is the time for all good men to come to the aid of the part";
const char* expected_slice_on_cons =
"ow is the time for all good men to come to the aid of the party"
"Now is the time for all good men to come to the aid of the part";
CHECK_EQ(String::New(expected_cons),
env->Global()->Get(v8_str("cons")));
CHECK_EQ(String::New(expected_slice),
env->Global()->Get(v8_str("slice")));
CHECK_EQ(String::New(expected_slice_on_cons),
env->Global()->Get(v8_str("slice_on_cons")));
}
i::DeleteArray(two_byte_string);
}
TEST(CompileExternalTwoByteSource) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// This is a very short list of sources, which currently is to check for a
// regression caused by r2703.
const char* ascii_sources[] = {
"0.5",
"-0.5", // This mainly testes PushBack in the Scanner.
"--0.5", // This mainly testes PushBack in the Scanner.
NULL
};
// Compile the sources as external two byte strings.
for (int i = 0; ascii_sources[i] != NULL; i++) {
uint16_t* two_byte_string = AsciiToTwoByteString(ascii_sources[i]);
UC16VectorResource uc16_resource(
i::Vector<const uint16_t>(two_byte_string,
i::StrLength(ascii_sources[i])));
v8::Local<v8::String> source = v8::String::NewExternal(&uc16_resource);
v8::Script::Compile(source);
i::DeleteArray(two_byte_string);
}
}
class RegExpStringModificationTest {
public:
RegExpStringModificationTest()
: block_(i::OS::CreateSemaphore(0)),
morphs_(0),
morphs_during_regexp_(0),
ascii_resource_(i::Vector<const char>("aaaaaaaaaaaaaab", 15)),
uc16_resource_(i::Vector<const uint16_t>(two_byte_content_, 15)) {}
~RegExpStringModificationTest() { delete block_; }
void RunTest() {
i::Factory* factory = i::Isolate::Current()->factory();
regexp_success_ = false;
morph_success_ = false;
// Initialize the contents of two_byte_content_ to be a uc16 representation
// of "aaaaaaaaaaaaaab".
for (int i = 0; i < 14; i++) {
two_byte_content_[i] = 'a';
}
two_byte_content_[14] = 'b';
// Create the input string for the regexp - the one we are going to change
// properties of.
input_ = factory->NewExternalStringFromAscii(&ascii_resource_);
// Inject the input as a global variable.
i::Handle<i::String> input_name =
factory->NewStringFromAscii(i::Vector<const char>("input", 5));
i::Isolate::Current()->native_context()->global_object()->SetProperty(
*input_name,
*input_,
NONE,
i::kNonStrictMode)->ToObjectChecked();
MorphThread morph_thread(this);
morph_thread.Start();
v8::Locker::StartPreemption(1);
LongRunningRegExp();
{
v8::Unlocker unlock(CcTest::default_isolate());
morph_thread.Join();
}
v8::Locker::StopPreemption();
CHECK(regexp_success_);
CHECK(morph_success_);
}
private:
// Number of string modifications required.
static const int kRequiredModifications = 5;
static const int kMaxModifications = 100;
class MorphThread : public i::Thread {
public:
explicit MorphThread(RegExpStringModificationTest* test)
: Thread("MorphThread"), test_(test) {}
virtual void Run() {
test_->MorphString();
}
private:
RegExpStringModificationTest* test_;
};
void MorphString() {
block_->Wait();
while (morphs_during_regexp_ < kRequiredModifications &&
morphs_ < kMaxModifications) {
{
v8::Locker lock(CcTest::default_isolate());
// Swap string between ascii and two-byte representation.
i::String* string = *input_;
MorphAString(string, &ascii_resource_, &uc16_resource_);
morphs_++;
}
i::OS::Sleep(1);
}
morph_success_ = true;
}
void LongRunningRegExp() {
block_->Signal(); // Enable morphing thread on next preemption.
while (morphs_during_regexp_ < kRequiredModifications &&
morphs_ < kMaxModifications) {
int morphs_before = morphs_;
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
// Match 15-30 "a"'s against 14 and a "b".
const char* c_source =
"/a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaa/"
".exec(input) === null";
Local<String> source = String::New(c_source);
Local<Script> script = Script::Compile(source);
Local<Value> result = script->Run();
CHECK(result->IsTrue());
}
int morphs_after = morphs_;
morphs_during_regexp_ += morphs_after - morphs_before;
}
regexp_success_ = true;
}
i::uc16 two_byte_content_[15];
i::Semaphore* block_;
int morphs_;
int morphs_during_regexp_;
bool regexp_success_;
bool morph_success_;
i::Handle<i::String> input_;
AsciiVectorResource ascii_resource_;
UC16VectorResource uc16_resource_;
};
// Test that a regular expression execution can be interrupted and
// the string changed without failing.
TEST(RegExpStringModification) {
v8::Locker lock(CcTest::default_isolate());
v8::V8::Initialize();
v8::HandleScope scope(CcTest::default_isolate());
Local<Context> local_env;
{
LocalContext env;
local_env = env.local();
}
// Local context should still be live.
CHECK(!local_env.IsEmpty());
local_env->Enter();
// Should complete without problems.
RegExpStringModificationTest().RunTest();
local_env->Exit();
}
// Test that we cannot set a property on the global object if there
// is a read-only property in the prototype chain.
TEST(ReadOnlyPropertyInGlobalProto) {
i::FLAG_es5_readonly = true;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New();
LocalContext context(0, templ);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::Object> global_proto =
v8::Handle<v8::Object>::Cast(global->Get(v8_str("__proto__")));
global_proto->Set(v8_str("x"), v8::Integer::New(0), v8::ReadOnly);
global_proto->Set(v8_str("y"), v8::Integer::New(0), v8::ReadOnly);
// Check without 'eval' or 'with'.
v8::Handle<v8::Value> res =
CompileRun("function f() { x = 42; return x; }; f()");
CHECK_EQ(v8::Integer::New(0), res);
// Check with 'eval'.
res = CompileRun("function f() { eval('1'); y = 43; return y; }; f()");
CHECK_EQ(v8::Integer::New(0), res);
// Check with 'with'.
res = CompileRun("function f() { with (this) { y = 44 }; return y; }; f()");
CHECK_EQ(v8::Integer::New(0), res);
}
static int force_set_set_count = 0;
static int force_set_get_count = 0;
bool pass_on_get = false;
static void ForceSetGetter(v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
force_set_get_count++;
if (pass_on_get) {
return;
}
info.GetReturnValue().Set(3);
}
static void ForceSetSetter(v8::Local<v8::String> name,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<void>& info) {
force_set_set_count++;
}
static void ForceSetInterceptSetter(
v8::Local<v8::String> name,
v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
force_set_set_count++;
info.GetReturnValue().SetUndefined();
}
TEST(ForceSet) {
force_set_get_count = 0;
force_set_set_count = 0;
pass_on_get = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New();
v8::Handle<v8::String> access_property = v8::String::New("a");
templ->SetAccessor(access_property, ForceSetGetter, ForceSetSetter);
LocalContext context(NULL, templ);
v8::Handle<v8::Object> global = context->Global();
// Ordinary properties
v8::Handle<v8::String> simple_property = v8::String::New("p");
global->Set(simple_property, v8::Int32::New(4), v8::ReadOnly);
CHECK_EQ(4, global->Get(simple_property)->Int32Value());
// This should fail because the property is read-only
global->Set(simple_property, v8::Int32::New(5));
CHECK_EQ(4, global->Get(simple_property)->Int32Value());
// This should succeed even though the property is read-only
global->ForceSet(simple_property, v8::Int32::New(6));
CHECK_EQ(6, global->Get(simple_property)->Int32Value());
// Accessors
CHECK_EQ(0, force_set_set_count);
CHECK_EQ(0, force_set_get_count);
CHECK_EQ(3, global->Get(access_property)->Int32Value());
// CHECK_EQ the property shouldn't override it, just call the setter
// which in this case does nothing.
global->Set(access_property, v8::Int32::New(7));
CHECK_EQ(3, global->Get(access_property)->Int32Value());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(2, force_set_get_count);
// Forcing the property to be set should override the accessor without
// calling it
global->ForceSet(access_property, v8::Int32::New(8));
CHECK_EQ(8, global->Get(access_property)->Int32Value());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(2, force_set_get_count);
}
TEST(ForceSetWithInterceptor) {
force_set_get_count = 0;
force_set_set_count = 0;
pass_on_get = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New();
templ->SetNamedPropertyHandler(ForceSetGetter, ForceSetInterceptSetter);
LocalContext context(NULL, templ);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::String> some_property = v8::String::New("a");
CHECK_EQ(0, force_set_set_count);
CHECK_EQ(0, force_set_get_count);
CHECK_EQ(3, global->Get(some_property)->Int32Value());
// Setting the property shouldn't override it, just call the setter
// which in this case does nothing.
global->Set(some_property, v8::Int32::New(7));
CHECK_EQ(3, global->Get(some_property)->Int32Value());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(2, force_set_get_count);
// Getting the property when the interceptor returns an empty handle
// should yield undefined, since the property isn't present on the
// object itself yet.
pass_on_get = true;
CHECK(global->Get(some_property)->IsUndefined());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(3, force_set_get_count);
// Forcing the property to be set should cause the value to be
// set locally without calling the interceptor.
global->ForceSet(some_property, v8::Int32::New(8));
CHECK_EQ(8, global->Get(some_property)->Int32Value());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(4, force_set_get_count);
// Reenabling the interceptor should cause it to take precedence over
// the property
pass_on_get = false;
CHECK_EQ(3, global->Get(some_property)->Int32Value());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(5, force_set_get_count);
// The interceptor should also work for other properties
CHECK_EQ(3, global->Get(v8::String::New("b"))->Int32Value());
CHECK_EQ(1, force_set_set_count);
CHECK_EQ(6, force_set_get_count);
}
THREADED_TEST(ForceDelete) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New();
LocalContext context(NULL, templ);
v8::Handle<v8::Object> global = context->Global();
// Ordinary properties
v8::Handle<v8::String> simple_property = v8::String::New("p");
global->Set(simple_property, v8::Int32::New(4), v8::DontDelete);
CHECK_EQ(4, global->Get(simple_property)->Int32Value());
// This should fail because the property is dont-delete.
CHECK(!global->Delete(simple_property));
CHECK_EQ(4, global->Get(simple_property)->Int32Value());
// This should succeed even though the property is dont-delete.
CHECK(global->ForceDelete(simple_property));
CHECK(global->Get(simple_property)->IsUndefined());
}
static int force_delete_interceptor_count = 0;
static bool pass_on_delete = false;
static void ForceDeleteDeleter(
v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Boolean>& info) {
force_delete_interceptor_count++;
if (pass_on_delete) return;
info.GetReturnValue().Set(true);
}
THREADED_TEST(ForceDeleteWithInterceptor) {
force_delete_interceptor_count = 0;
pass_on_delete = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New();
templ->SetNamedPropertyHandler(0, 0, 0, ForceDeleteDeleter);
LocalContext context(NULL, templ);
v8::Handle<v8::Object> global = context->Global();
v8::Handle<v8::String> some_property = v8::String::New("a");
global->Set(some_property, v8::Integer::New(42), v8::DontDelete);
// Deleting a property should get intercepted and nothing should
// happen.
CHECK_EQ(0, force_delete_interceptor_count);
CHECK(global->Delete(some_property));
CHECK_EQ(1, force_delete_interceptor_count);
CHECK_EQ(42, global->Get(some_property)->Int32Value());
// Deleting the property when the interceptor returns an empty
// handle should not delete the property since it is DontDelete.
pass_on_delete = true;
CHECK(!global->Delete(some_property));
CHECK_EQ(2, force_delete_interceptor_count);
CHECK_EQ(42, global->Get(some_property)->Int32Value());
// Forcing the property to be deleted should delete the value
// without calling the interceptor.
CHECK(global->ForceDelete(some_property));
CHECK(global->Get(some_property)->IsUndefined());
CHECK_EQ(2, force_delete_interceptor_count);
}
// Make sure that forcing a delete invalidates any IC stubs, so we
// don't read the hole value.
THREADED_TEST(ForceDeleteIC) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// Create a DontDelete variable on the global object.
CompileRun("this.__proto__ = { foo: 'horse' };"
"var foo = 'fish';"
"function f() { return foo.length; }");
// Initialize the IC for foo in f.
CompileRun("for (var i = 0; i < 4; i++) f();");
// Make sure the value of foo is correct before the deletion.
CHECK_EQ(4, CompileRun("f()")->Int32Value());
// Force the deletion of foo.
CHECK(context->Global()->ForceDelete(v8_str("foo")));
// Make sure the value for foo is read from the prototype, and that
// we don't get in trouble with reading the deleted cell value
// sentinel.
CHECK_EQ(5, CompileRun("f()")->Int32Value());
}
TEST(InlinedFunctionAcrossContexts) {
i::FLAG_allow_natives_syntax = true;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope outer_scope(isolate);
v8::Local<v8::Context> ctx1 = v8::Context::New(isolate);
v8::Local<v8::Context> ctx2 = v8::Context::New(isolate);
ctx1->Enter();
{
v8::HandleScope inner_scope(v8::Isolate::GetCurrent());
CompileRun("var G = 42; function foo() { return G; }");
v8::Local<v8::Value> foo = ctx1->Global()->Get(v8_str("foo"));
ctx2->Enter();
ctx2->Global()->Set(v8_str("o"), foo);
v8::Local<v8::Value> res = CompileRun(
"function f() { return o(); }"
"for (var i = 0; i < 10; ++i) f();"
"%OptimizeFunctionOnNextCall(f);"
"f();");
CHECK_EQ(42, res->Int32Value());
ctx2->Exit();
v8::Handle<v8::String> G_property = v8::String::New("G");
CHECK(ctx1->Global()->ForceDelete(G_property));
ctx2->Enter();
ExpectString(
"(function() {"
" try {"
" return f();"
" } catch(e) {"
" return e.toString();"
" }"
" })()",
"ReferenceError: G is not defined");
ctx2->Exit();
ctx1->Exit();
}
}
static v8::Local<Context> calling_context0;
static v8::Local<Context> calling_context1;
static v8::Local<Context> calling_context2;
// Check that the call to the callback is initiated in
// calling_context2, the directly calling context is calling_context1
// and the callback itself is in calling_context0.
static void GetCallingContextCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
ApiTestFuzzer::Fuzz();
CHECK(Context::GetCurrent() == calling_context0);
CHECK(args.GetIsolate()->GetCurrentContext() == calling_context0);
CHECK(Context::GetCalling() == calling_context1);
CHECK(Context::GetEntered() == calling_context2);
args.GetReturnValue().Set(42);
}
THREADED_TEST(GetCurrentContextWhenNotInContext) {
i::Isolate* isolate = i::Isolate::Current();
CHECK(isolate != NULL);
CHECK(isolate->context() == NULL);
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8::HandleScope scope(v8_isolate);
// The following should not crash, but return an empty handle.
v8::Local<v8::Context> current = v8_isolate->GetCurrentContext();
CHECK(current.IsEmpty());
}
THREADED_TEST(GetCallingContext) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
Local<Context> calling_context0(Context::New(isolate));
Local<Context> calling_context1(Context::New(isolate));
Local<Context> calling_context2(Context::New(isolate));
::calling_context0 = calling_context0;
::calling_context1 = calling_context1;
::calling_context2 = calling_context2;
// Allow cross-domain access.
Local<String> token = v8_str("<security token>");
calling_context0->SetSecurityToken(token);
calling_context1->SetSecurityToken(token);
calling_context2->SetSecurityToken(token);
// Create an object with a C++ callback in context0.
calling_context0->Enter();
Local<v8::FunctionTemplate> callback_templ =
v8::FunctionTemplate::New(GetCallingContextCallback);
calling_context0->Global()->Set(v8_str("callback"),
callback_templ->GetFunction());
calling_context0->Exit();
// Expose context0 in context1 and set up a function that calls the
// callback function.
calling_context1->Enter();
calling_context1->Global()->Set(v8_str("context0"),
calling_context0->Global());
CompileRun("function f() { context0.callback() }");
calling_context1->Exit();
// Expose context1 in context2 and call the callback function in
// context0 indirectly through f in context1.
calling_context2->Enter();
calling_context2->Global()->Set(v8_str("context1"),
calling_context1->Global());
CompileRun("context1.f()");
calling_context2->Exit();
::calling_context0.Clear();
::calling_context1.Clear();
::calling_context2.Clear();
}
// Check that a variable declaration with no explicit initialization
// value does shadow an existing property in the prototype chain.
THREADED_TEST(InitGlobalVarInProtoChain) {
i::FLAG_es52_globals = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// Introduce a variable in the prototype chain.
CompileRun("__proto__.x = 42");
v8::Handle<v8::Value> result = CompileRun("var x = 43; x");
CHECK(!result->IsUndefined());
CHECK_EQ(43, result->Int32Value());
}
// Regression test for issue 398.
// If a function is added to an object, creating a constant function
// field, and the result is cloned, replacing the constant function on the
// original should not affect the clone.
// See http://code.google.com/p/v8/issues/detail?id=398
THREADED_TEST(ReplaceConstantFunction) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Object> obj = v8::Object::New();
v8::Handle<v8::FunctionTemplate> func_templ = v8::FunctionTemplate::New();
v8::Handle<v8::String> foo_string = v8::String::New("foo");
obj->Set(foo_string, func_templ->GetFunction());
v8::Handle<v8::Object> obj_clone = obj->Clone();
obj_clone->Set(foo_string, v8::String::New("Hello"));
CHECK(!obj->Get(foo_string)->IsUndefined());
}
// Regression test for http://crbug.com/16276.
THREADED_TEST(Regress16276) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// Force the IC in f to be a dictionary load IC.
CompileRun("function f(obj) { return obj.x; }\n"
"var obj = { x: { foo: 42 }, y: 87 };\n"
"var x = obj.x;\n"
"delete obj.y;\n"
"for (var i = 0; i < 5; i++) f(obj);");
// Detach the global object to make 'this' refer directly to the
// global object (not the proxy), and make sure that the dictionary
// load IC doesn't mess up loading directly from the global object.
context->DetachGlobal();
CHECK_EQ(42, CompileRun("f(this).foo")->Int32Value());
}
THREADED_TEST(PixelArray) {
LocalContext context;
i::Factory* factory = i::Isolate::Current()->factory();
v8::HandleScope scope(context->GetIsolate());
const int kElementCount = 260;
uint8_t* pixel_data = reinterpret_cast<uint8_t*>(malloc(kElementCount));
i::Handle<i::ExternalPixelArray> pixels =
i::Handle<i::ExternalPixelArray>::cast(
factory->NewExternalArray(kElementCount,
v8::kExternalPixelArray,
pixel_data));
// Force GC to trigger verification.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
for (int i = 0; i < kElementCount; i++) {
pixels->set(i, i % 256);
}
// Force GC to trigger verification.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
for (int i = 0; i < kElementCount; i++) {
CHECK_EQ(i % 256, pixels->get_scalar(i));
CHECK_EQ(i % 256, pixel_data[i]);
}
v8::Handle<v8::Object> obj = v8::Object::New();
i::Handle<i::JSObject> jsobj = v8::Utils::OpenHandle(*obj);
// Set the elements to be the pixels.
// jsobj->set_elements(*pixels);
obj->SetIndexedPropertiesToPixelData(pixel_data, kElementCount);
CHECK_EQ(1, i::Smi::cast(jsobj->GetElement(1)->ToObjectChecked())->value());
obj->Set(v8_str("field"), v8::Int32::New(1503));
context->Global()->Set(v8_str("pixels"), obj);
v8::Handle<v8::Value> result = CompileRun("pixels.field");
CHECK_EQ(1503, result->Int32Value());
result = CompileRun("pixels[1]");
CHECK_EQ(1, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i] = pixels[i] = -i;"
"}"
"sum;");
CHECK_EQ(-28, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i] = pixels[i] = 0;"
"}"
"sum;");
CHECK_EQ(0, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i] = pixels[i] = 255;"
"}"
"sum;");
CHECK_EQ(8 * 255, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i] = pixels[i] = 256 + i;"
"}"
"sum;");
CHECK_EQ(2076, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i] = pixels[i] = i;"
"}"
"sum;");
CHECK_EQ(28, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i];"
"}"
"sum;");
CHECK_EQ(28, result->Int32Value());
i::Handle<i::Smi> value(i::Smi::FromInt(2),
reinterpret_cast<i::Isolate*>(context->GetIsolate()));
i::Handle<i::Object> no_failure;
no_failure =
i::JSObject::SetElement(jsobj, 1, value, NONE, i::kNonStrictMode);
ASSERT(!no_failure.is_null());
i::USE(no_failure);
CHECK_EQ(2, i::Smi::cast(jsobj->GetElement(1)->ToObjectChecked())->value());
*value.location() = i::Smi::FromInt(256);
no_failure =
i::JSObject::SetElement(jsobj, 1, value, NONE, i::kNonStrictMode);
ASSERT(!no_failure.is_null());
i::USE(no_failure);
CHECK_EQ(255,
i::Smi::cast(jsobj->GetElement(1)->ToObjectChecked())->value());
*value.location() = i::Smi::FromInt(-1);
no_failure =
i::JSObject::SetElement(jsobj, 1, value, NONE, i::kNonStrictMode);
ASSERT(!no_failure.is_null());
i::USE(no_failure);
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(1)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[i] = (i * 65) - 109;"
"}"
"pixels[1] + pixels[6];");
CHECK_EQ(255, result->Int32Value());
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(0)->ToObjectChecked())->value());
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(1)->ToObjectChecked())->value());
CHECK_EQ(21,
i::Smi::cast(jsobj->GetElement(2)->ToObjectChecked())->value());
CHECK_EQ(86,
i::Smi::cast(jsobj->GetElement(3)->ToObjectChecked())->value());
CHECK_EQ(151,
i::Smi::cast(jsobj->GetElement(4)->ToObjectChecked())->value());
CHECK_EQ(216,
i::Smi::cast(jsobj->GetElement(5)->ToObjectChecked())->value());
CHECK_EQ(255,
i::Smi::cast(jsobj->GetElement(6)->ToObjectChecked())->value());
CHECK_EQ(255,
i::Smi::cast(jsobj->GetElement(7)->ToObjectChecked())->value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i];"
"}"
"sum;");
CHECK_EQ(984, result->Int32Value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[i] = (i * 1.1);"
"}"
"pixels[1] + pixels[6];");
CHECK_EQ(8, result->Int32Value());
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(0)->ToObjectChecked())->value());
CHECK_EQ(1, i::Smi::cast(jsobj->GetElement(1)->ToObjectChecked())->value());
CHECK_EQ(2, i::Smi::cast(jsobj->GetElement(2)->ToObjectChecked())->value());
CHECK_EQ(3, i::Smi::cast(jsobj->GetElement(3)->ToObjectChecked())->value());
CHECK_EQ(4, i::Smi::cast(jsobj->GetElement(4)->ToObjectChecked())->value());
CHECK_EQ(6, i::Smi::cast(jsobj->GetElement(5)->ToObjectChecked())->value());
CHECK_EQ(7, i::Smi::cast(jsobj->GetElement(6)->ToObjectChecked())->value());
CHECK_EQ(8, i::Smi::cast(jsobj->GetElement(7)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[7] = undefined;"
"}"
"pixels[7];");
CHECK_EQ(0, result->Int32Value());
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(7)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[6] = '2.3';"
"}"
"pixels[6];");
CHECK_EQ(2, result->Int32Value());
CHECK_EQ(2, i::Smi::cast(jsobj->GetElement(6)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[5] = NaN;"
"}"
"pixels[5];");
CHECK_EQ(0, result->Int32Value());
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(5)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[8] = Infinity;"
"}"
"pixels[8];");
CHECK_EQ(255, result->Int32Value());
CHECK_EQ(255,
i::Smi::cast(jsobj->GetElement(8)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" pixels[9] = -Infinity;"
"}"
"pixels[9];");
CHECK_EQ(0, result->Int32Value());
CHECK_EQ(0, i::Smi::cast(jsobj->GetElement(9)->ToObjectChecked())->value());
result = CompileRun("pixels[3] = 33;"
"delete pixels[3];"
"pixels[3];");
CHECK_EQ(33, result->Int32Value());
result = CompileRun("pixels[0] = 10; pixels[1] = 11;"
"pixels[2] = 12; pixels[3] = 13;"
"pixels.__defineGetter__('2',"
"function() { return 120; });"
"pixels[2];");
CHECK_EQ(12, result->Int32Value());
result = CompileRun("var js_array = new Array(40);"
"js_array[0] = 77;"
"js_array;");
CHECK_EQ(77, v8::Object::Cast(*result)->Get(v8_str("0"))->Int32Value());
result = CompileRun("pixels[1] = 23;"
"pixels.__proto__ = [];"
"js_array.__proto__ = pixels;"
"js_array.concat(pixels);");
CHECK_EQ(77, v8::Object::Cast(*result)->Get(v8_str("0"))->Int32Value());
CHECK_EQ(23, v8::Object::Cast(*result)->Get(v8_str("1"))->Int32Value());
result = CompileRun("pixels[1] = 23;");
CHECK_EQ(23, result->Int32Value());
// Test for index greater than 255. Regression test for:
// http://code.google.com/p/chromium/issues/detail?id=26337.
result = CompileRun("pixels[256] = 255;");
CHECK_EQ(255, result->Int32Value());
result = CompileRun("var i = 0;"
"for (var j = 0; j < 8; j++) { i = pixels[256]; }"
"i");
CHECK_EQ(255, result->Int32Value());
// Make sure that pixel array ICs recognize when a non-pixel array
// is passed to it.
result = CompileRun("function pa_load(p) {"
" var sum = 0;"
" for (var j = 0; j < 256; j++) { sum += p[j]; }"
" return sum;"
"}"
"for (var i = 0; i < 256; ++i) { pixels[i] = i; }"
"for (var i = 0; i < 10; ++i) { pa_load(pixels); }"
"just_ints = new Object();"
"for (var i = 0; i < 256; ++i) { just_ints[i] = i; }"
"for (var i = 0; i < 10; ++i) {"
" result = pa_load(just_ints);"
"}"
"result");
CHECK_EQ(32640, result->Int32Value());
// Make sure that pixel array ICs recognize out-of-bound accesses.
result = CompileRun("function pa_load(p, start) {"
" var sum = 0;"
" for (var j = start; j < 256; j++) { sum += p[j]; }"
" return sum;"
"}"
"for (var i = 0; i < 256; ++i) { pixels[i] = i; }"
"for (var i = 0; i < 10; ++i) { pa_load(pixels,0); }"
"for (var i = 0; i < 10; ++i) {"
" result = pa_load(pixels,-10);"
"}"
"result");
CHECK_EQ(0, result->Int32Value());
// Make sure that generic ICs properly handles a pixel array.
result = CompileRun("function pa_load(p) {"
" var sum = 0;"
" for (var j = 0; j < 256; j++) { sum += p[j]; }"
" return sum;"
"}"
"for (var i = 0; i < 256; ++i) { pixels[i] = i; }"
"just_ints = new Object();"
"for (var i = 0; i < 256; ++i) { just_ints[i] = i; }"
"for (var i = 0; i < 10; ++i) { pa_load(just_ints); }"
"for (var i = 0; i < 10; ++i) {"
" result = pa_load(pixels);"
"}"
"result");
CHECK_EQ(32640, result->Int32Value());
// Make sure that generic load ICs recognize out-of-bound accesses in
// pixel arrays.
result = CompileRun("function pa_load(p, start) {"
" var sum = 0;"
" for (var j = start; j < 256; j++) { sum += p[j]; }"
" return sum;"
"}"
"for (var i = 0; i < 256; ++i) { pixels[i] = i; }"
"just_ints = new Object();"
"for (var i = 0; i < 256; ++i) { just_ints[i] = i; }"
"for (var i = 0; i < 10; ++i) { pa_load(just_ints,0); }"
"for (var i = 0; i < 10; ++i) { pa_load(pixels,0); }"
"for (var i = 0; i < 10; ++i) {"
" result = pa_load(pixels,-10);"
"}"
"result");
CHECK_EQ(0, result->Int32Value());
// Make sure that generic ICs properly handles other types than pixel
// arrays (that the inlined fast pixel array test leaves the right information
// in the right registers).
result = CompileRun("function pa_load(p) {"
" var sum = 0;"
" for (var j = 0; j < 256; j++) { sum += p[j]; }"
" return sum;"
"}"
"for (var i = 0; i < 256; ++i) { pixels[i] = i; }"
"just_ints = new Object();"
"for (var i = 0; i < 256; ++i) { just_ints[i] = i; }"
"for (var i = 0; i < 10; ++i) { pa_load(just_ints); }"
"for (var i = 0; i < 10; ++i) { pa_load(pixels); }"
"sparse_array = new Object();"
"for (var i = 0; i < 256; ++i) { sparse_array[i] = i; }"
"sparse_array[1000000] = 3;"
"for (var i = 0; i < 10; ++i) {"
" result = pa_load(sparse_array);"
"}"
"result");
CHECK_EQ(32640, result->Int32Value());
// Make sure that pixel array store ICs clamp values correctly.
result = CompileRun("function pa_store(p) {"
" for (var j = 0; j < 256; j++) { p[j] = j * 2; }"
"}"
"pa_store(pixels);"
"var sum = 0;"
"for (var j = 0; j < 256; j++) { sum += pixels[j]; }"
"sum");
CHECK_EQ(48896, result->Int32Value());
// Make sure that pixel array stores correctly handle accesses outside
// of the pixel array..
result = CompileRun("function pa_store(p,start) {"
" for (var j = 0; j < 256; j++) {"
" p[j+start] = j * 2;"
" }"
"}"
"pa_store(pixels,0);"
"pa_store(pixels,-128);"
"var sum = 0;"
"for (var j = 0; j < 256; j++) { sum += pixels[j]; }"
"sum");
CHECK_EQ(65280, result->Int32Value());
// Make sure that the generic store stub correctly handle accesses outside
// of the pixel array..
result = CompileRun("function pa_store(p,start) {"
" for (var j = 0; j < 256; j++) {"
" p[j+start] = j * 2;"
" }"
"}"
"pa_store(pixels,0);"
"just_ints = new Object();"
"for (var i = 0; i < 256; ++i) { just_ints[i] = i; }"
"pa_store(just_ints, 0);"
"pa_store(pixels,-128);"
"var sum = 0;"
"for (var j = 0; j < 256; j++) { sum += pixels[j]; }"
"sum");
CHECK_EQ(65280, result->Int32Value());
// Make sure that the generic keyed store stub clamps pixel array values
// correctly.
result = CompileRun("function pa_store(p) {"
" for (var j = 0; j < 256; j++) { p[j] = j * 2; }"
"}"
"pa_store(pixels);"
"just_ints = new Object();"
"pa_store(just_ints);"
"pa_store(pixels);"
"var sum = 0;"
"for (var j = 0; j < 256; j++) { sum += pixels[j]; }"
"sum");
CHECK_EQ(48896, result->Int32Value());
// Make sure that pixel array loads are optimized by crankshaft.
result = CompileRun("function pa_load(p) {"
" var sum = 0;"
" for (var i=0; i<256; ++i) {"
" sum += p[i];"
" }"
" return sum; "
"}"
"for (var i = 0; i < 256; ++i) { pixels[i] = i; }"
"for (var i = 0; i < 5000; ++i) {"
" result = pa_load(pixels);"
"}"
"result");
CHECK_EQ(32640, result->Int32Value());
// Make sure that pixel array stores are optimized by crankshaft.
result = CompileRun("function pa_init(p) {"
"for (var i = 0; i < 256; ++i) { p[i] = i; }"
"}"
"function pa_load(p) {"
" var sum = 0;"
" for (var i=0; i<256; ++i) {"
" sum += p[i];"
" }"
" return sum; "
"}"
"for (var i = 0; i < 5000; ++i) {"
" pa_init(pixels);"
"}"
"result = pa_load(pixels);"
"result");
CHECK_EQ(32640, result->Int32Value());
free(pixel_data);
}
THREADED_TEST(PixelArrayInfo) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
for (int size = 0; size < 100; size += 10) {
uint8_t* pixel_data = reinterpret_cast<uint8_t*>(malloc(size));
v8::Handle<v8::Object> obj = v8::Object::New();
obj->SetIndexedPropertiesToPixelData(pixel_data, size);
CHECK(obj->HasIndexedPropertiesInPixelData());
CHECK_EQ(pixel_data, obj->GetIndexedPropertiesPixelData());
CHECK_EQ(size, obj->GetIndexedPropertiesPixelDataLength());
free(pixel_data);
}
}
static void NotHandledIndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
}
static void NotHandledIndexedPropertySetter(
uint32_t index,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
ApiTestFuzzer::Fuzz();
}
THREADED_TEST(PixelArrayWithInterceptor) {
LocalContext context;
i::Factory* factory = i::Isolate::Current()->factory();
v8::HandleScope scope(context->GetIsolate());
const int kElementCount = 260;
uint8_t* pixel_data = reinterpret_cast<uint8_t*>(malloc(kElementCount));
i::Handle<i::ExternalPixelArray> pixels =
i::Handle<i::ExternalPixelArray>::cast(
factory->NewExternalArray(kElementCount,
v8::kExternalPixelArray,
pixel_data));
for (int i = 0; i < kElementCount; i++) {
pixels->set(i, i % 256);
}
v8::Handle<v8::ObjectTemplate> templ = v8::ObjectTemplate::New();
templ->SetIndexedPropertyHandler(NotHandledIndexedPropertyGetter,
NotHandledIndexedPropertySetter);
v8::Handle<v8::Object> obj = templ->NewInstance();
obj->SetIndexedPropertiesToPixelData(pixel_data, kElementCount);
context->Global()->Set(v8_str("pixels"), obj);
v8::Handle<v8::Value> result = CompileRun("pixels[1]");
CHECK_EQ(1, result->Int32Value());
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += pixels[i] = pixels[i] = -i;"
"}"
"sum;");
CHECK_EQ(-28, result->Int32Value());
result = CompileRun("pixels.hasOwnProperty('1')");
CHECK(result->BooleanValue());
free(pixel_data);
}
static int ExternalArrayElementSize(v8::ExternalArrayType array_type) {
switch (array_type) {
case v8::kExternalByteArray:
case v8::kExternalUnsignedByteArray:
case v8::kExternalPixelArray:
return 1;
break;
case v8::kExternalShortArray:
case v8::kExternalUnsignedShortArray:
return 2;
break;
case v8::kExternalIntArray:
case v8::kExternalUnsignedIntArray:
case v8::kExternalFloatArray:
return 4;
break;
case v8::kExternalDoubleArray:
return 8;
break;
default:
UNREACHABLE();
return -1;
}
UNREACHABLE();
return -1;
}
template <class ExternalArrayClass, class ElementType>
static void ObjectWithExternalArrayTestHelper(
Handle<Context> context,
v8::Handle<Object> obj,
int element_count,
v8::ExternalArrayType array_type,
int64_t low, int64_t high) {
i::Handle<i::JSObject> jsobj = v8::Utils::OpenHandle(*obj);
obj->Set(v8_str("field"), v8::Int32::New(1503));
context->Global()->Set(v8_str("ext_array"), obj);
v8::Handle<v8::Value> result = CompileRun("ext_array.field");
CHECK_EQ(1503, result->Int32Value());
result = CompileRun("ext_array[1]");
CHECK_EQ(1, result->Int32Value());
// Check pass through of assigned smis
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += ext_array[i] = ext_array[i] = -i;"
"}"
"sum;");
CHECK_EQ(-28, result->Int32Value());
// Check assigned smis
result = CompileRun("for (var i = 0; i < 8; i++) {"
" ext_array[i] = i;"
"}"
"var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += ext_array[i];"
"}"
"sum;");
CHECK_EQ(28, result->Int32Value());
// Check assigned smis in reverse order
result = CompileRun("for (var i = 8; --i >= 0; ) {"
" ext_array[i] = i;"
"}"
"var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" sum += ext_array[i];"
"}"
"sum;");
CHECK_EQ(28, result->Int32Value());
// Check pass through of assigned HeapNumbers
result = CompileRun("var sum = 0;"
"for (var i = 0; i < 16; i+=2) {"
" sum += ext_array[i] = ext_array[i] = (-i * 0.5);"
"}"
"sum;");
CHECK_EQ(-28, result->Int32Value());
// Check assigned HeapNumbers
result = CompileRun("for (var i = 0; i < 16; i+=2) {"
" ext_array[i] = (i * 0.5);"
"}"
"var sum = 0;"
"for (var i = 0; i < 16; i+=2) {"
" sum += ext_array[i];"
"}"
"sum;");
CHECK_EQ(28, result->Int32Value());
// Check assigned HeapNumbers in reverse order
result = CompileRun("for (var i = 14; i >= 0; i-=2) {"
" ext_array[i] = (i * 0.5);"
"}"
"var sum = 0;"
"for (var i = 0; i < 16; i+=2) {"
" sum += ext_array[i];"
"}"
"sum;");
CHECK_EQ(28, result->Int32Value());
i::ScopedVector<char> test_buf(1024);
// Check legal boundary conditions.
// The repeated loads and stores ensure the ICs are exercised.
const char* boundary_program =
"var res = 0;"
"for (var i = 0; i < 16; i++) {"
" ext_array[i] = %lld;"
" if (i > 8) {"
" res = ext_array[i];"
" }"
"}"
"res;";
i::OS::SNPrintF(test_buf,
boundary_program,
low);
result = CompileRun(test_buf.start());
CHECK_EQ(low, result->IntegerValue());
i::OS::SNPrintF(test_buf,
boundary_program,
high);
result = CompileRun(test_buf.start());
CHECK_EQ(high, result->IntegerValue());
// Check misprediction of type in IC.
result = CompileRun("var tmp_array = ext_array;"
"var sum = 0;"
"for (var i = 0; i < 8; i++) {"
" tmp_array[i] = i;"
" sum += tmp_array[i];"
" if (i == 4) {"
" tmp_array = {};"
" }"
"}"
"sum;");
// Force GC to trigger verification.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(28, result->Int32Value());
// Make sure out-of-range loads do not throw.
i::OS::SNPrintF(test_buf,
"var caught_exception = false;"
"try {"
" ext_array[%d];"
"} catch (e) {"
" caught_exception = true;"
"}"
"caught_exception;",
element_count);
result = CompileRun(test_buf.start());
CHECK_EQ(false, result->BooleanValue());
// Make sure out-of-range stores do not throw.
i::OS::SNPrintF(test_buf,
"var caught_exception = false;"
"try {"
" ext_array[%d] = 1;"
"} catch (e) {"
" caught_exception = true;"
"}"
"caught_exception;",
element_count);
result = CompileRun(test_buf.start());
CHECK_EQ(false, result->BooleanValue());
// Check other boundary conditions, values and operations.
result = CompileRun("for (var i = 0; i < 8; i++) {"
" ext_array[7] = undefined;"
"}"
"ext_array[7];");
CHECK_EQ(0, result->Int32Value());
if (array_type == v8::kExternalDoubleArray ||
array_type == v8::kExternalFloatArray) {
CHECK_EQ(
static_cast<int>(i::OS::nan_value()),
static_cast<int>(jsobj->GetElement(7)->ToObjectChecked()->Number()));
} else {
CHECK_EQ(0, static_cast<int>(
jsobj->GetElement(7)->ToObjectChecked()->Number()));
}
result = CompileRun("for (var i = 0; i < 8; i++) {"
" ext_array[6] = '2.3';"
"}"
"ext_array[6];");
CHECK_EQ(2, result->Int32Value());
CHECK_EQ(
2, static_cast<int>(jsobj->GetElement(6)->ToObjectChecked()->Number()));
if (array_type != v8::kExternalFloatArray &&
array_type != v8::kExternalDoubleArray) {
// Though the specification doesn't state it, be explicit about
// converting NaNs and +/-Infinity to zero.
result = CompileRun("for (var i = 0; i < 8; i++) {"
" ext_array[i] = 5;"
"}"
"for (var i = 0; i < 8; i++) {"
" ext_array[i] = NaN;"
"}"
"ext_array[5];");
CHECK_EQ(0, result->Int32Value());
CHECK_EQ(0,
i::Smi::cast(jsobj->GetElement(5)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" ext_array[i] = 5;"
"}"
"for (var i = 0; i < 8; i++) {"
" ext_array[i] = Infinity;"
"}"
"ext_array[5];");
int expected_value =
(array_type == v8::kExternalPixelArray) ? 255 : 0;
CHECK_EQ(expected_value, result->Int32Value());
CHECK_EQ(expected_value,
i::Smi::cast(jsobj->GetElement(5)->ToObjectChecked())->value());
result = CompileRun("for (var i = 0; i < 8; i++) {"
" ext_array[i] = 5;"
"}"
"for (var i = 0; i < 8; i++) {"
" ext_array[i] = -Infinity;"
"}"
"ext_array[5];");
CHECK_EQ(0, result->Int32Value());
CHECK_EQ(0,
i::Smi::cast(jsobj->GetElement(5)->ToObjectChecked())->value());
// Check truncation behavior of integral arrays.
const char* unsigned_data =
"var source_data = [0.6, 10.6];"
"var expected_results = [0, 10];";
const char* signed_data =
"var source_data = [0.6, 10.6, -0.6, -10.6];"
"var expected_results = [0, 10, 0, -10];";
const char* pixel_data =
"var source_data = [0.6, 10.6];"
"var expected_results = [1, 11];";
bool is_unsigned =
(array_type == v8::kExternalUnsignedByteArray ||
array_type == v8::kExternalUnsignedShortArray ||
array_type == v8::kExternalUnsignedIntArray);
bool is_pixel_data = array_type == v8::kExternalPixelArray;
i::OS::SNPrintF(test_buf,
"%s"
"var all_passed = true;"
"for (var i = 0; i < source_data.length; i++) {"
" for (var j = 0; j < 8; j++) {"
" ext_array[j] = source_data[i];"
" }"
" all_passed = all_passed &&"
" (ext_array[5] == expected_results[i]);"
"}"
"all_passed;",
(is_unsigned ?
unsigned_data :
(is_pixel_data ? pixel_data : signed_data)));
result = CompileRun(test_buf.start());
CHECK_EQ(true, result->BooleanValue());
}
i::Handle<ExternalArrayClass> array(
ExternalArrayClass::cast(jsobj->elements()));
for (int i = 0; i < element_count; i++) {
array->set(i, static_cast<ElementType>(i));
}
// Test complex assignments
result = CompileRun("function ee_op_test_complex_func(sum) {"
" for (var i = 0; i < 40; ++i) {"
" sum += (ext_array[i] += 1);"
" sum += (ext_array[i] -= 1);"
" } "
" return sum;"
"}"
"sum=0;"
"for (var i=0;i<10000;++i) {"
" sum=ee_op_test_complex_func(sum);"
"}"
"sum;");
CHECK_EQ(16000000, result->Int32Value());
// Test count operations
result = CompileRun("function ee_op_test_count_func(sum) {"
" for (var i = 0; i < 40; ++i) {"
" sum += (++ext_array[i]);"
" sum += (--ext_array[i]);"
" } "
" return sum;"
"}"
"sum=0;"
"for (var i=0;i<10000;++i) {"
" sum=ee_op_test_count_func(sum);"
"}"
"sum;");
CHECK_EQ(16000000, result->Int32Value());
result = CompileRun("ext_array[3] = 33;"
"delete ext_array[3];"
"ext_array[3];");
CHECK_EQ(33, result->Int32Value());
result = CompileRun("ext_array[0] = 10; ext_array[1] = 11;"
"ext_array[2] = 12; ext_array[3] = 13;"
"ext_array.__defineGetter__('2',"
"function() { return 120; });"
"ext_array[2];");
CHECK_EQ(12, result->Int32Value());
result = CompileRun("var js_array = new Array(40);"
"js_array[0] = 77;"
"js_array;");
CHECK_EQ(77, v8::Object::Cast(*result)->Get(v8_str("0"))->Int32Value());
result = CompileRun("ext_array[1] = 23;"
"ext_array.__proto__ = [];"
"js_array.__proto__ = ext_array;"
"js_array.concat(ext_array);");
CHECK_EQ(77, v8::Object::Cast(*result)->Get(v8_str("0"))->Int32Value());
CHECK_EQ(23, v8::Object::Cast(*result)->Get(v8_str("1"))->Int32Value());
result = CompileRun("ext_array[1] = 23;");
CHECK_EQ(23, result->Int32Value());
}
template <class ExternalArrayClass, class ElementType>
static void ExternalArrayTestHelper(v8::ExternalArrayType array_type,
int64_t low,
int64_t high) {
LocalContext context;
i::Factory* factory = i::Isolate::Current()->factory();
v8::HandleScope scope(context->GetIsolate());
const int kElementCount = 40;
int element_size = ExternalArrayElementSize(array_type);
ElementType* array_data =
static_cast<ElementType*>(malloc(kElementCount * element_size));
i::Handle<ExternalArrayClass> array =
i::Handle<ExternalArrayClass>::cast(
factory->NewExternalArray(kElementCount, array_type, array_data));
// Force GC to trigger verification.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
for (int i = 0; i < kElementCount; i++) {
array->set(i, static_cast<ElementType>(i));
}
// Force GC to trigger verification.
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
for (int i = 0; i < kElementCount; i++) {
CHECK_EQ(static_cast<int64_t>(i),
static_cast<int64_t>(array->get_scalar(i)));
CHECK_EQ(static_cast<int64_t>(i), static_cast<int64_t>(array_data[i]));
}
v8::Handle<v8::Object> obj = v8::Object::New();
i::Handle<i::JSObject> jsobj = v8::Utils::OpenHandle(*obj);
// Set the elements to be the external array.
obj->SetIndexedPropertiesToExternalArrayData(array_data,
array_type,
kElementCount);
CHECK_EQ(
1, static_cast<int>(jsobj->GetElement(1)->ToObjectChecked()->Number()));
ObjectWithExternalArrayTestHelper<ExternalArrayClass, ElementType>(
context.local(), obj, kElementCount, array_type, low, high);
v8::Handle<v8::Value> result;
// Test more complex manipulations which cause eax to contain values
// that won't be completely overwritten by loads from the arrays.
// This catches bugs in the instructions used for the KeyedLoadIC
// for byte and word types.
{
const int kXSize = 300;
const int kYSize = 300;
const int kLargeElementCount = kXSize * kYSize * 4;
ElementType* large_array_data =
static_cast<ElementType*>(malloc(kLargeElementCount * element_size));
v8::Handle<v8::Object> large_obj = v8::Object::New();
// Set the elements to be the external array.
large_obj->SetIndexedPropertiesToExternalArrayData(large_array_data,
array_type,
kLargeElementCount);
context->Global()->Set(v8_str("large_array"), large_obj);
// Initialize contents of a few rows.
for (int x = 0; x < 300; x++) {
int row = 0;
int offset = row * 300 * 4;
large_array_data[offset + 4 * x + 0] = (ElementType) 127;
large_array_data[offset + 4 * x + 1] = (ElementType) 0;
large_array_data[offset + 4 * x + 2] = (ElementType) 0;
large_array_data[offset + 4 * x + 3] = (ElementType) 127;
row = 150;
offset = row * 300 * 4;
large_array_data[offset + 4 * x + 0] = (ElementType) 127;
large_array_data[offset + 4 * x + 1] = (ElementType) 0;
large_array_data[offset + 4 * x + 2] = (ElementType) 0;
large_array_data[offset + 4 * x + 3] = (ElementType) 127;
row = 298;
offset = row * 300 * 4;
large_array_data[offset + 4 * x + 0] = (ElementType) 127;
large_array_data[offset + 4 * x + 1] = (ElementType) 0;
large_array_data[offset + 4 * x + 2] = (ElementType) 0;
large_array_data[offset + 4 * x + 3] = (ElementType) 127;
}
// The goal of the code below is to make "offset" large enough
// that the computation of the index (which goes into eax) has
// high bits set which will not be overwritten by a byte or short
// load.
result = CompileRun("var failed = false;"
"var offset = 0;"
"for (var i = 0; i < 300; i++) {"
" if (large_array[4 * i] != 127 ||"
" large_array[4 * i + 1] != 0 ||"
" large_array[4 * i + 2] != 0 ||"
" large_array[4 * i + 3] != 127) {"
" failed = true;"
" }"
"}"
"offset = 150 * 300 * 4;"
"for (var i = 0; i < 300; i++) {"
" if (large_array[offset + 4 * i] != 127 ||"
" large_array[offset + 4 * i + 1] != 0 ||"
" large_array[offset + 4 * i + 2] != 0 ||"
" large_array[offset + 4 * i + 3] != 127) {"
" failed = true;"
" }"
"}"
"offset = 298 * 300 * 4;"
"for (var i = 0; i < 300; i++) {"
" if (large_array[offset + 4 * i] != 127 ||"
" large_array[offset + 4 * i + 1] != 0 ||"
" large_array[offset + 4 * i + 2] != 0 ||"
" large_array[offset + 4 * i + 3] != 127) {"
" failed = true;"
" }"
"}"
"!failed;");
CHECK_EQ(true, result->BooleanValue());
free(large_array_data);
}
// The "" property descriptor is overloaded to store information about
// the external array. Ensure that setting and accessing the "" property
// works (it should overwrite the information cached about the external
// array in the DescriptorArray) in various situations.
result = CompileRun("ext_array[''] = 23; ext_array['']");
CHECK_EQ(23, result->Int32Value());
// Property "" set after the external array is associated with the object.
{
v8::Handle<v8::Object> obj2 = v8::Object::New();
obj2->Set(v8_str("ee_test_field"), v8::Int32::New(256));
obj2->Set(v8_str(""), v8::Int32::New(1503));
// Set the elements to be the external array.
obj2->SetIndexedPropertiesToExternalArrayData(array_data,
array_type,
kElementCount);
context->Global()->Set(v8_str("ext_array"), obj2);
result = CompileRun("ext_array['']");
CHECK_EQ(1503, result->Int32Value());
}
// Property "" set after the external array is associated with the object.
{
v8::Handle<v8::Object> obj2 = v8::Object::New();
obj2->Set(v8_str("ee_test_field_2"), v8::Int32::New(256));
// Set the elements to be the external array.
obj2->SetIndexedPropertiesToExternalArrayData(array_data,
array_type,
kElementCount);
obj2->Set(v8_str(""), v8::Int32::New(1503));
context->Global()->Set(v8_str("ext_array"), obj2);
result = CompileRun("ext_array['']");
CHECK_EQ(1503, result->Int32Value());
}
// Should reuse the map from previous test.
{
v8::Handle<v8::Object> obj2 = v8::Object::New();
obj2->Set(v8_str("ee_test_field_2"), v8::Int32::New(256));
// Set the elements to be the external array. Should re-use the map
// from previous test.
obj2->SetIndexedPropertiesToExternalArrayData(array_data,
array_type,
kElementCount);
context->Global()->Set(v8_str("ext_array"), obj2);
result = CompileRun("ext_array['']");
}
// Property "" is a constant function that shouldn't not be interfered with
// when an external array is set.
{
v8::Handle<v8::Object> obj2 = v8::Object::New();
// Start
obj2->Set(v8_str("ee_test_field3"), v8::Int32::New(256));
// Add a constant function to an object.
context->Global()->Set(v8_str("ext_array"), obj2);
result = CompileRun("ext_array[''] = function() {return 1503;};"
"ext_array['']();");
// Add an external array transition to the same map that
// has the constant transition.
v8::Handle<v8::Object> obj3 = v8::Object::New();
obj3->Set(v8_str("ee_test_field3"), v8::Int32::New(256));
obj3->SetIndexedPropertiesToExternalArrayData(array_data,
array_type,
kElementCount);
context->Global()->Set(v8_str("ext_array"), obj3);
}
// If a external array transition is in the map, it should get clobbered
// by a constant function.
{
// Add an external array transition.
v8::Handle<v8::Object> obj3 = v8::Object::New();
obj3->Set(v8_str("ee_test_field4"), v8::Int32::New(256));
obj3->SetIndexedPropertiesToExternalArrayData(array_data,
array_type,
kElementCount);
// Add a constant function to the same map that just got an external array
// transition.
v8::Handle<v8::Object> obj2 = v8::Object::New();
obj2->Set(v8_str("ee_test_field4"), v8::Int32::New(256));
context->Global()->Set(v8_str("ext_array"), obj2);
result = CompileRun("ext_array[''] = function() {return 1503;};"
"ext_array['']();");
}
free(array_data);
}
THREADED_TEST(ExternalByteArray) {
ExternalArrayTestHelper<i::ExternalByteArray, int8_t>(
v8::kExternalByteArray,
-128,
127);
}
THREADED_TEST(ExternalUnsignedByteArray) {
ExternalArrayTestHelper<i::ExternalUnsignedByteArray, uint8_t>(
v8::kExternalUnsignedByteArray,
0,
255);
}
THREADED_TEST(ExternalPixelArray) {
ExternalArrayTestHelper<i::ExternalPixelArray, uint8_t>(
v8::kExternalPixelArray,
0,
255);
}
THREADED_TEST(ExternalShortArray) {
ExternalArrayTestHelper<i::ExternalShortArray, int16_t>(
v8::kExternalShortArray,
-32768,
32767);
}
THREADED_TEST(ExternalUnsignedShortArray) {
ExternalArrayTestHelper<i::ExternalUnsignedShortArray, uint16_t>(
v8::kExternalUnsignedShortArray,
0,
65535);
}
THREADED_TEST(ExternalIntArray) {
ExternalArrayTestHelper<i::ExternalIntArray, int32_t>(
v8::kExternalIntArray,
INT_MIN, // -2147483648
INT_MAX); // 2147483647
}
THREADED_TEST(ExternalUnsignedIntArray) {
ExternalArrayTestHelper<i::ExternalUnsignedIntArray, uint32_t>(
v8::kExternalUnsignedIntArray,
0,
UINT_MAX); // 4294967295
}
THREADED_TEST(ExternalFloatArray) {
ExternalArrayTestHelper<i::ExternalFloatArray, float>(
v8::kExternalFloatArray,
-500,
500);
}
THREADED_TEST(ExternalDoubleArray) {
ExternalArrayTestHelper<i::ExternalDoubleArray, double>(
v8::kExternalDoubleArray,
-500,
500);
}
THREADED_TEST(ExternalArrays) {
TestExternalByteArray();
TestExternalUnsignedByteArray();
TestExternalShortArray();
TestExternalUnsignedShortArray();
TestExternalIntArray();
TestExternalUnsignedIntArray();
TestExternalFloatArray();
}
void ExternalArrayInfoTestHelper(v8::ExternalArrayType array_type) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
for (int size = 0; size < 100; size += 10) {
int element_size = ExternalArrayElementSize(array_type);
void* external_data = malloc(size * element_size);
v8::Handle<v8::Object> obj = v8::Object::New();
obj->SetIndexedPropertiesToExternalArrayData(
external_data, array_type, size);
CHECK(obj->HasIndexedPropertiesInExternalArrayData());
CHECK_EQ(external_data, obj->GetIndexedPropertiesExternalArrayData());
CHECK_EQ(array_type, obj->GetIndexedPropertiesExternalArrayDataType());
CHECK_EQ(size, obj->GetIndexedPropertiesExternalArrayDataLength());
free(external_data);
}
}
THREADED_TEST(ExternalArrayInfo) {
ExternalArrayInfoTestHelper(v8::kExternalByteArray);
ExternalArrayInfoTestHelper(v8::kExternalUnsignedByteArray);
ExternalArrayInfoTestHelper(v8::kExternalShortArray);
ExternalArrayInfoTestHelper(v8::kExternalUnsignedShortArray);
ExternalArrayInfoTestHelper(v8::kExternalIntArray);
ExternalArrayInfoTestHelper(v8::kExternalUnsignedIntArray);
ExternalArrayInfoTestHelper(v8::kExternalFloatArray);
ExternalArrayInfoTestHelper(v8::kExternalDoubleArray);
ExternalArrayInfoTestHelper(v8::kExternalPixelArray);
}
void ExternalArrayLimitTestHelper(v8::ExternalArrayType array_type, int size) {
v8::Handle<v8::Object> obj = v8::Object::New();
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
last_location = last_message = NULL;
obj->SetIndexedPropertiesToExternalArrayData(NULL, array_type, size);
CHECK(!obj->HasIndexedPropertiesInExternalArrayData());
CHECK_NE(NULL, last_location);
CHECK_NE(NULL, last_message);
}
TEST(ExternalArrayLimits) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
ExternalArrayLimitTestHelper(v8::kExternalByteArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalByteArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalUnsignedByteArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalUnsignedByteArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalShortArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalShortArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalUnsignedShortArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalUnsignedShortArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalIntArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalIntArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalUnsignedIntArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalUnsignedIntArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalFloatArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalFloatArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalDoubleArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalDoubleArray, 0xffffffff);
ExternalArrayLimitTestHelper(v8::kExternalPixelArray, 0x40000000);
ExternalArrayLimitTestHelper(v8::kExternalPixelArray, 0xffffffff);
}
template <typename ElementType, typename TypedArray,
class ExternalArrayClass>
void TypedArrayTestHelper(v8::ExternalArrayType array_type,
int64_t low, int64_t high) {
const int kElementCount = 50;
i::ScopedVector<ElementType> backing_store(kElementCount+2);
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(
backing_store.start(), (kElementCount+2)*sizeof(ElementType));
Local<TypedArray> ta =
TypedArray::New(ab, 2*sizeof(ElementType), kElementCount);
CheckInternalFieldsAreZero<v8::ArrayBufferView>(ta);
CHECK_EQ(kElementCount, static_cast<int>(ta->Length()));
CHECK_EQ(2*sizeof(ElementType), static_cast<int>(ta->ByteOffset()));
CHECK_EQ(kElementCount*sizeof(ElementType),
static_cast<int>(ta->ByteLength()));
CHECK_EQ(ab, ta->Buffer());
ElementType* data = backing_store.start() + 2;
for (int i = 0; i < kElementCount; i++) {
data[i] = static_cast<ElementType>(i);
}
ObjectWithExternalArrayTestHelper<ExternalArrayClass, ElementType>(
env.local(), ta, kElementCount, array_type, low, high);
}
THREADED_TEST(Uint8Array) {
TypedArrayTestHelper<uint8_t, v8::Uint8Array, i::ExternalUnsignedByteArray>(
v8::kExternalUnsignedByteArray, 0, 0xFF);
}
THREADED_TEST(Int8Array) {
TypedArrayTestHelper<int8_t, v8::Int8Array, i::ExternalByteArray>(
v8::kExternalByteArray, -0x80, 0x7F);
}
THREADED_TEST(Uint16Array) {
TypedArrayTestHelper<uint16_t,
v8::Uint16Array,
i::ExternalUnsignedShortArray>(
v8::kExternalUnsignedShortArray, 0, 0xFFFF);
}
THREADED_TEST(Int16Array) {
TypedArrayTestHelper<int16_t, v8::Int16Array, i::ExternalShortArray>(
v8::kExternalShortArray, -0x8000, 0x7FFF);
}
THREADED_TEST(Uint32Array) {
TypedArrayTestHelper<uint32_t, v8::Uint32Array, i::ExternalUnsignedIntArray>(
v8::kExternalUnsignedIntArray, 0, UINT_MAX);
}
THREADED_TEST(Int32Array) {
TypedArrayTestHelper<int32_t, v8::Int32Array, i::ExternalIntArray>(
v8::kExternalIntArray, INT_MIN, INT_MAX);
}
THREADED_TEST(Float32Array) {
TypedArrayTestHelper<float, v8::Float32Array, i::ExternalFloatArray>(
v8::kExternalFloatArray, -500, 500);
}
THREADED_TEST(Float64Array) {
TypedArrayTestHelper<double, v8::Float64Array, i::ExternalDoubleArray>(
v8::kExternalDoubleArray, -500, 500);
}
THREADED_TEST(Uint8ClampedArray) {
TypedArrayTestHelper<uint8_t, v8::Uint8ClampedArray, i::ExternalPixelArray>(
v8::kExternalPixelArray, 0, 0xFF);
}
THREADED_TEST(DataView) {
const int kSize = 50;
i::ScopedVector<uint8_t> backing_store(kSize+2);
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(
backing_store.start(), 2 + kSize);
Local<v8::DataView> dv =
v8::DataView::New(ab, 2, kSize);
CheckInternalFieldsAreZero<v8::ArrayBufferView>(dv);
CHECK_EQ(2, static_cast<int>(dv->ByteOffset()));
CHECK_EQ(kSize, static_cast<int>(dv->ByteLength()));
CHECK_EQ(ab, dv->Buffer());
}
#define IS_ARRAY_BUFFER_VIEW_TEST(View) \
THREADED_TEST(Is##View) { \
i::FLAG_harmony_array_buffer = true; \
i::FLAG_harmony_typed_arrays = true; \
LocalContext env; \
v8::Isolate* isolate = env->GetIsolate(); \
v8::HandleScope handle_scope(isolate); \
\
Handle<Value> result = CompileRun( \
"var ab = new ArrayBuffer(128);" \
"new " #View "(ab)"); \
CHECK(result->IsArrayBufferView()); \
CHECK(result->Is##View()); \
CheckInternalFieldsAreZero<v8::ArrayBufferView>(result.As<v8::View>()); \
}
IS_ARRAY_BUFFER_VIEW_TEST(Uint8Array)
IS_ARRAY_BUFFER_VIEW_TEST(Int8Array)
IS_ARRAY_BUFFER_VIEW_TEST(Uint16Array)
IS_ARRAY_BUFFER_VIEW_TEST(Int16Array)
IS_ARRAY_BUFFER_VIEW_TEST(Uint32Array)
IS_ARRAY_BUFFER_VIEW_TEST(Int32Array)
IS_ARRAY_BUFFER_VIEW_TEST(Float32Array)
IS_ARRAY_BUFFER_VIEW_TEST(Float64Array)
IS_ARRAY_BUFFER_VIEW_TEST(Uint8ClampedArray)
IS_ARRAY_BUFFER_VIEW_TEST(DataView)
#undef IS_ARRAY_BUFFER_VIEW_TEST
THREADED_TEST(ScriptContextDependence) {
LocalContext c1;
v8::HandleScope scope(c1->GetIsolate());
const char *source = "foo";
v8::Handle<v8::Script> dep = v8::Script::Compile(v8::String::New(source));
v8::Handle<v8::Script> indep = v8::Script::New(v8::String::New(source));
c1->Global()->Set(v8::String::New("foo"), v8::Integer::New(100));
CHECK_EQ(dep->Run()->Int32Value(), 100);
CHECK_EQ(indep->Run()->Int32Value(), 100);
LocalContext c2;
c2->Global()->Set(v8::String::New("foo"), v8::Integer::New(101));
CHECK_EQ(dep->Run()->Int32Value(), 100);
CHECK_EQ(indep->Run()->Int32Value(), 101);
}
THREADED_TEST(StackTrace) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
const char *source = "function foo() { FAIL.FAIL; }; foo();";
v8::Handle<v8::String> src = v8::String::New(source);
v8::Handle<v8::String> origin = v8::String::New("stack-trace-test");
v8::Script::New(src, origin)->Run();
CHECK(try_catch.HasCaught());
v8::String::Utf8Value stack(try_catch.StackTrace());
CHECK(strstr(*stack, "at foo (stack-trace-test") != NULL);
}
// Checks that a StackFrame has certain expected values.
void checkStackFrame(const char* expected_script_name,
const char* expected_func_name, int expected_line_number,
int expected_column, bool is_eval, bool is_constructor,
v8::Handle<v8::StackFrame> frame) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::String::Utf8Value func_name(frame->GetFunctionName());
v8::String::Utf8Value script_name(frame->GetScriptName());
if (*script_name == NULL) {
// The situation where there is no associated script, like for evals.
CHECK(expected_script_name == NULL);
} else {
CHECK(strstr(*script_name, expected_script_name) != NULL);
}
CHECK(strstr(*func_name, expected_func_name) != NULL);
CHECK_EQ(expected_line_number, frame->GetLineNumber());
CHECK_EQ(expected_column, frame->GetColumn());
CHECK_EQ(is_eval, frame->IsEval());
CHECK_EQ(is_constructor, frame->IsConstructor());
}
void AnalyzeStackInNativeCode(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
const char* origin = "capture-stack-trace-test";
const int kOverviewTest = 1;
const int kDetailedTest = 2;
ASSERT(args.Length() == 1);
int testGroup = args[0]->Int32Value();
if (testGroup == kOverviewTest) {
v8::Handle<v8::StackTrace> stackTrace =
v8::StackTrace::CurrentStackTrace(10, v8::StackTrace::kOverview);
CHECK_EQ(4, stackTrace->GetFrameCount());
checkStackFrame(origin, "bar", 2, 10, false, false,
stackTrace->GetFrame(0));
checkStackFrame(origin, "foo", 6, 3, false, false,
stackTrace->GetFrame(1));
// This is the source string inside the eval which has the call to foo.
checkStackFrame(NULL, "", 1, 5, false, false,
stackTrace->GetFrame(2));
// The last frame is an anonymous function which has the initial eval call.
checkStackFrame(origin, "", 8, 7, false, false,
stackTrace->GetFrame(3));
CHECK(stackTrace->AsArray()->IsArray());
} else if (testGroup == kDetailedTest) {
v8::Handle<v8::StackTrace> stackTrace =
v8::StackTrace::CurrentStackTrace(10, v8::StackTrace::kDetailed);
CHECK_EQ(4, stackTrace->GetFrameCount());
checkStackFrame(origin, "bat", 4, 22, false, false,
stackTrace->GetFrame(0));
checkStackFrame(origin, "baz", 8, 3, false, true,
stackTrace->GetFrame(1));
#ifdef ENABLE_DEBUGGER_SUPPORT
bool is_eval = true;
#else // ENABLE_DEBUGGER_SUPPORT
bool is_eval = false;
#endif // ENABLE_DEBUGGER_SUPPORT
// This is the source string inside the eval which has the call to baz.
checkStackFrame(NULL, "", 1, 5, is_eval, false,
stackTrace->GetFrame(2));
// The last frame is an anonymous function which has the initial eval call.
checkStackFrame(origin, "", 10, 1, false, false,
stackTrace->GetFrame(3));
CHECK(stackTrace->AsArray()->IsArray());
}
}
// Tests the C++ StackTrace API.
// TODO(3074796): Reenable this as a THREADED_TEST once it passes.
// THREADED_TEST(CaptureStackTrace) {
TEST(CaptureStackTrace) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Handle<v8::String> origin = v8::String::New("capture-stack-trace-test");
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("AnalyzeStackInNativeCode"),
v8::FunctionTemplate::New(AnalyzeStackInNativeCode));
LocalContext context(0, templ);
// Test getting OVERVIEW information. Should ignore information that is not
// script name, function name, line number, and column offset.
const char *overview_source =
"function bar() {\n"
" var y; AnalyzeStackInNativeCode(1);\n"
"}\n"
"function foo() {\n"
"\n"
" bar();\n"
"}\n"
"var x;eval('new foo();');";
v8::Handle<v8::String> overview_src = v8::String::New(overview_source);
v8::Handle<Value> overview_result(
v8::Script::New(overview_src, origin)->Run());
CHECK(!overview_result.IsEmpty());
CHECK(overview_result->IsObject());
// Test getting DETAILED information.
const char *detailed_source =
"function bat() {AnalyzeStackInNativeCode(2);\n"
"}\n"
"\n"
"function baz() {\n"
" bat();\n"
"}\n"
"eval('new baz();');";
v8::Handle<v8::String> detailed_src = v8::String::New(detailed_source);
// Make the script using a non-zero line and column offset.
v8::Handle<v8::Integer> line_offset = v8::Integer::New(3);
v8::Handle<v8::Integer> column_offset = v8::Integer::New(5);
v8::ScriptOrigin detailed_origin(origin, line_offset, column_offset);
v8::Handle<v8::Script> detailed_script(
v8::Script::New(detailed_src, &detailed_origin));
v8::Handle<Value> detailed_result(detailed_script->Run());
CHECK(!detailed_result.IsEmpty());
CHECK(detailed_result->IsObject());
}
static void StackTraceForUncaughtExceptionListener(
v8::Handle<v8::Message> message,
v8::Handle<Value>) {
v8::Handle<v8::StackTrace> stack_trace = message->GetStackTrace();
CHECK_EQ(2, stack_trace->GetFrameCount());
checkStackFrame("origin", "foo", 2, 3, false, false,
stack_trace->GetFrame(0));
checkStackFrame("origin", "bar", 5, 3, false, false,
stack_trace->GetFrame(1));
}
TEST(CaptureStackTraceForUncaughtException) {
report_count = 0;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::V8::AddMessageListener(StackTraceForUncaughtExceptionListener);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true);
Script::Compile(v8_str("function foo() {\n"
" throw 1;\n"
"};\n"
"function bar() {\n"
" foo();\n"
"};"),
v8_str("origin"))->Run();
v8::Local<v8::Object> global = env->Global();
Local<Value> trouble = global->Get(v8_str("bar"));
CHECK(trouble->IsFunction());
Function::Cast(*trouble)->Call(global, 0, NULL);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(false);
v8::V8::RemoveMessageListeners(StackTraceForUncaughtExceptionListener);
}
TEST(CaptureStackTraceForUncaughtExceptionAndSetters) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true,
1024,
v8::StackTrace::kDetailed);
CompileRun(
"var setters = ['column', 'lineNumber', 'scriptName',\n"
" 'scriptNameOrSourceURL', 'functionName', 'isEval',\n"
" 'isConstructor'];\n"
"for (var i = 0; i < setters.length; i++) {\n"
" var prop = setters[i];\n"
" Object.prototype.__defineSetter__(prop, function() { throw prop; });\n"
"}\n");
CompileRun("throw 'exception';");
v8::V8::SetCaptureStackTraceForUncaughtExceptions(false);
}
static void RethrowStackTraceHandler(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
// Use the frame where JavaScript is called from.
v8::Handle<v8::StackTrace> stack_trace = message->GetStackTrace();
CHECK(!stack_trace.IsEmpty());
int frame_count = stack_trace->GetFrameCount();
CHECK_EQ(3, frame_count);
int line_number[] = {1, 2, 5};
for (int i = 0; i < frame_count; i++) {
CHECK_EQ(line_number[i], stack_trace->GetFrame(i)->GetLineNumber());
}
}
// Test that we only return the stack trace at the site where the exception
// is first thrown (not where it is rethrown).
TEST(RethrowStackTrace) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// We make sure that
// - the stack trace of the ReferenceError in g() is reported.
// - the stack trace is not overwritten when e1 is rethrown by t().
// - the stack trace of e2 does not overwrite that of e1.
const char* source =
"function g() { error; } \n"
"function f() { g(); } \n"
"function t(e) { throw e; } \n"
"try { \n"
" f(); \n"
"} catch (e1) { \n"
" try { \n"
" error; \n"
" } catch (e2) { \n"
" t(e1); \n"
" } \n"
"} \n";
v8::V8::AddMessageListener(RethrowStackTraceHandler);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true);
CompileRun(source);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(false);
v8::V8::RemoveMessageListeners(RethrowStackTraceHandler);
}
static void RethrowPrimitiveStackTraceHandler(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
v8::Handle<v8::StackTrace> stack_trace = message->GetStackTrace();
CHECK(!stack_trace.IsEmpty());
int frame_count = stack_trace->GetFrameCount();
CHECK_EQ(2, frame_count);
int line_number[] = {3, 7};
for (int i = 0; i < frame_count; i++) {
CHECK_EQ(line_number[i], stack_trace->GetFrame(i)->GetLineNumber());
}
}
// Test that we do not recognize identity for primitive exceptions.
TEST(RethrowPrimitiveStackTrace) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
// We do not capture stack trace for non Error objects on creation time.
// Instead, we capture the stack trace on last throw.
const char* source =
"function g() { throw 404; } \n"
"function f() { g(); } \n"
"function t(e) { throw e; } \n"
"try { \n"
" f(); \n"
"} catch (e1) { \n"
" t(e1) \n"
"} \n";
v8::V8::AddMessageListener(RethrowPrimitiveStackTraceHandler);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true);
CompileRun(source);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(false);
v8::V8::RemoveMessageListeners(RethrowPrimitiveStackTraceHandler);
}
static void RethrowExistingStackTraceHandler(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
// Use the frame where JavaScript is called from.
v8::Handle<v8::StackTrace> stack_trace = message->GetStackTrace();
CHECK(!stack_trace.IsEmpty());
CHECK_EQ(1, stack_trace->GetFrameCount());
CHECK_EQ(1, stack_trace->GetFrame(0)->GetLineNumber());
}
// Test that the stack trace is captured when the error object is created and
// not where it is thrown.
TEST(RethrowExistingStackTrace) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* source =
"var e = new Error(); \n"
"throw e; \n";
v8::V8::AddMessageListener(RethrowExistingStackTraceHandler);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true);
CompileRun(source);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(false);
v8::V8::RemoveMessageListeners(RethrowExistingStackTraceHandler);
}
static void RethrowBogusErrorStackTraceHandler(v8::Handle<v8::Message> message,
v8::Handle<v8::Value> data) {
// Use the frame where JavaScript is called from.
v8::Handle<v8::StackTrace> stack_trace = message->GetStackTrace();
CHECK(!stack_trace.IsEmpty());
CHECK_EQ(1, stack_trace->GetFrameCount());
CHECK_EQ(2, stack_trace->GetFrame(0)->GetLineNumber());
}
// Test that the stack trace is captured where the bogus Error object is thrown.
TEST(RethrowBogusErrorStackTrace) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* source =
"var e = {__proto__: new Error()} \n"
"throw e; \n";
v8::V8::AddMessageListener(RethrowBogusErrorStackTraceHandler);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(true);
CompileRun(source);
v8::V8::SetCaptureStackTraceForUncaughtExceptions(false);
v8::V8::RemoveMessageListeners(RethrowBogusErrorStackTraceHandler);
}
void AnalyzeStackOfEvalWithSourceURL(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::StackTrace> stackTrace =
v8::StackTrace::CurrentStackTrace(10, v8::StackTrace::kDetailed);
CHECK_EQ(5, stackTrace->GetFrameCount());
v8::Handle<v8::String> url = v8_str("eval_url");
for (int i = 0; i < 3; i++) {
v8::Handle<v8::String> name =
stackTrace->GetFrame(i)->GetScriptNameOrSourceURL();
CHECK(!name.IsEmpty());
CHECK_EQ(url, name);
}
}
TEST(SourceURLInStackTrace) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("AnalyzeStackOfEvalWithSourceURL"),
v8::FunctionTemplate::New(AnalyzeStackOfEvalWithSourceURL));
LocalContext context(0, templ);
const char *source =
"function outer() {\n"
"function bar() {\n"
" AnalyzeStackOfEvalWithSourceURL();\n"
"}\n"
"function foo() {\n"
"\n"
" bar();\n"
"}\n"
"foo();\n"
"}\n"
"eval('(' + outer +')()%s');";
i::ScopedVector<char> code(1024);
i::OS::SNPrintF(code, source, "//# sourceURL=eval_url");
CHECK(CompileRun(code.start())->IsUndefined());
i::OS::SNPrintF(code, source, "//@ sourceURL=eval_url");
CHECK(CompileRun(code.start())->IsUndefined());
}
void AnalyzeStackOfInlineScriptWithSourceURL(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::StackTrace> stackTrace =
v8::StackTrace::CurrentStackTrace(10, v8::StackTrace::kDetailed);
CHECK_EQ(4, stackTrace->GetFrameCount());
v8::Handle<v8::String> url = v8_str("url");
for (int i = 0; i < 3; i++) {
v8::Handle<v8::String> name =
stackTrace->GetFrame(i)->GetScriptNameOrSourceURL();
CHECK(!name.IsEmpty());
CHECK_EQ(url, name);
}
}
TEST(InlineScriptWithSourceURLInStackTrace) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("AnalyzeStackOfInlineScriptWithSourceURL"),
v8::FunctionTemplate::New(
AnalyzeStackOfInlineScriptWithSourceURL));
LocalContext context(0, templ);
const char *source =
"function outer() {\n"
"function bar() {\n"
" AnalyzeStackOfInlineScriptWithSourceURL();\n"
"}\n"
"function foo() {\n"
"\n"
" bar();\n"
"}\n"
"foo();\n"
"}\n"
"outer()\n%s";
i::ScopedVector<char> code(1024);
i::OS::SNPrintF(code, source, "//# sourceURL=source_url");
CHECK(CompileRunWithOrigin(code.start(), "url", 0, 1)->IsUndefined());
i::OS::SNPrintF(code, source, "//@ sourceURL=source_url");
CHECK(CompileRunWithOrigin(code.start(), "url", 0, 1)->IsUndefined());
}
void AnalyzeStackOfDynamicScriptWithSourceURL(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::Handle<v8::StackTrace> stackTrace =
v8::StackTrace::CurrentStackTrace(10, v8::StackTrace::kDetailed);
CHECK_EQ(4, stackTrace->GetFrameCount());
v8::Handle<v8::String> url = v8_str("source_url");
for (int i = 0; i < 3; i++) {
v8::Handle<v8::String> name =
stackTrace->GetFrame(i)->GetScriptNameOrSourceURL();
CHECK(!name.IsEmpty());
CHECK_EQ(url, name);
}
}
TEST(DynamicWithSourceURLInStackTrace) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->Set(v8_str("AnalyzeStackOfDynamicScriptWithSourceURL"),
v8::FunctionTemplate::New(
AnalyzeStackOfDynamicScriptWithSourceURL));
LocalContext context(0, templ);
const char *source =
"function outer() {\n"
"function bar() {\n"
" AnalyzeStackOfDynamicScriptWithSourceURL();\n"
"}\n"
"function foo() {\n"
"\n"
" bar();\n"
"}\n"
"foo();\n"
"}\n"
"outer()\n%s";
i::ScopedVector<char> code(1024);
i::OS::SNPrintF(code, source, "//# sourceURL=source_url");
CHECK(CompileRunWithOrigin(code.start(), "url", 0, 0)->IsUndefined());
i::OS::SNPrintF(code, source, "//@ sourceURL=source_url");
CHECK(CompileRunWithOrigin(code.start(), "url", 0, 0)->IsUndefined());
}
static void CreateGarbageInOldSpace() {
i::Factory* factory = i::Isolate::Current()->factory();
v8::HandleScope scope(v8::Isolate::GetCurrent());
i::AlwaysAllocateScope always_allocate;
for (int i = 0; i < 1000; i++) {
factory->NewFixedArray(1000, i::TENURED);
}
}
// Test that idle notification can be handled and eventually returns true.
TEST(IdleNotification) {
const intptr_t MB = 1024 * 1024;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
intptr_t initial_size = HEAP->SizeOfObjects();
CreateGarbageInOldSpace();
intptr_t size_with_garbage = HEAP->SizeOfObjects();
CHECK_GT(size_with_garbage, initial_size + MB);
bool finished = false;
for (int i = 0; i < 200 && !finished; i++) {
finished = v8::V8::IdleNotification();
}
intptr_t final_size = HEAP->SizeOfObjects();
CHECK(finished);
CHECK_LT(final_size, initial_size + 1);
}
// Test that idle notification can be handled and eventually collects garbage.
TEST(IdleNotificationWithSmallHint) {
const intptr_t MB = 1024 * 1024;
const int IdlePauseInMs = 900;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
intptr_t initial_size = HEAP->SizeOfObjects();
CreateGarbageInOldSpace();
intptr_t size_with_garbage = HEAP->SizeOfObjects();
CHECK_GT(size_with_garbage, initial_size + MB);
bool finished = false;
for (int i = 0; i < 200 && !finished; i++) {
finished = v8::V8::IdleNotification(IdlePauseInMs);
}
intptr_t final_size = HEAP->SizeOfObjects();
CHECK(finished);
CHECK_LT(final_size, initial_size + 1);
}
// Test that idle notification can be handled and eventually collects garbage.
TEST(IdleNotificationWithLargeHint) {
const intptr_t MB = 1024 * 1024;
const int IdlePauseInMs = 900;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
intptr_t initial_size = HEAP->SizeOfObjects();
CreateGarbageInOldSpace();
intptr_t size_with_garbage = HEAP->SizeOfObjects();
CHECK_GT(size_with_garbage, initial_size + MB);
bool finished = false;
for (int i = 0; i < 200 && !finished; i++) {
finished = v8::V8::IdleNotification(IdlePauseInMs);
}
intptr_t final_size = HEAP->SizeOfObjects();
CHECK(finished);
CHECK_LT(final_size, initial_size + 1);
}
TEST(Regress2107) {
const intptr_t MB = 1024 * 1024;
const int kShortIdlePauseInMs = 100;
const int kLongIdlePauseInMs = 1000;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(env->GetIsolate());
intptr_t initial_size = HEAP->SizeOfObjects();
// Send idle notification to start a round of incremental GCs.
v8::V8::IdleNotification(kShortIdlePauseInMs);
// Emulate 7 page reloads.
for (int i = 0; i < 7; i++) {
{
v8::HandleScope inner_scope(env->GetIsolate());
v8::Local<v8::Context> ctx = v8::Context::New(isolate);
ctx->Enter();
CreateGarbageInOldSpace();
ctx->Exit();
}
v8::V8::ContextDisposedNotification();
v8::V8::IdleNotification(kLongIdlePauseInMs);
}
// Create garbage and check that idle notification still collects it.
CreateGarbageInOldSpace();
intptr_t size_with_garbage = HEAP->SizeOfObjects();
CHECK_GT(size_with_garbage, initial_size + MB);
bool finished = false;
for (int i = 0; i < 200 && !finished; i++) {
finished = v8::V8::IdleNotification(kShortIdlePauseInMs);
}
intptr_t final_size = HEAP->SizeOfObjects();
CHECK_LT(final_size, initial_size + 1);
}
static uint32_t* stack_limit;
static void GetStackLimitCallback(
const v8::FunctionCallbackInfo<v8::Value>& args) {
stack_limit = reinterpret_cast<uint32_t*>(
i::Isolate::Current()->stack_guard()->real_climit());
}
// Uses the address of a local variable to determine the stack top now.
// Given a size, returns an address that is that far from the current
// top of stack.
static uint32_t* ComputeStackLimit(uint32_t size) {
uint32_t* answer = &size - (size / sizeof(size));
// If the size is very large and the stack is very near the bottom of
// memory then the calculation above may wrap around and give an address
// that is above the (downwards-growing) stack. In that case we return
// a very low address.
if (answer > &size) return reinterpret_cast<uint32_t*>(sizeof(size));
return answer;
}
// We need at least 165kB for an x64 debug build with clang and ASAN.
static const int stack_breathing_room = 256 * i::KB;
TEST(SetResourceConstraints) {
uint32_t* set_limit = ComputeStackLimit(stack_breathing_room);
// Set stack limit.
v8::ResourceConstraints constraints;
constraints.set_stack_limit(set_limit);
CHECK(v8::SetResourceConstraints(&constraints));
// Execute a script.
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(GetStackLimitCallback);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("get_stack_limit"), fun);
CompileRun("get_stack_limit();");
CHECK(stack_limit == set_limit);
}
TEST(SetResourceConstraintsInThread) {
uint32_t* set_limit;
{
v8::Locker locker(CcTest::default_isolate());
set_limit = ComputeStackLimit(stack_breathing_room);
// Set stack limit.
v8::ResourceConstraints constraints;
constraints.set_stack_limit(set_limit);
CHECK(v8::SetResourceConstraints(&constraints));
// Execute a script.
v8::HandleScope scope(CcTest::default_isolate());
LocalContext env;
Local<v8::FunctionTemplate> fun_templ =
v8::FunctionTemplate::New(GetStackLimitCallback);
Local<Function> fun = fun_templ->GetFunction();
env->Global()->Set(v8_str("get_stack_limit"), fun);
CompileRun("get_stack_limit();");
CHECK(stack_limit == set_limit);
}
{
v8::Locker locker(CcTest::default_isolate());
CHECK(stack_limit == set_limit);
}
}
THREADED_TEST(GetHeapStatistics) {
LocalContext c1;
v8::HandleScope scope(c1->GetIsolate());
v8::HeapStatistics heap_statistics;
CHECK_EQ(static_cast<int>(heap_statistics.total_heap_size()), 0);
CHECK_EQ(static_cast<int>(heap_statistics.used_heap_size()), 0);
c1->GetIsolate()->GetHeapStatistics(&heap_statistics);
CHECK_NE(static_cast<int>(heap_statistics.total_heap_size()), 0);
CHECK_NE(static_cast<int>(heap_statistics.used_heap_size()), 0);
}
class VisitorImpl : public v8::ExternalResourceVisitor {
public:
explicit VisitorImpl(TestResource** resource) {
for (int i = 0; i < 4; i++) {
resource_[i] = resource[i];
found_resource_[i] = false;
}
}
virtual ~VisitorImpl() {}
virtual void VisitExternalString(v8::Handle<v8::String> string) {
if (!string->IsExternal()) {
CHECK(string->IsExternalAscii());
return;
}
v8::String::ExternalStringResource* resource =
string->GetExternalStringResource();
CHECK(resource);
for (int i = 0; i < 4; i++) {
if (resource_[i] == resource) {
CHECK(!found_resource_[i]);
found_resource_[i] = true;
}
}
}
void CheckVisitedResources() {
for (int i = 0; i < 4; i++) {
CHECK(found_resource_[i]);
}
}
private:
v8::String::ExternalStringResource* resource_[4];
bool found_resource_[4];
};
TEST(VisitExternalStrings) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
const char* string = "Some string";
uint16_t* two_byte_string = AsciiToTwoByteString(string);
TestResource* resource[4];
resource[0] = new TestResource(two_byte_string);
v8::Local<v8::String> string0 = v8::String::NewExternal(resource[0]);
resource[1] = new TestResource(two_byte_string);
v8::Local<v8::String> string1 = v8::String::NewExternal(resource[1]);
// Externalized symbol.
resource[2] = new TestResource(two_byte_string);
v8::Local<v8::String> string2 = v8::String::NewSymbol(string);
CHECK(string2->MakeExternal(resource[2]));
// Symbolized External.
resource[3] = new TestResource(AsciiToTwoByteString("Some other string"));
v8::Local<v8::String> string3 = v8::String::NewExternal(resource[3]);
HEAP->CollectAllAvailableGarbage(); // Tenure string.
// Turn into a symbol.
i::Handle<i::String> string3_i = v8::Utils::OpenHandle(*string3);
CHECK(!HEAP->InternalizeString(*string3_i)->IsFailure());
CHECK(string3_i->IsInternalizedString());
// We need to add usages for string* to avoid warnings in GCC 4.7
CHECK(string0->IsExternal());
CHECK(string1->IsExternal());
CHECK(string2->IsExternal());
CHECK(string3->IsExternal());
VisitorImpl visitor(resource);
v8::V8::VisitExternalResources(&visitor);
visitor.CheckVisitedResources();
}
static double DoubleFromBits(uint64_t value) {
double target;
i::OS::MemCopy(&target, &value, sizeof(target));
return target;
}
static uint64_t DoubleToBits(double value) {
uint64_t target;
i::OS::MemCopy(&target, &value, sizeof(target));
return target;
}
static double DoubleToDateTime(double input) {
double date_limit = 864e13;
if (std::isnan(input) || input < -date_limit || input > date_limit) {
return i::OS::nan_value();
}
return (input < 0) ? -(floor(-input)) : floor(input);
}
// We don't have a consistent way to write 64-bit constants syntactically, so we
// split them into two 32-bit constants and combine them programmatically.
static double DoubleFromBits(uint32_t high_bits, uint32_t low_bits) {
return DoubleFromBits((static_cast<uint64_t>(high_bits) << 32) | low_bits);
}
THREADED_TEST(QuietSignalingNaNs) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::TryCatch try_catch;
// Special double values.
double snan = DoubleFromBits(0x7ff00000, 0x00000001);
double qnan = DoubleFromBits(0x7ff80000, 0x00000000);
double infinity = DoubleFromBits(0x7ff00000, 0x00000000);
double max_normal = DoubleFromBits(0x7fefffff, 0xffffffffu);
double min_normal = DoubleFromBits(0x00100000, 0x00000000);
double max_denormal = DoubleFromBits(0x000fffff, 0xffffffffu);
double min_denormal = DoubleFromBits(0x00000000, 0x00000001);
// Date values are capped at +/-100000000 days (times 864e5 ms per day)
// on either side of the epoch.
double date_limit = 864e13;
double test_values[] = {
snan,
qnan,
infinity,
max_normal,
date_limit + 1,
date_limit,
min_normal,
max_denormal,
min_denormal,
0,
-0,
-min_denormal,
-max_denormal,
-min_normal,
-date_limit,
-date_limit - 1,
-max_normal,
-infinity,
-qnan,
-snan
};
int num_test_values = 20;
for (int i = 0; i < num_test_values; i++) {
double test_value = test_values[i];
// Check that Number::New preserves non-NaNs and quiets SNaNs.
v8::Handle<v8::Value> number = v8::Number::New(test_value);
double stored_number = number->NumberValue();
if (!std::isnan(test_value)) {
CHECK_EQ(test_value, stored_number);
} else {
uint64_t stored_bits = DoubleToBits(stored_number);
// Check if quiet nan (bits 51..62 all set).
#if defined(V8_TARGET_ARCH_MIPS) && !defined(USE_SIMULATOR)
// Most significant fraction bit for quiet nan is set to 0
// on MIPS architecture. Allowed by IEEE-754.
CHECK_EQ(0xffe, static_cast<int>((stored_bits >> 51) & 0xfff));
#else
CHECK_EQ(0xfff, static_cast<int>((stored_bits >> 51) & 0xfff));
#endif
}
// Check that Date::New preserves non-NaNs in the date range and
// quiets SNaNs.
v8::Handle<v8::Value> date = v8::Date::New(test_value);
double expected_stored_date = DoubleToDateTime(test_value);
double stored_date = date->NumberValue();
if (!std::isnan(expected_stored_date)) {
CHECK_EQ(expected_stored_date, stored_date);
} else {
uint64_t stored_bits = DoubleToBits(stored_date);
// Check if quiet nan (bits 51..62 all set).
#if defined(V8_TARGET_ARCH_MIPS) && !defined(USE_SIMULATOR)
// Most significant fraction bit for quiet nan is set to 0
// on MIPS architecture. Allowed by IEEE-754.
CHECK_EQ(0xffe, static_cast<int>((stored_bits >> 51) & 0xfff));
#else
CHECK_EQ(0xfff, static_cast<int>((stored_bits >> 51) & 0xfff));
#endif
}
}
}
static void SpaghettiIncident(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
v8::TryCatch tc;
v8::Handle<v8::String> str(args[0]->ToString());
USE(str);
if (tc.HasCaught())
tc.ReThrow();
}
// Test that an exception can be propagated down through a spaghetti
// stack using ReThrow.
THREADED_TEST(SpaghettiStackReThrow) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
context->Global()->Set(
v8::String::New("s"),
v8::FunctionTemplate::New(SpaghettiIncident)->GetFunction());
v8::TryCatch try_catch;
CompileRun(
"var i = 0;"
"var o = {"
" toString: function () {"
" if (i == 10) {"
" throw 'Hey!';"
" } else {"
" i++;"
" return s(o);"
" }"
" }"
"};"
"s(o);");
CHECK(try_catch.HasCaught());
v8::String::Utf8Value value(try_catch.Exception());
CHECK_EQ(0, strcmp(*value, "Hey!"));
}
TEST(Regress528) {
v8::V8::Initialize();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
v8::Local<Context> other_context;
int gc_count;
// Create a context used to keep the code from aging in the compilation
// cache.
other_context = Context::New(isolate);
// Context-dependent context data creates reference from the compilation
// cache to the global object.
const char* source_simple = "1";
{
v8::HandleScope scope(isolate);
v8::Local<Context> context = Context::New(isolate);
context->Enter();
Local<v8::String> obj = v8::String::New("");
context->SetEmbedderData(0, obj);
CompileRun(source_simple);
context->Exit();
}
v8::V8::ContextDisposedNotification();
for (gc_count = 1; gc_count < 10; gc_count++) {
other_context->Enter();
CompileRun(source_simple);
other_context->Exit();
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
if (GetGlobalObjectsCount() == 1) break;
}
CHECK_GE(2, gc_count);
CHECK_EQ(1, GetGlobalObjectsCount());
// Eval in a function creates reference from the compilation cache to the
// global object.
const char* source_eval = "function f(){eval('1')}; f()";
{
v8::HandleScope scope(isolate);
v8::Local<Context> context = Context::New(isolate);
context->Enter();
CompileRun(source_eval);
context->Exit();
}
v8::V8::ContextDisposedNotification();
for (gc_count = 1; gc_count < 10; gc_count++) {
other_context->Enter();
CompileRun(source_eval);
other_context->Exit();
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
if (GetGlobalObjectsCount() == 1) break;
}
CHECK_GE(2, gc_count);
CHECK_EQ(1, GetGlobalObjectsCount());
// Looking up the line number for an exception creates reference from the
// compilation cache to the global object.
const char* source_exception = "function f(){throw 1;} f()";
{
v8::HandleScope scope(isolate);
v8::Local<Context> context = Context::New(isolate);
context->Enter();
v8::TryCatch try_catch;
CompileRun(source_exception);
CHECK(try_catch.HasCaught());
v8::Handle<v8::Message> message = try_catch.Message();
CHECK(!message.IsEmpty());
CHECK_EQ(1, message->GetLineNumber());
context->Exit();
}
v8::V8::ContextDisposedNotification();
for (gc_count = 1; gc_count < 10; gc_count++) {
other_context->Enter();
CompileRun(source_exception);
other_context->Exit();
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
if (GetGlobalObjectsCount() == 1) break;
}
CHECK_GE(2, gc_count);
CHECK_EQ(1, GetGlobalObjectsCount());
v8::V8::ContextDisposedNotification();
}
THREADED_TEST(ScriptOrigin) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::ScriptOrigin origin = v8::ScriptOrigin(v8::String::New("test"));
v8::Handle<v8::String> script = v8::String::New(
"function f() {}\n\nfunction g() {}");
v8::Script::Compile(script, &origin)->Run();
v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("f")));
v8::Local<v8::Function> g = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("g")));
v8::ScriptOrigin script_origin_f = f->GetScriptOrigin();
CHECK_EQ("test", *v8::String::Utf8Value(script_origin_f.ResourceName()));
CHECK_EQ(0, script_origin_f.ResourceLineOffset()->Int32Value());
v8::ScriptOrigin script_origin_g = g->GetScriptOrigin();
CHECK_EQ("test", *v8::String::Utf8Value(script_origin_g.ResourceName()));
CHECK_EQ(0, script_origin_g.ResourceLineOffset()->Int32Value());
}
THREADED_TEST(FunctionGetInferredName) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::ScriptOrigin origin = v8::ScriptOrigin(v8::String::New("test"));
v8::Handle<v8::String> script = v8::String::New(
"var foo = { bar : { baz : function() {}}}; var f = foo.bar.baz;");
v8::Script::Compile(script, &origin)->Run();
v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("f")));
CHECK_EQ("foo.bar.baz", *v8::String::Utf8Value(f->GetInferredName()));
}
THREADED_TEST(ScriptLineNumber) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::ScriptOrigin origin = v8::ScriptOrigin(v8::String::New("test"));
v8::Handle<v8::String> script = v8::String::New(
"function f() {}\n\nfunction g() {}");
v8::Script::Compile(script, &origin)->Run();
v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("f")));
v8::Local<v8::Function> g = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("g")));
CHECK_EQ(0, f->GetScriptLineNumber());
CHECK_EQ(2, g->GetScriptLineNumber());
}
THREADED_TEST(ScriptColumnNumber) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::ScriptOrigin origin = v8::ScriptOrigin(v8::String::New("test"),
v8::Integer::New(3), v8::Integer::New(2));
v8::Handle<v8::String> script = v8::String::New(
"function foo() {}\n\n function bar() {}");
v8::Script::Compile(script, &origin)->Run();
v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("foo")));
v8::Local<v8::Function> bar = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("bar")));
CHECK_EQ(14, foo->GetScriptColumnNumber());
CHECK_EQ(17, bar->GetScriptColumnNumber());
}
THREADED_TEST(FunctionGetScriptId) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::ScriptOrigin origin = v8::ScriptOrigin(v8::String::New("test"),
v8::Integer::New(3), v8::Integer::New(2));
v8::Handle<v8::String> scriptSource = v8::String::New(
"function foo() {}\n\n function bar() {}");
v8::Local<v8::Script> script(v8::Script::Compile(scriptSource, &origin));
script->Run();
v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("foo")));
v8::Local<v8::Function> bar = v8::Local<v8::Function>::Cast(
env->Global()->Get(v8::String::New("bar")));
CHECK_EQ(script->Id(), foo->GetScriptId());
CHECK_EQ(script->Id(), bar->GetScriptId());
}
static void GetterWhichReturns42(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CHECK(v8::Utils::OpenHandle(*info.This())->IsJSObject());
CHECK(v8::Utils::OpenHandle(*info.Holder())->IsJSObject());
info.GetReturnValue().Set(v8_num(42));
}
static void SetterWhichSetsYOnThisTo23(
Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<void>& info) {
CHECK(v8::Utils::OpenHandle(*info.This())->IsJSObject());
CHECK(v8::Utils::OpenHandle(*info.Holder())->IsJSObject());
info.This()->Set(v8_str("y"), v8_num(23));
}
void FooGetInterceptor(Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CHECK(v8::Utils::OpenHandle(*info.This())->IsJSObject());
CHECK(v8::Utils::OpenHandle(*info.Holder())->IsJSObject());
if (!name->Equals(v8_str("foo"))) return;
info.GetReturnValue().Set(v8_num(42));
}
void FooSetInterceptor(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CHECK(v8::Utils::OpenHandle(*info.This())->IsJSObject());
CHECK(v8::Utils::OpenHandle(*info.Holder())->IsJSObject());
if (!name->Equals(v8_str("foo"))) return;
info.This()->Set(v8_str("y"), v8_num(23));
info.GetReturnValue().Set(v8_num(23));
}
TEST(SetterOnConstructorPrototype) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"),
GetterWhichReturns42,
SetterWhichSetsYOnThisTo23);
LocalContext context;
context->Global()->Set(v8_str("P"), templ->NewInstance());
CompileRun("function C1() {"
" this.x = 23;"
"};"
"C1.prototype = P;"
"function C2() {"
" this.x = 23"
"};"
"C2.prototype = { };"
"C2.prototype.__proto__ = P;");
v8::Local<v8::Script> script;
script = v8::Script::Compile(v8_str("new C1();"));
for (int i = 0; i < 10; i++) {
v8::Handle<v8::Object> c1 = v8::Handle<v8::Object>::Cast(script->Run());
CHECK_EQ(42, c1->Get(v8_str("x"))->Int32Value());
CHECK_EQ(23, c1->Get(v8_str("y"))->Int32Value());
}
script = v8::Script::Compile(v8_str("new C2();"));
for (int i = 0; i < 10; i++) {
v8::Handle<v8::Object> c2 = v8::Handle<v8::Object>::Cast(script->Run());
CHECK_EQ(42, c2->Get(v8_str("x"))->Int32Value());
CHECK_EQ(23, c2->Get(v8_str("y"))->Int32Value());
}
}
static void NamedPropertyGetterWhichReturns42(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8_num(42));
}
static void NamedPropertySetterWhichSetsYOnThisTo23(
Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<v8::Value>& info) {
if (name->Equals(v8_str("x"))) {
info.This()->Set(v8_str("y"), v8_num(23));
}
}
THREADED_TEST(InterceptorOnConstructorPrototype) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(NamedPropertyGetterWhichReturns42,
NamedPropertySetterWhichSetsYOnThisTo23);
LocalContext context;
context->Global()->Set(v8_str("P"), templ->NewInstance());
CompileRun("function C1() {"
" this.x = 23;"
"};"
"C1.prototype = P;"
"function C2() {"
" this.x = 23"
"};"
"C2.prototype = { };"
"C2.prototype.__proto__ = P;");
v8::Local<v8::Script> script;
script = v8::Script::Compile(v8_str("new C1();"));
for (int i = 0; i < 10; i++) {
v8::Handle<v8::Object> c1 = v8::Handle<v8::Object>::Cast(script->Run());
CHECK_EQ(23, c1->Get(v8_str("x"))->Int32Value());
CHECK_EQ(42, c1->Get(v8_str("y"))->Int32Value());
}
script = v8::Script::Compile(v8_str("new C2();"));
for (int i = 0; i < 10; i++) {
v8::Handle<v8::Object> c2 = v8::Handle<v8::Object>::Cast(script->Run());
CHECK_EQ(23, c2->Get(v8_str("x"))->Int32Value());
CHECK_EQ(42, c2->Get(v8_str("y"))->Int32Value());
}
}
TEST(Regress618) {
const char* source = "function C1() {"
" this.x = 23;"
"};"
"C1.prototype = P;";
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Local<v8::Script> script;
// Use a simple object as prototype.
v8::Local<v8::Object> prototype = v8::Object::New();
prototype->Set(v8_str("y"), v8_num(42));
context->Global()->Set(v8_str("P"), prototype);
// This compile will add the code to the compilation cache.
CompileRun(source);
script = v8::Script::Compile(v8_str("new C1();"));
// Allow enough iterations for the inobject slack tracking logic
// to finalize instance size and install the fast construct stub.
for (int i = 0; i < 256; i++) {
v8::Handle<v8::Object> c1 = v8::Handle<v8::Object>::Cast(script->Run());
CHECK_EQ(23, c1->Get(v8_str("x"))->Int32Value());
CHECK_EQ(42, c1->Get(v8_str("y"))->Int32Value());
}
// Use an API object with accessors as prototype.
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("x"),
GetterWhichReturns42,
SetterWhichSetsYOnThisTo23);
context->Global()->Set(v8_str("P"), templ->NewInstance());
// This compile will get the code from the compilation cache.
CompileRun(source);
script = v8::Script::Compile(v8_str("new C1();"));
for (int i = 0; i < 10; i++) {
v8::Handle<v8::Object> c1 = v8::Handle<v8::Object>::Cast(script->Run());
CHECK_EQ(42, c1->Get(v8_str("x"))->Int32Value());
CHECK_EQ(23, c1->Get(v8_str("y"))->Int32Value());
}
}
int prologue_call_count = 0;
int epilogue_call_count = 0;
int prologue_call_count_second = 0;
int epilogue_call_count_second = 0;
void PrologueCallback(v8::GCType, v8::GCCallbackFlags) {
++prologue_call_count;
}
void EpilogueCallback(v8::GCType, v8::GCCallbackFlags) {
++epilogue_call_count;
}
void PrologueCallbackSecond(v8::GCType, v8::GCCallbackFlags) {
++prologue_call_count_second;
}
void EpilogueCallbackSecond(v8::GCType, v8::GCCallbackFlags) {
++epilogue_call_count_second;
}
TEST(GCCallbacks) {
LocalContext context;
v8::V8::AddGCPrologueCallback(PrologueCallback);
v8::V8::AddGCEpilogueCallback(EpilogueCallback);
CHECK_EQ(0, prologue_call_count);
CHECK_EQ(0, epilogue_call_count);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(1, prologue_call_count);
CHECK_EQ(1, epilogue_call_count);
v8::V8::AddGCPrologueCallback(PrologueCallbackSecond);
v8::V8::AddGCEpilogueCallback(EpilogueCallbackSecond);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(2, prologue_call_count);
CHECK_EQ(2, epilogue_call_count);
CHECK_EQ(1, prologue_call_count_second);
CHECK_EQ(1, epilogue_call_count_second);
v8::V8::RemoveGCPrologueCallback(PrologueCallback);
v8::V8::RemoveGCEpilogueCallback(EpilogueCallback);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(2, prologue_call_count);
CHECK_EQ(2, epilogue_call_count);
CHECK_EQ(2, prologue_call_count_second);
CHECK_EQ(2, epilogue_call_count_second);
v8::V8::RemoveGCPrologueCallback(PrologueCallbackSecond);
v8::V8::RemoveGCEpilogueCallback(EpilogueCallbackSecond);
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
CHECK_EQ(2, prologue_call_count);
CHECK_EQ(2, epilogue_call_count);
CHECK_EQ(2, prologue_call_count_second);
CHECK_EQ(2, epilogue_call_count_second);
}
THREADED_TEST(AddToJSFunctionResultCache) {
i::FLAG_stress_compaction = false;
i::FLAG_allow_natives_syntax = true;
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
const char* code =
"(function() {"
" var key0 = 'a';"
" var key1 = 'b';"
" var r0 = %_GetFromCache(0, key0);"
" var r1 = %_GetFromCache(0, key1);"
" var r0_ = %_GetFromCache(0, key0);"
" if (r0 !== r0_)"
" return 'Different results for ' + key0 + ': ' + r0 + ' vs. ' + r0_;"
" var r1_ = %_GetFromCache(0, key1);"
" if (r1 !== r1_)"
" return 'Different results for ' + key1 + ': ' + r1 + ' vs. ' + r1_;"
" return 'PASSED';"
"})()";
HEAP->ClearJSFunctionResultCaches();
ExpectString(code, "PASSED");
}
static const int k0CacheSize = 16;
THREADED_TEST(FillJSFunctionResultCache) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
const char* code =
"(function() {"
" var k = 'a';"
" var r = %_GetFromCache(0, k);"
" for (var i = 0; i < 16; i++) {"
" %_GetFromCache(0, 'a' + i);"
" };"
" if (r === %_GetFromCache(0, k))"
" return 'FAILED: k0CacheSize is too small';"
" return 'PASSED';"
"})()";
HEAP->ClearJSFunctionResultCaches();
ExpectString(code, "PASSED");
}
THREADED_TEST(RoundRobinGetFromCache) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
const char* code =
"(function() {"
" var keys = [];"
" for (var i = 0; i < 16; i++) keys.push(i);"
" var values = [];"
" for (var i = 0; i < 16; i++) values[i] = %_GetFromCache(0, keys[i]);"
" for (var i = 0; i < 16; i++) {"
" var v = %_GetFromCache(0, keys[i]);"
" if (v.toString() !== values[i].toString())"
" return 'Wrong value for ' + "
" keys[i] + ': ' + v + ' vs. ' + values[i];"
" };"
" return 'PASSED';"
"})()";
HEAP->ClearJSFunctionResultCaches();
ExpectString(code, "PASSED");
}
THREADED_TEST(ReverseGetFromCache) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
const char* code =
"(function() {"
" var keys = [];"
" for (var i = 0; i < 16; i++) keys.push(i);"
" var values = [];"
" for (var i = 0; i < 16; i++) values[i] = %_GetFromCache(0, keys[i]);"
" for (var i = 15; i >= 16; i--) {"
" var v = %_GetFromCache(0, keys[i]);"
" if (v !== values[i])"
" return 'Wrong value for ' + "
" keys[i] + ': ' + v + ' vs. ' + values[i];"
" };"
" return 'PASSED';"
"})()";
HEAP->ClearJSFunctionResultCaches();
ExpectString(code, "PASSED");
}
THREADED_TEST(TestEviction) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
const char* code =
"(function() {"
" for (var i = 0; i < 2*16; i++) {"
" %_GetFromCache(0, 'a' + i);"
" };"
" return 'PASSED';"
"})()";
HEAP->ClearJSFunctionResultCaches();
ExpectString(code, "PASSED");
}
THREADED_TEST(TwoByteStringInAsciiCons) {
// See Chromium issue 47824.
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
const char* init_code =
"var str1 = 'abelspendabel';"
"var str2 = str1 + str1 + str1;"
"str2;";
Local<Value> result = CompileRun(init_code);
Local<Value> indexof = CompileRun("str2.indexOf('els')");
Local<Value> lastindexof = CompileRun("str2.lastIndexOf('dab')");
CHECK(result->IsString());
i::Handle<i::String> string = v8::Utils::OpenHandle(String::Cast(*result));
int length = string->length();
CHECK(string->IsOneByteRepresentation());
FlattenString(string);
i::Handle<i::String> flat_string = FlattenGetString(string);
CHECK(string->IsOneByteRepresentation());
CHECK(flat_string->IsOneByteRepresentation());
// Create external resource.
uint16_t* uc16_buffer = new uint16_t[length + 1];
i::String::WriteToFlat(*flat_string, uc16_buffer, 0, length);
uc16_buffer[length] = 0;
TestResource resource(uc16_buffer);
flat_string->MakeExternal(&resource);
CHECK(flat_string->IsTwoByteRepresentation());
// If the cons string has been short-circuited, skip the following checks.
if (!string.is_identical_to(flat_string)) {
// At this point, we should have a Cons string which is flat and ASCII,
// with a first half that is a two-byte string (although it only contains
// ASCII characters). This is a valid sequence of steps, and it can happen
// in real pages.
CHECK(string->IsOneByteRepresentation());
i::ConsString* cons = i::ConsString::cast(*string);
CHECK_EQ(0, cons->second()->length());
CHECK(cons->first()->IsTwoByteRepresentation());
}
// Check that some string operations work.
// Atom RegExp.
Local<Value> reresult = CompileRun("str2.match(/abel/g).length;");
CHECK_EQ(6, reresult->Int32Value());
// Nonatom RegExp.
reresult = CompileRun("str2.match(/abe./g).length;");
CHECK_EQ(6, reresult->Int32Value());
reresult = CompileRun("str2.search(/bel/g);");
CHECK_EQ(1, reresult->Int32Value());
reresult = CompileRun("str2.search(/be./g);");
CHECK_EQ(1, reresult->Int32Value());
ExpectTrue("/bel/g.test(str2);");
ExpectTrue("/be./g.test(str2);");
reresult = CompileRun("/bel/g.exec(str2);");
CHECK(!reresult->IsNull());
reresult = CompileRun("/be./g.exec(str2);");
CHECK(!reresult->IsNull());
ExpectString("str2.substring(2, 10);", "elspenda");
ExpectString("str2.substring(2, 20);", "elspendabelabelspe");
ExpectString("str2.charAt(2);", "e");
ExpectObject("str2.indexOf('els');", indexof);
ExpectObject("str2.lastIndexOf('dab');", lastindexof);
reresult = CompileRun("str2.charCodeAt(2);");
CHECK_EQ(static_cast<int32_t>('e'), reresult->Int32Value());
}
TEST(ContainsOnlyOneByte) {
v8::V8::Initialize();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
// Make a buffer long enough that it won't automatically be converted.
const int length = 512;
// Ensure word aligned assignment.
const int aligned_length = length*sizeof(uintptr_t)/sizeof(uint16_t);
i::SmartArrayPointer<uintptr_t>
aligned_contents(new uintptr_t[aligned_length]);
uint16_t* string_contents = reinterpret_cast<uint16_t*>(*aligned_contents);
// Set to contain only one byte.
for (int i = 0; i < length-1; i++) {
string_contents[i] = 0x41;
}
string_contents[length-1] = 0;
// Simple case.
Handle<String> string;
string = String::NewExternal(new TestResource(string_contents));
CHECK(!string->IsOneByte() && string->ContainsOnlyOneByte());
// Counter example.
string = String::NewFromTwoByte(isolate, string_contents);
CHECK(string->IsOneByte() && string->ContainsOnlyOneByte());
// Test left right and balanced cons strings.
Handle<String> base = String::NewFromUtf8(isolate, "a");
Handle<String> left = base;
Handle<String> right = base;
for (int i = 0; i < 1000; i++) {
left = String::Concat(base, left);
right = String::Concat(right, base);
}
Handle<String> balanced = String::Concat(left, base);
balanced = String::Concat(balanced, right);
Handle<String> cons_strings[] = {left, balanced, right};
Handle<String> two_byte =
String::NewExternal(new TestResource(string_contents));
for (size_t i = 0; i < ARRAY_SIZE(cons_strings); i++) {
// Base assumptions.
string = cons_strings[i];
CHECK(string->IsOneByte() && string->ContainsOnlyOneByte());
// Test left and right concatentation.
string = String::Concat(two_byte, cons_strings[i]);
CHECK(!string->IsOneByte() && string->ContainsOnlyOneByte());
string = String::Concat(cons_strings[i], two_byte);
CHECK(!string->IsOneByte() && string->ContainsOnlyOneByte());
}
// Set bits in different positions
// for strings of different lengths and alignments.
for (int alignment = 0; alignment < 7; alignment++) {
for (int size = 2; alignment + size < length; size *= 2) {
int zero_offset = size + alignment;
string_contents[zero_offset] = 0;
for (int i = 0; i < size; i++) {
int shift = 8 + (i % 7);
string_contents[alignment + i] = 1 << shift;
string =
String::NewExternal(new TestResource(string_contents + alignment));
CHECK_EQ(size, string->Length());
CHECK(!string->ContainsOnlyOneByte());
string_contents[alignment + i] = 0x41;
}
string_contents[zero_offset] = 0x41;
}
}
}
// Failed access check callback that performs a GC on each invocation.
void FailedAccessCheckCallbackGC(Local<v8::Object> target,
v8::AccessType type,
Local<v8::Value> data) {
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
}
TEST(GCInFailedAccessCheckCallback) {
// Install a failed access check callback that performs a GC on each
// invocation. Then force the callback to be called from va
v8::V8::Initialize();
v8::V8::SetFailedAccessCheckCallbackFunction(&FailedAccessCheckCallbackGC);
v8::HandleScope scope(v8::Isolate::GetCurrent());
// Create an ObjectTemplate for global objects and install access
// check callbacks that will block access.
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedGetAccessBlocker,
IndexedGetAccessBlocker,
v8::Handle<v8::Value>(),
false);
// Create a context and set an x property on it's global object.
LocalContext context0(NULL, global_template);
context0->Global()->Set(v8_str("x"), v8_num(42));
v8::Handle<v8::Object> global0 = context0->Global();
// Create a context with a different security token so that the
// failed access check callback will be called on each access.
LocalContext context1(NULL, global_template);
context1->Global()->Set(v8_str("other"), global0);
// Get property with failed access check.
ExpectUndefined("other.x");
// Get element with failed access check.
ExpectUndefined("other[0]");
// Set property with failed access check.
v8::Handle<v8::Value> result = CompileRun("other.x = new Object()");
CHECK(result->IsObject());
// Set element with failed access check.
result = CompileRun("other[0] = new Object()");
CHECK(result->IsObject());
// Get property attribute with failed access check.
ExpectFalse("\'x\' in other");
// Get property attribute for element with failed access check.
ExpectFalse("0 in other");
// Delete property.
ExpectFalse("delete other.x");
// Delete element.
CHECK_EQ(false, global0->Delete(0));
// DefineAccessor.
CHECK_EQ(false,
global0->SetAccessor(v8_str("x"), GetXValue, NULL, v8_str("x")));
// Define JavaScript accessor.
ExpectUndefined("Object.prototype.__defineGetter__.call("
" other, \'x\', function() { return 42; })");
// LookupAccessor.
ExpectUndefined("Object.prototype.__lookupGetter__.call("
" other, \'x\')");
// HasLocalElement.
ExpectFalse("Object.prototype.hasOwnProperty.call(other, \'0\')");
CHECK_EQ(false, global0->HasRealIndexedProperty(0));
CHECK_EQ(false, global0->HasRealNamedProperty(v8_str("x")));
CHECK_EQ(false, global0->HasRealNamedCallbackProperty(v8_str("x")));
// Reset the failed access check callback so it does not influence
// the other tests.
v8::V8::SetFailedAccessCheckCallbackFunction(NULL);
}
TEST(DefaultIsolateGetCurrent) {
CHECK(v8::Isolate::GetCurrent() != NULL);
v8::Isolate* isolate = v8::Isolate::GetCurrent();
CHECK(reinterpret_cast<i::Isolate*>(isolate)->IsDefaultIsolate());
printf("*** %s\n", "DefaultIsolateGetCurrent success");
}
TEST(IsolateNewDispose) {
v8::Isolate* current_isolate = v8::Isolate::GetCurrent();
v8::Isolate* isolate = v8::Isolate::New();
CHECK(isolate != NULL);
CHECK(!reinterpret_cast<i::Isolate*>(isolate)->IsDefaultIsolate());
CHECK(current_isolate != isolate);
CHECK(current_isolate == v8::Isolate::GetCurrent());
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
last_location = last_message = NULL;
isolate->Dispose();
CHECK_EQ(last_location, NULL);
CHECK_EQ(last_message, NULL);
}
TEST(IsolateEnterExitDefault) {
v8::Isolate* current_isolate = v8::Isolate::GetCurrent();
CHECK(current_isolate != NULL); // Default isolate.
v8::HandleScope scope(current_isolate);
LocalContext context;
ExpectString("'hello'", "hello");
current_isolate->Enter();
ExpectString("'still working'", "still working");
current_isolate->Exit();
ExpectString("'still working 2'", "still working 2");
current_isolate->Exit();
// Default isolate is always, well, 'default current'.
CHECK_EQ(v8::Isolate::GetCurrent(), current_isolate);
// Still working since default isolate is auto-entering any thread
// that has no isolate and attempts to execute V8 APIs.
ExpectString("'still working 3'", "still working 3");
}
TEST(DisposeDefaultIsolate) {
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
// Run some V8 code to trigger default isolate to become 'current'.
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
ExpectString("'run some V8'", "run some V8");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
CHECK(reinterpret_cast<i::Isolate*>(isolate)->IsDefaultIsolate());
last_location = last_message = NULL;
isolate->Dispose();
// It is not possible to dispose default isolate via Isolate API.
CHECK_NE(last_location, NULL);
CHECK_NE(last_message, NULL);
}
TEST(RunDefaultAndAnotherIsolate) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
LocalContext context;
// Enter new isolate.
v8::Isolate* isolate = v8::Isolate::New();
CHECK(isolate);
isolate->Enter();
{ // Need this block because subsequent Exit() will deallocate Heap,
// so we need all scope objects to be deconstructed when it happens.
v8::HandleScope scope_new(isolate);
LocalContext context_new;
// Run something in new isolate.
CompileRun("var foo = 153;");
ExpectTrue("function f() { return foo == 153; }; f()");
}
isolate->Exit();
// This runs automatically in default isolate.
// Variables in another isolate should be not available.
ExpectTrue("function f() {"
" try {"
" foo;"
" return false;"
" } catch(e) {"
" return true;"
" }"
"};"
"var bar = 371;"
"f()");
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
last_location = last_message = NULL;
isolate->Dispose();
CHECK_EQ(last_location, NULL);
CHECK_EQ(last_message, NULL);
// Check that default isolate still runs.
ExpectTrue("function f() { return bar == 371; }; f()");
}
TEST(DisposeIsolateWhenInUse) {
v8::Isolate* isolate = v8::Isolate::New();
CHECK(isolate);
isolate->Enter();
v8::HandleScope scope(isolate);
LocalContext context;
// Run something in this isolate.
ExpectTrue("true");
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
last_location = last_message = NULL;
// Still entered, should fail.
isolate->Dispose();
CHECK_NE(last_location, NULL);
CHECK_NE(last_message, NULL);
}
TEST(RunTwoIsolatesOnSingleThread) {
// Run isolate 1.
v8::Isolate* isolate1 = v8::Isolate::New();
isolate1->Enter();
v8::Persistent<v8::Context> context1;
{
v8::HandleScope scope(isolate1);
context1.Reset(isolate1, Context::New(isolate1));
}
{
v8::HandleScope scope(isolate1);
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(isolate1, context1);
v8::Context::Scope context_scope(context);
// Run something in new isolate.
CompileRun("var foo = 'isolate 1';");
ExpectString("function f() { return foo; }; f()", "isolate 1");
}
// Run isolate 2.
v8::Isolate* isolate2 = v8::Isolate::New();
v8::Persistent<v8::Context> context2;
{
v8::Isolate::Scope iscope(isolate2);
v8::HandleScope scope(isolate2);
context2.Reset(isolate2, Context::New(isolate2));
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(isolate2, context2);
v8::Context::Scope context_scope(context);
// Run something in new isolate.
CompileRun("var foo = 'isolate 2';");
ExpectString("function f() { return foo; }; f()", "isolate 2");
}
{
v8::HandleScope scope(isolate1);
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(isolate1, context1);
v8::Context::Scope context_scope(context);
// Now again in isolate 1
ExpectString("function f() { return foo; }; f()", "isolate 1");
}
isolate1->Exit();
// Run some stuff in default isolate.
v8::Persistent<v8::Context> context_default;
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Isolate::Scope iscope(isolate);
v8::HandleScope scope(isolate);
context_default.Reset(isolate, Context::New(isolate));
}
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(v8::Isolate::GetCurrent(), context_default);
v8::Context::Scope context_scope(context);
// Variables in other isolates should be not available, verify there
// is an exception.
ExpectTrue("function f() {"
" try {"
" foo;"
" return false;"
" } catch(e) {"
" return true;"
" }"
"};"
"var isDefaultIsolate = true;"
"f()");
}
isolate1->Enter();
{
v8::Isolate::Scope iscope(isolate2);
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(isolate2, context2);
v8::Context::Scope context_scope(context);
ExpectString("function f() { return foo; }; f()", "isolate 2");
}
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(v8::Isolate::GetCurrent(), context1);
v8::Context::Scope context_scope(context);
ExpectString("function f() { return foo; }; f()", "isolate 1");
}
{
v8::Isolate::Scope iscope(isolate2);
context2.Dispose();
}
context1.Dispose();
isolate1->Exit();
v8::V8::SetFatalErrorHandler(StoringErrorCallback);
last_location = last_message = NULL;
isolate1->Dispose();
CHECK_EQ(last_location, NULL);
CHECK_EQ(last_message, NULL);
isolate2->Dispose();
CHECK_EQ(last_location, NULL);
CHECK_EQ(last_message, NULL);
// Check that default isolate still runs.
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Local<v8::Context> context =
v8::Local<v8::Context>::New(v8::Isolate::GetCurrent(), context_default);
v8::Context::Scope context_scope(context);
ExpectTrue("function f() { return isDefaultIsolate; }; f()");
}
}
static int CalcFibonacci(v8::Isolate* isolate, int limit) {
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope scope(isolate);
LocalContext context;
i::ScopedVector<char> code(1024);
i::OS::SNPrintF(code, "function fib(n) {"
" if (n <= 2) return 1;"
" return fib(n-1) + fib(n-2);"
"}"
"fib(%d)", limit);
Local<Value> value = CompileRun(code.start());
CHECK(value->IsNumber());
return static_cast<int>(value->NumberValue());
}
class IsolateThread : public v8::internal::Thread {
public:
IsolateThread(v8::Isolate* isolate, int fib_limit)
: Thread("IsolateThread"),
isolate_(isolate),
fib_limit_(fib_limit),
result_(0) { }
void Run() {
result_ = CalcFibonacci(isolate_, fib_limit_);
}
int result() { return result_; }
private:
v8::Isolate* isolate_;
int fib_limit_;
int result_;
};
TEST(MultipleIsolatesOnIndividualThreads) {
v8::Isolate* isolate1 = v8::Isolate::New();
v8::Isolate* isolate2 = v8::Isolate::New();
IsolateThread thread1(isolate1, 21);
IsolateThread thread2(isolate2, 12);
// Compute some fibonacci numbers on 3 threads in 3 isolates.
thread1.Start();
thread2.Start();
int result1 = CalcFibonacci(v8::Isolate::GetCurrent(), 21);
int result2 = CalcFibonacci(v8::Isolate::GetCurrent(), 12);
thread1.Join();
thread2.Join();
// Compare results. The actual fibonacci numbers for 12 and 21 are taken
// (I'm lazy!) from http://en.wikipedia.org/wiki/Fibonacci_number
CHECK_EQ(result1, 10946);
CHECK_EQ(result2, 144);
CHECK_EQ(result1, thread1.result());
CHECK_EQ(result2, thread2.result());
isolate1->Dispose();
isolate2->Dispose();
}
TEST(IsolateDifferentContexts) {
v8::Isolate* isolate = v8::Isolate::New();
Local<v8::Context> context;
{
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
Local<Value> v = CompileRun("2");
CHECK(v->IsNumber());
CHECK_EQ(2, static_cast<int>(v->NumberValue()));
}
{
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
context = v8::Context::New(isolate);
v8::Context::Scope context_scope(context);
Local<Value> v = CompileRun("22");
CHECK(v->IsNumber());
CHECK_EQ(22, static_cast<int>(v->NumberValue()));
}
}
class InitDefaultIsolateThread : public v8::internal::Thread {
public:
enum TestCase {
IgnoreOOM,
SetResourceConstraints,
SetFatalHandler,
SetCounterFunction,
SetCreateHistogramFunction,
SetAddHistogramSampleFunction
};
explicit InitDefaultIsolateThread(TestCase testCase)
: Thread("InitDefaultIsolateThread"),
testCase_(testCase),
result_(false) { }
void Run() {
switch (testCase_) {
case IgnoreOOM:
v8::V8::IgnoreOutOfMemoryException();
break;
case SetResourceConstraints: {
static const int K = 1024;
v8::ResourceConstraints constraints;
constraints.set_max_young_space_size(256 * K);
constraints.set_max_old_space_size(4 * K * K);
v8::SetResourceConstraints(&constraints);
break;
}
case SetFatalHandler:
v8::V8::SetFatalErrorHandler(NULL);
break;
case SetCounterFunction:
v8::V8::SetCounterFunction(NULL);
break;
case SetCreateHistogramFunction:
v8::V8::SetCreateHistogramFunction(NULL);
break;
case SetAddHistogramSampleFunction:
v8::V8::SetAddHistogramSampleFunction(NULL);
break;
}
result_ = true;
}
bool result() { return result_; }
private:
TestCase testCase_;
bool result_;
};
static void InitializeTestHelper(InitDefaultIsolateThread::TestCase testCase) {
InitDefaultIsolateThread thread(testCase);
thread.Start();
thread.Join();
CHECK_EQ(thread.result(), true);
}
TEST(InitializeDefaultIsolateOnSecondaryThread1) {
InitializeTestHelper(InitDefaultIsolateThread::IgnoreOOM);
}
TEST(InitializeDefaultIsolateOnSecondaryThread2) {
InitializeTestHelper(InitDefaultIsolateThread::SetResourceConstraints);
}
TEST(InitializeDefaultIsolateOnSecondaryThread3) {
InitializeTestHelper(InitDefaultIsolateThread::SetFatalHandler);
}
TEST(InitializeDefaultIsolateOnSecondaryThread4) {
InitializeTestHelper(InitDefaultIsolateThread::SetCounterFunction);
}
TEST(InitializeDefaultIsolateOnSecondaryThread5) {
InitializeTestHelper(InitDefaultIsolateThread::SetCreateHistogramFunction);
}
TEST(InitializeDefaultIsolateOnSecondaryThread6) {
InitializeTestHelper(InitDefaultIsolateThread::SetAddHistogramSampleFunction);
}
TEST(StringCheckMultipleContexts) {
const char* code =
"(function() { return \"a\".charAt(0); })()";
{
// Run the code twice in the first context to initialize the call IC.
LocalContext context1;
v8::HandleScope scope(context1->GetIsolate());
ExpectString(code, "a");
ExpectString(code, "a");
}
{
// Change the String.prototype in the second context and check
// that the right function gets called.
LocalContext context2;
v8::HandleScope scope(context2->GetIsolate());
CompileRun("String.prototype.charAt = function() { return \"not a\"; }");
ExpectString(code, "not a");
}
}
TEST(NumberCheckMultipleContexts) {
const char* code =
"(function() { return (42).toString(); })()";
{
// Run the code twice in the first context to initialize the call IC.
LocalContext context1;
v8::HandleScope scope(context1->GetIsolate());
ExpectString(code, "42");
ExpectString(code, "42");
}
{
// Change the Number.prototype in the second context and check
// that the right function gets called.
LocalContext context2;
v8::HandleScope scope(context2->GetIsolate());
CompileRun("Number.prototype.toString = function() { return \"not 42\"; }");
ExpectString(code, "not 42");
}
}
TEST(BooleanCheckMultipleContexts) {
const char* code =
"(function() { return true.toString(); })()";
{
// Run the code twice in the first context to initialize the call IC.
LocalContext context1;
v8::HandleScope scope(context1->GetIsolate());
ExpectString(code, "true");
ExpectString(code, "true");
}
{
// Change the Boolean.prototype in the second context and check
// that the right function gets called.
LocalContext context2;
v8::HandleScope scope(context2->GetIsolate());
CompileRun("Boolean.prototype.toString = function() { return \"\"; }");
ExpectString(code, "");
}
}
TEST(DontDeleteCellLoadIC) {
const char* function_code =
"function readCell() { while (true) { return cell; } }";
{
// Run the code twice in the first context to initialize the load
// IC for a don't delete cell.
LocalContext context1;
v8::HandleScope scope(context1->GetIsolate());
CompileRun("var cell = \"first\";");
ExpectBoolean("delete cell", false);
CompileRun(function_code);
ExpectString("readCell()", "first");
ExpectString("readCell()", "first");
}
{
// Use a deletable cell in the second context.
LocalContext context2;
v8::HandleScope scope(context2->GetIsolate());
CompileRun("cell = \"second\";");
CompileRun(function_code);
ExpectString("readCell()", "second");
ExpectBoolean("delete cell", true);
ExpectString("(function() {"
" try {"
" return readCell();"
" } catch(e) {"
" return e.toString();"
" }"
"})()",
"ReferenceError: cell is not defined");
CompileRun("cell = \"new_second\";");
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
ExpectString("readCell()", "new_second");
ExpectString("readCell()", "new_second");
}
}
TEST(DontDeleteCellLoadICForceDelete) {
const char* function_code =
"function readCell() { while (true) { return cell; } }";
// Run the code twice to initialize the load IC for a don't delete
// cell.
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
CompileRun("var cell = \"value\";");
ExpectBoolean("delete cell", false);
CompileRun(function_code);
ExpectString("readCell()", "value");
ExpectString("readCell()", "value");
// Delete the cell using the API and check the inlined code works
// correctly.
CHECK(context->Global()->ForceDelete(v8_str("cell")));
ExpectString("(function() {"
" try {"
" return readCell();"
" } catch(e) {"
" return e.toString();"
" }"
"})()",
"ReferenceError: cell is not defined");
}
TEST(DontDeleteCellLoadICAPI) {
const char* function_code =
"function readCell() { while (true) { return cell; } }";
// Run the code twice to initialize the load IC for a don't delete
// cell created using the API.
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
context->Global()->Set(v8_str("cell"), v8_str("value"), v8::DontDelete);
ExpectBoolean("delete cell", false);
CompileRun(function_code);
ExpectString("readCell()", "value");
ExpectString("readCell()", "value");
// Delete the cell using the API and check the inlined code works
// correctly.
CHECK(context->Global()->ForceDelete(v8_str("cell")));
ExpectString("(function() {"
" try {"
" return readCell();"
" } catch(e) {"
" return e.toString();"
" }"
"})()",
"ReferenceError: cell is not defined");
}
class Visitor42 : public v8::PersistentHandleVisitor {
public:
explicit Visitor42(v8::Persistent<v8::Object>* object)
: counter_(0), object_(object) { }
virtual void VisitPersistentHandle(Persistent<Value>* value,
uint16_t class_id) {
if (class_id != 42) return;
CHECK_EQ(42, value->WrapperClassId());
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::Value> handle = v8::Local<v8::Value>::New(isolate, *value);
v8::Handle<v8::Value> object =
v8::Local<v8::Object>::New(isolate, *object_);
CHECK(handle->IsObject());
CHECK_EQ(Handle<Object>::Cast(handle), object);
++counter_;
}
int counter_;
v8::Persistent<v8::Object>* object_;
};
TEST(PersistentHandleVisitor) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope scope(isolate);
v8::Persistent<v8::Object> object(isolate, v8::Object::New());
CHECK_EQ(0, object.WrapperClassId(isolate));
object.SetWrapperClassId(isolate, 42);
CHECK_EQ(42, object.WrapperClassId(isolate));
Visitor42 visitor(&object);
v8::V8::VisitHandlesWithClassIds(&visitor);
CHECK_EQ(1, visitor.counter_);
object.Dispose(isolate);
}
TEST(WrapperClassId) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope scope(isolate);
v8::Persistent<v8::Object> object(isolate, v8::Object::New());
CHECK_EQ(0, object.WrapperClassId(isolate));
object.SetWrapperClassId(isolate, 65535);
CHECK_EQ(65535, object.WrapperClassId(isolate));
object.Dispose(isolate);
}
TEST(PersistentHandleInNewSpaceVisitor) {
LocalContext context;
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope scope(isolate);
v8::Persistent<v8::Object> object1(isolate, v8::Object::New());
CHECK_EQ(0, object1.WrapperClassId(isolate));
object1.SetWrapperClassId(isolate, 42);
CHECK_EQ(42, object1.WrapperClassId(isolate));
HEAP->CollectAllGarbage(i::Heap::kNoGCFlags);
v8::Persistent<v8::Object> object2(isolate, v8::Object::New());
CHECK_EQ(0, object2.WrapperClassId(isolate));
object2.SetWrapperClassId(isolate, 42);
CHECK_EQ(42, object2.WrapperClassId(isolate));
Visitor42 visitor(&object2);
v8::V8::VisitHandlesForPartialDependence(isolate, &visitor);
CHECK_EQ(1, visitor.counter_);
object1.Dispose(isolate);
object2.Dispose(isolate);
}
TEST(RegExp) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::RegExp> re = v8::RegExp::New(v8_str("foo"), v8::RegExp::kNone);
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("foo")));
CHECK_EQ(v8::RegExp::kNone, re->GetFlags());
re = v8::RegExp::New(v8_str("bar"),
static_cast<v8::RegExp::Flags>(v8::RegExp::kIgnoreCase |
v8::RegExp::kGlobal));
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("bar")));
CHECK_EQ(v8::RegExp::kIgnoreCase | v8::RegExp::kGlobal,
static_cast<int>(re->GetFlags()));
re = v8::RegExp::New(v8_str("baz"),
static_cast<v8::RegExp::Flags>(v8::RegExp::kIgnoreCase |
v8::RegExp::kMultiline));
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("baz")));
CHECK_EQ(v8::RegExp::kIgnoreCase | v8::RegExp::kMultiline,
static_cast<int>(re->GetFlags()));
re = CompileRun("/quux/").As<v8::RegExp>();
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("quux")));
CHECK_EQ(v8::RegExp::kNone, re->GetFlags());
re = CompileRun("/quux/gm").As<v8::RegExp>();
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("quux")));
CHECK_EQ(v8::RegExp::kGlobal | v8::RegExp::kMultiline,
static_cast<int>(re->GetFlags()));
// Override the RegExp constructor and check the API constructor
// still works.
CompileRun("RegExp = function() {}");
re = v8::RegExp::New(v8_str("foobar"), v8::RegExp::kNone);
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("foobar")));
CHECK_EQ(v8::RegExp::kNone, re->GetFlags());
re = v8::RegExp::New(v8_str("foobarbaz"),
static_cast<v8::RegExp::Flags>(v8::RegExp::kIgnoreCase |
v8::RegExp::kMultiline));
CHECK(re->IsRegExp());
CHECK(re->GetSource()->Equals(v8_str("foobarbaz")));
CHECK_EQ(v8::RegExp::kIgnoreCase | v8::RegExp::kMultiline,
static_cast<int>(re->GetFlags()));
context->Global()->Set(v8_str("re"), re);
ExpectTrue("re.test('FoobarbaZ')");
// RegExps are objects on which you can set properties.
re->Set(v8_str("property"), v8::Integer::New(32));
v8::Handle<v8::Value> value(CompileRun("re.property"));
CHECK_EQ(32, value->Int32Value());
v8::TryCatch try_catch;
re = v8::RegExp::New(v8_str("foo["), v8::RegExp::kNone);
CHECK(re.IsEmpty());
CHECK(try_catch.HasCaught());
context->Global()->Set(v8_str("ex"), try_catch.Exception());
ExpectTrue("ex instanceof SyntaxError");
}
THREADED_TEST(Equals) {
LocalContext localContext;
v8::HandleScope handleScope(localContext->GetIsolate());
v8::Handle<v8::Object> globalProxy = localContext->Global();
v8::Handle<Value> global = globalProxy->GetPrototype();
CHECK(global->StrictEquals(global));
CHECK(!global->StrictEquals(globalProxy));
CHECK(!globalProxy->StrictEquals(global));
CHECK(globalProxy->StrictEquals(globalProxy));
CHECK(global->Equals(global));
CHECK(!global->Equals(globalProxy));
CHECK(!globalProxy->Equals(global));
CHECK(globalProxy->Equals(globalProxy));
}
static void Getter(v8::Local<v8::String> property,
const v8::PropertyCallbackInfo<v8::Value>& info ) {
info.GetReturnValue().Set(v8_str("42!"));
}
static void Enumerator(const v8::PropertyCallbackInfo<v8::Array>& info) {
v8::Handle<v8::Array> result = v8::Array::New();
result->Set(0, v8_str("universalAnswer"));
info.GetReturnValue().Set(result);
}
TEST(NamedEnumeratorAndForIn) {
LocalContext context;
v8::HandleScope handle_scope(context->GetIsolate());
v8::Context::Scope context_scope(context.local());
v8::Handle<v8::ObjectTemplate> tmpl = v8::ObjectTemplate::New();
tmpl->SetNamedPropertyHandler(Getter, NULL, NULL, NULL, Enumerator);
context->Global()->Set(v8_str("o"), tmpl->NewInstance());
v8::Handle<v8::Array> result = v8::Handle<v8::Array>::Cast(CompileRun(
"var result = []; for (var k in o) result.push(k); result"));
CHECK_EQ(1, result->Length());
CHECK_EQ(v8_str("universalAnswer"), result->Get(0));
}
TEST(DefinePropertyPostDetach) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
v8::Handle<v8::Object> proxy = context->Global();
v8::Handle<v8::Function> define_property =
CompileRun("(function() {"
" Object.defineProperty("
" this,"
" 1,"
" { configurable: true, enumerable: true, value: 3 });"
"})").As<Function>();
context->DetachGlobal();
define_property->Call(proxy, 0, NULL);
}
static void InstallContextId(v8::Handle<Context> context, int id) {
Context::Scope scope(context);
CompileRun("Object.prototype").As<Object>()->
Set(v8_str("context_id"), v8::Integer::New(id));
}
static void CheckContextId(v8::Handle<Object> object, int expected) {
CHECK_EQ(expected, object->Get(v8_str("context_id"))->Int32Value());
}
THREADED_TEST(CreationContext) {
HandleScope handle_scope(v8::Isolate::GetCurrent());
Handle<Context> context1 = Context::New(v8::Isolate::GetCurrent());
InstallContextId(context1, 1);
Handle<Context> context2 = Context::New(v8::Isolate::GetCurrent());
InstallContextId(context2, 2);
Handle<Context> context3 = Context::New(v8::Isolate::GetCurrent());
InstallContextId(context3, 3);
Local<v8::FunctionTemplate> tmpl = v8::FunctionTemplate::New();
Local<Object> object1;
Local<Function> func1;
{
Context::Scope scope(context1);
object1 = Object::New();
func1 = tmpl->GetFunction();
}
Local<Object> object2;
Local<Function> func2;
{
Context::Scope scope(context2);
object2 = Object::New();
func2 = tmpl->GetFunction();
}
Local<Object> instance1;
Local<Object> instance2;
{
Context::Scope scope(context3);
instance1 = func1->NewInstance();
instance2 = func2->NewInstance();
}
CHECK(object1->CreationContext() == context1);
CheckContextId(object1, 1);
CHECK(func1->CreationContext() == context1);
CheckContextId(func1, 1);
CHECK(instance1->CreationContext() == context1);
CheckContextId(instance1, 1);
CHECK(object2->CreationContext() == context2);
CheckContextId(object2, 2);
CHECK(func2->CreationContext() == context2);
CheckContextId(func2, 2);
CHECK(instance2->CreationContext() == context2);
CheckContextId(instance2, 2);
{
Context::Scope scope(context1);
CHECK(object1->CreationContext() == context1);
CheckContextId(object1, 1);
CHECK(func1->CreationContext() == context1);
CheckContextId(func1, 1);
CHECK(instance1->CreationContext() == context1);
CheckContextId(instance1, 1);
CHECK(object2->CreationContext() == context2);
CheckContextId(object2, 2);
CHECK(func2->CreationContext() == context2);
CheckContextId(func2, 2);
CHECK(instance2->CreationContext() == context2);
CheckContextId(instance2, 2);
}
{
Context::Scope scope(context2);
CHECK(object1->CreationContext() == context1);
CheckContextId(object1, 1);
CHECK(func1->CreationContext() == context1);
CheckContextId(func1, 1);
CHECK(instance1->CreationContext() == context1);
CheckContextId(instance1, 1);
CHECK(object2->CreationContext() == context2);
CheckContextId(object2, 2);
CHECK(func2->CreationContext() == context2);
CheckContextId(func2, 2);
CHECK(instance2->CreationContext() == context2);
CheckContextId(instance2, 2);
}
}
THREADED_TEST(CreationContextOfJsFunction) {
HandleScope handle_scope(v8::Isolate::GetCurrent());
Handle<Context> context = Context::New(v8::Isolate::GetCurrent());
InstallContextId(context, 1);
Local<Object> function;
{
Context::Scope scope(context);
function = CompileRun("function foo() {}; foo").As<Object>();
}
CHECK(function->CreationContext() == context);
CheckContextId(function, 1);
}
void HasOwnPropertyIndexedPropertyGetter(
uint32_t index,
const v8::PropertyCallbackInfo<v8::Value>& info) {
if (index == 42) info.GetReturnValue().Set(v8_str("yes"));
}
void HasOwnPropertyNamedPropertyGetter(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
if (property->Equals(v8_str("foo"))) info.GetReturnValue().Set(v8_str("yes"));
}
void HasOwnPropertyIndexedPropertyQuery(
uint32_t index, const v8::PropertyCallbackInfo<v8::Integer>& info) {
if (index == 42) info.GetReturnValue().Set(1);
}
void HasOwnPropertyNamedPropertyQuery(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Integer>& info) {
if (property->Equals(v8_str("foo"))) info.GetReturnValue().Set(1);
}
void HasOwnPropertyNamedPropertyQuery2(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Integer>& info) {
if (property->Equals(v8_str("bar"))) info.GetReturnValue().Set(1);
}
void HasOwnPropertyAccessorGetter(
Local<String> property,
const v8::PropertyCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(v8_str("yes"));
}
TEST(HasOwnProperty) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
{ // Check normal properties and defined getters.
Handle<Value> value = CompileRun(
"function Foo() {"
" this.foo = 11;"
" this.__defineGetter__('baz', function() { return 1; });"
"};"
"function Bar() { "
" this.bar = 13;"
" this.__defineGetter__('bla', function() { return 2; });"
"};"
"Bar.prototype = new Foo();"
"new Bar();");
CHECK(value->IsObject());
Handle<Object> object = value->ToObject();
CHECK(object->Has(v8_str("foo")));
CHECK(!object->HasOwnProperty(v8_str("foo")));
CHECK(object->HasOwnProperty(v8_str("bar")));
CHECK(object->Has(v8_str("baz")));
CHECK(!object->HasOwnProperty(v8_str("baz")));
CHECK(object->HasOwnProperty(v8_str("bla")));
}
{ // Check named getter interceptors.
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(HasOwnPropertyNamedPropertyGetter);
Handle<Object> instance = templ->NewInstance();
CHECK(!instance->HasOwnProperty(v8_str("42")));
CHECK(instance->HasOwnProperty(v8_str("foo")));
CHECK(!instance->HasOwnProperty(v8_str("bar")));
}
{ // Check indexed getter interceptors.
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(HasOwnPropertyIndexedPropertyGetter);
Handle<Object> instance = templ->NewInstance();
CHECK(instance->HasOwnProperty(v8_str("42")));
CHECK(!instance->HasOwnProperty(v8_str("43")));
CHECK(!instance->HasOwnProperty(v8_str("foo")));
}
{ // Check named query interceptors.
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(0, 0, HasOwnPropertyNamedPropertyQuery);
Handle<Object> instance = templ->NewInstance();
CHECK(instance->HasOwnProperty(v8_str("foo")));
CHECK(!instance->HasOwnProperty(v8_str("bar")));
}
{ // Check indexed query interceptors.
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(0, 0, HasOwnPropertyIndexedPropertyQuery);
Handle<Object> instance = templ->NewInstance();
CHECK(instance->HasOwnProperty(v8_str("42")));
CHECK(!instance->HasOwnProperty(v8_str("41")));
}
{ // Check callbacks.
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("foo"), HasOwnPropertyAccessorGetter);
Handle<Object> instance = templ->NewInstance();
CHECK(instance->HasOwnProperty(v8_str("foo")));
CHECK(!instance->HasOwnProperty(v8_str("bar")));
}
{ // Check that query wins on disagreement.
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetNamedPropertyHandler(HasOwnPropertyNamedPropertyGetter,
0,
HasOwnPropertyNamedPropertyQuery2);
Handle<Object> instance = templ->NewInstance();
CHECK(!instance->HasOwnProperty(v8_str("foo")));
CHECK(instance->HasOwnProperty(v8_str("bar")));
}
}
TEST(IndexedInterceptorWithStringProto) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetIndexedPropertyHandler(NULL,
NULL,
HasOwnPropertyIndexedPropertyQuery);
LocalContext context;
context->Global()->Set(v8_str("obj"), templ->NewInstance());
CompileRun("var s = new String('foobar'); obj.__proto__ = s;");
// These should be intercepted.
CHECK(CompileRun("42 in obj")->BooleanValue());
CHECK(CompileRun("'42' in obj")->BooleanValue());
// These should fall through to the String prototype.
CHECK(CompileRun("0 in obj")->BooleanValue());
CHECK(CompileRun("'0' in obj")->BooleanValue());
// And these should both fail.
CHECK(!CompileRun("32 in obj")->BooleanValue());
CHECK(!CompileRun("'32' in obj")->BooleanValue());
}
void CheckCodeGenerationAllowed() {
Handle<Value> result = CompileRun("eval('42')");
CHECK_EQ(42, result->Int32Value());
result = CompileRun("(function(e) { return e('42'); })(eval)");
CHECK_EQ(42, result->Int32Value());
result = CompileRun("var f = new Function('return 42'); f()");
CHECK_EQ(42, result->Int32Value());
}
void CheckCodeGenerationDisallowed() {
TryCatch try_catch;
Handle<Value> result = CompileRun("eval('42')");
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
try_catch.Reset();
result = CompileRun("(function(e) { return e('42'); })(eval)");
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
try_catch.Reset();
result = CompileRun("var f = new Function('return 42'); f()");
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
}
bool CodeGenerationAllowed(Local<Context> context) {
ApiTestFuzzer::Fuzz();
return true;
}
bool CodeGenerationDisallowed(Local<Context> context) {
ApiTestFuzzer::Fuzz();
return false;
}
THREADED_TEST(AllowCodeGenFromStrings) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// eval and the Function constructor allowed by default.
CHECK(context->IsCodeGenerationFromStringsAllowed());
CheckCodeGenerationAllowed();
// Disallow eval and the Function constructor.
context->AllowCodeGenerationFromStrings(false);
CHECK(!context->IsCodeGenerationFromStringsAllowed());
CheckCodeGenerationDisallowed();
// Allow again.
context->AllowCodeGenerationFromStrings(true);
CheckCodeGenerationAllowed();
// Disallow but setting a global callback that will allow the calls.
context->AllowCodeGenerationFromStrings(false);
V8::SetAllowCodeGenerationFromStringsCallback(&CodeGenerationAllowed);
CHECK(!context->IsCodeGenerationFromStringsAllowed());
CheckCodeGenerationAllowed();
// Set a callback that disallows the code generation.
V8::SetAllowCodeGenerationFromStringsCallback(&CodeGenerationDisallowed);
CHECK(!context->IsCodeGenerationFromStringsAllowed());
CheckCodeGenerationDisallowed();
}
TEST(SetErrorMessageForCodeGenFromStrings) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
TryCatch try_catch;
Handle<String> message = v8_str("Message") ;
Handle<String> expected_message = v8_str("Uncaught EvalError: Message");
V8::SetAllowCodeGenerationFromStringsCallback(&CodeGenerationDisallowed);
context->AllowCodeGenerationFromStrings(false);
context->SetErrorMessageForCodeGenerationFromStrings(message);
Handle<Value> result = CompileRun("eval('42')");
CHECK(result.IsEmpty());
CHECK(try_catch.HasCaught());
Handle<String> actual_message = try_catch.Message()->Get();
CHECK(expected_message->Equals(actual_message));
}
static void NonObjectThis(const v8::FunctionCallbackInfo<v8::Value>& args) {
}
THREADED_TEST(CallAPIFunctionOnNonObject) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Handle<FunctionTemplate> templ = v8::FunctionTemplate::New(NonObjectThis);
Handle<Function> function = templ->GetFunction();
context->Global()->Set(v8_str("f"), function);
TryCatch try_catch;
CompileRun("f.call(2)");
}
// Regression test for issue 1470.
THREADED_TEST(ReadOnlyIndexedProperties) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Local<ObjectTemplate> templ = ObjectTemplate::New();
LocalContext context;
Local<v8::Object> obj = templ->NewInstance();
context->Global()->Set(v8_str("obj"), obj);
obj->Set(v8_str("1"), v8_str("DONT_CHANGE"), v8::ReadOnly);
obj->Set(v8_str("1"), v8_str("foobar"));
CHECK_EQ(v8_str("DONT_CHANGE"), obj->Get(v8_str("1")));
obj->Set(v8_num(2), v8_str("DONT_CHANGE"), v8::ReadOnly);
obj->Set(v8_num(2), v8_str("foobar"));
CHECK_EQ(v8_str("DONT_CHANGE"), obj->Get(v8_num(2)));
// Test non-smi case.
obj->Set(v8_str("2000000000"), v8_str("DONT_CHANGE"), v8::ReadOnly);
obj->Set(v8_str("2000000000"), v8_str("foobar"));
CHECK_EQ(v8_str("DONT_CHANGE"), obj->Get(v8_str("2000000000")));
}
THREADED_TEST(Regress1516) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
{ v8::HandleScope temp_scope(context->GetIsolate());
CompileRun("({'a': 0})");
}
int elements;
{ i::MapCache* map_cache =
i::MapCache::cast(i::Isolate::Current()->context()->map_cache());
elements = map_cache->NumberOfElements();
CHECK_LE(1, elements);
}
i::Isolate::Current()->heap()->CollectAllGarbage(
i::Heap::kAbortIncrementalMarkingMask);
{ i::Object* raw_map_cache = i::Isolate::Current()->context()->map_cache();
if (raw_map_cache != i::Isolate::Current()->heap()->undefined_value()) {
i::MapCache* map_cache = i::MapCache::cast(raw_map_cache);
CHECK_GT(elements, map_cache->NumberOfElements());
}
}
}
static bool BlockProtoNamedSecurityTestCallback(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
// Only block read access to __proto__.
if (type == v8::ACCESS_GET &&
name->IsString() &&
name->ToString()->Length() == 9 &&
name->ToString()->Utf8Length() == 9) {
char buffer[10];
CHECK_EQ(10, name->ToString()->WriteUtf8(buffer));
return strncmp(buffer, "__proto__", 9) != 0;
}
return true;
}
THREADED_TEST(Regress93759) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
HandleScope scope(isolate);
// Template for object with security check.
Local<ObjectTemplate> no_proto_template = v8::ObjectTemplate::New();
// We don't do indexing, so any callback can be used for that.
no_proto_template->SetAccessCheckCallbacks(
BlockProtoNamedSecurityTestCallback,
IndexedSecurityTestCallback);
// Templates for objects with hidden prototypes and possibly security check.
Local<FunctionTemplate> hidden_proto_template = v8::FunctionTemplate::New();
hidden_proto_template->SetHiddenPrototype(true);
Local<FunctionTemplate> protected_hidden_proto_template =
v8::FunctionTemplate::New();
protected_hidden_proto_template->InstanceTemplate()->SetAccessCheckCallbacks(
BlockProtoNamedSecurityTestCallback,
IndexedSecurityTestCallback);
protected_hidden_proto_template->SetHiddenPrototype(true);
// Context for "foreign" objects used in test.
Local<Context> context = v8::Context::New(isolate);
context->Enter();
// Plain object, no security check.
Local<Object> simple_object = Object::New();
// Object with explicit security check.
Local<Object> protected_object =
no_proto_template->NewInstance();
// JSGlobalProxy object, always have security check.
Local<Object> proxy_object =
context->Global();
// Global object, the prototype of proxy_object. No security checks.
Local<Object> global_object =
proxy_object->GetPrototype()->ToObject();
// Hidden prototype without security check.
Local<Object> hidden_prototype =
hidden_proto_template->GetFunction()->NewInstance();
Local<Object> object_with_hidden =
Object::New();
object_with_hidden->SetPrototype(hidden_prototype);
// Hidden prototype with security check on the hidden prototype.
Local<Object> protected_hidden_prototype =
protected_hidden_proto_template->GetFunction()->NewInstance();
Local<Object> object_with_protected_hidden =
Object::New();
object_with_protected_hidden->SetPrototype(protected_hidden_prototype);
context->Exit();
// Template for object for second context. Values to test are put on it as
// properties.
Local<ObjectTemplate> global_template = ObjectTemplate::New();
global_template->Set(v8_str("simple"), simple_object);
global_template->Set(v8_str("protected"), protected_object);
global_template->Set(v8_str("global"), global_object);
global_template->Set(v8_str("proxy"), proxy_object);
global_template->Set(v8_str("hidden"), object_with_hidden);
global_template->Set(v8_str("phidden"), object_with_protected_hidden);
LocalContext context2(NULL, global_template);
Local<Value> result1 = CompileRun("Object.getPrototypeOf(simple)");
CHECK(result1->Equals(simple_object->GetPrototype()));
Local<Value> result2 = CompileRun("Object.getPrototypeOf(protected)");
CHECK(result2->Equals(Undefined()));
Local<Value> result3 = CompileRun("Object.getPrototypeOf(global)");
CHECK(result3->Equals(global_object->GetPrototype()));
Local<Value> result4 = CompileRun("Object.getPrototypeOf(proxy)");
CHECK(result4->Equals(Undefined()));
Local<Value> result5 = CompileRun("Object.getPrototypeOf(hidden)");
CHECK(result5->Equals(
object_with_hidden->GetPrototype()->ToObject()->GetPrototype()));
Local<Value> result6 = CompileRun("Object.getPrototypeOf(phidden)");
CHECK(result6->Equals(Undefined()));
}
THREADED_TEST(Regress125988) {
v8::HandleScope scope(v8::Isolate::GetCurrent());
Handle<FunctionTemplate> intercept = FunctionTemplate::New();
AddInterceptor(intercept, EmptyInterceptorGetter, EmptyInterceptorSetter);
LocalContext env;
env->Global()->Set(v8_str("Intercept"), intercept->GetFunction());
CompileRun("var a = new Object();"
"var b = new Intercept();"
"var c = new Object();"
"c.__proto__ = b;"
"b.__proto__ = a;"
"a.x = 23;"
"for (var i = 0; i < 3; i++) c.x;");
ExpectBoolean("c.hasOwnProperty('x')", false);
ExpectInt32("c.x", 23);
CompileRun("a.y = 42;"
"for (var i = 0; i < 3; i++) c.x;");
ExpectBoolean("c.hasOwnProperty('x')", false);
ExpectInt32("c.x", 23);
ExpectBoolean("c.hasOwnProperty('y')", false);
ExpectInt32("c.y", 42);
}
static void TestReceiver(Local<Value> expected_result,
Local<Value> expected_receiver,
const char* code) {
Local<Value> result = CompileRun(code);
CHECK(result->IsObject());
CHECK(expected_receiver->Equals(result->ToObject()->Get(1)));
CHECK(expected_result->Equals(result->ToObject()->Get(0)));
}
THREADED_TEST(ForeignFunctionReceiver) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
HandleScope scope(isolate);
// Create two contexts with different "id" properties ('i' and 'o').
// Call a function both from its own context and from a the foreign
// context, and see what "this" is bound to (returning both "this"
// and "this.id" for comparison).
Local<Context> foreign_context = v8::Context::New(isolate);
foreign_context->Enter();
Local<Value> foreign_function =
CompileRun("function func() { return { 0: this.id, "
" 1: this, "
" toString: function() { "
" return this[0];"
" }"
" };"
"}"
"var id = 'i';"
"func;");
CHECK(foreign_function->IsFunction());
foreign_context->Exit();
LocalContext context;
Local<String> password = v8_str("Password");
// Don't get hit by security checks when accessing foreign_context's
// global receiver (aka. global proxy).
context->SetSecurityToken(password);
foreign_context->SetSecurityToken(password);
Local<String> i = v8_str("i");
Local<String> o = v8_str("o");
Local<String> id = v8_str("id");
CompileRun("function ownfunc() { return { 0: this.id, "
" 1: this, "
" toString: function() { "
" return this[0];"
" }"
" };"
"}"
"var id = 'o';"
"ownfunc");
context->Global()->Set(v8_str("func"), foreign_function);
// Sanity check the contexts.
CHECK(i->Equals(foreign_context->Global()->Get(id)));
CHECK(o->Equals(context->Global()->Get(id)));
// Checking local function's receiver.
// Calling function using its call/apply methods.
TestReceiver(o, context->Global(), "ownfunc.call()");
TestReceiver(o, context->Global(), "ownfunc.apply()");
// Making calls through built-in functions.
TestReceiver(o, context->Global(), "[1].map(ownfunc)[0]");
CHECK(o->Equals(CompileRun("'abcbd'.replace(/b/,ownfunc)[1]")));
CHECK(o->Equals(CompileRun("'abcbd'.replace(/b/g,ownfunc)[1]")));
CHECK(o->Equals(CompileRun("'abcbd'.replace(/b/g,ownfunc)[3]")));
// Calling with environment record as base.
TestReceiver(o, context->Global(), "ownfunc()");
// Calling with no base.
TestReceiver(o, context->Global(), "(1,ownfunc)()");
// Checking foreign function return value.
// Calling function using its call/apply methods.
TestReceiver(i, foreign_context->Global(), "func.call()");
TestReceiver(i, foreign_context->Global(), "func.apply()");
// Calling function using another context's call/apply methods.
TestReceiver(i, foreign_context->Global(),
"Function.prototype.call.call(func)");
TestReceiver(i, foreign_context->Global(),
"Function.prototype.call.apply(func)");
TestReceiver(i, foreign_context->Global(),
"Function.prototype.apply.call(func)");
TestReceiver(i, foreign_context->Global(),
"Function.prototype.apply.apply(func)");
// Making calls through built-in functions.
TestReceiver(i, foreign_context->Global(), "[1].map(func)[0]");
// ToString(func()) is func()[0], i.e., the returned this.id.
CHECK(i->Equals(CompileRun("'abcbd'.replace(/b/,func)[1]")));
CHECK(i->Equals(CompileRun("'abcbd'.replace(/b/g,func)[1]")));
CHECK(i->Equals(CompileRun("'abcbd'.replace(/b/g,func)[3]")));
// TODO(1547): Make the following also return "i".
// Calling with environment record as base.
TestReceiver(o, context->Global(), "func()");
// Calling with no base.
TestReceiver(o, context->Global(), "(1,func)()");
}
uint8_t callback_fired = 0;
void CallCompletedCallback1() {
i::OS::Print("Firing callback 1.\n");
callback_fired ^= 1; // Toggle first bit.
}
void CallCompletedCallback2() {
i::OS::Print("Firing callback 2.\n");
callback_fired ^= 2; // Toggle second bit.
}
void RecursiveCall(const v8::FunctionCallbackInfo<v8::Value>& args) {
int32_t level = args[0]->Int32Value();
if (level < 3) {
level++;
i::OS::Print("Entering recursion level %d.\n", level);
char script[64];
i::Vector<char> script_vector(script, sizeof(script));
i::OS::SNPrintF(script_vector, "recursion(%d)", level);
CompileRun(script_vector.start());
i::OS::Print("Leaving recursion level %d.\n", level);
CHECK_EQ(0, callback_fired);
} else {
i::OS::Print("Recursion ends.\n");
CHECK_EQ(0, callback_fired);
}
}
TEST(CallCompletedCallback) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::Handle<v8::FunctionTemplate> recursive_runtime =
v8::FunctionTemplate::New(RecursiveCall);
env->Global()->Set(v8_str("recursion"),
recursive_runtime->GetFunction());
// Adding the same callback a second time has no effect.
v8::V8::AddCallCompletedCallback(CallCompletedCallback1);
v8::V8::AddCallCompletedCallback(CallCompletedCallback1);
v8::V8::AddCallCompletedCallback(CallCompletedCallback2);
i::OS::Print("--- Script (1) ---\n");
Local<Script> script =
v8::Script::Compile(v8::String::New("recursion(0)"));
script->Run();
CHECK_EQ(3, callback_fired);
i::OS::Print("\n--- Script (2) ---\n");
callback_fired = 0;
v8::V8::RemoveCallCompletedCallback(CallCompletedCallback1);
script->Run();
CHECK_EQ(2, callback_fired);
i::OS::Print("\n--- Function ---\n");
callback_fired = 0;
Local<Function> recursive_function =
Local<Function>::Cast(env->Global()->Get(v8_str("recursion")));
v8::Handle<Value> args[] = { v8_num(0) };
recursive_function->Call(env->Global(), 1, args);
CHECK_EQ(2, callback_fired);
}
void CallCompletedCallbackNoException() {
v8::HandleScope scope(v8::Isolate::GetCurrent());
CompileRun("1+1;");
}
void CallCompletedCallbackException() {
v8::HandleScope scope(v8::Isolate::GetCurrent());
CompileRun("throw 'second exception';");
}
TEST(CallCompletedCallbackOneException) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::V8::AddCallCompletedCallback(CallCompletedCallbackNoException);
CompileRun("throw 'exception';");
}
TEST(CallCompletedCallbackTwoExceptions) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
v8::V8::AddCallCompletedCallback(CallCompletedCallbackException);
CompileRun("throw 'first exception';");
}
static int probes_counter = 0;
static int misses_counter = 0;
static int updates_counter = 0;
static int* LookupCounter(const char* name) {
if (strcmp(name, "c:V8.MegamorphicStubCacheProbes") == 0) {
return &probes_counter;
} else if (strcmp(name, "c:V8.MegamorphicStubCacheMisses") == 0) {
return &misses_counter;
} else if (strcmp(name, "c:V8.MegamorphicStubCacheUpdates") == 0) {
return &updates_counter;
}
return NULL;
}
static const char* kMegamorphicTestProgram =
"function ClassA() { };"
"function ClassB() { };"
"ClassA.prototype.foo = function() { };"
"ClassB.prototype.foo = function() { };"
"function fooify(obj) { obj.foo(); };"
"var a = new ClassA();"
"var b = new ClassB();"
"for (var i = 0; i < 10000; i++) {"
" fooify(a);"
" fooify(b);"
"}";
static void StubCacheHelper(bool primary) {
V8::SetCounterFunction(LookupCounter);
USE(kMegamorphicTestProgram);
#ifdef DEBUG
i::FLAG_native_code_counters = true;
if (primary) {
i::FLAG_test_primary_stub_cache = true;
} else {
i::FLAG_test_secondary_stub_cache = true;
}
i::FLAG_crankshaft = false;
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
int initial_probes = probes_counter;
int initial_misses = misses_counter;
int initial_updates = updates_counter;
CompileRun(kMegamorphicTestProgram);
int probes = probes_counter - initial_probes;
int misses = misses_counter - initial_misses;
int updates = updates_counter - initial_updates;
CHECK_LT(updates, 10);
CHECK_LT(misses, 10);
CHECK_GE(probes, 10000);
#endif
}
TEST(SecondaryStubCache) {
StubCacheHelper(true);
}
TEST(PrimaryStubCache) {
StubCacheHelper(false);
}
TEST(StaticGetters) {
LocalContext context;
i::Factory* factory = i::Isolate::Current()->factory();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
i::Handle<i::Object> undefined_value = factory->undefined_value();
CHECK(*v8::Utils::OpenHandle(*v8::Undefined()) == *undefined_value);
CHECK(*v8::Utils::OpenHandle(*v8::Undefined(isolate)) == *undefined_value);
i::Handle<i::Object> null_value = factory->null_value();
CHECK(*v8::Utils::OpenHandle(*v8::Null()) == *null_value);
CHECK(*v8::Utils::OpenHandle(*v8::Null(isolate)) == *null_value);
i::Handle<i::Object> true_value = factory->true_value();
CHECK(*v8::Utils::OpenHandle(*v8::True()) == *true_value);
CHECK(*v8::Utils::OpenHandle(*v8::True(isolate)) == *true_value);
i::Handle<i::Object> false_value = factory->false_value();
CHECK(*v8::Utils::OpenHandle(*v8::False()) == *false_value);
CHECK(*v8::Utils::OpenHandle(*v8::False(isolate)) == *false_value);
}
TEST(IsolateEmbedderData) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
CHECK_EQ(NULL, isolate->GetData());
CHECK_EQ(NULL, ISOLATE->GetData());
static void* data1 = reinterpret_cast<void*>(0xacce55ed);
isolate->SetData(data1);
CHECK_EQ(data1, isolate->GetData());
CHECK_EQ(data1, ISOLATE->GetData());
static void* data2 = reinterpret_cast<void*>(0xdecea5ed);
ISOLATE->SetData(data2);
CHECK_EQ(data2, isolate->GetData());
CHECK_EQ(data2, ISOLATE->GetData());
ISOLATE->TearDown();
CHECK_EQ(data2, isolate->GetData());
CHECK_EQ(data2, ISOLATE->GetData());
}
TEST(StringEmpty) {
LocalContext context;
i::Factory* factory = i::Isolate::Current()->factory();
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
i::Handle<i::Object> empty_string = factory->empty_string();
CHECK(*v8::Utils::OpenHandle(*v8::String::Empty()) == *empty_string);
CHECK(*v8::Utils::OpenHandle(*v8::String::Empty(isolate)) == *empty_string);
}
static int instance_checked_getter_count = 0;
static void InstanceCheckedGetter(
Local<String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
CHECK_EQ(name, v8_str("foo"));
instance_checked_getter_count++;
info.GetReturnValue().Set(v8_num(11));
}
static int instance_checked_setter_count = 0;
static void InstanceCheckedSetter(Local<String> name,
Local<Value> value,
const v8::PropertyCallbackInfo<void>& info) {
CHECK_EQ(name, v8_str("foo"));
CHECK_EQ(value, v8_num(23));
instance_checked_setter_count++;
}
static void CheckInstanceCheckedResult(int getters,
int setters,
bool expects_callbacks,
TryCatch* try_catch) {
if (expects_callbacks) {
CHECK(!try_catch->HasCaught());
CHECK_EQ(getters, instance_checked_getter_count);
CHECK_EQ(setters, instance_checked_setter_count);
} else {
CHECK(try_catch->HasCaught());
CHECK_EQ(0, instance_checked_getter_count);
CHECK_EQ(0, instance_checked_setter_count);
}
try_catch->Reset();
}
static void CheckInstanceCheckedAccessors(bool expects_callbacks) {
instance_checked_getter_count = 0;
instance_checked_setter_count = 0;
TryCatch try_catch;
// Test path through generic runtime code.
CompileRun("obj.foo");
CheckInstanceCheckedResult(1, 0, expects_callbacks, &try_catch);
CompileRun("obj.foo = 23");
CheckInstanceCheckedResult(1, 1, expects_callbacks, &try_catch);
// Test path through generated LoadIC and StoredIC.
CompileRun("function test_get(o) { o.foo; }"
"test_get(obj);");
CheckInstanceCheckedResult(2, 1, expects_callbacks, &try_catch);
CompileRun("test_get(obj);");
CheckInstanceCheckedResult(3, 1, expects_callbacks, &try_catch);
CompileRun("test_get(obj);");
CheckInstanceCheckedResult(4, 1, expects_callbacks, &try_catch);
CompileRun("function test_set(o) { o.foo = 23; }"
"test_set(obj);");
CheckInstanceCheckedResult(4, 2, expects_callbacks, &try_catch);
CompileRun("test_set(obj);");
CheckInstanceCheckedResult(4, 3, expects_callbacks, &try_catch);
CompileRun("test_set(obj);");
CheckInstanceCheckedResult(4, 4, expects_callbacks, &try_catch);
// Test path through optimized code.
CompileRun("%OptimizeFunctionOnNextCall(test_get);"
"test_get(obj);");
CheckInstanceCheckedResult(5, 4, expects_callbacks, &try_catch);
CompileRun("%OptimizeFunctionOnNextCall(test_set);"
"test_set(obj);");
CheckInstanceCheckedResult(5, 5, expects_callbacks, &try_catch);
// Cleanup so that closures start out fresh in next check.
CompileRun("%DeoptimizeFunction(test_get);"
"%ClearFunctionTypeFeedback(test_get);"
"%DeoptimizeFunction(test_set);"
"%ClearFunctionTypeFeedback(test_set);");
}
THREADED_TEST(InstanceCheckOnInstanceAccessor) {
v8::internal::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<FunctionTemplate> templ = FunctionTemplate::New();
Local<ObjectTemplate> inst = templ->InstanceTemplate();
inst->SetAccessor(v8_str("foo"),
InstanceCheckedGetter, InstanceCheckedSetter,
Handle<Value>(),
v8::DEFAULT,
v8::None,
v8::AccessorSignature::New(templ));
context->Global()->Set(v8_str("f"), templ->GetFunction());
printf("Testing positive ...\n");
CompileRun("var obj = new f();");
CHECK(templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(true);
printf("Testing negative ...\n");
CompileRun("var obj = {};"
"obj.__proto__ = new f();");
CHECK(!templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(false);
}
THREADED_TEST(InstanceCheckOnInstanceAccessorWithInterceptor) {
v8::internal::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<FunctionTemplate> templ = FunctionTemplate::New();
Local<ObjectTemplate> inst = templ->InstanceTemplate();
AddInterceptor(templ, EmptyInterceptorGetter, EmptyInterceptorSetter);
inst->SetAccessor(v8_str("foo"),
InstanceCheckedGetter, InstanceCheckedSetter,
Handle<Value>(),
v8::DEFAULT,
v8::None,
v8::AccessorSignature::New(templ));
context->Global()->Set(v8_str("f"), templ->GetFunction());
printf("Testing positive ...\n");
CompileRun("var obj = new f();");
CHECK(templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(true);
printf("Testing negative ...\n");
CompileRun("var obj = {};"
"obj.__proto__ = new f();");
CHECK(!templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(false);
}
THREADED_TEST(InstanceCheckOnPrototypeAccessor) {
v8::internal::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<FunctionTemplate> templ = FunctionTemplate::New();
Local<ObjectTemplate> proto = templ->PrototypeTemplate();
proto->SetAccessor(v8_str("foo"),
InstanceCheckedGetter, InstanceCheckedSetter,
Handle<Value>(),
v8::DEFAULT,
v8::None,
v8::AccessorSignature::New(templ));
context->Global()->Set(v8_str("f"), templ->GetFunction());
printf("Testing positive ...\n");
CompileRun("var obj = new f();");
CHECK(templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(true);
printf("Testing negative ...\n");
CompileRun("var obj = {};"
"obj.__proto__ = new f();");
CHECK(!templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(false);
printf("Testing positive with modified prototype chain ...\n");
CompileRun("var obj = new f();"
"var pro = {};"
"pro.__proto__ = obj.__proto__;"
"obj.__proto__ = pro;");
CHECK(templ->HasInstance(context->Global()->Get(v8_str("obj"))));
CheckInstanceCheckedAccessors(true);
}
TEST(TryFinallyMessage) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
{
// Test that the original error message is not lost if there is a
// recursive call into Javascript is done in the finally block, e.g. to
// initialize an IC. (crbug.com/129171)
TryCatch try_catch;
const char* trigger_ic =
"try { \n"
" throw new Error('test'); \n"
"} finally { \n"
" var x = 0; \n"
" x++; \n" // Trigger an IC initialization here.
"} \n";
CompileRun(trigger_ic);
CHECK(try_catch.HasCaught());
Local<Message> message = try_catch.Message();
CHECK(!message.IsEmpty());
CHECK_EQ(2, message->GetLineNumber());
}
{
// Test that the original exception message is indeed overwritten if
// a new error is thrown in the finally block.
TryCatch try_catch;
const char* throw_again =
"try { \n"
" throw new Error('test'); \n"
"} finally { \n"
" var x = 0; \n"
" x++; \n"
" throw new Error('again'); \n" // This is the new uncaught error.
"} \n";
CompileRun(throw_again);
CHECK(try_catch.HasCaught());
Local<Message> message = try_catch.Message();
CHECK(!message.IsEmpty());
CHECK_EQ(6, message->GetLineNumber());
}
}
static void Helper137002(bool do_store,
bool polymorphic,
bool remove_accessor,
bool interceptor) {
LocalContext context;
Local<ObjectTemplate> templ = ObjectTemplate::New();
if (interceptor) {
templ->SetNamedPropertyHandler(FooGetInterceptor, FooSetInterceptor);
} else {
templ->SetAccessor(v8_str("foo"),
GetterWhichReturns42,
SetterWhichSetsYOnThisTo23);
}
context->Global()->Set(v8_str("obj"), templ->NewInstance());
// Turn monomorphic on slow object with native accessor, then turn
// polymorphic, finally optimize to create negative lookup and fail.
CompileRun(do_store ?
"function f(x) { x.foo = void 0; }" :
"function f(x) { return x.foo; }");
CompileRun("obj.y = void 0;");
if (!interceptor) {
CompileRun("%OptimizeObjectForAddingMultipleProperties(obj, 1);");
}
CompileRun("obj.__proto__ = null;"
"f(obj); f(obj); f(obj);");
if (polymorphic) {
CompileRun("f({});");
}
CompileRun("obj.y = void 0;"
"%OptimizeFunctionOnNextCall(f);");
if (remove_accessor) {
CompileRun("delete obj.foo;");
}
CompileRun("var result = f(obj);");
if (do_store) {
CompileRun("result = obj.y;");
}
if (remove_accessor && !interceptor) {
CHECK(context->Global()->Get(v8_str("result"))->IsUndefined());
} else {
CHECK_EQ(do_store ? 23 : 42,
context->Global()->Get(v8_str("result"))->Int32Value());
}
}
THREADED_TEST(Regress137002a) {
i::FLAG_allow_natives_syntax = true;
i::FLAG_compilation_cache = false;
v8::HandleScope scope(v8::Isolate::GetCurrent());
for (int i = 0; i < 16; i++) {
Helper137002(i & 8, i & 4, i & 2, i & 1);
}
}
THREADED_TEST(Regress137002b) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("foo"),
GetterWhichReturns42,
SetterWhichSetsYOnThisTo23);
context->Global()->Set(v8_str("obj"), templ->NewInstance());
// Turn monomorphic on slow object with native accessor, then just
// delete the property and fail.
CompileRun("function load(x) { return x.foo; }"
"function store(x) { x.foo = void 0; }"
"function keyed_load(x, key) { return x[key]; }"
// Second version of function has a different source (add void 0)
// so that it does not share code with the first version. This
// ensures that the ICs are monomorphic.
"function load2(x) { void 0; return x.foo; }"
"function store2(x) { void 0; x.foo = void 0; }"
"function keyed_load2(x, key) { void 0; return x[key]; }"
"obj.y = void 0;"
"obj.__proto__ = null;"
"var subobj = {};"
"subobj.y = void 0;"
"subobj.__proto__ = obj;"
"%OptimizeObjectForAddingMultipleProperties(obj, 1);"
// Make the ICs monomorphic.
"load(obj); load(obj);"
"load2(subobj); load2(subobj);"
"store(obj); store(obj);"
"store2(subobj); store2(subobj);"
"keyed_load(obj, 'foo'); keyed_load(obj, 'foo');"
"keyed_load2(subobj, 'foo'); keyed_load2(subobj, 'foo');"
// Actually test the shiny new ICs and better not crash. This
// serves as a regression test for issue 142088 as well.
"load(obj);"
"load2(subobj);"
"store(obj);"
"store2(subobj);"
"keyed_load(obj, 'foo');"
"keyed_load2(subobj, 'foo');"
// Delete the accessor. It better not be called any more now.
"delete obj.foo;"
"obj.y = void 0;"
"subobj.y = void 0;"
"var load_result = load(obj);"
"var load_result2 = load2(subobj);"
"var keyed_load_result = keyed_load(obj, 'foo');"
"var keyed_load_result2 = keyed_load2(subobj, 'foo');"
"store(obj);"
"store2(subobj);"
"var y_from_obj = obj.y;"
"var y_from_subobj = subobj.y;");
CHECK(context->Global()->Get(v8_str("load_result"))->IsUndefined());
CHECK(context->Global()->Get(v8_str("load_result2"))->IsUndefined());
CHECK(context->Global()->Get(v8_str("keyed_load_result"))->IsUndefined());
CHECK(context->Global()->Get(v8_str("keyed_load_result2"))->IsUndefined());
CHECK(context->Global()->Get(v8_str("y_from_obj"))->IsUndefined());
CHECK(context->Global()->Get(v8_str("y_from_subobj"))->IsUndefined());
}
THREADED_TEST(Regress142088) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetAccessor(v8_str("foo"),
GetterWhichReturns42,
SetterWhichSetsYOnThisTo23);
context->Global()->Set(v8_str("obj"), templ->NewInstance());
CompileRun("function load(x) { return x.foo; }"
"var o = Object.create(obj);"
"%OptimizeObjectForAddingMultipleProperties(obj, 1);"
"load(o); load(o); load(o); load(o);");
}
THREADED_TEST(Regress137496) {
i::FLAG_expose_gc = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
// Compile a try-finally clause where the finally block causes a GC
// while there still is a message pending for external reporting.
TryCatch try_catch;
try_catch.SetVerbose(true);
CompileRun("try { throw new Error(); } finally { gc(); }");
CHECK(try_catch.HasCaught());
}
THREADED_TEST(Regress149912) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Handle<FunctionTemplate> templ = FunctionTemplate::New();
AddInterceptor(templ, EmptyInterceptorGetter, EmptyInterceptorSetter);
context->Global()->Set(v8_str("Bug"), templ->GetFunction());
CompileRun("Number.prototype.__proto__ = new Bug; var x = 0; x.foo();");
}
THREADED_TEST(Regress157124) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<ObjectTemplate> templ = ObjectTemplate::New();
Local<Object> obj = templ->NewInstance();
obj->GetIdentityHash();
obj->DeleteHiddenValue(v8_str("Bug"));
}
THREADED_TEST(Regress2535) {
i::FLAG_harmony_collections = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<Value> set_value = CompileRun("new Set();");
Local<Object> set_object(Local<Object>::Cast(set_value));
CHECK_EQ(0, set_object->InternalFieldCount());
Local<Value> map_value = CompileRun("new Map();");
Local<Object> map_object(Local<Object>::Cast(map_value));
CHECK_EQ(0, map_object->InternalFieldCount());
}
THREADED_TEST(Regress2746) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<Object> obj = Object::New();
Local<String> key = String::New("key");
obj->SetHiddenValue(key, v8::Undefined());
Local<Value> value = obj->GetHiddenValue(key);
CHECK(!value.IsEmpty());
CHECK(value->IsUndefined());
}
THREADED_TEST(Regress260106) {
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Local<FunctionTemplate> templ = FunctionTemplate::New(DummyCallHandler);
CompileRun("for (var i = 0; i < 128; i++) Object.prototype[i] = 0;");
Local<Function> function = templ->GetFunction();
CHECK(!function.IsEmpty());
CHECK(function->IsFunction());
}
THREADED_TEST(JSONParseObject) {
LocalContext context;
HandleScope scope(context->GetIsolate());
Local<Value> obj = v8::JSON::Parse(v8_str("{\"x\":42}"));
Handle<Object> global = context->Global();
global->Set(v8_str("obj"), obj);
ExpectString("JSON.stringify(obj)", "{\"x\":42}");
}
THREADED_TEST(JSONParseNumber) {
LocalContext context;
HandleScope scope(context->GetIsolate());
Local<Value> obj = v8::JSON::Parse(v8_str("42"));
Handle<Object> global = context->Global();
global->Set(v8_str("obj"), obj);
ExpectString("JSON.stringify(obj)", "42");
}
#ifndef WIN32
class ThreadInterruptTest {
public:
ThreadInterruptTest() : sem_(NULL), sem_value_(0) { }
~ThreadInterruptTest() { delete sem_; }
void RunTest() {
sem_ = i::OS::CreateSemaphore(0);
InterruptThread i_thread(this);
i_thread.Start();
sem_->Wait();
CHECK_EQ(kExpectedValue, sem_value_);
}
private:
static const int kExpectedValue = 1;
class InterruptThread : public i::Thread {
public:
explicit InterruptThread(ThreadInterruptTest* test)
: Thread("InterruptThread"), test_(test) {}
virtual void Run() {
struct sigaction action;
// Ensure that we'll enter waiting condition
i::OS::Sleep(100);
// Setup signal handler
memset(&action, 0, sizeof(action));
action.sa_handler = SignalHandler;
sigaction(SIGCHLD, &action, NULL);
// Send signal
kill(getpid(), SIGCHLD);
// Ensure that if wait has returned because of error
i::OS::Sleep(100);
// Set value and signal semaphore
test_->sem_value_ = 1;
test_->sem_->Signal();
}
static void SignalHandler(int signal) {
}
private:
ThreadInterruptTest* test_;
};
i::Semaphore* sem_;
volatile int sem_value_;
};
THREADED_TEST(SemaphoreInterruption) {
ThreadInterruptTest().RunTest();
}
static bool NamedAccessAlwaysBlocked(Local<v8::Object> global,
Local<Value> name,
v8::AccessType type,
Local<Value> data) {
i::PrintF("Named access blocked.\n");
return false;
}
static bool IndexAccessAlwaysBlocked(Local<v8::Object> global,
uint32_t key,
v8::AccessType type,
Local<Value> data) {
i::PrintF("Indexed access blocked.\n");
return false;
}
void UnreachableCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(false);
}
TEST(JSONStringifyAccessCheck) {
v8::V8::Initialize();
v8::HandleScope scope(v8::Isolate::GetCurrent());
// Create an ObjectTemplate for global objects and install access
// check callbacks that will block access.
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedAccessAlwaysBlocked,
IndexAccessAlwaysBlocked);
// Create a context and set an x property on it's global object.
LocalContext context0(NULL, global_template);
v8::Handle<v8::Object> global0 = context0->Global();
global0->Set(v8_str("x"), v8_num(42));
ExpectString("JSON.stringify(this)", "{\"x\":42}");
for (int i = 0; i < 2; i++) {
if (i == 1) {
// Install a toJSON function on the second run.
v8::Handle<v8::FunctionTemplate> toJSON =
v8::FunctionTemplate::New(UnreachableCallback);
global0->Set(v8_str("toJSON"), toJSON->GetFunction());
}
// Create a context with a different security token so that the
// failed access check callback will be called on each access.
LocalContext context1(NULL, global_template);
context1->Global()->Set(v8_str("other"), global0);
ExpectString("JSON.stringify(other)", "{}");
ExpectString("JSON.stringify({ 'a' : other, 'b' : ['c'] })",
"{\"a\":{},\"b\":[\"c\"]}");
ExpectString("JSON.stringify([other, 'b', 'c'])",
"[{},\"b\",\"c\"]");
v8::Handle<v8::Array> array = v8::Array::New(2);
array->Set(0, v8_str("a"));
array->Set(1, v8_str("b"));
context1->Global()->Set(v8_str("array"), array);
ExpectString("JSON.stringify(array)", "[\"a\",\"b\"]");
array->TurnOnAccessCheck();
ExpectString("JSON.stringify(array)", "[]");
ExpectString("JSON.stringify([array])", "[[]]");
ExpectString("JSON.stringify({'a' : array})", "{\"a\":[]}");
}
}
bool access_check_fail_thrown = false;
bool catch_callback_called = false;
// Failed access check callback that performs a GC on each invocation.
void FailedAccessCheckThrows(Local<v8::Object> target,
v8::AccessType type,
Local<v8::Value> data) {
access_check_fail_thrown = true;
i::PrintF("Access check failed. Error thrown.\n");
v8::ThrowException(v8::Exception::Error(v8_str("cross context")));
}
void CatcherCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
for (int i = 0; i < args.Length(); i++) {
i::PrintF("%s\n", *String::Utf8Value(args[i]));
}
catch_callback_called = true;
}
void HasOwnPropertyCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
args[0]->ToObject()->HasOwnProperty(args[1]->ToString());
}
void CheckCorrectThrow(const char* script) {
// Test that the script, when wrapped into a try-catch, triggers the catch
// clause due to failed access check throwing an exception.
// The subsequent try-catch should run without any exception.
access_check_fail_thrown = false;
catch_callback_called = false;
i::ScopedVector<char> source(1024);
i::OS::SNPrintF(source, "try { %s; } catch (e) { catcher(e); }", script);
CompileRun(source.start());
CHECK(access_check_fail_thrown);
CHECK(catch_callback_called);
access_check_fail_thrown = false;
catch_callback_called = false;
CompileRun("try { [1, 2, 3].sort(); } catch (e) { catcher(e) };");
CHECK(!access_check_fail_thrown);
CHECK(!catch_callback_called);
}
TEST(AccessCheckThrows) {
i::FLAG_allow_natives_syntax = true;
v8::V8::Initialize();
v8::V8::SetFailedAccessCheckCallbackFunction(&FailedAccessCheckThrows);
v8::HandleScope scope(v8::Isolate::GetCurrent());
// Create an ObjectTemplate for global objects and install access
// check callbacks that will block access.
v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
global_template->SetAccessCheckCallbacks(NamedAccessAlwaysBlocked,
IndexAccessAlwaysBlocked);
// Create a context and set an x property on it's global object.
LocalContext context0(NULL, global_template);
context0->Global()->Set(v8_str("x"), v8_num(42));
v8::Handle<v8::Object> global0 = context0->Global();
// Create a context with a different security token so that the
// failed access check callback will be called on each access.
LocalContext context1(NULL, global_template);
context1->Global()->Set(v8_str("other"), global0);
v8::Handle<v8::FunctionTemplate> catcher_fun =
v8::FunctionTemplate::New(CatcherCallback);
context1->Global()->Set(v8_str("catcher"), catcher_fun->GetFunction());
v8::Handle<v8::FunctionTemplate> has_own_property_fun =
v8::FunctionTemplate::New(HasOwnPropertyCallback);
context1->Global()->Set(v8_str("has_own_property"),
has_own_property_fun->GetFunction());
{ v8::TryCatch try_catch;
access_check_fail_thrown = false;
CompileRun("other.x;");
CHECK(access_check_fail_thrown);
CHECK(try_catch.HasCaught());
}
CheckCorrectThrow("other.x");
CheckCorrectThrow("other[1]");
CheckCorrectThrow("JSON.stringify(other)");
CheckCorrectThrow("has_own_property(other, 'x')");
CheckCorrectThrow("%GetProperty(other, 'x')");
CheckCorrectThrow("%SetProperty(other, 'x', 'foo', 1, 0)");
CheckCorrectThrow("%IgnoreAttributesAndSetProperty(other, 'x', 'foo')");
CheckCorrectThrow("%DeleteProperty(other, 'x', 0)");
CheckCorrectThrow("%DeleteProperty(other, '1', 0)");
CheckCorrectThrow("%HasLocalProperty(other, 'x')");
CheckCorrectThrow("%HasProperty(other, 'x')");
CheckCorrectThrow("%HasElement(other, 1)");
CheckCorrectThrow("%IsPropertyEnumerable(other, 'x')");
CheckCorrectThrow("%GetPropertyNames(other)");
CheckCorrectThrow("%GetLocalPropertyNames(other, true)");
CheckCorrectThrow("%DefineOrRedefineAccessorProperty("
"other, 'x', null, null, 1)");
}
THREADED_TEST(Regress256330) {
i::FLAG_allow_natives_syntax = true;
LocalContext context;
v8::HandleScope scope(context->GetIsolate());
Handle<FunctionTemplate> templ = FunctionTemplate::New();
AddInterceptor(templ, EmptyInterceptorGetter, EmptyInterceptorSetter);
context->Global()->Set(v8_str("Bug"), templ->GetFunction());
CompileRun("\"use strict\"; var o = new Bug;"
"function f(o) { o.x = 10; };"
"f(o); f(o); f(o);"
"%OptimizeFunctionOnNextCall(f);"
"f(o);");
ExpectBoolean("%GetOptimizationStatus(f) != 2", true);
}
#endif // WIN32
| indashnet/InDashNet.Open.UN2000 | android/external/chromium_org/v8/test/cctest/test-api.cc | C++ | apache-2.0 | 691,663 |
/*
* Copyright 2003-2009 the original author or 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.
*/
import groovy.util.AllTestSuite;
import junit.framework.Test;
import junit.framework.TestCase;
/**
* Collecting all Groovy unit tests that are written in Groovy, not in root, and not Bug-related.
*
* @author Paul King
*/
public class UberTestCaseGroovySourceSubPackages_VM6 extends TestCase {
public static Test suite() {
return AllTestSuite.suite("src/test", "groovy/**/vm6/*Test.groovy");
}
} | Selventa/model-builder | tools/groovy/src/src/test/UberTestCaseGroovySourceSubPackages_VM6.java | Java | apache-2.0 | 1,037 |
---
layout: post
title: "Springboot实现多数据源"
subtitle: " \"Springboot实现多数据源\""
date: 2018-08-30 13:50:00
author: "gmg"
header-img: "img/post/sayBye2017.jpg"
catalog: true
tags:
- 工作
---
> "Springboot实现多数据源"
## Springboot实现多数据源
技术栈:springboot+mysql+mybatis
### 1、配置Maven:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
```
### 2、配置application.properties
```
## master
master.datasource.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf8
master.datasource.username=root
master.datasource.password=082900
master.datasource.driverClassName=com.mysql.jdbc.Driver
## cluster
cluster.datasource.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf8
cluster.datasource.username=root
cluster.datasource.password=082900
cluster.datasource.driverClassName=com.mysql.jdbc.Driver
```
### 3、加载配置
下面是master数据源对应的配置,cluster同理。
```
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
// 精确到 master 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.example.demo.gmg.mapper.master";
static final String MAPPER_LOCATION = "classpath:com/gmg/master/*.xml";
@Value("${master.datasource.url}")
private String url;
@Value("${master.datasource.username}")
private String user;
@Value("${master.datasource.password}")
private String password;
@Value("${master.datasource.driverClassName}")
private String driverClass;
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(masterDataSource());
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(MasterDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
```
### 4、编写业务逻辑
代码结构如下图:

具体的代码逻辑不再赘述,源代码[请戳](https://github.com/gmg0829/SpringbootLearningExample/tree/master/Springboot-MultiDataSource)
| ChangeWorldByCoding/ChangeWorldByCoding.github.io | _posts/2018/2018-08-30-multiDatasource.md | Markdown | apache-2.0 | 3,444 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_91) on Tue Jan 10 13:10:48 CET 2017 -->
<title>N-Index</title>
<meta name="date" content="2017-01-10">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="N-Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-13.html">Prev Letter</a></li>
<li><a href="index-15.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-14.html" target="_top">Frames</a></li>
<li><a href="index-14.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">J</a> <a href="index-11.html">K</a> <a href="index-12.html">L</a> <a href="index-13.html">M</a> <a href="index-14.html">N</a> <a href="index-15.html">O</a> <a href="index-16.html">P</a> <a href="index-17.html">Q</a> <a href="index-18.html">R</a> <a href="index-19.html">S</a> <a href="index-20.html">T</a> <a href="index-21.html">U</a> <a href="index-22.html">V</a> <a href="index-23.html">W</a> <a name="I:N">
<!-- -->
</a>
<h2 class="title">N</h2>
<dl>
<dt><a href="../vu/cltl/storyteller/input/NafTokenLayerIndex.html" title="class in vu.cltl.storyteller.input"><span class="typeNameLink">NafTokenLayerIndex</span></a> - Class in <a href="../vu/cltl/storyteller/input/package-summary.html">vu.cltl.storyteller.input</a></dt>
<dd>
<div class="block">Created by piek on 20/07/16.</div>
</dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/input/NafTokenLayerIndex.html#NafTokenLayerIndex--">NafTokenLayerIndex()</a></span> - Constructor for class vu.cltl.storyteller.input.<a href="../vu/cltl/storyteller/input/NafTokenLayerIndex.html" title="class in vu.cltl.storyteller.input">NafTokenLayerIndex</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/input/NafTokenLayerIndex.html#NafTokenLayerIndex-java.util.Vector-">NafTokenLayerIndex(Vector<String>)</a></span> - Constructor for class vu.cltl.storyteller.input.<a href="../vu/cltl/storyteller/input/NafTokenLayerIndex.html" title="class in vu.cltl.storyteller.input">NafTokenLayerIndex</a></dt>
<dd> </dd>
<dt><a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects"><span class="typeNameLink">NameSpaces</span></a> - Class in <a href="../vu/cltl/storyteller/objects/package-summary.html">vu.cltl.storyteller.objects</a></dt>
<dd>
<div class="block">Created by piek on 05/01/2017.</div>
</dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#NameSpaces--">NameSpaces()</a></span> - Constructor for class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nb">nb</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/json/JsonStoryUtil.html#nMergedEvents">nMergedEvents</a></span> - Static variable in class vu.cltl.storyteller.json.<a href="../vu/cltl/storyteller/json/JsonStoryUtil.html" title="class in vu.cltl.storyteller.json">JsonStoryUtil</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/util/RoleLabels.html#NONPRIMEPARTICIPANT">NONPRIMEPARTICIPANT</a></span> - Static variable in class vu.cltl.storyteller.util.<a href="../vu/cltl/storyteller/util/RoleLabels.html" title="class in vu.cltl.storyteller.util">RoleLabels</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/PerspectiveJsonObject.html#normalizePerspectiveValue-java.lang.String-">normalizePerspectiveValue(String)</a></span> - Static method in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/PerspectiveJsonObject.html" title="class in vu.cltl.storyteller.objects">PerspectiveJsonObject</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/util/RoleLabels.html#normalizeProbBankValue-java.lang.String-">normalizeProbBankValue(String)</a></span> - Static method in class vu.cltl.storyteller.util.<a href="../vu/cltl/storyteller/util/RoleLabels.html" title="class in vu.cltl.storyteller.util">RoleLabels</a></dt>
<dd>
<div class="block">semRole="A0" agent
semRole="A1" patient
semRole="A2" instrument, benefactive, attribute
semRole="A3" starting point, benefactive, attribute
semRole="A4" ending point
semRole="A5"
semRole="AA" secondary argument, "John walked his dog"
AM modifier
semRole="AM-ADV" adverbials
semRole="AM-CAU" causative
semRole="AM-DIR" directional
semRole="AM-DIS" discourse
semRole="AM-EXT" extent, amount of change "raised prices by 15%"
semRole="AM-LOC" locative
semRole="AM-MNR" manner
semRole="AM-MOD" modal
semRole="AM-NEG" negation
semRole="AM-PNC"
semRole="AM-PRD" purpose
semRole="AM-REC" reciprocals
semRole="AM-TMP" temporal
semRole="C-A0"
semRole="C-A1"
semRole="C-A2"
semRole="R-A0"
semRole="R-A1"
semRole="R-A2"
semRole="R-A3"
semRole="R-A4"
semRole="R-AA"
semRole="R-AM-CAU"
semRole="R-AM-EXT"
semRole="R-AM-LOC"
semRole="R-AM-MNR"
semRole="R-AM-PNC"
semRole="R-AM-TMP"
COM comitatives "I sang a song with my sister [COM]"
GOL goal "I fed the cat for her mother [GOL]"
PRD secondary predicate "She kicked the locker shut [PRD]"
DSP direct speech
LVB light verb</div>
</dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/json/JsonStoryUtil.html#normalizeSourceValue-java.lang.String-">normalizeSourceValue(String)</a></span> - Static method in class vu.cltl.storyteller.json.<a href="../vu/cltl/storyteller/json/JsonStoryUtil.html" title="class in vu.cltl.storyteller.json">JsonStoryUtil</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwr">nwr</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrauthor">nwrauthor</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrcite">nwrcite</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrclass">nwrclass</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrdata">nwrdata</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrmagazine">nwrmagazine</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrontology">nwrontology</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrpublisher">nwrpublisher</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrsourceowner">nwrsourceowner</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrtime">nwrtime</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../vu/cltl/storyteller/objects/NameSpaces.html#nwrvalue">nwrvalue</a></span> - Static variable in class vu.cltl.storyteller.objects.<a href="../vu/cltl/storyteller/objects/NameSpaces.html" title="class in vu.cltl.storyteller.objects">NameSpaces</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">H</a> <a href="index-9.html">I</a> <a href="index-10.html">J</a> <a href="index-11.html">K</a> <a href="index-12.html">L</a> <a href="index-13.html">M</a> <a href="index-14.html">N</a> <a href="index-15.html">O</a> <a href="index-16.html">P</a> <a href="index-17.html">Q</a> <a href="index-18.html">R</a> <a href="index-19.html">S</a> <a href="index-20.html">T</a> <a href="index-21.html">U</a> <a href="index-22.html">V</a> <a href="index-23.html">W</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-13.html">Prev Letter</a></li>
<li><a href="index-15.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-14.html" target="_top">Frames</a></li>
<li><a href="index-14.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| cltl/StoryTeller | java-doc/index-files/index-14.html | HTML | apache-2.0 | 13,687 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ejercicio22;
import java.util.Scanner;
/**
*Introducir una frase por teclado. Imprimirla cinco veces en filas
consecutivas, pero cada impresion ir desplazada cuatro columnas hacia la
derecha.
* @author isaac
* @version 1.0
*/
public class ejercicio22 {
public static void main(String[] args) {
String[][] arr = new String[5][21];
String fras;
Scanner esc = new Scanner(System.in);
System.out.println("Introduce la frase: ");
fras = esc.nextLine();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 21; j++) {
if (j % 5 == 0) {
arr[i][j] = fras;
i=i+1;
}
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 21; j++) {
System.out.println("Frase " + arr[i][j] + " fila: " + i + " columna: " + j);
}
}
}
}
| ixxakk/ProyectoJava | EjerciciosJava/src/ejercicio22/ejercicio22.java | Java | apache-2.0 | 908 |
import json
import re
import tg
import pkg_resources
import pylons
pylons.c = pylons.tmpl_context
pylons.g = pylons.app_globals
from pylons import c
from ming.orm import ThreadLocalORMSession
from datadiff.tools import assert_equal
from allura import model as M
from allura.lib import helpers as h
from allura.tests import decorators as td
from alluratest.controller import TestController
class _TestCase(TestController):
def setUp(self):
super(_TestCase, self).setUp()
self.setup_with_tools()
@td.with_git
def setup_with_tools(self):
h.set_context('test', 'src-git', neighborhood='Projects')
repo_dir = pkg_resources.resource_filename(
'forgegit', 'tests/data')
c.app.repo.fs_path = repo_dir
c.app.repo.status = 'ready'
c.app.repo.name = 'testgit.git'
ThreadLocalORMSession.flush_all()
ThreadLocalORMSession.close_all()
h.set_context('test', 'src-git', neighborhood='Projects')
c.app.repo.refresh()
ThreadLocalORMSession.flush_all()
ThreadLocalORMSession.close_all()
class TestRootController(_TestCase):
def test_index(self):
resp = self.app.get('/src-git/').follow().follow()
assert 'git://' in resp
def test_index_empty(self):
self.app.get('/git/')
def test_commit_browser(self):
resp = self.app.get('/src-git/commit_browser')
def test_commit_browser_data(self):
resp = self.app.get('/src-git/commit_browser_data')
data = json.loads(resp.body);
assert data['max_row'] == 3
assert data['next_column'] == 1
assert_equal(data['built_tree']['df30427c488aeab84b2352bdf88a3b19223f9d7a'],
{u'url': u'/p/test/src-git/ci/df30427c488aeab84b2352bdf88a3b19223f9d7a/',
u'oid': u'df30427c488aeab84b2352bdf88a3b19223f9d7a',
u'column': 0,
u'parents': [u'6a45885ae7347f1cac5103b0050cc1be6a1496c8'],
u'message': u'Add README', u'row': 1})
def test_log(self):
resp = self.app.get('/src-git/ref/master~/log/')
def test_tags(self):
resp = self.app.get('/src-git/ref/master~/tags/')
def _get_ci(self):
r = self.app.get('/src-git/ref/master:/')
resp = r.follow()
for tag in resp.html.findAll('a'):
if tag['href'].startswith('/p/test/src-git/ci/'):
return tag['href']
return None
def test_commit(self):
ci = self._get_ci()
resp = self.app.get(ci)
assert 'Rick' in resp, resp.showbrowser()
def test_feed(self):
assert 'Add README' in self.app.get('/feed')
def test_tree(self):
ci = self._get_ci()
resp = self.app.get(ci + 'tree/')
assert len(resp.html.findAll('tr')) == 2, resp.showbrowser()
resp = self.app.get(ci + 'tree/')
assert 'README' in resp, resp.showbrowser()
links = [ a.get('href') for a in resp.html.findAll('a') ]
assert 'README' in links, resp.showbrowser()
assert 'README/' not in links, resp.showbrowser()
def test_tree_extra_params(self):
ci = self._get_ci()
resp = self.app.get(ci + 'tree/?format=raw')
assert 'README' in resp, resp.showbrowser()
def test_file(self):
ci = self._get_ci()
resp = self.app.get(ci + 'tree/README')
assert 'README' in resp.html.find('h2', {'class':'dark title'}).contents[2]
content = str(resp.html.find('div', {'class':'clip grid-19'}))
assert 'This is readme' in content, content
assert '<span id="l1" class="code_block">' in resp
assert 'var hash = window.location.hash.substring(1);' in resp
def test_invalid_file(self):
ci = self._get_ci()
self.app.get(ci + 'tree/READMEz', status=404)
def test_diff(self):
ci = self._get_ci()
resp = self.app.get(ci + 'tree/README?diff=df30427c488aeab84b2352bdf88a3b19223f9d7a')
assert 'readme' in resp, resp.showbrowser()
assert '+++' in resp, resp.showbrowser()
def test_refresh(self):
notification = M.Notification.query.find(
dict(subject='[test:src-git] 4 new commits to test Git')).first()
domain = '.'.join(reversed(c.app.url[1:-1].split('/'))).replace('_', '-')
common_suffix = tg.config.get('forgemail.domain', '.sourceforge.net')
email = 'noreply@%s%s' % (domain, common_suffix)
assert email in notification['reply_to_address']
def test_file_force_display(self):
ci = self._get_ci()
resp = self.app.get(ci + 'tree/README?force=True')
content = str(resp.html.find('div', {'class':'clip grid-19'}))
assert re.search(r'<pre>.*This is readme', content), content
assert '</pre>' in content, content
class TestRestController(_TestCase):
def test_index(self):
self.app.get('/rest/p/test/src-git/', status=200)
def test_commits(self):
self.app.get('/rest/p/test/src-git/commits', status=200)
class TestFork(_TestCase):
def setUp(self):
super(TestFork, self).setUp()
to_project = M.Project.query.get(
shortname='test2', neighborhood_id=c.project.neighborhood_id)
r = self.app.post('/src-git/fork', params=dict(
project_id=str(to_project._id),
mount_point='code',
mount_label='Test forked repository'))
assert "{status: 'error'}" not in str(r.follow())
cloned_from = c.app.repo
with h.push_context('test2', 'code', neighborhood='Projects'):
c.app.repo.init_as_clone(
cloned_from.full_fs_path,
cloned_from.app.config.script_name(),
cloned_from.full_fs_path)
def _follow(self, r, **kw):
if r.status_int == 302:
print r.request.url
while r.status_int == 302:
print ' ==> 302 ==> %s' % r.location
r = r.follow(**kw)
return r
def _upstream_page(self, **kw):
r = self.app.get('/src-git/', **kw)
r = self._follow(r, **kw)
return r
def _fork_page(self, **kw):
r = self.app.get('/p/test2/code/', **kw)
r = self._follow(r, **kw)
return r
def _request_merge(self, **kw):
r = self.app.get('/p/test2/code/request_merge', **kw)
r = self._follow(r, **kw)
r = r.forms[0].submit()
r = self._follow(r, **kw)
mr_num = r.request.url.split('/')[-2]
assert mr_num.isdigit(), mr_num
return r, mr_num
def test_fork_form(self):
r = self.app.get('%sfork/' % c.app.repo.url())
assert '<input type="text" name="mount_point" value="test"/>' in r
assert '<input type="text" name="mount_label" value="test - Git"/>' in r
def test_fork_listed_in_parent(self):
assert 'Forks' in self._upstream_page()
def test_fork_display(self):
r = self._fork_page()
assert 'Clone of' in r
assert 'Test forked repository' in r
def test_fork_links_go_to_fork(self):
r = self._fork_page()
hrefs = ( a.get('href') for a in r.html('a') )
hrefs = ( href for href in hrefs if href and '/ci/' in href )
for href in hrefs:
assert href.startswith('/p/test2/code/'), href
def test_merge_request_visible_to_admin(self):
assert 'Request Merge' in self._fork_page()
def test_merge_request_invisible_to_non_admin(self):
assert 'Request Merge' not in self._fork_page(
extra_environ=dict(username='test-user'))
def test_merge_action_available_to_admin(self):
self.app.get('/p/test2/code/request_merge')
def test_merge_action_unavailable_to_non_admin(self):
self.app.get(
'/p/test2/code/request_merge',
status=403, extra_environ=dict(username='test-user'))
def test_merge_request_detail_view(self):
r, mr_num = self._request_merge()
assert 'would like you to merge' in r, r.showbrowser()
def test_merge_request_list_view(self):
r, mr_num = self._request_merge()
r = self.app.get('/p/test/src-git/merge-requests/')
assert 'href="%s/"' % mr_num in r, r
def test_merge_request_update_status(self):
r, mr_num = self._request_merge()
r = self.app.post('/p/test/src-git/merge-requests/%s/save' % mr_num,
params=dict(status='rejected')).follow()
assert 'Merge Request #%s: (rejected)' % mr_num in r, r
| leotrubach/sourceforge-allura | ForgeGit/forgegit/tests/functional/test_controllers.py | Python | apache-2.0 | 8,569 |
# Musa emasculata var. zengani VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Musaceae/Musa/Musa paradisiaca/ Syn. Musa emasculata zengani/README.md | Markdown | apache-2.0 | 185 |
# Copyright 2011 OpenStack Foundation.
# 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.
from oslo_config import cfg
from oslo_utils import importutils
import webob
from neutron._i18n import _
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import base
from neutron.api.v2 import resource
from neutron.common import constants as const
from neutron.common import exceptions as n_exc
from neutron import manager
from neutron import quota
from neutron.quota import resource_registry
from neutron import wsgi
RESOURCE_NAME = 'quota'
RESOURCE_COLLECTION = RESOURCE_NAME + "s"
QUOTAS = quota.QUOTAS
DB_QUOTA_DRIVER = 'neutron.db.quota.driver.DbQuotaDriver'
EXTENDED_ATTRIBUTES_2_0 = {
RESOURCE_COLLECTION: {}
}
class QuotaSetsController(wsgi.Controller):
def __init__(self, plugin):
self._resource_name = RESOURCE_NAME
self._plugin = plugin
self._driver = importutils.import_class(
cfg.CONF.QUOTAS.quota_driver
)
self._update_extended_attributes = True
def _update_attributes(self):
for quota_resource in resource_registry.get_all_resources().keys():
attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION]
attr_dict[quota_resource] = {
'allow_post': False,
'allow_put': True,
'convert_to': attributes.convert_to_int,
'validate': {'type:range': [-1, const.DB_INTEGER_MAX_VALUE]},
'is_visible': True}
self._update_extended_attributes = False
def _get_quotas(self, request, tenant_id):
return self._driver.get_tenant_quotas(
request.context,
resource_registry.get_all_resources(),
tenant_id)
def create(self, request, body=None):
msg = _('POST requests are not supported on this resource.')
raise webob.exc.HTTPNotImplemented(msg)
def index(self, request):
context = request.context
self._check_admin(context)
return {self._resource_name + "s":
self._driver.get_all_quotas(
context, resource_registry.get_all_resources())}
def tenant(self, request):
"""Retrieve the tenant info in context."""
context = request.context
if not context.tenant_id:
raise n_exc.QuotaMissingTenant()
return {'tenant': {'tenant_id': context.tenant_id}}
def show(self, request, id):
if id != request.context.tenant_id:
self._check_admin(request.context,
reason=_("Only admin is authorized "
"to access quotas for another tenant"))
return {self._resource_name: self._get_quotas(request, id)}
def _check_admin(self, context,
reason=_("Only admin can view or configure quota")):
if not context.is_admin:
raise n_exc.AdminRequired(reason=reason)
def delete(self, request, id):
self._check_admin(request.context)
self._driver.delete_tenant_quota(request.context, id)
def update(self, request, id, body=None):
self._check_admin(request.context)
if self._update_extended_attributes:
self._update_attributes()
body = base.Controller.prepare_request_body(
request.context, body, False, self._resource_name,
EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION])
for key, value in body[self._resource_name].items():
self._driver.update_quota_limit(request.context, id, key, value)
return {self._resource_name: self._get_quotas(request, id)}
class Quotasv2(extensions.ExtensionDescriptor):
"""Quotas management support."""
@classmethod
def get_name(cls):
return "Quota management support"
@classmethod
def get_alias(cls):
return RESOURCE_COLLECTION
@classmethod
def get_description(cls):
description = 'Expose functions for quotas management'
if cfg.CONF.QUOTAS.quota_driver == DB_QUOTA_DRIVER:
description += ' per tenant'
return description
@classmethod
def get_updated(cls):
return "2012-07-29T10:00:00-00:00"
@classmethod
def get_resources(cls):
"""Returns Ext Resources."""
controller = resource.Resource(
QuotaSetsController(manager.NeutronManager.get_plugin()),
faults=base.FAULT_MAP)
return [extensions.ResourceExtension(
Quotasv2.get_alias(),
controller,
collection_actions={'tenant': 'GET'})]
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
| apporc/neutron | neutron/extensions/quotasv2.py | Python | apache-2.0 | 5,333 |
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/silicon_creator/lib/drivers/uart.h"
#include "gtest/gtest.h"
#include "sw/device/lib/base/mmio.h"
#include "sw/device/lib/base/testing/mock_abs_mmio.h"
#include "hw/top_earlgrey/sw/autogen/top_earlgrey.h"
#include "uart_regs.h" // Generated.
namespace uart_unittest {
namespace {
const std::vector<uint8_t> kBytesArray = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
};
class UartTest : public mask_rom_test::MaskRomTest {
protected:
uint32_t base_ = TOP_EARLGREY_UART0_BASE_ADDR;
mask_rom_test::MockAbsMmio mmio_;
void ExpectDeviceReset() {
EXPECT_ABS_WRITE32(base_ + UART_CTRL_REG_OFFSET, 0);
EXPECT_ABS_WRITE32(base_ + UART_FIFO_CTRL_REG_OFFSET,
{
{UART_FIFO_CTRL_RXRST_BIT, true},
{UART_FIFO_CTRL_TXRST_BIT, true},
});
EXPECT_ABS_WRITE32(base_ + UART_OVRD_REG_OFFSET, 0);
EXPECT_ABS_WRITE32(base_ + UART_TIMEOUT_CTRL_REG_OFFSET, 0);
EXPECT_ABS_WRITE32(base_ + UART_INTR_ENABLE_REG_OFFSET, 0);
EXPECT_ABS_WRITE32(base_ + UART_INTR_STATE_REG_OFFSET,
std::numeric_limits<uint32_t>::max());
}
};
class InitTest : public UartTest {};
TEST_F(InitTest, Initialize) {
ExpectDeviceReset();
EXPECT_ABS_WRITE32(base_ + UART_CTRL_REG_OFFSET,
{
{UART_CTRL_TX_BIT, true},
{UART_CTRL_NCO_OFFSET, 1},
});
EXPECT_ABS_WRITE32(base_ + UART_INTR_ENABLE_REG_OFFSET, 0);
EXPECT_EQ(uart_init(1), kErrorOk);
}
TEST_F(InitTest, InvalidInit) {
EXPECT_EQ(uart_init(0), kErrorUartInvalidArgument);
EXPECT_EQ(uart_init(65536), kErrorUartInvalidArgument);
}
class BytesSendTest : public UartTest {
protected:
/**
* Sets TX bytes expectations.
*
* Every sent byte by the "send bytes" routine is expected to result in the
* STATUS read of 0 (FIFO not full), and write to WDATA.
*/
void ExpectSendBytes(int num_elements = kBytesArray.size()) {
ASSERT_LE(num_elements, kBytesArray.size());
for (int i = 0; i < num_elements; ++i) {
uint32_t value = static_cast<uint32_t>(kBytesArray[i]);
EXPECT_ABS_READ32(base_ + UART_STATUS_REG_OFFSET,
{{UART_STATUS_TXFULL_BIT, false}});
EXPECT_ABS_WRITE32(base_ + UART_WDATA_REG_OFFSET, value);
EXPECT_ABS_READ32(base_ + UART_STATUS_REG_OFFSET,
{{UART_STATUS_TXIDLE_BIT, true}});
}
}
};
TEST_F(BytesSendTest, SendBuffer) {
ExpectSendBytes();
// Calling uart_write implicitly tests uart_putchar.
EXPECT_EQ(uart_write(kBytesArray.data(), kBytesArray.size()),
kBytesArray.size());
}
TEST_F(BytesSendTest, SendByteBusy) {
// FIFO full for one cycle, then empty.
EXPECT_ABS_READ32(base_ + UART_STATUS_REG_OFFSET,
{{UART_STATUS_TXFULL_BIT, true}});
EXPECT_ABS_READ32(base_ + UART_STATUS_REG_OFFSET,
{{UART_STATUS_TXFULL_BIT, false}});
// The value sent is 'X'
EXPECT_ABS_WRITE32(base_ + UART_WDATA_REG_OFFSET, 'X');
// Transmitter busy for one cycle, then idle.
EXPECT_ABS_READ32(base_ + UART_STATUS_REG_OFFSET,
{{UART_STATUS_TXIDLE_BIT, false}});
EXPECT_ABS_READ32(base_ + UART_STATUS_REG_OFFSET,
{{UART_STATUS_TXIDLE_BIT, true}});
uart_putchar('X');
}
} // namespace
} // namespace uart_unittest
| lowRISC/opentitan | sw/device/silicon_creator/lib/drivers/uart_unittest.cc | C++ | apache-2.0 | 3,700 |
# Stellaria humifusa f. multiflora Polunin FORM
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Stellaria/Stellaria humifusa/Stellaria humifusa multiflora/README.md | Markdown | apache-2.0 | 187 |
package net.ME1312.SubServers.Client.Common.Network.Packet;
import net.ME1312.Galaxi.Library.Map.ObjectMap;
import net.ME1312.Galaxi.Library.Util;
import net.ME1312.SubData.Client.Protocol.PacketObjectIn;
import net.ME1312.SubData.Client.Protocol.PacketObjectOut;
import net.ME1312.SubData.Client.SubDataSender;
import java.util.HashMap;
import java.util.UUID;
import java.util.function.Consumer;
/**
* Remove Server Packet
*/
public class PacketRemoveServer implements PacketObjectIn<Integer>, PacketObjectOut<Integer> {
private static HashMap<UUID, Consumer<ObjectMap<Integer>>[]> callbacks = new HashMap<UUID, Consumer<ObjectMap<Integer>>[]>();
private UUID player;
private String server;
private boolean force;
private UUID tracker;
/**
* New PacketRemoveServer (In)
*/
public PacketRemoveServer() {}
/**
* New PacketRemoveServer (Out)
*
* @param player Player Removing
* @param server Server
* @param callback Callbacks
*/
@SafeVarargs
public PacketRemoveServer(UUID player, String server, boolean force, Consumer<ObjectMap<Integer>>... callback) {
Util.nullpo(server, callback);
this.player = player;
this.server = server;
this.force = force;
this.tracker = Util.getNew(callbacks.keySet(), UUID::randomUUID);
callbacks.put(tracker, callback);
}
@Override
public ObjectMap<Integer> send(SubDataSender client) {
ObjectMap<Integer> data = new ObjectMap<Integer>();
data.set(0x0000, tracker);
data.set(0x0001, server);
data.set(0x0002, force);
if (player != null) data.set(0x0003, player);
return data;
}
@Override
public void receive(SubDataSender client, ObjectMap<Integer> data) {
for (Consumer<ObjectMap<Integer>> callback : callbacks.remove(data.getUUID(0x0000))) callback.accept(data);
}
}
| ME1312/SubServers-2 | SubServers.Client/Common/src/net/ME1312/SubServers/Client/Common/Network/Packet/PacketRemoveServer.java | Java | apache-2.0 | 1,919 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flex.compiler.internal.codegen.js.goog;
import org.apache.flex.compiler.driver.IBackend;
import org.apache.flex.compiler.internal.codegen.as.TestGlobalClasses;
import org.apache.flex.compiler.internal.driver.js.goog.GoogBackend;
import org.apache.flex.compiler.tree.as.IFunctionNode;
import org.apache.flex.compiler.tree.as.IVariableNode;
import org.junit.Test;
/**
* @author Erik de Bruin
*/
public class TestGoogGlobalClasses extends TestGlobalClasses
{
@Override
@Test
public void testArgumentError()
{
IVariableNode node = getVariable("var a:ArgumentError = new ArgumentError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {ArgumentError} */ a = new ArgumentError()");
}
@Override
@Test
public void testArguments()
{
IFunctionNode node = getMethod("function a():void {\ttrace(arguments);}");
asBlockWalker.visitFunction(node);
assertOut("FalconTest_A.prototype.a = function() {\n\tvar self = this;\n\ttrace(arguments);\n}");
}
@Override
@Test
public void testArray()
{
IVariableNode node = getVariable("var a:Array = new Array(1);");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Array} */ a = new Array(1)");
}
@Override
@Test
public void testBoolean()
{
IVariableNode node = getVariable("var a:Boolean = new Boolean(1);");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {boolean} */ a = new Boolean(1)");
}
@Override
@Test
public void testClass()
{
IVariableNode node = getVariable("var a:Class = new Class();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Object} */ a = new Class()");
}
@Override
@Test
public void testDate()
{
IVariableNode node = getVariable("var a:Date = new Date();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Date} */ a = new Date()");
}
@Override
@Test
public void testDefinitionError()
{
IVariableNode node = getVariable("var a:DefinitionError = new DefinitionError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {DefinitionError} */ a = new DefinitionError()");
}
@Override
@Test
public void testError()
{
IVariableNode node = getVariable("var a:Error = new Error();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Error} */ a = new Error()");
}
@Override
@Test
public void testEvalError()
{
IVariableNode node = getVariable("var a:EvalError = new EvalError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {EvalError} */ a = new EvalError()");
}
@Override
@Test
public void testFunction()
{
IVariableNode node = getVariable("var a:Function = new Function();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Function} */ a = new Function()");
}
@Override
@Test
public void testInt()
{
IVariableNode node = getVariable("var a:int = new int(1.8);");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {number} */ a = new int(1.8)");
}
@Override
@Test
public void testJSON()
{
IVariableNode node = getVariable("var a:JSON = new JSON();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {JSON} */ a = new JSON()");
}
@Override
@Test
public void testMath()
{
IVariableNode node = getVariable("var a:Number = Math.PI;");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {number} */ a = Math.PI");
}
@Override
@Test
public void testNamespace()
{
IVariableNode node = getVariable("var a:Namespace = new Namespace(\"http://example.com\");");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Namespace} */ a = new Namespace(\"http://example.com\")");
}
@Override
@Test
public void testNumber()
{
IVariableNode node = getVariable("var a:Number = new Number(\"1\");");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {number} */ a = new Number(\"1\")");
}
@Override
@Test
public void testObject()
{
IVariableNode node = getVariable("var a:Object = new Object();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Object} */ a = new Object()");
}
@Override
@Test
public void testQName()
{
IVariableNode node = getVariable("var a:QName = new QName();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {QName} */ a = new QName()");
}
@Override
@Test
public void testRangeError()
{
IVariableNode node = getVariable("var a:RangeError = new RangeError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {RangeError} */ a = new RangeError()");
}
@Override
@Test
public void testReferenceError()
{
IVariableNode node = getVariable("var a:ReferenceError = new ReferenceError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {ReferenceError} */ a = new ReferenceError()");
}
@Override
@Test
public void testRegExp_Literal()
{
IVariableNode node = getVariable("var a:RegExp = /test-\\d/i;");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {RegExp} */ a = /test-\\d/i");
}
@Override
@Test
public void testSecurityError()
{
IVariableNode node = getVariable("var a:SecurityError = new SecurityError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {SecurityError} */ a = new SecurityError()");
}
@Override
@Test
public void testString()
{
IVariableNode node = getVariable("var a:String = new String(\"100\");");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {string} */ a = new String(\"100\")");
}
@Override
@Test
public void testSyntaxError()
{
IVariableNode node = getVariable("var a:SyntaxError = new SyntaxError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {SyntaxError} */ a = new SyntaxError()");
}
@Override
@Test
public void testTypeError()
{
IVariableNode node = getVariable("var a:TypeError = new TypeError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {TypeError} */ a = new TypeError()");
}
@Override
@Test
public void testUint()
{
IVariableNode node = getVariable("var a:uint = new uint(-100);");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {number} */ a = new uint(-100)");
}
@Override
@Test
public void testURIError()
{
IVariableNode node = getVariable("var a:URIError = new URIError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {URIError} */ a = new URIError()");
}
@Override
@Test
public void testVector()
{
IVariableNode node = getVariable("var a:Vector.<String> = new Vector.<String>(['Hello', 'World']);");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {Vector.<string>} */ a = new Array(['Hello', 'World'])");
}
@Override
@Test
public void testVerifyError()
{
IVariableNode node = getVariable("var a:VerifyError = new VerifyError();");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {VerifyError} */ a = new VerifyError()");
}
@Override
@Test
public void testXML()
{
IVariableNode node = getVariable("var a:XML = new XML('@');");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {XML} */ a = new XML('@')");
}
@Override
@Test
public void testXMLList()
{
IVariableNode node = getVariable("var a:XMLList = new XMLList('<!-- comment -->');");
asBlockWalker.visitVariable(node);
assertOut("var /** @type {XMLList} */ a = new XMLList('<!-- comment -->')");
}
@Override
protected IBackend createBackend()
{
return new GoogBackend();
}
}
| greg-dove/flex-falcon | compiler-jx/src/test/java/org/apache/flex/compiler/internal/codegen/js/goog/TestGoogGlobalClasses.java | Java | apache-2.0 | 9,304 |
/*
* 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.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.internal.objectarrays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.error.ElementsShouldNotHave.elementsShouldNotHave;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.Lists.newArrayList;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.ObjectArrays;
import org.assertj.core.internal.ObjectArraysWithConditionBaseTest;
import org.junit.jupiter.api.Test;
/**
* Tests for
* <code>{@link ObjectArrays#assertDoNotHave(org.assertj.core.api.AssertionInfo, Object[], org.assertj.core.api.Condition)}</code>
* .
*
* @author Nicolas François
* @author Mikhail Mazursky
*/
class ObjectArrays_assertDoNotHave_Test extends ObjectArraysWithConditionBaseTest {
@Test
void should_pass_if_each_element_satisfies_condition() {
actual = array("Darth Vader", "Leia");
arrays.assertDoNotHave(someInfo(), actual, jediPower);
verify(conditions).assertIsNotNull(jediPower);
}
@Test
void should_throw_error_if_condition_is_null() {
assertThatNullPointerException().isThrownBy(() -> arrays.assertDoNotHave(someInfo(), actual, null))
.withMessage("The condition to evaluate should not be null");
verify(conditions).assertIsNotNull(null);
}
@Test
void should_fail_if_condition_is_met() {
testCondition.shouldMatch(false);
AssertionInfo info = someInfo();
actual = array("Darth Vader", "Leia", "Yoda");
Throwable error = catchThrowable(() -> arrays.assertDoNotHave(someInfo(), actual, jediPower));
assertThat(error).isInstanceOf(AssertionError.class);
verify(conditions).assertIsNotNull(jediPower);
verify(failures).failure(info, elementsShouldNotHave(actual, newArrayList("Yoda"), jediPower));
}
}
| hazendaz/assertj-core | src/test/java/org/assertj/core/internal/objectarrays/ObjectArrays_assertDoNotHave_Test.java | Java | apache-2.0 | 2,669 |
/*
* Copyright 2011 Edmunds.com, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.edmunds.zookeeper.treewatcher;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Wrapper around the ZooKeeperTreeNode's.
* <p/>
* The tree nodes are immutable so this class provides (mutable) maps to quickly look up elements in the tree
* and methods to perform tree manipulation.
*/
public class ZooKeeperTreeState {
private static final Logger logger = Logger.getLogger(ZooKeeperTreeState.class);
private static final Set<ZooKeeperTreeNode> EMPTY_SET = Collections.emptySet();
private static final ImmutableMap<String, ZooKeeperTreeNode> EMPTY_MAP = ImmutableMap.of();
/**
* Maps the path to the actual node.
*/
private final Map<String, ZooKeeperTreeNode> pathMapping;
/**
* Allows each node to lookup its parent.
* <p/>
* This is important, since there are no parent references in the tree.
*/
private final Map<ZooKeeperTreeNode, ZooKeeperTreeNode> parentMapping;
/**
* The node at the root of the tree.
*/
private ZooKeeperTreeNode rootNode;
/**
* Standard constructor that initializes a Tree State with a single root node.
* <p/>
* If both the data and the children are consistent the node is assumed to be fully consistent.
* <p/>
* Each node in the tree has a "level" typically the root node is level 0 and the level below that is 1 and so on.
* However it may be the case that logic that needs to process the tree needs the level to have a specific value.
* As a result it is possible to set the root to any value, the watcher then increments +1 for each level.
*
* @param rootLevel the level of the root node.
* @param rootPath the path to the root node.
* @param data the data contained in the root node.
* @param dataConsistent is the data consistent.
* @param childListConsistent are the child nodes consistent.
*/
public ZooKeeperTreeState(
int rootLevel, String rootPath, byte[] data, boolean dataConsistent, boolean childListConsistent) {
this.pathMapping = Maps.newHashMap();
this.parentMapping = Maps.newHashMap();
setRootNode(new ZooKeeperTreeNode(rootLevel, rootPath, data,
dataConsistent, childListConsistent, dataConsistent && childListConsistent));
}
/**
* Copy constructor.
* <p/>
* Since most of the tree is immutable copying it is a very cheap operation.
*
* @param other the other state to copy.
*/
public ZooKeeperTreeState(ZooKeeperTreeState other) {
this.pathMapping = Maps.newHashMap(other.pathMapping);
this.parentMapping = Maps.newHashMap(other.parentMapping);
this.rootNode = other.rootNode;
}
public ZooKeeperTreeNode getRootNode() {
return rootNode;
}
private void setRootNode(ZooKeeperTreeNode rootNode) {
pathMapping.put(rootNode.getPath(), rootNode);
this.rootNode = rootNode;
}
public ZooKeeperTreeNode getNode(String path) {
return pathMapping.get(path);
}
public void setFlags(String path, boolean dataConsistent, boolean childListConsistent) {
final ZooKeeperTreeNode oldNode = pathMapping.get(path);
final ZooKeeperTreeNode newNode = createNode(
oldNode, oldNode.getChildren(), oldNode.getData(),
dataConsistent, childListConsistent, true);
switchParent(oldNode, newNode);
}
public void setData(String path, byte[] data) {
final ZooKeeperTreeNode oldNode = pathMapping.get(path);
final ZooKeeperTreeNode newNode = createNode(
oldNode, oldNode.getChildren(), data,
true, oldNode.isChildListConsistent(), true);
switchParent(oldNode, newNode);
}
public void setChildren(String path, Collection<String> children) {
final ZooKeeperTreeNode parent = pathMapping.get(path);
final List<ZooKeeperTreeNode> deletedChildren = getDeletedChildren(parent, children);
final List<ZooKeeperTreeNode> insertedChildren = getInsertedChildren(parent, children);
updateNode(
parent, deletedChildren, insertedChildren,
parent.isDataConsistent(), true, insertedChildren.isEmpty());
}
public void insertNode(String parentPath, ZooKeeperTreeNode insertedNode) {
insertNodes(pathMapping.get(parentPath), Collections.singleton(insertedNode));
}
public void insertNodes(ZooKeeperTreeNode parent, Collection<ZooKeeperTreeNode> insertedNodes) {
Validate.notNull(parent, "parent cannot be null");
Validate.notNull(insertedNodes, "node cannot be null");
for (ZooKeeperTreeNode insertedNode : insertedNodes) {
if (parent.getChild(insertedNode.getName()) != null) {
final String msg = "Cannot overwrite existing node: " + insertedNode.getPath();
logger.error(msg);
throw new IllegalStateException(msg);
}
}
updateNode(parent, EMPTY_SET, insertedNodes, parent.isDataConsistent(), parent.isChildListConsistent(), true);
}
public void deleteNode(String path) {
Validate.notEmpty(path);
final ZooKeeperTreeNode node = pathMapping.get(path);
Validate.notNull(node);
final ZooKeeperTreeNode parent = parentMapping.get(node);
Validate.notNull(parent);
deleteNodes(parent, Collections.singleton(node));
}
public void deleteNodes(ZooKeeperTreeNode parent, Collection<ZooKeeperTreeNode> deletedNodes) {
Validate.notNull(parent, "parent cannot be null");
Validate.notNull(deletedNodes, "deletedNode cannot be null");
updateNode(parent, deletedNodes, EMPTY_SET, parent.isDataConsistent(), parent.isChildListConsistent(), true);
}
private void updateNode(
ZooKeeperTreeNode parent,
Collection<ZooKeeperTreeNode> deletedNodes, Collection<ZooKeeperTreeNode> insertedNodes,
boolean dataConsistent, boolean childListConsistent, boolean checkConsistent) {
for (ZooKeeperTreeNode deletedNode : deletedNodes) {
deleteSubTree(deletedNode);
}
for (ZooKeeperTreeNode insertedNode : insertedNodes) {
// This call will set the wrong parent (we need newParent).
insertSubTree(parent, insertedNode);
}
// Correct the parent of the children during the creation.
final ZooKeeperTreeNode newParent = createParent(
parent, deletedNodes, insertedNodes,
dataConsistent, childListConsistent, checkConsistent);
switchParent(parent, newParent);
}
private void insertSubTree(ZooKeeperTreeNode parent, ZooKeeperTreeNode node) {
if (!parent.getPath().equals(node.getParentPath())) {
final String msg = "Child node has an incorrect parent: " +
"[" + node.getPath() + "] -> [" + parent.getPath() + "]";
logger.error(msg);
throw new IllegalStateException(msg);
}
pathMapping.put(node.getPath(), node);
parentMapping.put(node, parent);
for (ZooKeeperTreeNode child : node.getChildren().values()) {
insertSubTree(node, child);
}
}
private void deleteSubTree(ZooKeeperTreeNode node) {
for (ZooKeeperTreeNode child : node.getChildren().values()) {
deleteSubTree(child);
}
if (pathMapping.remove(node.getPath()) == null) {
logger.error("Tried to remove a node that is not in the path mapping: " + node.getPath());
}
if (parentMapping.remove(node) == null) {
logger.error("Tried to remove a node that is not in the tree: " + node.getPath());
}
}
private List<ZooKeeperTreeNode> getInsertedChildren(ZooKeeperTreeNode parent, Collection<String> children) {
final List<ZooKeeperTreeNode> insertedChildren = Lists.newArrayList();
final int childLevel = parent.getLevel() + 1;
final String parentPath = parent.getPath();
for (String child : children) {
if (parent.getChild(child) == null) {
insertedChildren.add(
new ZooKeeperTreeNode(childLevel, parentPath, child, null, EMPTY_MAP, false, false, false));
}
}
return insertedChildren;
}
private List<ZooKeeperTreeNode> getDeletedChildren(ZooKeeperTreeNode parent, Collection<String> children) {
final List<ZooKeeperTreeNode> deletedChildren = Lists.newArrayList();
final HashSet<String> childrenSet = Sets.newHashSet(children);
for (ZooKeeperTreeNode child : parent.getChildren().values()) {
if (!childrenSet.contains(child.getName())) {
deletedChildren.add(child);
}
}
return deletedChildren;
}
private ZooKeeperTreeNode createParent(
ZooKeeperTreeNode parent,
Collection<ZooKeeperTreeNode> deletedNodes, Collection<ZooKeeperTreeNode> insertedNodes,
boolean dataConsistent, boolean childListConsistent, boolean checkConsistent) {
final HashMap<String, ZooKeeperTreeNode> children = Maps.newHashMap(parent.getChildren());
// Remove any deleted nodes.
for (ZooKeeperTreeNode deletedNode : deletedNodes) {
children.remove(deletedNode.getName());
}
// Add any inserted nodes.
for (ZooKeeperTreeNode insertedNode : insertedNodes) {
children.put(insertedNode.getName(), insertedNode);
}
return createNode(
parent, children, parent.getData(),
dataConsistent, childListConsistent, checkConsistent);
}
private ZooKeeperTreeNode createNode(
ZooKeeperTreeNode oldNode, Map<String, ZooKeeperTreeNode> children, byte[] data,
boolean dataConsistent, boolean childListConsistent, boolean checkConsistent) {
boolean fullyConsistent =
dataConsistent && childListConsistent &&
checkConsistent && isFullyConsistent(children.values());
final ZooKeeperTreeNode newParent = new ZooKeeperTreeNode(
oldNode,
data, ImmutableMap.copyOf(children),
dataConsistent, childListConsistent, fullyConsistent);
// At this point the parent mappings will be incorrect, we need update to the newly created node.
for (ZooKeeperTreeNode child : newParent.getChildren().values()) {
parentMapping.put(child, newParent);
}
return newParent;
}
private void switchParent(ZooKeeperTreeNode oldNode, ZooKeeperTreeNode newNode) {
Validate.notNull(oldNode, "oldNode cannot be null");
Validate.notNull(newNode, "newNode cannot be null");
// Have we reached the root?
while (oldNode != getRootNode()) {
final String path = newNode.getPath();
final ZooKeeperTreeNode oldValue = pathMapping.put(path, newNode);
if (oldValue != oldNode) {
final String msg = "oldNode was not in the pathMapping: " + oldNode.getPath();
logger.error(msg);
throw new IllegalStateException(msg);
}
final ZooKeeperTreeNode parent = parentMapping.remove(oldNode);
if (parent == null) {
final String msg = "oldNode does not have a parent: " + oldNode.getPath();
logger.error(msg);
throw new IllegalStateException(msg);
}
// Move up one level (towards the root)
newNode = createParent(
parent, Collections.singleton(oldNode), Collections.singleton(newNode),
parent.isDataConsistent(), parent.isChildListConsistent(), newNode.isFullyConsistent());
oldNode = parent;
}
setRootNode(newNode);
}
private boolean isFullyConsistent(Collection<ZooKeeperTreeNode> children) {
for (ZooKeeperTreeNode child : children) {
if (!child.isFullyConsistent()) {
return false;
}
}
return true;
}
/**
* Helper method to support testing.
*
* @param node the node to lookup the parent for.
* @return the parent or null.
*/
ZooKeeperTreeNode getParent(ZooKeeperTreeNode node) {
return parentMapping.get(node);
}
int getParentMappingSize() {
return parentMapping.size();
}
int getPathMappingSize() {
return pathMapping.size();
}
}
| edmunds/zookeeper-common | src/main/java/com/edmunds/zookeeper/treewatcher/ZooKeeperTreeState.java | Java | apache-2.0 | 13,693 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<style>
body {font-family:"consolas","微软雅黑","宋体";font-size:17px;line-height:30px;}
input {outline:none;font-family:"Arial","微软雅黑","宋体";font-size:17px;}
/* input框的一些样式 */
.textRight {text-align:right;}
.textCenter {text-align:center;}
.textLeft {text-align:left;}
.noBorder {border-width:0px;}
.lineBorder {border-width:0px 0px 1px 0px;border-color:black;}
/* button的样式 */
.button {
margin:3px;
font-size:17px;
line-height:17px;
height:40px;
min-width:100px;
border-radius:4px;
border-color:#e3e3e3;
border-style:solid;
border-width:1px;
background-color:#bddfe0;
cursor:pointer;
outline:none;
background:-webkit-gradient(linear,0%0%,0%100%,from(#d2eeff),to(#c4c5c9));
}
/* 标题框样式 */
.bigTtitleBox {
/*border-width:3px;
border-color:#40ca30;
border-style:solid;*/
border-radius:8px;
padding:16px;
margin:26px;
background-color:#dbf7ff;
}
/* 大标题的样式 */
.bigTtitleBox input {
outline:none;font-family:"Arial","微软雅黑","宋体";font-size:17px;
background-color:#dbf7ff;
}
/* 内容框的样式 */
.contextBox {
border-width:1px;
border-color:#6198a8;
border-style:solid;
border-radius:8px;
padding:16px;
margin:26px;
background-color:#8ed0e4;
}
.contextBox input {
outline:none;font-family:"Arial","微软雅黑","宋体";font-size:17px;
background-color:#8ed0e4;
}
</style>
</head>
<body>
</body>
</html> | MengShaoying/framework | application/templates/index/index.html | HTML | apache-2.0 | 1,776 |
package com.pepoc.joke.presenter;
import android.content.Context;
import com.pepoc.joke.data.bean.JokeContent;
import com.pepoc.joke.net.http.HttpRequestManager;
import com.pepoc.joke.net.http.request.RequestGetPublishedJokes;
import com.pepoc.joke.view.iview.IPersonalCenterView;
import java.util.List;
/**
* Created by Yangchen on 2015/12/29.
*/
public class PersonalCenterPresenter {
private IPersonalCenterView iPersonalCenterView;
/** 是否还有更多数据 */
private boolean isHasMoreData = true;
/** 是否正在请求数据 */
private boolean isRequesting = false;
private int page = 1;
public PersonalCenterPresenter(IPersonalCenterView iPersonalCenterView) {
this.iPersonalCenterView = iPersonalCenterView;
}
/**
* 获取数据
* @param isRefresh true:是刷新 false:加载更多
*/
public void getData(Context context, final boolean isRefresh, String userId) {
if (isRefresh) {
page = 1;
isHasMoreData = true;
} else {
if (!isHasMoreData) {
// Toast.makeText(context, "没有更多的数据了", Toast.LENGTH_SHORT).show();
return ;
}
page++;
}
RequestGetPublishedJokes request = new RequestGetPublishedJokes(context, new HttpRequestManager.OnHttpResponseListener() {
@Override
public void onHttpResponse(Object result) {
List<JokeContent> datas = (List<JokeContent>) result;
if (datas.size() < 20) {
isHasMoreData = false;
}
iPersonalCenterView.updateData(datas, isRefresh);
}
@Override
public void onError() {
iPersonalCenterView.onFail();
}
});
request.putParam("page", String.valueOf(page));
request.putParam("userId", userId);
HttpRequestManager.getInstance().sendRequest(request);
}
}
| pepoc/Joke | Joke/app/src/main/java/com/pepoc/joke/presenter/PersonalCenterPresenter.java | Java | apache-2.0 | 2,009 |
//------------------------------------------------------------------------------
// <generado automáticamente>
// Este código fue generado por una herramienta.
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </generado automáticamente>
//------------------------------------------------------------------------------
namespace WebApplication1 {
public partial class SiteMaster {
/// <summary>
/// Control MainContent.
/// </summary>
/// <remarks>
/// Campo generado automáticamente.
/// Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent;
}
}
| fioritonicolas/eLaw | WebApplication1/Site.Master.designer.cs | C# | apache-2.0 | 892 |
# Arachis macedoi Krapov. & W.C.Greg. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Bonplandia 8:55. 1994
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Arachis/Arachis macedoi/README.md | Markdown | apache-2.0 | 210 |
redes-servidor-smtp
===================
Implementaçao minima de um servidor SMTP para a disciplinas de rede
Contém hierarquia de pastas para demonstração de uso do git na
disciplina de construção de software
| ufgup/projeto-gcs-trabalho1-grupo-02 | README.md | Markdown | apache-2.0 | 216 |
from adt.util.prog import Prog
from adt.util.literal import Literal
from adt.util.expr import Expr
from adt.util.unary_op import Unary_op
from adt.util.binary_op import Binary_op
from adt.util.block import Block
from adt.util.context import Context
from adt.util.instr import Instr
from adt.types.bool import Bool
from adt.types.nat import Nat
from adt.types.char import Char
from adt.types.string import String
from adt.types.relative import Z
from adt.types.relative_list import List
from adt.types.map import Map
def test_eval_expr():
var = String('var')
lit1 = Literal.lit_nat(Nat(5))
lit2 = Literal.lit_nat(Nat(3))
context = Context.cons(c=Context.empty(), k=var, v=lit2)
expr = Expr.expr_lit(lit1)
# literal
assert Prog.eval_expr(expr=expr, context=context) == lit1
# variable
assert Prog.eval_expr(expr=Expr.expr_variable(var), context=context) == lit2
# unary operations
# o.not
lit_true = Literal.lit_bool(Bool.true())
lit_false = Literal.lit_bool(Bool.false())
op = Unary_op.o_not()
expr_bool = Expr.expr_unary(op=op, expr=Expr.expr_lit(lit_true))
assert Prog.eval_expr(expr=expr_bool, context=context) == lit_false
assert Prog.eval_expr(expr=expr_bool, context=context) != lit_true
# uSub
lit_z = Literal.lit_z(Z(2))
lit_z2 = Literal.lit_z(Z(-2))
op = Unary_op.uSub()
expr_z = Expr.expr_unary(op=op, expr=Expr.expr_lit(lit_z))
assert Prog.eval_expr(expr=expr_z, context=context) == lit_z2
# binary operations
# add
lit_z1 = Literal.lit_z(Z(2))
lit_z2 = Literal.lit_z(Z(-5))
lit_z3 = Literal.lit_z(Z(-3))
op = Binary_op.add()
expr = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_z1), expr2=Expr.expr_lit(lit_z2))
assert Prog.eval_expr(expr=expr, context=context) == lit_z3
# sub
lit_z3 = Literal.lit_z(Z(7))
op = Binary_op.sub()
expr = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_z1), expr2=Expr.expr_lit(lit_z2))
assert Prog.eval_expr(expr=expr, context=context) == lit_z3
# mult
lit_z3 = Literal.lit_z(Z(10))
op = Binary_op.mult()
expr = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_z1), expr2=Expr.expr_lit(lit_z2))
# assert Prog.eval_expr(expr=expr, context=context) == lit_z3
# div
lit_z3 = Literal.lit_z(Z(2))
op = Binary_op.div()
expr = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_z2), expr2=Expr.expr_lit(lit_z1))
# assert Prog.eval_expr(expr=expr, context=context) == lit_z3
# modulo
lit_z3 = Literal.lit_z(Z(1))
op = Binary_op.modulo()
expr = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_z2), expr2=Expr.expr_lit(lit_z1))
# assert Prog.eval_expr(expr=expr, context=context) == lit_z3
# and
op = Binary_op.o_and()
expr1 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_true), expr2=Expr.expr_lit(lit_true))
expr2 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_false), expr2=Expr.expr_lit(lit_true))
assert Prog.eval_expr(expr=expr1, context=context) == lit_true
assert Prog.eval_expr(expr=expr2, context=context) == lit_false
assert Prog.eval_expr(expr=expr2, context=context) != lit_true
# or
op = Binary_op.o_or()
expr1 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_false), expr2=Expr.expr_lit(lit_false))
expr2 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_false), expr2=Expr.expr_lit(lit_true))
assert Prog.eval_expr(expr=expr1, context=context) == lit_false
assert Prog.eval_expr(expr=expr2, context=context) == lit_true
assert Prog.eval_expr(expr=expr2, context=context) != lit_false
# xor
op = Binary_op.xor()
expr1 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_true), expr2=Expr.expr_lit(lit_true))
expr2 = Expr.expr_binary(op=op, expr1=Expr.expr_lit(lit_false), expr2=Expr.expr_lit(lit_true))
assert Prog.eval_expr(expr=expr1, context=context) == lit_false
assert Prog.eval_expr(expr=expr2, context=context) == lit_true
assert Prog.eval_expr(expr=expr2, context=context) != lit_false
| mencattini/ideal-pancake | adt/tests/prog_test.py | Python | apache-2.0 | 4,066 |
/*!
* ${copyright}
*/
sap.ui.define([
"jquery.sap.global",
"./_Helper",
"./_MetadataConverter"
], function (jQuery, _Helper, _MetadataConverter) {
"use strict";
var sEdmxNamespace = "http://docs.oasis-open.org/odata/ns/edmx",
V4MetadataConverter,
oAnnotationConfig = _MetadataConverter.oAnnotationConfig,
oAliasConfig = {
"Reference" : {
"Include" : {__processor : _MetadataConverter.processAlias}
},
"DataServices" : {
"Schema" : {__processor : _MetadataConverter.processAlias}
}
},
oStructuredTypeConfig = {
"Property" : {
__processor : processTypeProperty,
__include : [oAnnotationConfig]
},
"NavigationProperty" : {
__processor : processTypeNavigationProperty,
__include : [oAnnotationConfig],
"OnDelete" : {
__processor : processTypeNavigationPropertyOnDelete,
__include : [oAnnotationConfig]
},
"ReferentialConstraint" : {
__processor : processTypeNavigationPropertyReferentialConstraint,
__include : [oAnnotationConfig]
}
}
},
oEntitySetConfig = {
"NavigationPropertyBinding" : {
__processor : processNavigationPropertyBinding
}
},
oActionOrFunctionConfig = {
"Parameter" : {
__processor : processParameter,
__include : [oAnnotationConfig]
},
"ReturnType" : {
__processor : processReturnType,
__include : [oAnnotationConfig]
}
},
oFullConfig = {
__processor : processEdmx,
__include : [_MetadataConverter.oReferenceInclude],
"DataServices" : {
"Schema" : {
__processor : processSchema,
__include : [_MetadataConverter.oAnnotationsConfig, oAnnotationConfig],
"Action" : {
__processor : processActionOrFunction,
__include : [oActionOrFunctionConfig, oAnnotationConfig]
},
"Function" : {
__processor : processActionOrFunction,
__include : [oActionOrFunctionConfig, oAnnotationConfig]
},
"EntityType" : {
__processor : processEntityType,
__include : [oStructuredTypeConfig, oAnnotationConfig],
"Key" : {
"PropertyRef" : {
__processor : processEntityTypeKeyPropertyRef
}
}
},
"ComplexType" : {
__processor : processComplexType,
__include : [oStructuredTypeConfig, oAnnotationConfig]
},
"EntityContainer" : {
__processor : processEntityContainer,
__include : [oAnnotationConfig],
"ActionImport" : {
__processor : processImport.bind(null, "Action"),
__include : [oAnnotationConfig]
},
"EntitySet" : {
__processor : processEntitySet,
__include : [oEntitySetConfig, oAnnotationConfig]
},
"FunctionImport" : {
__processor : processImport.bind(null, "Function"),
__include : [oAnnotationConfig]
},
"Singleton" : {
__processor : processSingleton,
__include : [oEntitySetConfig, oAnnotationConfig]
}
},
"EnumType" : {
__processor : processEnumType,
__include : [oAnnotationConfig],
"Member" : {
__processor : processEnumTypeMember,
__include : [oAnnotationConfig]
}
},
"Term" : {
__processor : processTerm,
__include : [oAnnotationConfig]
},
"TypeDefinition" : {
__processor : processTypeDefinition,
__include : [oAnnotationConfig]
}
}
}
};
/**
* Processes an Action or Function element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processActionOrFunction(oElement, oAggregate) {
var sKind = oElement.localName,
sQualifiedName = oAggregate.namespace + oElement.getAttribute("Name"),
oAction = {
$kind : sKind
};
V4MetadataConverter.processAttributes(oElement, oAction, {
"IsBound" : V4MetadataConverter.setIfTrue,
"EntitySetPath" : V4MetadataConverter.setValue,
"IsComposable" : V4MetadataConverter.setIfTrue
});
V4MetadataConverter.getOrCreateArray(oAggregate.result, sQualifiedName).push(oAction);
oAggregate.actionOrFunction = oAction;
V4MetadataConverter.annotatable(oAggregate, oAction);
}
/**
* Processes a ComplexType element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processComplexType(oElement, oAggregate) {
processType(oElement, oAggregate, {"$kind" : "ComplexType"});
}
/**
* Processes the Edmx element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEdmx(oElement, oAggregate) {
V4MetadataConverter.processAttributes(oElement, oAggregate.result, {
"Version" : V4MetadataConverter.setValue
});
}
/**
* Processes an EntityContainer element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEntityContainer(oElement, oAggregate) {
var sQualifiedName = oAggregate.namespace + oElement.getAttribute("Name");
oAggregate.result[sQualifiedName] = oAggregate.entityContainer = {
"$kind" : "EntityContainer"
};
oAggregate.result.$EntityContainer = sQualifiedName;
V4MetadataConverter.annotatable(oAggregate, sQualifiedName);
}
/**
* Processes an EntitySet element at the EntityContainer.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEntitySet(oElement, oAggregate) {
var sName = oElement.getAttribute("Name");
oAggregate.entityContainer[sName] = oAggregate.entitySet = {
$kind : "EntitySet",
$Type :
V4MetadataConverter.resolveAlias(oElement.getAttribute("EntityType"), oAggregate)
};
V4MetadataConverter.processAttributes(oElement, oAggregate.entitySet, {
"IncludeInServiceDocument" : V4MetadataConverter.setIfFalse
});
V4MetadataConverter.annotatable(oAggregate, sName);
}
/**
* Processes an EntityType element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEntityType(oElement, oAggregate) {
processType(oElement, oAggregate, {
$kind : "EntityType"
});
}
/**
* Processes a PropertyRef element of the EntityType's Key.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEntityTypeKeyPropertyRef(oElement, oAggregate) {
var sAlias = oElement.getAttribute("Alias"),
vKey,
sName = oElement.getAttribute("Name");
if (sAlias) {
vKey = {};
vKey[sAlias] = sName;
} else {
vKey = sName;
}
V4MetadataConverter.getOrCreateArray(oAggregate.type, "$Key").push(vKey);
}
/**
* Processes an EnumType element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEnumType(oElement, oAggregate) {
var sQualifiedName = oAggregate.namespace + oElement.getAttribute("Name"),
oEnumType = {
"$kind" : "EnumType"
};
V4MetadataConverter.processAttributes(oElement, oEnumType, {
"IsFlags" : V4MetadataConverter.setIfTrue,
"UnderlyingType" : function (sValue) {
return sValue !== "Edm.Int32" ? sValue : undefined;
}
});
oAggregate.result[sQualifiedName] = oAggregate.enumType = oEnumType;
oAggregate.enumTypeMemberCounter = 0;
V4MetadataConverter.annotatable(oAggregate, sQualifiedName);
}
/**
* Processes a Member element within an EnumType.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processEnumTypeMember(oElement, oAggregate) {
var sName = oElement.getAttribute("Name"),
sValue = oElement.getAttribute("Value"),
vValue;
if (sValue) {
vValue = parseInt(sValue, 10);
if (!_Helper.isSafeInteger(vValue)) {
vValue = sValue;
}
} else {
vValue = oAggregate.enumTypeMemberCounter;
oAggregate.enumTypeMemberCounter++;
}
oAggregate.enumType[sName] = vValue;
V4MetadataConverter.annotatable(oAggregate, sName);
}
/**
* Processes an ActionImport or FunctionImport element.
* @param {string} sWhat "Action" or "Function"
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processImport(sWhat, oElement, oAggregate) {
var oImport = {
$kind : sWhat + "Import"
},
sName = oElement.getAttribute("Name");
oImport["$" + sWhat]
= V4MetadataConverter.resolveAlias(oElement.getAttribute(sWhat), oAggregate);
V4MetadataConverter.processAttributes(oElement, oImport, {
"EntitySet" : function (sValue) {
return V4MetadataConverter.resolveTargetPath(sValue, oAggregate);
},
"IncludeInServiceDocument" : V4MetadataConverter.setIfTrue
});
oAggregate.entityContainer[sName] = oImport;
V4MetadataConverter.annotatable(oAggregate, sName);
}
/**
* Processes a NavigationPropertyBinding element within an EntitySet or Singleton.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processNavigationPropertyBinding(oElement, oAggregate) {
var oNavigationPropertyBinding = V4MetadataConverter.getOrCreateObject(
oAggregate.entitySet, "$NavigationPropertyBinding");
oNavigationPropertyBinding[oElement.getAttribute("Path")]
= V4MetadataConverter.resolveTargetPath(oElement.getAttribute("Target"), oAggregate);
}
/**
* Processes a Parameter element within an Action or Function.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processParameter(oElement, oAggregate) {
var oActionOrFunction = oAggregate.actionOrFunction,
oParameter = {};
processTypedCollection(oElement.getAttribute("Type"), oParameter, oAggregate);
V4MetadataConverter.processAttributes(oElement, oParameter, {
"Name" : V4MetadataConverter.setValue,
"Nullable" : V4MetadataConverter.setIfFalse
});
V4MetadataConverter.processFacetAttributes(oElement, oParameter);
V4MetadataConverter.getOrCreateArray(oActionOrFunction, "$Parameter").push(oParameter);
V4MetadataConverter.annotatable(oAggregate, oParameter);
}
/**
* Processes a ReturnType element within an Action or Function.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processReturnType(oElement, oAggregate) {
var oActionOrFunction = oAggregate.actionOrFunction,
oReturnType = {};
processTypedCollection(oElement.getAttribute("Type"), oReturnType, oAggregate);
V4MetadataConverter.processAttributes(oElement, oReturnType, {
"Nullable" : V4MetadataConverter.setIfFalse
});
V4MetadataConverter.processFacetAttributes(oElement, oReturnType);
oActionOrFunction.$ReturnType = oReturnType;
V4MetadataConverter.annotatable(oAggregate, oReturnType);
}
/**
* Processes a Schema element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processSchema(oElement, oAggregate) {
oAggregate.namespace = oElement.getAttribute("Namespace") + ".";
oAggregate.result[oAggregate.namespace] = oAggregate.schema = {
"$kind" : "Schema"
};
V4MetadataConverter.annotatable(oAggregate, oAggregate.schema);
}
/**
* Processes a Singleton element at the EntityContainer.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processSingleton(oElement, oAggregate) {
var sName = oElement.getAttribute("Name");
oAggregate.entityContainer[sName] = oAggregate.entitySet = {
$kind : "Singleton",
$Type : V4MetadataConverter.resolveAlias(oElement.getAttribute("Type"), oAggregate)
};
V4MetadataConverter.annotatable(oAggregate, sName);
}
/**
* Processes a Term element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processTerm(oElement, oAggregate) {
var sQualifiedName = oAggregate.namespace + oElement.getAttribute("Name"),
oTerm = {
$kind : "Term"
};
processTypedCollection(oElement.getAttribute("Type"), oTerm, oAggregate);
V4MetadataConverter.processAttributes(oElement, oTerm, {
"Nullable" : V4MetadataConverter.setIfFalse,
"BaseTerm" : function (sValue) {
return sValue ? V4MetadataConverter.resolveAlias(sValue, oAggregate) : undefined;
}
});
V4MetadataConverter.processFacetAttributes(oElement, oTerm);
oAggregate.result[sQualifiedName] = oTerm;
V4MetadataConverter.annotatable(oAggregate, sQualifiedName);
}
/**
* Processes a ComplexType or EntityType element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
* @param {object} oType The initial typed result object
*/
function processType(oElement, oAggregate, oType) {
var sQualifiedName = oAggregate.namespace + oElement.getAttribute("Name");
V4MetadataConverter.processAttributes(oElement, oType, {
"OpenType" : V4MetadataConverter.setIfTrue,
"HasStream" : V4MetadataConverter.setIfTrue,
"Abstract" : V4MetadataConverter.setIfTrue,
"BaseType" : function (sType) {
return sType ? V4MetadataConverter.resolveAlias(sType, oAggregate) : undefined;
}
});
oAggregate.result[sQualifiedName] = oAggregate.type = oType;
V4MetadataConverter.annotatable(oAggregate, sQualifiedName);
}
/**
* Processes the type in the form "Type" or "Collection(Type)" and sets the appropriate
* properties.
* @param {string} sType The type attribute from the Element
* @param {object} oProperty The property attribute in the JSON
* @param {object} oAggregate The aggregate
*/
function processTypedCollection(sType, oProperty, oAggregate) {
var aMatches = V4MetadataConverter.rCollection.exec(sType);
if (aMatches) {
oProperty.$isCollection = true;
sType = aMatches[1];
}
oProperty.$Type = V4MetadataConverter.resolveAlias(sType, oAggregate);
}
/**
* Processes a TypeDefinition element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processTypeDefinition(oElement, oAggregate) {
var sQualifiedName = oAggregate.namespace + oElement.getAttribute("Name"),
oTypeDefinition = {
"$kind" : "TypeDefinition",
"$UnderlyingType" : oElement.getAttribute("UnderlyingType")
};
oAggregate.result[sQualifiedName] = oTypeDefinition;
V4MetadataConverter.processFacetAttributes(oElement, oTypeDefinition);
V4MetadataConverter.annotatable(oAggregate, sQualifiedName);
}
/**
* Processes a NavigationProperty element of a structured type.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processTypeNavigationProperty(oElement, oAggregate) {
var sName = oElement.getAttribute("Name"),
oProperty = {
$kind : "NavigationProperty"
};
processTypedCollection(oElement.getAttribute("Type"), oProperty, oAggregate);
V4MetadataConverter.processAttributes(oElement, oProperty, {
"Nullable" : V4MetadataConverter.setIfFalse,
"Partner" : V4MetadataConverter.setValue,
"ContainsTarget" : V4MetadataConverter.setIfTrue
});
oAggregate.type[sName] = oAggregate.navigationProperty = oProperty;
V4MetadataConverter.annotatable(oAggregate, sName);
}
/**
* Processes a NavigationProperty OnDelete element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processTypeNavigationPropertyOnDelete(oElement, oAggregate) {
oAggregate.navigationProperty.$OnDelete = oElement.getAttribute("Action");
V4MetadataConverter.annotatable(oAggregate, oAggregate.navigationProperty, "$OnDelete");
}
/**
* Processes a NavigationProperty OnDelete element.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processTypeNavigationPropertyReferentialConstraint(oElement, oAggregate) {
var sProperty = oElement.getAttribute("Property"),
oReferentialConstraint = V4MetadataConverter.getOrCreateObject(
oAggregate.navigationProperty, "$ReferentialConstraint");
oReferentialConstraint[sProperty] = oElement.getAttribute("ReferencedProperty");
V4MetadataConverter.annotatable(oAggregate, oReferentialConstraint, sProperty);
}
/**
* Processes a Property element of a structured type.
* @param {Element} oElement The element
* @param {object} oAggregate The aggregate
*/
function processTypeProperty(oElement, oAggregate) {
var sName = oElement.getAttribute("Name"),
oProperty = {
"$kind" : "Property"
};
processTypedCollection(oElement.getAttribute("Type"), oProperty, oAggregate);
V4MetadataConverter.processAttributes(oElement, oProperty, {
"Nullable" : V4MetadataConverter.setIfFalse,
"DefaultValue" : V4MetadataConverter.setValue
});
V4MetadataConverter.processFacetAttributes(oElement, oProperty);
oAggregate.type[sName] = oProperty;
V4MetadataConverter.annotatable(oAggregate, sName);
}
V4MetadataConverter = jQuery.extend({}, _MetadataConverter, {
/**
* Converts the metadata from XML format to a JSON object.
*
* @param {Document} oDocument
* The XML DOM document
* @param {string} sUrl
* The URL by which this document has been loaded (for error messages)
* @returns {object}
* The metadata JSON
*/
convertXMLMetadata : function (oDocument, sUrl) {
var oAggregate, oElement;
jQuery.sap.measure.average("convertXMLMetadata", "",
"sap.ui.model.odata.v4.lib._V4MetadataConverter");
oElement = oDocument.documentElement;
if (oElement.localName !== "Edmx" || oElement.namespaceURI !== sEdmxNamespace) {
throw new Error(sUrl + " is not a valid OData V4 metadata document");
}
oAggregate = {
"actionOrFunction" : null, // the current action or function
"aliases" : {}, // maps alias -> namespace
"annotatable" : null, // the current annotatable, see function annotatable
"entityContainer" : null, // the current EntityContainer
"entitySet" : null, // the current EntitySet/Singleton
"enumType" : null, // the current EnumType
"enumTypeMemberCounter" : 0, // the current EnumType member value counter
"namespace" : null, // the namespace of the current Schema
"navigationProperty" : null, // the current NavigationProperty
"processFacetAttributes" : V4MetadataConverter.processFacetAttributes,
"processTypedCollection" : processTypedCollection,
"reference" : null, // the current Reference
"schema" : null, // the current Schema
"type" : null, // the current EntityType/ComplexType
"result" : {}
};
// first round: find aliases
V4MetadataConverter.traverse(oElement, oAggregate, oAliasConfig);
// second round, full conversion
V4MetadataConverter.traverse(oElement, oAggregate, oFullConfig);
if (oAggregate.result.$Version !== "4.0") {
throw new Error(sUrl + ": Unsupported OData version " + oAggregate.result.$Version);
}
jQuery.sap.measure.end("convertXMLMetadata");
return oAggregate.result;
},
/**
* Processes the TFacetAttributes and TPropertyFacetAttributes of the elements Property,
* TypeDefinition etc.
* @param {Element} oElement The element
* @param {object} oResult The result object to fill
*/
processFacetAttributes : function (oElement, oResult) {
V4MetadataConverter.processAttributes(oElement, oResult, {
"MaxLength" : function (sValue) {
return sValue === "max" ? undefined : V4MetadataConverter.setNumber(sValue);
},
"Precision" : V4MetadataConverter.setNumber,
"Scale" : function (sValue) {
return sValue === "variable" ? sValue : V4MetadataConverter.setNumber(sValue);
},
"SRID" : V4MetadataConverter.setValue,
"Unicode" : V4MetadataConverter.setIfFalse
});
}
});
return V4MetadataConverter;
}, /* bExport= */false);
| nzamani/openui5 | src/sap.ui.core/src/sap/ui/model/odata/v4/lib/_V4MetadataConverter.js | JavaScript | apache-2.0 | 19,617 |
/**
* Copyright 2014 Christian Kreutzfeldt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mnxfst.stream.pipeline.message;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import akka.actor.ActorRef;
/**
* Reports an update of element {@link ActorRef references}
* @author mnxfst
* @since 05.03.2014
*
*/
@JsonRootName ( value = "pipelineElementReferenceUpdateMessage" )
public class PipelineElementReferenceUpdateMessage implements Serializable {
private static final long serialVersionUID = 2822558124362700694L;
/** identifier of pipeline the referenced elements belong to */
@JsonProperty ( value = "pipelineId", required = true )
private String pipelineId;
/** element identifiers along with their node references */
@JsonProperty ( value = "elementReferences", required = true )
private Map<String, ActorRef> elementReferences = new HashMap<>();
/**
* Default constructor
*/
public PipelineElementReferenceUpdateMessage() {
}
/**
* Initializes the message using the provided input
* @param pipelineId
*/
public PipelineElementReferenceUpdateMessage(final String pipelineId) {
this.pipelineId = pipelineId;
}
/**
* Adds a new element reference
* @param elementId
* @param elementReference
*/
public void addElementReference(final String elementId, final ActorRef elementReference) {
this.elementReferences.put(elementId, elementReference);
}
public String getPipelineId() {
return pipelineId;
}
public void setPipelineId(String pipelineId) {
this.pipelineId = pipelineId;
}
public Map<String, ActorRef> getElementReferences() {
return elementReferences;
}
public void setElementReferences(Map<String, ActorRef> elementReferences) {
this.elementReferences = elementReferences;
}
}
| mnxfst/stream-analyzer | src/main/java/com/mnxfst/stream/pipeline/message/PipelineElementReferenceUpdateMessage.java | Java | apache-2.0 | 2,439 |
package com.github.megatronking.svg.iconlibs;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import com.github.megatronking.svg.support.SVGRenderer;
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SVG-Generator. It should not be modified by hand.
*/
public class ic_phone extends SVGRenderer {
public ic_phone(Context context) {
super(context);
mAlpha = 1.0f;
mWidth = dip2px(24.0f);
mHeight = dip2px(24.0f);
}
@Override
public void render(Canvas canvas, int w, int h, ColorFilter filter) {
final float scaleX = w / 24.0f;
final float scaleY = h / 24.0f;
mPath.reset();
mRenderPath.reset();
mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
mFinalPathMatrix.postScale(scaleX, scaleY);
mPath.moveTo(6.62f, 10.79f);
mPath.rCubicTo(1.44f, 2.83f, 3.76f, 5.14f, 6.59f, 6.59f);
mPath.rLineTo(2.2f, -2.2f);
mPath.rCubicTo(0.27f, -0.27f, 0.67f, -0.36f, 1.02f, -0.24f);
mPath.rCubicTo(1.12f, 0.37f, 2.33f, 0.57f, 3.57f, 0.57f);
mPath.rCubicTo(0.55f, 0.0f, 1.0f, 0.45f, 1.0f, 1.0f);
mPath.lineTo(21.0f, 20.0f);
mPath.rCubicTo(0.0f, 0.55f, -0.45f, 1.0f, -1.0f, 1.0f);
mPath.rCubicTo(-9.39f, 0.0f, -17.0f, -7.61f, -17.0f, -17.0f);
mPath.rCubicTo(0.0f, -0.55f, 0.45f, -1.0f, 1.0f, -1.0f);
mPath.rLineTo(3.5f, 0f);
mPath.rCubicTo(0.55f, 0.0f, 1.0f, 0.45f, 1.0f, 1.0f);
mPath.rCubicTo(0.0f, 1.25f, 0.2f, 2.45f, 0.57f, 3.57f);
mPath.rCubicTo(0.11f, 0.35f, 0.03f, 0.74f, -0.25f, 1.02f);
mPath.rLineTo(-2.2f, 2.2f);
mPath.close();
mPath.moveTo(6.62f, 10.79f);
mRenderPath.addPath(mPath, mFinalPathMatrix);
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
mFillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, mFillPaint);
}
} | MegatronKing/SVG-Android | svg-iconlibs/communication/src/main/java/com/github/megatronking/svg/iconlibs/ic_phone.java | Java | apache-2.0 | 2,288 |
# Mycena vitilis f. pumila Kühner FORM
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Encyclop. Mycol. 10: 303 (1938)
#### Original name
Mycena vitilis f. pumila Kühner
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Mycenaceae/Mycena/Mycena vitilis/Mycena vitilis pumila/README.md | Markdown | apache-2.0 | 217 |
package com.elytradev.movingworld.common.chunk.assembly;
import com.elytradev.movingworld.MovingWorldMod;
import com.elytradev.movingworld.common.chunk.LocatedBlock;
import com.elytradev.movingworld.common.chunk.MovingWorldAssemblyInteractor;
import com.elytradev.movingworld.common.chunk.MovingWorldSizeOverflowException;
import com.elytradev.movingworld.common.event.AssembleBlockEvent;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class ChunkAssembler {
public final BlockPos start;
private final int maxBlocks;
private World worldObj;
public ChunkAssembler(World world, BlockPos startPos, int maxMovingWorldBlocks) {
worldObj = world;
start = startPos;
maxBlocks = maxMovingWorldBlocks;
}
public AssembleResult doAssemble(MovingWorldAssemblyInteractor interactor) {
AssembleResult result = new AssembleResult();
result.offset = start;
result.assemblyInteractor = interactor;
try {
if (MovingWorldMod.INSTANCE.getNetworkConfig().getShared().iterativeAlgorithm) {
assembleIterative(result, result.assemblyInteractor, start);
} else {
assembleRecursive(result, new HashSet<>(), result.assemblyInteractor, start);
}
if (result.movingWorldMarkingBlock == null) {
result.resultType = AssembleResult.ResultType.RESULT_MISSING_MARKER;
} else {
result.resultType = AssembleResult.ResultType.RESULT_OK;
}
} catch (MovingWorldSizeOverflowException e) {
result.resultType = AssembleResult.ResultType.RESULT_BLOCK_OVERFLOW;
} catch (Error e) {
result.resultType = AssembleResult.ResultType.RESULT_ERROR_OCCURED;
MovingWorldMod.LOG.error(e.toString());
}
result.assemblyInteractor.chunkAssembled(result);
return result;
}
private void assembleIterative(AssembleResult result, MovingWorldAssemblyInteractor assemblyInteractor, BlockPos worldPos) throws MovingWorldSizeOverflowException {
HashSet<BlockPos> openSet = new HashSet<>();
HashSet<BlockPos> closedSet = new HashSet<>();
List<BlockPos> iterator = new ArrayList<>();
LocatedBlock movingWorldMarker = null;
openSet.add(new BlockPos(worldPos));
while (!openSet.isEmpty()) {
iterator.addAll(openSet);
for (BlockPos mobileChunkPos : iterator) {
openSet.remove(mobileChunkPos);
if (closedSet.contains(mobileChunkPos)) {
continue;
}
if (result.assembledBlocks.size() > maxBlocks) {
throw new MovingWorldSizeOverflowException();
}
worldPos = new BlockPos(mobileChunkPos);
closedSet.add(mobileChunkPos);
IBlockState blockState = worldObj.getBlockState(worldPos);
CanAssemble canAssemble = canUseBlockForVehicle(new LocatedBlock(blockState, worldObj.getTileEntity(worldPos), worldPos), assemblyInteractor);
if (canAssemble.justCancel) {
continue;
}
LocatedBlock lb = new LocatedBlock(blockState, worldObj.getTileEntity(worldPos), mobileChunkPos);
assemblyInteractor.blockAssembled(lb);
if (assemblyInteractor.isTileMovingWorldMarker(lb.tileEntity) || assemblyInteractor.isBlockMovingWorldMarker(lb.blockState.getBlock())) {
if (movingWorldMarker == null)
movingWorldMarker = lb;
}
AssembleBlockEvent event = new AssembleBlockEvent(lb);
MinecraftForge.EVENT_BUS.post(event);
result.assembleBlock(lb);
if (!canAssemble.assembleThenCancel) {
openSet.add(worldPos.add(-1, 0, 0));
openSet.add(worldPos.add(0, -1, 0));
openSet.add(worldPos.add(0, 0, -1));
openSet.add(worldPos.add(1, 0, 0));
openSet.add(worldPos.add(0, 1, 0));
openSet.add(worldPos.add(0, 0, 1));
if (assemblyInteractor.doDiagonalAssembly()) {
openSet.add(worldPos.add(-1, -1, +0));
openSet.add(worldPos.add(+1, -1, +0));
openSet.add(worldPos.add(+1, +1, +0));
openSet.add(worldPos.add(-1, +1, +0));
openSet.add(worldPos.add(-1, +0, -1));
openSet.add(worldPos.add(+1, +0, -1));
openSet.add(worldPos.add(+1, +0, +1));
openSet.add(worldPos.add(-1, +0, +1));
openSet.add(worldPos.add(+0, -1, -1));
openSet.add(worldPos.add(+0, +1, -1));
openSet.add(worldPos.add(+0, +1, +1));
openSet.add(worldPos.add(+0, -1, +1));
}
}
}
}
result.movingWorldMarkingBlock = movingWorldMarker;
}
private void assembleRecursive(AssembleResult result, HashSet<BlockPos> set, MovingWorldAssemblyInteractor assemblyInteractor, BlockPos pos) throws MovingWorldSizeOverflowException {
LocatedBlock movingWorldMarker = null;
if (result.assembledBlocks.size() > maxBlocks) {
throw new MovingWorldSizeOverflowException();
}
if (set.contains(pos)) return;
set.add(pos);
IBlockState blockState = worldObj.getBlockState(pos);
Block block = blockState.getBlock();
CanAssemble canAssemble = canUseBlockForVehicle(new LocatedBlock(blockState, worldObj.getTileEntity(pos), pos), assemblyInteractor);
if (canAssemble.justCancel) {
return;
}
LocatedBlock lb = new LocatedBlock(blockState, worldObj.getTileEntity(pos), pos);
assemblyInteractor.blockAssembled(lb);
if (assemblyInteractor.isBlockMovingWorldMarker(block) || assemblyInteractor.isTileMovingWorldMarker(lb.tileEntity)) {
if (movingWorldMarker == null)
movingWorldMarker = lb;
}
AssembleBlockEvent event = new AssembleBlockEvent(lb);
MinecraftForge.EVENT_BUS.post(event);
result.assembleBlock(lb);
if (!canAssemble.assembleThenCancel) {
assembleRecursive(result, set, assemblyInteractor, pos.add(-1, +0, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, -1, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, +0, -1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+1, +0, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, +1, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, +0, +1));
if (assemblyInteractor.doDiagonalAssembly()) {
assembleRecursive(result, set, assemblyInteractor, pos.add(-1, -1, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(+1, -1, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(+1, +1, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(-1, +1, +0));
assembleRecursive(result, set, assemblyInteractor, pos.add(-1, +0, -1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+1, +0, -1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+1, +0, +1));
assembleRecursive(result, set, assemblyInteractor, pos.add(-1, +0, +1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, -1, -1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, +1, -1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, +1, +1));
assembleRecursive(result, set, assemblyInteractor, pos.add(+0, -1, +1));
}
}
result.movingWorldMarkingBlock = movingWorldMarker;
}
public CanAssemble canUseBlockForVehicle(LocatedBlock lb, MovingWorldAssemblyInteractor assemblyInteractor) {
return assemblyInteractor.isBlockAllowed(worldObj, lb);
}
}
| elytra/MovingWorld | src/main/java/com/elytradev/movingworld/common/chunk/assembly/ChunkAssembler.java | Java | apache-2.0 | 8,619 |
using System.Linq;
using Audiotica.Web.MatchEngine.Interfaces.Validators;
namespace Audiotica.Web.MatchEngine.Validators
{
/// <summary>
/// A base for implementing <see cref="ISongTypeValidator" /> that comes with a
/// <see cref="IsTypeValid" />
/// helper that uses the <see cref="SongTypeValidatorBase.IsNameValidType" /> helper to determine if is valid.
/// </summary>
public abstract class BasicSongTypeValidatorBase : SongTypeValidatorBase
{
/// <summary>
/// Validates the specified name against each type provided.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="matchName">Title of the match.</param>
/// <param name="types">The types, each one should be interchangeable.</param>
/// <returns></returns>
protected bool IsTypeValid(string name, string matchName, params string[] types)
{
name = name.ToLower();
matchName = matchName.ToLower();
var isSupposedType = false;
var isType = false;
foreach (var loweredType in types.Select(type => type.ToLower()))
{
if (!isType)
isType = IsNameValidType(matchName, loweredType);
if (!isSupposedType)
isSupposedType = IsNameValidType(name, loweredType);
if (isSupposedType && isType)
return true;
}
return !isSupposedType && !isType;
}
}
} | zumicts/Audiotica | Audiotica.Web/MatchEngine/Validators/BasicSongTypeValidatorBase.cs | C# | apache-2.0 | 1,556 |
# Atata Sample App Tests
[](https://dev.azure.com/atata-framework/atata-sample-app-tests/_build/latest?definitionId=26)
[](https://atata.io)
[](https://gitter.im/atata-framework/atata)
[](https://join.slack.com/t/atata-framework/shared_invite/zt-5j3lyln7-WD1ZtMDzXBhPm0yXLDBzbA)
[](https://twitter.com/AtataFramework)
Automated UI tests C#/.NET application based on [Atata Framework](https://github.com/atata-framework/atata).
It uses [Atata Sample App](https://demo.atata.io) ([repository](https://github.com/atata-framework/atata-sample-app)) as a testing website and NUnit 3 as a test engine.
Tests application demonstrates different testing approaches and features of Atata Framework.
## Features
* Atata configuation and settings set-up.
* Page navigation.
* Controls finding.
* Data input and verification.
* Validation messages verification.
* Usage of triggers.
* Interaction with pop-ups (Bootstrap modal) and alerts.
* Work with tables.
* Logging and screenshots.
* Page HTML validation.
## Sample Test
```cs
[Test]
public void User_Create()
{
string firstName, lastName, email;
Office office = Office.NewYork;
Gender gender = Gender.Male;
Login().
New().
ModalTitle.Should.Be("New User").
General.FirstName.SetRandom(out firstName).
General.LastName.SetRandom(out lastName).
General.Email.SetRandom(out email).
General.Office.Set(office).
General.Gender.Set(gender).
Save().
Users.Rows[x => x.Email == email].View().
AggregateAssert(x => x.
Header.Should.Be($"{firstName} {lastName}").
Email.Should.Be(email).
Office.Should.Be(office).
Gender.Should.Be(gender).
Birthday.Should.Not.Exist().
Notes.Should.Not.Exist());
}
```
## License
Atata is an open source software, licensed under the Apache License 2.0. See [LICENSE](LICENSE) for details.
| atata-framework/atata-sample-app-tests | README.md | Markdown | apache-2.0 | 2,449 |
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigtable.hbase;
import com.google.bigtable.v2.MutateRowRequest;
import com.google.bigtable.v2.MutateRowResponse;
import com.google.cloud.bigtable.config.BigtableOptions;
import com.google.cloud.bigtable.grpc.BigtableDataClient;
import com.google.cloud.bigtable.grpc.BigtableDataGrpcClient;
import com.google.cloud.bigtable.grpc.BigtableSession;
import com.google.cloud.bigtable.grpc.BigtableSessionSharedThreadPools;
import com.google.cloud.bigtable.grpc.io.ChannelPool;
import com.google.cloud.bigtable.hbase.adapters.HBaseRequestAdapter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import io.grpc.CallOptions;
import io.grpc.ClientCall;
import io.grpc.ManagedChannel;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class PutMicroBenchmark {
static final int NUM_CELLS = 10;
private static final byte[] COLUMN_FAMILY = Bytes.toBytes("test_family");
private final static int REAL_CHANNEL_PUT_COUNT = 100;
private final static int FAKE_CHANNEL_PUT_COUNT = 100_000;
private static final int VALUE_SIZE = 100;
private static BigtableOptions options;
public static void main(String[] args) throws Exception {
String projectId = args.length > 0 ? args[0] : "project";
String instanceId = args.length > 1 ? args[1] : "instanceId";
String tableId = args.length > 2 ? args[2] : "table";
options = new BigtableOptions.Builder()
.setProjectId(projectId)
.setInstanceId(instanceId)
.setUserAgent("put_microbenchmark")
.build();
boolean useRealConnection = args.length >= 2;
int putCount = useRealConnection ? REAL_CHANNEL_PUT_COUNT : FAKE_CHANNEL_PUT_COUNT;
HBaseRequestAdapter hbaseAdapter =
new HBaseRequestAdapter(options, TableName.valueOf(tableId), new Configuration(false));
testCreatePuts(10_000);
Put put = createPut();
System.out.println(String.format("Put size: %d, proto size: %d", put.heapSize(),
hbaseAdapter.adapt(put).getSerializedSize()));
run(hbaseAdapter, put, getChannelPool(useRealConnection), putCount);
}
protected static ManagedChannel getChannelPool(final boolean useRealConnection)
throws IOException, GeneralSecurityException {
if (useRealConnection) {
return BigtableSession.createChannelPool(options.getDataHost(), options);
} else {
return new ChannelPool(createFakeChannels(), 1);
}
}
protected static ChannelPool.ChannelFactory createFakeChannels() {
final ManagedChannel channel = createFakeChannel();
return new ChannelPool.ChannelFactory() {
@Override
public ManagedChannel create() throws IOException {
return channel;
}
};
}
private static void createRandomData() {
DataGenerationHelper dataHelper = new DataGenerationHelper();
dataHelper.randomData("testrow-");
for (int i = 0; i < NUM_CELLS; ++i) {
dataHelper.randomData("testQualifier-");
dataHelper.randomData("testValue-");
}
}
private static Put createPut() {
DataGenerationHelper dataHelper = new DataGenerationHelper();
return createPuts(dataHelper.randomData("testrow-"),
dataHelper.randomData("testQualifier-", NUM_CELLS),
dataHelper.randomData("testValue-", NUM_CELLS));
}
protected static Put createPuts(byte[] rowKey, byte[][] quals, byte[][] values) {
Put put = new Put(rowKey);
for (int i = 0; i < NUM_CELLS; ++i) {
put.addImmutable(COLUMN_FAMILY, quals[i], values[i]);
}
return put;
}
protected static void run(final HBaseRequestAdapter hbaseAdapter, final Put put, ManagedChannel cp,
final int putCount) throws InterruptedException {
final BigtableDataClient client = new BigtableDataGrpcClient(cp,
BigtableSessionSharedThreadPools.getInstance().getRetryExecutor(), options);
Runnable r1 = new Runnable() {
@Override
public void run() {
long start = System.nanoTime();
for (int i = 0; i < putCount; i++) {
client.mutateRow(hbaseAdapter.adapt(put));
}
print("constantly adapted", start, putCount);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
long start = System.nanoTime();
final MutateRowRequest adapted = hbaseAdapter.adapt(put);
for (int i = 0; i < putCount; i++) {
client.mutateRow(adapted);
}
print("preadapted", start, putCount);
}
};
r1.run();
r2.run();
int roundCount = 20;
System.out.println("====== Running serially");
serialRun("constantly adapted", putCount, r1, roundCount);
serialRun("pre adapted", putCount, r2, roundCount);
System.out.println("====== Running in parallel");
runParallel("constantly adapted", r1, putCount, roundCount);
runParallel("pre adapted", r2, putCount, roundCount);
System.out.println("====== Running serially");
serialRun("constantly adapted", putCount, r1, roundCount);
serialRun("pre adapted", putCount, r2, roundCount);
}
protected static void runParallel(final String key, Runnable r, final int putCount,
int roundCount) throws InterruptedException {
ExecutorService e = Executors.newFixedThreadPool(roundCount);
long start = System.nanoTime();
for (int i = 0; i < roundCount; i++) {
e.execute(r);
}
e.shutdown();
e.awaitTermination(10, TimeUnit.HOURS);
print(key, start, putCount * roundCount);
}
private static void testCreatePuts(int putCount) {
long start = System.nanoTime();
for (int i = 0; i < putCount; i++) {
createRandomData();
}
print("Created random data", start, putCount);
DataGenerationHelper dataHelper = new DataGenerationHelper();
byte[] key = dataHelper.randomData("testrow-");
byte[][] quals = dataHelper.randomData("testQualifier-", NUM_CELLS);
byte[][] vals = dataHelper.randomData("testValue-", NUM_CELLS, VALUE_SIZE);
for (int j = 0; j < 20; j++) {
start = System.nanoTime();
for (int i = 0; i < putCount; i++) {
createPuts(key, quals, vals);
}
print("Created Puts", start, putCount);
}
}
private static void serialRun(String key, final int putCount, Runnable r, int roundCount) {
long start = System.nanoTime();
for (int i = 0; i < roundCount; i++) {
r.run();
}
print(key, start, putCount * roundCount);
}
private static void print(String key, long startTimeNanos, int count) {
long totalTime = System.nanoTime() - startTimeNanos;
System.out.printf(
"%s, Put %,d in %d ms. %,d nanos/put. %,f put/sec", key,
count, totalTime / 1000000, totalTime / count, count * 1000000000.0 / totalTime);
System.out.println();
}
final static ManagedChannel channel = new ManagedChannel() {
@Override
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT>
newCall(MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
return createNewCall();
}
@Override
public String authority() {
return null;
}
@Override
public ManagedChannel shutdownNow() {
return null;
}
@Override
public ManagedChannel shutdown() {
return null;
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public boolean isShutdown() {
return false;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return false;
}
};
private static ManagedChannel createFakeChannel() {
return channel;
}
protected static <RequestT, ResponseT> ClientCall<RequestT, ResponseT> createNewCall() {
return new ClientCall<RequestT, ResponseT>() {
private ClientCall.Listener<ResponseT> responseListener;
@Override
public void start(ClientCall.Listener<ResponseT> responseListener, Metadata headers) {
this.responseListener = responseListener;
}
@Override
public void request(int numMessages) {
}
@Override
public void halfClose() {
}
@Override
@SuppressWarnings("unchecked")
public void sendMessage(RequestT message) {
responseListener.onMessage((ResponseT) MutateRowResponse.getDefaultInstance());
responseListener.onClose(Status.OK, null);
}
@Override
public void cancel(String message, Throwable cause) {
}
};
}
}
| kevinsi4508/cloud-bigtable-client | bigtable-client-core-parent/bigtable-hbase/src/test/java/com/google/cloud/bigtable/hbase/PutMicroBenchmark.java | Java | apache-2.0 | 9,432 |
package io.crnk.client;
import io.crnk.core.engine.document.Document;
import io.crnk.core.engine.http.HttpHeaders;
import io.crnk.core.engine.internal.utils.ClassUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* Specifies in which format request and responses are sent.
*/
public enum ClientFormat {
/**
* Default
*/
JSONAPI(HttpHeaders.JSONAPI_CONTENT_TYPE_AND_CHARSET, HttpHeaders.JSONAPI_CONTENT_TYPE, Document.class.getName()),
/**
* Enabled if PlainJsonFormatModule is present.
*/
PLAINJSON(HttpHeaders.JSON_CONTENT_TYPE + "; charset=" + HttpHeaders.DEFAULT_CHARSET,
HttpHeaders.JSON_CONTENT_TYPE, "io.crnk.format.plainjson.internal.PlainJsonDocument");
private final String documentClassName;
private final String contentType;
private final String acceptType;
private Class<? extends Document> documentClass;
private Constructor transportDocumentFactory;
ClientFormat(String contentType, String acceptType, String documentClassName) {
this.contentType = contentType;
this.acceptType = acceptType;
this.documentClassName = documentClassName;
}
public String getContentType() {
return contentType;
}
public String getAcceptType() {
return acceptType;
}
public Class<? extends Document> getDocumentClass() {
if (documentClass == null) {
documentClass = (Class<? extends Document>) ClassUtils.loadClass(getClass().getClassLoader(), documentClassName);
}
return documentClass;
}
public Document toTransportDocument(Document document) {
Class<? extends Document> documentClass = getDocumentClass();
if (!documentClass.isInstance(document)) {
try {
if (transportDocumentFactory == null) {
transportDocumentFactory = documentClass.getConstructor(Document.class);
}
return (Document) transportDocumentFactory.newInstance(document);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
return document;
}}
| crnk-project/crnk-framework | crnk-client/src/main/java/io/crnk/client/ClientFormat.java | Java | apache-2.0 | 2,309 |
goog.module('grrUi.forms.outputPluginDescriptorFormDirective');
goog.module.declareLegacyNamespace();
const apiService = goog.requireType('grrUi.core.apiService');
const reflectionService = goog.requireType('grrUi.core.reflectionService');
/**
* Controller for OutputPluginDescriptorFormDirective.
* @unrestricted
*/
const OutputPluginDescriptorFormController = class {
/**
* @param {!angular.Scope} $scope
* @param {!apiService.ApiService} grrApiService
* @param {!reflectionService.ReflectionService}
* grrReflectionService
* @ngInject
*/
constructor($scope, grrApiService, grrReflectionService) {
/** @private {!angular.Scope} */
this.scope_ = $scope;
/** @private {!apiService.ApiService} */
this.grrApiService_ = grrApiService;
/** @private {!reflectionService.ReflectionService} */
this.grrReflectionService_ = grrReflectionService;
/** @type {Object} */
this.outputPluginsDescriptors;
/** @type {Array<string>} */
this.allowedPluginsNames;
this.grrApiService_.get('/output-plugins/all').then(function(response) {
this.outputPluginsDescriptors = {};
angular.forEach(response['data']['items'], function(item) {
if (item['plugin_type'] === 'LEGACY') {
this.outputPluginsDescriptors[item['name']] = item;
}
}.bind(this));
this.allowedPluginsNames =
Object
.keys(
/** @type {!Object} */ (this.outputPluginsDescriptors))
.sort();
if (angular.isUndefined(
this.scope_.$eval('value.value.plugin_name.value'))) {
this.scope_['value']['value']['plugin_name'] = {
type: 'RDFString',
value: this.allowedPluginsNames[0]
};
}
this.scope_.$watch('value.value.plugin_name.value', function(newValue) {
if (angular.isDefined(newValue)) {
var argsType = this.outputPluginsDescriptors[newValue]['args_type'];
var pluginArgs = this.scope_['value']['value']['plugin_args'];
// We want to replace the plugin args only if they're undefined or
// their type differs from the selected ones. This check helps
// prefilled forms to keep prefilled data.
if (angular.isUndefined(pluginArgs) ||
pluginArgs['type'] != argsType) {
this.grrReflectionService_.getRDFValueDescriptor(argsType).then(
function(descriptor) {
this.scope_['value']['value']['plugin_args'] =
angular.copy(descriptor['default']);
}.bind(this));
}
}
}.bind(this));
}.bind(this));
}
};
/**
* OutputPluginDescriptorFormDirective definition.
*
* @return {angular.Directive} Directive definition object.
*/
exports.OutputPluginDescriptorFormDirective = function() {
return {
restrict: 'E',
scope: {value: '='},
templateUrl: '/static/angular-components/forms/' +
'output-plugin-descriptor-form.html',
controller: OutputPluginDescriptorFormController,
controllerAs: 'controller'
};
};
/**
* Directive's name in Angular.
*
* @const
* @export
*/
exports.OutputPluginDescriptorFormDirective.directive_name =
'grrOutputPluginDescriptorForm';
/**
* Semantic type corresponding to this directive.
*
* @const
* @export
*/
exports.OutputPluginDescriptorFormDirective.semantic_type =
'OutputPluginDescriptor';
| google/grr | grr/server/grr_response_server/gui/static/angular-components/forms/output-plugin-descriptor-form-directive.js | JavaScript | apache-2.0 | 3,457 |
package com.yuyh.sprintnba.retrofit.okhttp;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* @author yuyh.
* @date 2016/8/2.
*/
public class CommonParamsInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host())
.addQueryParameter("appver", "1.0.2.2")
.addQueryParameter("appvid", "1.0.2.2")
.addQueryParameter("network", "wifi");
Request newRequest = oldRequest.newBuilder()
.method(oldRequest.method(), oldRequest.body())
.url(authorizedUrlBuilder.build())
.build();
return chain.proceed(newRequest);
}
}
| xqgdmg/DavidNBA-master | app/src/main/java/com/yuyh/sprintnba/retrofit/okhttp/CommonParamsInterceptor.java | Java | apache-2.0 | 1,016 |
package scuba.test.testcase.container.stack;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The <tt>ResizingArrayStack</tt> class represents a last-in-first-out (LIFO) stack
* of generic items.
* It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
* for peeking at the top item, testing if the stack is empty, and iterating through
* the items in LIFO order.
* <p>
* This implementation uses a resizing array, which double the underlying array
* when it is full and halves the underlying array when it is one-quarter full.
* The <em>push</em> and <em>pop</em> operations take constant amortized time.
* The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
* constant time in the worst case.
* <p>
* For additional documentation, see <a href="/algs4/13stacks">Section 1.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class ResizingArrayStack<Item> implements Iterable<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
private int index;
/**
* Initializes an empty stack.
*/
public ResizingArrayStack() {
a = (Item[]) new Object[2];
}
/**
* Is this stack empty?
* @return true if this stack is empty; false otherwise
*/
public boolean isEmpty() {
return N == 0;
}
/**
* Returns the number of items in the stack.
* @return the number of items in the stack
*/
public int size() {
return N;
}
// resize the underlying array holding the elements
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
/**
* Adds the item to this stack.
* @param item the item to add
*/
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
/**
* Removes and returns the item most recently added to this stack.
* @return the item most recently added
* @throws java.util.NoSuchElementException if this stack is empty
*/
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4) resize(a.length/2);
return item;
}
/**
* Returns (but does not remove) the item most recently added to this stack.
* @return the item most recently added to this stack
* @throws java.util.NoSuchElementException if this stack is empty
*/
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return a[N-1];
}
/**
* Returns an iterator to this stack that iterates through the items in LIFO order.
* @return an iterator to this stack that iterates through the items in LIFO order.
*/
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
private Item current, next, first, prev;
public ReverseArrayIterator() {
i = N;
Item[] t = a;
while (i < t.length && (next = a[index++]) == null)
;
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
//some dummy operations which our analysis should skip it.
current = a[--i];
if(current != null) {
next = current;
prev = current;
first = current;
}
current = null;
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
} | fredfeng/ScubaTest | Test2/src/scuba/test/testcase/container/stack/ResizingArrayStack.java | Java | apache-2.0 | 4,267 |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/errors/authorization_error.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V10.Errors {
/// <summary>Holder for reflection information generated from google/ads/googleads/v10/errors/authorization_error.proto</summary>
public static partial class AuthorizationErrorReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v10/errors/authorization_error.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static AuthorizationErrorReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjlnb29nbGUvYWRzL2dvb2dsZWFkcy92MTAvZXJyb3JzL2F1dGhvcml6YXRp",
"b25fZXJyb3IucHJvdG8SH2dvb2dsZS5hZHMuZ29vZ2xlYWRzLnYxMC5lcnJv",
"cnMaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8i2gMKFkF1dGhvcml6",
"YXRpb25FcnJvckVudW0ivwMKEkF1dGhvcml6YXRpb25FcnJvchIPCgtVTlNQ",
"RUNJRklFRBAAEgsKB1VOS05PV04QARIaChZVU0VSX1BFUk1JU1NJT05fREVO",
"SUVEEAISJAogREVWRUxPUEVSX1RPS0VOX05PVF9PTl9BTExPV0xJU1QQDRIe",
"ChpERVZFTE9QRVJfVE9LRU5fUFJPSElCSVRFRBAEEhQKEFBST0pFQ1RfRElT",
"QUJMRUQQBRIXChNBVVRIT1JJWkFUSU9OX0VSUk9SEAYSGAoUQUNUSU9OX05P",
"VF9QRVJNSVRURUQQBxIVChFJTkNPTVBMRVRFX1NJR05VUBAIEhgKFENVU1RP",
"TUVSX05PVF9FTkFCTEVEEBgSDwoLTUlTU0lOR19UT1MQCRIgChxERVZFTE9Q",
"RVJfVE9LRU5fTk9UX0FQUFJPVkVEEAoSPQo5SU5WQUxJRF9MT0dJTl9DVVNU",
"T01FUl9JRF9TRVJWSU5HX0NVU1RPTUVSX0lEX0NPTUJJTkFUSU9OEAsSGQoV",
"U0VSVklDRV9BQ0NFU1NfREVOSUVEEAwSIgoeQUNDRVNTX0RFTklFRF9GT1Jf",
"QUNDT1VOVF9UWVBFEBlC9wEKI2NvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52",
"MTAuZXJyb3JzQhdBdXRob3JpemF0aW9uRXJyb3JQcm90b1ABWkVnb29nbGUu",
"Z29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMv",
"djEwL2Vycm9ycztlcnJvcnOiAgNHQUGqAh9Hb29nbGUuQWRzLkdvb2dsZUFk",
"cy5WMTAuRXJyb3JzygIfR29vZ2xlXEFkc1xHb29nbGVBZHNcVjEwXEVycm9y",
"c+oCI0dvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlYxMDo6RXJyb3JzYgZwcm90",
"bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V10.Errors.AuthorizationErrorEnum), global::Google.Ads.GoogleAds.V10.Errors.AuthorizationErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V10.Errors.AuthorizationErrorEnum.Types.AuthorizationError) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible authorization errors.
/// </summary>
public sealed partial class AuthorizationErrorEnum : pb::IMessage<AuthorizationErrorEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<AuthorizationErrorEnum> _parser = new pb::MessageParser<AuthorizationErrorEnum>(() => new AuthorizationErrorEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<AuthorizationErrorEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V10.Errors.AuthorizationErrorReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public AuthorizationErrorEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public AuthorizationErrorEnum(AuthorizationErrorEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public AuthorizationErrorEnum Clone() {
return new AuthorizationErrorEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as AuthorizationErrorEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(AuthorizationErrorEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(AuthorizationErrorEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the AuthorizationErrorEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// Enum describing possible authorization errors.
/// </summary>
public enum AuthorizationError {
/// <summary>
/// Enum unspecified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The received error code is not known in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// User doesn't have permission to access customer. Note: If you're
/// accessing a client customer, the manager's customer ID must be set in the
/// `login-customer-id` header. Learn more at
/// https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid
/// </summary>
[pbr::OriginalName("USER_PERMISSION_DENIED")] UserPermissionDenied = 2,
/// <summary>
/// The developer token is not on the allow-list.
/// </summary>
[pbr::OriginalName("DEVELOPER_TOKEN_NOT_ON_ALLOWLIST")] DeveloperTokenNotOnAllowlist = 13,
/// <summary>
/// The developer token is not allowed with the project sent in the request.
/// </summary>
[pbr::OriginalName("DEVELOPER_TOKEN_PROHIBITED")] DeveloperTokenProhibited = 4,
/// <summary>
/// The Google Cloud project sent in the request does not have permission to
/// access the api.
/// </summary>
[pbr::OriginalName("PROJECT_DISABLED")] ProjectDisabled = 5,
/// <summary>
/// Authorization of the client failed.
/// </summary>
[pbr::OriginalName("AUTHORIZATION_ERROR")] AuthorizationError = 6,
/// <summary>
/// The user does not have permission to perform this action
/// (e.g., ADD, UPDATE, REMOVE) on the resource or call a method.
/// </summary>
[pbr::OriginalName("ACTION_NOT_PERMITTED")] ActionNotPermitted = 7,
/// <summary>
/// Signup not complete.
/// </summary>
[pbr::OriginalName("INCOMPLETE_SIGNUP")] IncompleteSignup = 8,
/// <summary>
/// The customer can't be used because it isn't enabled.
/// </summary>
[pbr::OriginalName("CUSTOMER_NOT_ENABLED")] CustomerNotEnabled = 24,
/// <summary>
/// The developer must sign the terms of service. They can be found here:
/// ads.google.com/aw/apicenter
/// </summary>
[pbr::OriginalName("MISSING_TOS")] MissingTos = 9,
/// <summary>
/// The developer token is not approved. Non-approved developer tokens can
/// only be used with test accounts.
/// </summary>
[pbr::OriginalName("DEVELOPER_TOKEN_NOT_APPROVED")] DeveloperTokenNotApproved = 10,
/// <summary>
/// The login customer specified does not have access to the account
/// specified, so the request is invalid.
/// </summary>
[pbr::OriginalName("INVALID_LOGIN_CUSTOMER_ID_SERVING_CUSTOMER_ID_COMBINATION")] InvalidLoginCustomerIdServingCustomerIdCombination = 11,
/// <summary>
/// The developer specified does not have access to the service.
/// </summary>
[pbr::OriginalName("SERVICE_ACCESS_DENIED")] ServiceAccessDenied = 12,
/// <summary>
/// The customer (or login customer) isn't in Google Ads. It belongs to
/// another ads system.
/// </summary>
[pbr::OriginalName("ACCESS_DENIED_FOR_ACCOUNT_TYPE")] AccessDeniedForAccountType = 25,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| googleads/google-ads-dotnet | src/V10/Services/AuthorizationError.g.cs | C# | apache-2.0 | 12,709 |
/*
* Artifactory is a binaries repository manager.
* Copyright (C) 2012 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.addon.plugin.download;
import org.artifactory.addon.plugin.PluginAction;
import org.artifactory.repo.RepoPath;
/**
* @author Yoav Landman
*/
public interface AltRemotePathAction extends PluginAction {
void altRemotePath(RepoPath originalRepoPath);
} | alancnet/artifactory | backend/core/src/main/java/org/artifactory/addon/plugin/download/AltRemotePathAction.java | Java | apache-2.0 | 1,038 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kafka.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.kafka.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* PrometheusMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class PrometheusMarshaller {
private static final MarshallingInfo<StructuredPojo> JMXEXPORTER_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("jmxExporter").build();
private static final MarshallingInfo<StructuredPojo> NODEEXPORTER_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("nodeExporter").build();
private static final PrometheusMarshaller instance = new PrometheusMarshaller();
public static PrometheusMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(Prometheus prometheus, ProtocolMarshaller protocolMarshaller) {
if (prometheus == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(prometheus.getJmxExporter(), JMXEXPORTER_BINDING);
protocolMarshaller.marshall(prometheus.getNodeExporter(), NODEEXPORTER_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-kafka/src/main/java/com/amazonaws/services/kafka/model/transform/PrometheusMarshaller.java | Java | apache-2.0 | 2,254 |
<?php
/**
* SettingsGetConstantsReversedResponse
*
* PHP version 5
*
* @category Class
* @package BumbalClient
* @author Swaagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Bumbal Client Api
*
* Bumbal API documentation
*
* OpenAPI spec version: 2.0
* Contact: gerb@bumbal.eu
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace BumbalClient\Model;
use \ArrayAccess;
/**
* SettingsGetConstantsReversedResponse Class Doc Comment
*
* @category Class
* @package BumbalClient
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class SettingsGetConstantsReversedResponse implements ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
* @var string
*/
protected static $swaggerModelName = 'SettingsGetConstantsReversedResponse';
/**
* Array of property to type mappings. Used for (de)serialization
* @var string[]
*/
protected static $swaggerTypes = [
'irregularity_category' => 'object',
'irregularity_cause' => 'object',
'instruction_type' => 'object',
'reference_type' => 'object',
'relation_type' => 'object',
'week_day' => 'object',
'action_type' => 'object',
'activity_type' => 'object',
'special_activity' => 'object',
'ae_activity' => 'object',
'address_type' => 'object',
'ae_address_type' => 'object',
'communication_delivery_method' => 'object',
'communication_message_type' => 'object',
'counter' => 'object',
'equipment_type' => 'object',
'file_type' => 'object',
'incoterm' => 'object',
'log_type' => 'object',
'object_type' => 'object',
'optimisation_objective' => 'object',
'party_type' => 'object',
'phone_nr_type' => 'object',
'recurrence_period' => 'object',
'recurrence_type' => 'object',
'role' => 'object',
'saywhen_status' => 'object',
'settings' => 'object',
'settings_group' => 'object',
'status_type' => 'object',
'route_status' => 'object',
'activity_status' => 'object',
'shipment_status' => 'object',
'package_line_status' => 'object',
'assignment_status' => 'object',
'message_status' => 'object',
'user_status' => 'object',
'job_status' => 'object',
'api_request_status' => 'object',
'system_provider' => 'object',
'provider' => 'object',
'time_slot_type' => 'object',
'transaction_type' => 'object',
'uom' => 'object',
'uom_group' => 'object',
'vehicle_type' => 'object',
'package_type' => 'object'
];
/**
* Array of property to format mappings. Used for (de)serialization
* @var string[]
*/
protected static $swaggerFormats = [
'irregularity_category' => null,
'irregularity_cause' => null,
'instruction_type' => null,
'reference_type' => null,
'relation_type' => null,
'week_day' => null,
'action_type' => null,
'activity_type' => null,
'special_activity' => null,
'ae_activity' => null,
'address_type' => null,
'ae_address_type' => null,
'communication_delivery_method' => null,
'communication_message_type' => null,
'counter' => null,
'equipment_type' => null,
'file_type' => null,
'incoterm' => null,
'log_type' => null,
'object_type' => null,
'optimisation_objective' => null,
'party_type' => null,
'phone_nr_type' => null,
'recurrence_period' => null,
'recurrence_type' => null,
'role' => null,
'saywhen_status' => null,
'settings' => null,
'settings_group' => null,
'status_type' => null,
'route_status' => null,
'activity_status' => null,
'shipment_status' => null,
'package_line_status' => null,
'assignment_status' => null,
'message_status' => null,
'user_status' => null,
'job_status' => null,
'api_request_status' => null,
'system_provider' => null,
'provider' => null,
'time_slot_type' => null,
'transaction_type' => null,
'uom' => null,
'uom_group' => null,
'vehicle_type' => null,
'package_type' => null
];
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name, and the value is the original name
* @var string[]
*/
protected static $attributeMap = [
'irregularity_category' => 'irregularity_category',
'irregularity_cause' => 'irregularity_cause',
'instruction_type' => 'instruction_type',
'reference_type' => 'reference_type',
'relation_type' => 'relation_type',
'week_day' => 'week_day',
'action_type' => 'action_type',
'activity_type' => 'activity_type',
'special_activity' => 'special_activity',
'ae_activity' => 'ae_activity',
'address_type' => 'address_type',
'ae_address_type' => 'ae_address_type',
'communication_delivery_method' => 'communication_delivery_method',
'communication_message_type' => 'communication_message_type',
'counter' => 'counter',
'equipment_type' => 'equipment_type',
'file_type' => 'file_type',
'incoterm' => 'incoterm',
'log_type' => 'log_type',
'object_type' => 'object_type',
'optimisation_objective' => 'optimisation_objective',
'party_type' => 'party_type',
'phone_nr_type' => 'phone_nr_type',
'recurrence_period' => 'recurrence_period',
'recurrence_type' => 'recurrence_type',
'role' => 'role',
'saywhen_status' => 'saywhen_status',
'settings' => 'settings',
'settings_group' => 'settings_group',
'status_type' => 'status_type',
'route_status' => 'route_status',
'activity_status' => 'activity_status',
'shipment_status' => 'shipment_status',
'package_line_status' => 'package_line_status',
'assignment_status' => 'assignment_status',
'message_status' => 'message_status',
'user_status' => 'user_status',
'job_status' => 'job_status',
'api_request_status' => 'api_request_status',
'system_provider' => 'system_provider',
'provider' => 'provider',
'time_slot_type' => 'time_slot_type',
'transaction_type' => 'transaction_type',
'uom' => 'uom',
'uom_group' => 'uom_group',
'vehicle_type' => 'vehicle_type',
'package_type' => 'package_type'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
* @var string[]
*/
protected static $setters = [
'irregularity_category' => 'setIrregularityCategory',
'irregularity_cause' => 'setIrregularityCause',
'instruction_type' => 'setInstructionType',
'reference_type' => 'setReferenceType',
'relation_type' => 'setRelationType',
'week_day' => 'setWeekDay',
'action_type' => 'setActionType',
'activity_type' => 'setActivityType',
'special_activity' => 'setSpecialActivity',
'ae_activity' => 'setAeActivity',
'address_type' => 'setAddressType',
'ae_address_type' => 'setAeAddressType',
'communication_delivery_method' => 'setCommunicationDeliveryMethod',
'communication_message_type' => 'setCommunicationMessageType',
'counter' => 'setCounter',
'equipment_type' => 'setEquipmentType',
'file_type' => 'setFileType',
'incoterm' => 'setIncoterm',
'log_type' => 'setLogType',
'object_type' => 'setObjectType',
'optimisation_objective' => 'setOptimisationObjective',
'party_type' => 'setPartyType',
'phone_nr_type' => 'setPhoneNrType',
'recurrence_period' => 'setRecurrencePeriod',
'recurrence_type' => 'setRecurrenceType',
'role' => 'setRole',
'saywhen_status' => 'setSaywhenStatus',
'settings' => 'setSettings',
'settings_group' => 'setSettingsGroup',
'status_type' => 'setStatusType',
'route_status' => 'setRouteStatus',
'activity_status' => 'setActivityStatus',
'shipment_status' => 'setShipmentStatus',
'package_line_status' => 'setPackageLineStatus',
'assignment_status' => 'setAssignmentStatus',
'message_status' => 'setMessageStatus',
'user_status' => 'setUserStatus',
'job_status' => 'setJobStatus',
'api_request_status' => 'setApiRequestStatus',
'system_provider' => 'setSystemProvider',
'provider' => 'setProvider',
'time_slot_type' => 'setTimeSlotType',
'transaction_type' => 'setTransactionType',
'uom' => 'setUom',
'uom_group' => 'setUomGroup',
'vehicle_type' => 'setVehicleType',
'package_type' => 'setPackageType'
];
/**
* Array of attributes to getter functions (for serialization of requests)
* @var string[]
*/
protected static $getters = [
'irregularity_category' => 'getIrregularityCategory',
'irregularity_cause' => 'getIrregularityCause',
'instruction_type' => 'getInstructionType',
'reference_type' => 'getReferenceType',
'relation_type' => 'getRelationType',
'week_day' => 'getWeekDay',
'action_type' => 'getActionType',
'activity_type' => 'getActivityType',
'special_activity' => 'getSpecialActivity',
'ae_activity' => 'getAeActivity',
'address_type' => 'getAddressType',
'ae_address_type' => 'getAeAddressType',
'communication_delivery_method' => 'getCommunicationDeliveryMethod',
'communication_message_type' => 'getCommunicationMessageType',
'counter' => 'getCounter',
'equipment_type' => 'getEquipmentType',
'file_type' => 'getFileType',
'incoterm' => 'getIncoterm',
'log_type' => 'getLogType',
'object_type' => 'getObjectType',
'optimisation_objective' => 'getOptimisationObjective',
'party_type' => 'getPartyType',
'phone_nr_type' => 'getPhoneNrType',
'recurrence_period' => 'getRecurrencePeriod',
'recurrence_type' => 'getRecurrenceType',
'role' => 'getRole',
'saywhen_status' => 'getSaywhenStatus',
'settings' => 'getSettings',
'settings_group' => 'getSettingsGroup',
'status_type' => 'getStatusType',
'route_status' => 'getRouteStatus',
'activity_status' => 'getActivityStatus',
'shipment_status' => 'getShipmentStatus',
'package_line_status' => 'getPackageLineStatus',
'assignment_status' => 'getAssignmentStatus',
'message_status' => 'getMessageStatus',
'user_status' => 'getUserStatus',
'job_status' => 'getJobStatus',
'api_request_status' => 'getApiRequestStatus',
'system_provider' => 'getSystemProvider',
'provider' => 'getProvider',
'time_slot_type' => 'getTimeSlotType',
'transaction_type' => 'getTransactionType',
'uom' => 'getUom',
'uom_group' => 'getUomGroup',
'vehicle_type' => 'getVehicleType',
'package_type' => 'getPackageType'
];
public static function attributeMap()
{
return self::$attributeMap;
}
public static function setters()
{
return self::$setters;
}
public static function getters()
{
return self::$getters;
}
/**
* Associative array for storing property values
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
* @param mixed[] $data Associated array of property values initializing the model
*/
public function __construct(array $data = null)
{
$this->container['irregularity_category'] = isset($data['irregularity_category']) ? $data['irregularity_category'] : null;
$this->container['irregularity_cause'] = isset($data['irregularity_cause']) ? $data['irregularity_cause'] : null;
$this->container['instruction_type'] = isset($data['instruction_type']) ? $data['instruction_type'] : null;
$this->container['reference_type'] = isset($data['reference_type']) ? $data['reference_type'] : null;
$this->container['relation_type'] = isset($data['relation_type']) ? $data['relation_type'] : null;
$this->container['week_day'] = isset($data['week_day']) ? $data['week_day'] : null;
$this->container['action_type'] = isset($data['action_type']) ? $data['action_type'] : null;
$this->container['activity_type'] = isset($data['activity_type']) ? $data['activity_type'] : null;
$this->container['special_activity'] = isset($data['special_activity']) ? $data['special_activity'] : null;
$this->container['ae_activity'] = isset($data['ae_activity']) ? $data['ae_activity'] : null;
$this->container['address_type'] = isset($data['address_type']) ? $data['address_type'] : null;
$this->container['ae_address_type'] = isset($data['ae_address_type']) ? $data['ae_address_type'] : null;
$this->container['communication_delivery_method'] = isset($data['communication_delivery_method']) ? $data['communication_delivery_method'] : null;
$this->container['communication_message_type'] = isset($data['communication_message_type']) ? $data['communication_message_type'] : null;
$this->container['counter'] = isset($data['counter']) ? $data['counter'] : null;
$this->container['equipment_type'] = isset($data['equipment_type']) ? $data['equipment_type'] : null;
$this->container['file_type'] = isset($data['file_type']) ? $data['file_type'] : null;
$this->container['incoterm'] = isset($data['incoterm']) ? $data['incoterm'] : null;
$this->container['log_type'] = isset($data['log_type']) ? $data['log_type'] : null;
$this->container['object_type'] = isset($data['object_type']) ? $data['object_type'] : null;
$this->container['optimisation_objective'] = isset($data['optimisation_objective']) ? $data['optimisation_objective'] : null;
$this->container['party_type'] = isset($data['party_type']) ? $data['party_type'] : null;
$this->container['phone_nr_type'] = isset($data['phone_nr_type']) ? $data['phone_nr_type'] : null;
$this->container['recurrence_period'] = isset($data['recurrence_period']) ? $data['recurrence_period'] : null;
$this->container['recurrence_type'] = isset($data['recurrence_type']) ? $data['recurrence_type'] : null;
$this->container['role'] = isset($data['role']) ? $data['role'] : null;
$this->container['saywhen_status'] = isset($data['saywhen_status']) ? $data['saywhen_status'] : null;
$this->container['settings'] = isset($data['settings']) ? $data['settings'] : null;
$this->container['settings_group'] = isset($data['settings_group']) ? $data['settings_group'] : null;
$this->container['status_type'] = isset($data['status_type']) ? $data['status_type'] : null;
$this->container['route_status'] = isset($data['route_status']) ? $data['route_status'] : null;
$this->container['activity_status'] = isset($data['activity_status']) ? $data['activity_status'] : null;
$this->container['shipment_status'] = isset($data['shipment_status']) ? $data['shipment_status'] : null;
$this->container['package_line_status'] = isset($data['package_line_status']) ? $data['package_line_status'] : null;
$this->container['assignment_status'] = isset($data['assignment_status']) ? $data['assignment_status'] : null;
$this->container['message_status'] = isset($data['message_status']) ? $data['message_status'] : null;
$this->container['user_status'] = isset($data['user_status']) ? $data['user_status'] : null;
$this->container['job_status'] = isset($data['job_status']) ? $data['job_status'] : null;
$this->container['api_request_status'] = isset($data['api_request_status']) ? $data['api_request_status'] : null;
$this->container['system_provider'] = isset($data['system_provider']) ? $data['system_provider'] : null;
$this->container['provider'] = isset($data['provider']) ? $data['provider'] : null;
$this->container['time_slot_type'] = isset($data['time_slot_type']) ? $data['time_slot_type'] : null;
$this->container['transaction_type'] = isset($data['transaction_type']) ? $data['transaction_type'] : null;
$this->container['uom'] = isset($data['uom']) ? $data['uom'] : null;
$this->container['uom_group'] = isset($data['uom_group']) ? $data['uom_group'] : null;
$this->container['vehicle_type'] = isset($data['vehicle_type']) ? $data['vehicle_type'] : null;
$this->container['package_type'] = isset($data['package_type']) ? $data['package_type'] : null;
}
/**
* show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalid_properties = [];
return $invalid_properties;
}
/**
* validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return true;
}
/**
* Gets irregularity_category
* @return object
*/
public function getIrregularityCategory()
{
return $this->container['irregularity_category'];
}
/**
* Sets irregularity_category
* @param object $irregularity_category Irregularity Categories
* @return $this
*/
public function setIrregularityCategory($irregularity_category)
{
$this->container['irregularity_category'] = $irregularity_category;
return $this;
}
/**
* Gets irregularity_cause
* @return object
*/
public function getIrregularityCause()
{
return $this->container['irregularity_cause'];
}
/**
* Sets irregularity_cause
* @param object $irregularity_cause Irregularity Causes
* @return $this
*/
public function setIrregularityCause($irregularity_cause)
{
$this->container['irregularity_cause'] = $irregularity_cause;
return $this;
}
/**
* Gets instruction_type
* @return object
*/
public function getInstructionType()
{
return $this->container['instruction_type'];
}
/**
* Sets instruction_type
* @param object $instruction_type Instruction Types
* @return $this
*/
public function setInstructionType($instruction_type)
{
$this->container['instruction_type'] = $instruction_type;
return $this;
}
/**
* Gets reference_type
* @return object
*/
public function getReferenceType()
{
return $this->container['reference_type'];
}
/**
* Sets reference_type
* @param object $reference_type Reference Types
* @return $this
*/
public function setReferenceType($reference_type)
{
$this->container['reference_type'] = $reference_type;
return $this;
}
/**
* Gets relation_type
* @return object
*/
public function getRelationType()
{
return $this->container['relation_type'];
}
/**
* Sets relation_type
* @param object $relation_type Relation Types
* @return $this
*/
public function setRelationType($relation_type)
{
$this->container['relation_type'] = $relation_type;
return $this;
}
/**
* Gets week_day
* @return object
*/
public function getWeekDay()
{
return $this->container['week_day'];
}
/**
* Sets week_day
* @param object $week_day Names of the days in the week
* @return $this
*/
public function setWeekDay($week_day)
{
$this->container['week_day'] = $week_day;
return $this;
}
/**
* Gets action_type
* @return object
*/
public function getActionType()
{
return $this->container['action_type'];
}
/**
* Sets action_type
* @param object $action_type Action Types
* @return $this
*/
public function setActionType($action_type)
{
$this->container['action_type'] = $action_type;
return $this;
}
/**
* Gets activity_type
* @return object
*/
public function getActivityType()
{
return $this->container['activity_type'];
}
/**
* Sets activity_type
* @param object $activity_type Activity Types
* @return $this
*/
public function setActivityType($activity_type)
{
$this->container['activity_type'] = $activity_type;
return $this;
}
/**
* Gets special_activity
* @return object
*/
public function getSpecialActivity()
{
return $this->container['special_activity'];
}
/**
* Sets special_activity
* @param object $special_activity Special Activities
* @return $this
*/
public function setSpecialActivity($special_activity)
{
$this->container['special_activity'] = $special_activity;
return $this;
}
/**
* Gets ae_activity
* @return object
*/
public function getAeActivity()
{
return $this->container['ae_activity'];
}
/**
* Sets ae_activity
* @param object $ae_activity EA Activity
* @return $this
*/
public function setAeActivity($ae_activity)
{
$this->container['ae_activity'] = $ae_activity;
return $this;
}
/**
* Gets address_type
* @return object
*/
public function getAddressType()
{
return $this->container['address_type'];
}
/**
* Sets address_type
* @param object $address_type Address Types
* @return $this
*/
public function setAddressType($address_type)
{
$this->container['address_type'] = $address_type;
return $this;
}
/**
* Gets ae_address_type
* @return object
*/
public function getAeAddressType()
{
return $this->container['ae_address_type'];
}
/**
* Sets ae_address_type
* @param object $ae_address_type EA Address Types
* @return $this
*/
public function setAeAddressType($ae_address_type)
{
$this->container['ae_address_type'] = $ae_address_type;
return $this;
}
/**
* Gets communication_delivery_method
* @return object
*/
public function getCommunicationDeliveryMethod()
{
return $this->container['communication_delivery_method'];
}
/**
* Sets communication_delivery_method
* @param object $communication_delivery_method Communication Delivery Methods
* @return $this
*/
public function setCommunicationDeliveryMethod($communication_delivery_method)
{
$this->container['communication_delivery_method'] = $communication_delivery_method;
return $this;
}
/**
* Gets communication_message_type
* @return object
*/
public function getCommunicationMessageType()
{
return $this->container['communication_message_type'];
}
/**
* Sets communication_message_type
* @param object $communication_message_type Communication Message Types
* @return $this
*/
public function setCommunicationMessageType($communication_message_type)
{
$this->container['communication_message_type'] = $communication_message_type;
return $this;
}
/**
* Gets counter
* @return object
*/
public function getCounter()
{
return $this->container['counter'];
}
/**
* Sets counter
* @param object $counter Counters
* @return $this
*/
public function setCounter($counter)
{
$this->container['counter'] = $counter;
return $this;
}
/**
* Gets equipment_type
* @return object
*/
public function getEquipmentType()
{
return $this->container['equipment_type'];
}
/**
* Sets equipment_type
* @param object $equipment_type Equipment Types
* @return $this
*/
public function setEquipmentType($equipment_type)
{
$this->container['equipment_type'] = $equipment_type;
return $this;
}
/**
* Gets file_type
* @return object
*/
public function getFileType()
{
return $this->container['file_type'];
}
/**
* Sets file_type
* @param object $file_type File Types
* @return $this
*/
public function setFileType($file_type)
{
$this->container['file_type'] = $file_type;
return $this;
}
/**
* Gets incoterm
* @return object
*/
public function getIncoterm()
{
return $this->container['incoterm'];
}
/**
* Sets incoterm
* @param object $incoterm Incoterms
* @return $this
*/
public function setIncoterm($incoterm)
{
$this->container['incoterm'] = $incoterm;
return $this;
}
/**
* Gets log_type
* @return object
*/
public function getLogType()
{
return $this->container['log_type'];
}
/**
* Sets log_type
* @param object $log_type Log Types
* @return $this
*/
public function setLogType($log_type)
{
$this->container['log_type'] = $log_type;
return $this;
}
/**
* Gets object_type
* @return object
*/
public function getObjectType()
{
return $this->container['object_type'];
}
/**
* Sets object_type
* @param object $object_type Object Types
* @return $this
*/
public function setObjectType($object_type)
{
$this->container['object_type'] = $object_type;
return $this;
}
/**
* Gets optimisation_objective
* @return object
*/
public function getOptimisationObjective()
{
return $this->container['optimisation_objective'];
}
/**
* Sets optimisation_objective
* @param object $optimisation_objective Optimisation Objectives
* @return $this
*/
public function setOptimisationObjective($optimisation_objective)
{
$this->container['optimisation_objective'] = $optimisation_objective;
return $this;
}
/**
* Gets party_type
* @return object
*/
public function getPartyType()
{
return $this->container['party_type'];
}
/**
* Sets party_type
* @param object $party_type Party Types
* @return $this
*/
public function setPartyType($party_type)
{
$this->container['party_type'] = $party_type;
return $this;
}
/**
* Gets phone_nr_type
* @return object
*/
public function getPhoneNrType()
{
return $this->container['phone_nr_type'];
}
/**
* Sets phone_nr_type
* @param object $phone_nr_type Phone NR Types
* @return $this
*/
public function setPhoneNrType($phone_nr_type)
{
$this->container['phone_nr_type'] = $phone_nr_type;
return $this;
}
/**
* Gets recurrence_period
* @return object
*/
public function getRecurrencePeriod()
{
return $this->container['recurrence_period'];
}
/**
* Sets recurrence_period
* @param object $recurrence_period Recurrence Periods
* @return $this
*/
public function setRecurrencePeriod($recurrence_period)
{
$this->container['recurrence_period'] = $recurrence_period;
return $this;
}
/**
* Gets recurrence_type
* @return object
*/
public function getRecurrenceType()
{
return $this->container['recurrence_type'];
}
/**
* Sets recurrence_type
* @param object $recurrence_type Recurrence Types
* @return $this
*/
public function setRecurrenceType($recurrence_type)
{
$this->container['recurrence_type'] = $recurrence_type;
return $this;
}
/**
* Gets role
* @return object
*/
public function getRole()
{
return $this->container['role'];
}
/**
* Sets role
* @param object $role Roles
* @return $this
*/
public function setRole($role)
{
$this->container['role'] = $role;
return $this;
}
/**
* Gets saywhen_status
* @return object
*/
public function getSaywhenStatus()
{
return $this->container['saywhen_status'];
}
/**
* Sets saywhen_status
* @param object $saywhen_status SayWhen Statuses
* @return $this
*/
public function setSaywhenStatus($saywhen_status)
{
$this->container['saywhen_status'] = $saywhen_status;
return $this;
}
/**
* Gets settings
* @return object
*/
public function getSettings()
{
return $this->container['settings'];
}
/**
* Sets settings
* @param object $settings Settings
* @return $this
*/
public function setSettings($settings)
{
$this->container['settings'] = $settings;
return $this;
}
/**
* Gets settings_group
* @return object
*/
public function getSettingsGroup()
{
return $this->container['settings_group'];
}
/**
* Sets settings_group
* @param object $settings_group Settings Groups
* @return $this
*/
public function setSettingsGroup($settings_group)
{
$this->container['settings_group'] = $settings_group;
return $this;
}
/**
* Gets status_type
* @return object
*/
public function getStatusType()
{
return $this->container['status_type'];
}
/**
* Sets status_type
* @param object $status_type Status Types
* @return $this
*/
public function setStatusType($status_type)
{
$this->container['status_type'] = $status_type;
return $this;
}
/**
* Gets route_status
* @return object
*/
public function getRouteStatus()
{
return $this->container['route_status'];
}
/**
* Sets route_status
* @param object $route_status Route Statuses
* @return $this
*/
public function setRouteStatus($route_status)
{
$this->container['route_status'] = $route_status;
return $this;
}
/**
* Gets activity_status
* @return object
*/
public function getActivityStatus()
{
return $this->container['activity_status'];
}
/**
* Sets activity_status
* @param object $activity_status Activity Statuses
* @return $this
*/
public function setActivityStatus($activity_status)
{
$this->container['activity_status'] = $activity_status;
return $this;
}
/**
* Gets shipment_status
* @return object
*/
public function getShipmentStatus()
{
return $this->container['shipment_status'];
}
/**
* Sets shipment_status
* @param object $shipment_status Shipment Statuses
* @return $this
*/
public function setShipmentStatus($shipment_status)
{
$this->container['shipment_status'] = $shipment_status;
return $this;
}
/**
* Gets package_line_status
* @return object
*/
public function getPackageLineStatus()
{
return $this->container['package_line_status'];
}
/**
* Sets package_line_status
* @param object $package_line_status Package Line Statuses
* @return $this
*/
public function setPackageLineStatus($package_line_status)
{
$this->container['package_line_status'] = $package_line_status;
return $this;
}
/**
* Gets assignment_status
* @return object
*/
public function getAssignmentStatus()
{
return $this->container['assignment_status'];
}
/**
* Sets assignment_status
* @param object $assignment_status Assignment Statuses
* @return $this
*/
public function setAssignmentStatus($assignment_status)
{
$this->container['assignment_status'] = $assignment_status;
return $this;
}
/**
* Gets message_status
* @return object
*/
public function getMessageStatus()
{
return $this->container['message_status'];
}
/**
* Sets message_status
* @param object $message_status Message Statuses
* @return $this
*/
public function setMessageStatus($message_status)
{
$this->container['message_status'] = $message_status;
return $this;
}
/**
* Gets user_status
* @return object
*/
public function getUserStatus()
{
return $this->container['user_status'];
}
/**
* Sets user_status
* @param object $user_status User Statuses
* @return $this
*/
public function setUserStatus($user_status)
{
$this->container['user_status'] = $user_status;
return $this;
}
/**
* Gets job_status
* @return object
*/
public function getJobStatus()
{
return $this->container['job_status'];
}
/**
* Sets job_status
* @param object $job_status Job Statuses
* @return $this
*/
public function setJobStatus($job_status)
{
$this->container['job_status'] = $job_status;
return $this;
}
/**
* Gets api_request_status
* @return object
*/
public function getApiRequestStatus()
{
return $this->container['api_request_status'];
}
/**
* Sets api_request_status
* @param object $api_request_status API Request Statuses
* @return $this
*/
public function setApiRequestStatus($api_request_status)
{
$this->container['api_request_status'] = $api_request_status;
return $this;
}
/**
* Gets system_provider
* @return object
*/
public function getSystemProvider()
{
return $this->container['system_provider'];
}
/**
* Sets system_provider
* @param object $system_provider System Providers
* @return $this
*/
public function setSystemProvider($system_provider)
{
$this->container['system_provider'] = $system_provider;
return $this;
}
/**
* Gets provider
* @return object
*/
public function getProvider()
{
return $this->container['provider'];
}
/**
* Sets provider
* @param object $provider Providers
* @return $this
*/
public function setProvider($provider)
{
$this->container['provider'] = $provider;
return $this;
}
/**
* Gets time_slot_type
* @return object
*/
public function getTimeSlotType()
{
return $this->container['time_slot_type'];
}
/**
* Sets time_slot_type
* @param object $time_slot_type Time Slot Types
* @return $this
*/
public function setTimeSlotType($time_slot_type)
{
$this->container['time_slot_type'] = $time_slot_type;
return $this;
}
/**
* Gets transaction_type
* @return object
*/
public function getTransactionType()
{
return $this->container['transaction_type'];
}
/**
* Sets transaction_type
* @param object $transaction_type Transaction Types
* @return $this
*/
public function setTransactionType($transaction_type)
{
$this->container['transaction_type'] = $transaction_type;
return $this;
}
/**
* Gets uom
* @return object
*/
public function getUom()
{
return $this->container['uom'];
}
/**
* Sets uom
* @param object $uom UOM
* @return $this
*/
public function setUom($uom)
{
$this->container['uom'] = $uom;
return $this;
}
/**
* Gets uom_group
* @return object
*/
public function getUomGroup()
{
return $this->container['uom_group'];
}
/**
* Sets uom_group
* @param object $uom_group UOM Groups
* @return $this
*/
public function setUomGroup($uom_group)
{
$this->container['uom_group'] = $uom_group;
return $this;
}
/**
* Gets vehicle_type
* @return object
*/
public function getVehicleType()
{
return $this->container['vehicle_type'];
}
/**
* Sets vehicle_type
* @param object $vehicle_type Vehicle Types
* @return $this
*/
public function setVehicleType($vehicle_type)
{
$this->container['vehicle_type'] = $vehicle_type;
return $this;
}
/**
* Gets package_type
* @return object
*/
public function getPackageType()
{
return $this->container['package_type'];
}
/**
* Sets package_type
* @param object $package_type Package Types
* @return $this
*/
public function setPackageType($package_type)
{
$this->container['package_type'] = $package_type;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
* @param integer $offset Offset
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
* @param integer $offset Offset
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
* @param integer $offset Offset
* @param mixed $value Value to be set
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
* @param integer $offset Offset
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
}
return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this));
}
}
| freightlive/bumbal-client-api-php | src/Model/SettingsGetConstantsReversedResponse.php | PHP | apache-2.0 | 39,770 |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using AODGameLibrary.GamePlay;
using AODGameLibrary.AIs;
namespace AODGameLibrary.Units
{
[Serializable]
/// <summary>
/// 表示一种单位,由大地无敌-范若余在2009年8月8日改良并使其支持XML
/// </summary>
public class UnitType
{
#region 声明字段
/// <summary>
/// 模型文件的位置
/// </summary>
public string Modelname = @"AODModelTypes\TestModel";
/// <summary>
/// 单位名称
/// </summary>
public string Name = "未知目标";
/// <summary>
/// 模型缩放值
/// </summary>
public float Scale = 1;
/// <summary>
/// 模型3轴旋转角度
/// </summary>
public Vector3 ModelRotation = Vector3.Zero;
/// <summary>
/// 能量护盾最大值
/// </summary>
public int MaxShield = 100;
/// <summary>
/// 护甲最大值
/// </summary>
public int MaxArmor = 100;
/// <summary>
/// 飞船的质量,和运动时的速度等量有关
/// </summary>
public float Mass = 10;
/// <summary>
/// 最大功率,数值上等于frictionForce与最大速度的乘积
/// </summary>
public float MaxPower = 60000;
/// <summary>
/// move()方法向前移动中的最大推力大小,即在达到最大功率前的推力,应大于frictionForce
/// </summary>
public float ThrustForce = 2000;
/// <summary>
/// 只要在运动中就一直会受到的摩擦力大小
/// </summary>
public float FrictionForce = 200;
/// <summary>
/// 转向速率,转向时每秒旋转角度
/// </summary>
public float AngularRate = 540;
/// <summary>
/// 未受伤害时开始恢复护盾所需要的时间
/// </summary>
public float ShieldRestoreTime = 5.0f;
/// <summary>
/// 护盾恢复状态下每秒回复的护盾值
/// </summary>
public float ShieldRestoreRate = 500.0f;
/// <summary>
/// 每秒回复的护甲值(护甲一直回复但速度慢)
/// </summary>
public float ArmorRestoreRate = 18.0f;
/// <summary>
/// 武器,4个
/// </summary>
public List<string> Weapons = new List<string>(4);
/// <summary>
/// 导弹
/// </summary>
public List<string> MissileWeapons = new List<string>(4);
/// <summary>
/// 技能列表
/// </summary>
public List<string> Skills = new List<string>(8);
/// <summary>
/// 单位AI选项名
/// </summary>
public AISettings AISettings;
public bool Bounding = false;
public bool Heavy = false;
public int MaxWeaponNum;
public int MaxMissileWeaponNum;
public int MaxSkillNum;
public List<LootEntry> Loots;
#endregion
public UnitType Clone()
{
return (UnitType)this.MemberwiseClone();
}
}
[Serializable]
/// <summary>
/// 大地无敌-范若余在2009年10月5日建立,表示一个Loot的参数
/// </summary>
public class LootEntry
{
/// <summary>
/// 属于类型的别名
/// </summary>
public string LootAssetName;
/// <summary>
/// 掉落率(0到1之间)
/// </summary>
public float Prob;
/// <summary>
/// 距离掉落单位中心的最大距离
/// </summary>
public float MaxRadius;
}
}
| WindyDarian/Art-of-Destiny | AODGameLibrary/Units/UnitType.cs | C# | apache-2.0 | 3,783 |
#ifndef color_xyz_akin_hsv
#define color_xyz_akin_hsv
#include "../../generic/akin/xyz.hpp"
#include "../category.hpp"
#include "../../hsv/category.hpp"
namespace color
{
namespace akin
{
template< >struct xyz< ::color::category::hsv_uint8 >{ typedef ::color::category::xyz_uint8 akin_type; };
template< >struct xyz< ::color::category::hsv_uint16 >{ typedef ::color::category::xyz_uint16 akin_type; };
template< >struct xyz< ::color::category::hsv_uint32 >{ typedef ::color::category::xyz_uint32 akin_type; };
template< >struct xyz< ::color::category::hsv_uint64 >{ typedef ::color::category::xyz_uint64 akin_type; };
template< >struct xyz< ::color::category::hsv_float >{ typedef ::color::category::xyz_float akin_type; };
template< >struct xyz< ::color::category::hsv_double >{ typedef ::color::category::xyz_double akin_type; };
template< >struct xyz< ::color::category::hsv_ldouble >{ typedef ::color::category::xyz_ldouble akin_type; };
}
}
#endif
| dmilos/color | src/color/xyz/akin/hsv.hpp | C++ | apache-2.0 | 1,036 |
# Tfjs google/imagenet/inception_v2/feature_vector/1/default/1
TF.js deployment of google/imagenet/inception_v2/feature_vector/1.
<!-- asset-path: legacy -->
<!-- parent-model: google/imagenet/inception_v2/feature_vector/1 -->
## Origin
This model is based on [google/imagenet/inception_v2/feature_vector/1](https://tfhub.dev/google/imagenet/inception_v2/feature_vector/1).
This model has been automatically converted using the [TF.js converter](https://github.com/tensorflow/tfjs/tree/master/tfjs-converter).
## Example use
This model can be loaded using TF.js as:
```javascript
tf.loadGraphModel("https://tfhub.dev/google/tfjs-model/imagenet/inception_v2/feature_vector/1/default/1", { fromTFHub: true })
```
| tensorflow/tfhub.dev | assets/docs/google/models/imagenet/inception_v2/feature_vector/1/default/tfjs/1.md | Markdown | apache-2.0 | 717 |
/*
* Copyright (C) 2014 Stratio (http://stratio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.cassandra.lucene
import java.nio.file.Paths
import com.stratio.cassandra.lucene.IndexOptions._
import com.stratio.cassandra.lucene.partitioning.{PartitionerOnNone, PartitionerOnToken}
import org.apache.cassandra.config.Config
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
/** Tests for [[IndexOptions]].
*
* @author Andres de la Pena `adelapena@stratio.com`
*/
@RunWith(classOf[JUnitRunner])
class IndexOptionsTest extends BaseScalaTest {
// Refresh seconds option tests
test("parse refresh seconds option with default") {
Config.setClientMode(true)
parseRefresh(Map()) shouldBe DEFAULT_REFRESH_SECONDS
}
test("parse refresh seconds option with integer") {
parseRefresh(Map(REFRESH_SECONDS_OPTION -> "1")) shouldBe 1
}
test("parse refresh seconds option with decimal") {
parseRefresh(Map(REFRESH_SECONDS_OPTION -> "0.1")) shouldBe 0.1
}
test("parse refresh seconds option with failing non numeric value") {
intercept[IndexException] {
parseRefresh(Map(REFRESH_SECONDS_OPTION -> "a"))
}.getMessage shouldBe s"'$REFRESH_SECONDS_OPTION' must be a strictly positive decimal, found: a"
}
test("parse refresh seconds option with failing zero value") {
intercept[IndexException] {
parseRefresh(Map(REFRESH_SECONDS_OPTION -> "0"))
}.getMessage shouldBe s"'$REFRESH_SECONDS_OPTION' must be strictly positive, found: 0.0"
}
test("parse refresh seconds option with failing negative value") {
intercept[IndexException] {
parseRefresh(Map(REFRESH_SECONDS_OPTION -> "-1"))
}.getMessage shouldBe s"'$REFRESH_SECONDS_OPTION' must be strictly positive, found: -1.0"
}
// RAM buffer MB option tests
test("parse RAM buffer MB option with default") {
parseRamBufferMB(Map()) shouldBe DEFAULT_RAM_BUFFER_MB
}
test("parse RAM buffer MB option with integer") {
parseRamBufferMB(Map(RAM_BUFFER_MB_OPTION -> "1")) shouldBe 1
}
test("parse RAM buffer MB option with failing decimal") {
intercept[IndexException] {
parseRamBufferMB(Map(RAM_BUFFER_MB_OPTION -> "0.1"))
}.getMessage shouldBe s"'$RAM_BUFFER_MB_OPTION' must be a strictly positive integer, found: 0.1"
}
test("parse RAM buffer MB option with failing non numeric value") {
intercept[IndexException] {
parseRamBufferMB(Map(RAM_BUFFER_MB_OPTION -> "a"))
}.getMessage shouldBe s"'$RAM_BUFFER_MB_OPTION' must be a strictly positive integer, found: a"
}
test("parse RAM buffer MB option with failing zero value") {
intercept[IndexException] {
parseRamBufferMB(Map(RAM_BUFFER_MB_OPTION -> "0"))
}.getMessage shouldBe s"'$RAM_BUFFER_MB_OPTION' must be strictly positive, found: 0"
}
test("parse RAM buffer MB option with failing negative value") {
intercept[IndexException] {
parseRamBufferMB(Map(RAM_BUFFER_MB_OPTION -> "-1"))
}.getMessage shouldBe s"'$RAM_BUFFER_MB_OPTION' must be strictly positive, found: -1"
}
// Max merge MB option tests
test("parse max merge MB option with default") {
parseMaxMergeMB(Map()) shouldBe DEFAULT_MAX_MERGE_MB
}
test("parse max merge MB option with integer") {
parseMaxMergeMB(Map(MAX_MERGE_MB_OPTION -> "1")) shouldBe 1
}
test("parse max merge MB option with failing decimal") {
intercept[IndexException] {
parseMaxMergeMB(Map(MAX_MERGE_MB_OPTION -> "0.1"))
}.getMessage shouldBe s"'$MAX_MERGE_MB_OPTION' must be a strictly positive integer, found: 0.1"
}
test("parse max merge MB option with failing non numeric value") {
intercept[IndexException] {
parseMaxMergeMB(Map(MAX_MERGE_MB_OPTION -> "a"))
}.getMessage shouldBe s"'$MAX_MERGE_MB_OPTION' must be a strictly positive integer, found: a"
}
test("parse max merge MB option with failing zero value") {
intercept[IndexException] {
parseMaxMergeMB(Map(MAX_MERGE_MB_OPTION -> "0"))
}.getMessage shouldBe s"'$MAX_MERGE_MB_OPTION' must be strictly positive, found: 0"
}
test("parse max merge MB option with failing negative value") {
intercept[IndexException] {
parseMaxMergeMB(Map(MAX_MERGE_MB_OPTION -> "-1"))
}.getMessage shouldBe s"'$MAX_MERGE_MB_OPTION' must be strictly positive, found: -1"
}
// Max cached MB option tests
test("parse max cached MB option with default") {
parseMaxCachedMB(Map()) shouldBe DEFAULT_MAX_CACHED_MB
}
test("parse max cached MB option with integer") {
parseMaxCachedMB(Map(MAX_CACHED_MB_OPTION -> "1")) shouldBe 1
}
test("parse max cached MB option with failing decimal") {
intercept[IndexException] {
parseMaxCachedMB(Map(MAX_CACHED_MB_OPTION -> "0.1"))
}.getMessage shouldBe s"'$MAX_CACHED_MB_OPTION' must be a strictly positive integer, found: 0.1"
}
test("parse max cached MB option with failing non numeric value") {
intercept[IndexException] {
parseMaxCachedMB(Map(MAX_CACHED_MB_OPTION -> "a"))
}.getMessage shouldBe s"'$MAX_CACHED_MB_OPTION' must be a strictly positive integer, found: a"
}
test("parse max cached MB option with failing zero value") {
intercept[IndexException] {
parseMaxCachedMB(Map(MAX_CACHED_MB_OPTION -> "0"))
}.getMessage shouldBe s"'$MAX_CACHED_MB_OPTION' must be strictly positive, found: 0"
}
test("parse max cached MB option with failing negative value") {
intercept[IndexException] {
parseMaxCachedMB(Map(MAX_CACHED_MB_OPTION -> "-1"))
}.getMessage shouldBe s"'$MAX_CACHED_MB_OPTION' must be strictly positive, found: -1"
}
// Indexing threads option tests
test("parse indexing threads option with default") {
parseIndexingThreads(Map()) shouldBe DEFAULT_INDEXING_THREADS
}
test("parse indexing threads option with integer") {
parseIndexingThreads(Map(INDEXING_THREADS_OPTION -> "1")) shouldBe 1
}
test("parse indexing threads option with failing decimal") {
intercept[IndexException] {
parseIndexingThreads(Map(INDEXING_THREADS_OPTION -> "0.1"))
}.getMessage shouldBe s"'$INDEXING_THREADS_OPTION' must be an integer, found: 0.1"
}
test("parse indexing threads option with failing non numeric value") {
intercept[IndexException] {
parseIndexingThreads(Map(INDEXING_THREADS_OPTION -> "a"))
}.getMessage shouldBe s"'$INDEXING_THREADS_OPTION' must be an integer, found: a"
}
test("parse indexing threads option with zero value") {
parseIndexingThreads(Map(INDEXING_THREADS_OPTION -> "-1")) shouldBe -1
}
test("parse indexing threads option with negative value") {
parseIndexingThreads(Map(INDEXING_THREADS_OPTION -> "-1")) shouldBe -1
}
// Indexing queues size option tests
test("parse indexing queues size option with default") {
parseIndexingQueuesSize(Map()) shouldBe DEFAULT_INDEXING_QUEUES_SIZE
}
test("parse indexing queues size option with integer") {
parseIndexingQueuesSize(Map(INDEXING_QUEUES_SIZE_OPTION -> "1")) shouldBe 1
}
test("parse indexing queues size option with failing decimal") {
intercept[IndexException] {
parseIndexingQueuesSize(Map(INDEXING_QUEUES_SIZE_OPTION -> "0.1"))
}.getMessage shouldBe
s"'$INDEXING_QUEUES_SIZE_OPTION' must be a strictly positive integer, found: 0.1"
}
test("parse indexing queues size option with failing non numeric value") {
intercept[IndexException] {
parseIndexingQueuesSize(Map(INDEXING_QUEUES_SIZE_OPTION -> "a"))
}.getMessage shouldBe
s"'$INDEXING_QUEUES_SIZE_OPTION' must be a strictly positive integer, found: a"
}
test("parse indexing queues size option with failing zero value") {
intercept[IndexException] {
parseIndexingQueuesSize(Map(INDEXING_QUEUES_SIZE_OPTION -> "0"))
}.getMessage shouldBe s"'$INDEXING_QUEUES_SIZE_OPTION' must be strictly positive, found: 0"
}
test("parse indexing queues size option with failing negative value") {
intercept[IndexException] {
parseIndexingQueuesSize(Map(INDEXING_QUEUES_SIZE_OPTION -> "-1"))
}.getMessage shouldBe s"'$INDEXING_QUEUES_SIZE_OPTION' must be strictly positive, found: -1"
}
// Excluded data centers size option tests
test("parse excluded data centers option with default") {
parseExcludedDataCenters(Map()) shouldBe DEFAULT_EXCLUDED_DATA_CENTERS
}
test("parse excluded data centers option with empty list") {
parseExcludedDataCenters(Map(EXCLUDED_DATA_CENTERS_OPTION -> "")) shouldBe List()
}
test("parse excluded data centers option with singleton list") {
parseExcludedDataCenters(Map(EXCLUDED_DATA_CENTERS_OPTION -> "dc1")) shouldBe List("dc1")
}
test("parse excluded data centers option with multiple list") {
val options = Map(EXCLUDED_DATA_CENTERS_OPTION -> " dc1,dc2 ")
parseExcludedDataCenters(options) shouldBe List("dc1", "dc2")
}
test("parse excluded data centers option with multiple list and spaces") {
val options = Map(EXCLUDED_DATA_CENTERS_OPTION -> " dc1 , dc2 ")
parseExcludedDataCenters(options) shouldBe List("dc1", "dc2")
}
// Partitioner option tests
test("parse partitioner option with default") {
parsePartitioner(Map(), null) shouldBe DEFAULT_PARTITIONER
}
test("parse partitioner with none partitioner") {
val json = "{type:\"none\"}"
parsePartitioner(Map(PARTITIONER_OPTION -> json), null) shouldBe PartitionerOnNone()
}
test("parse partitioner with token partitioner") {
val json = "{type:\"token\", partitions: 10, paths:[\"/home/a\",\"/home/b\",\"/home/c\",\"/home/d\",\"/home/e\",\"/home/f\",\"/home/g\",\"/home/h\",\"/home/i\",\"/home/j\"]}"
parsePartitioner(Map(PARTITIONER_OPTION -> json), null) shouldBe PartitionerOnToken(10,
Some(Array("/home/a",
"/home/b",
"/home/c",
"/home/d",
"/home/e",
"/home/f",
"/home/g",
"/home/h",
"/home/i",
"/home/j").map(Paths.get(_))))
}
// tests for File configuration collision among cassandra and scli
test("test custom partitioner with one path inside the cassandra directory") {
val partitionJson = "{type:\"token\", partitions: 3, paths:[\"/home/cassandra/c\", \"/home/eduard/\", \"/home/jp\"]}"
val path = "/path/"
val paths = Array("/home/cassandra/").map(Paths.get(_))
val baseTablePath = Paths.get("/home/d")
val tuple = parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
tuple._1 shouldBe Some(Paths.get(path))
}
test("test custom partitioner with every path inside the cassandra directory") {
val partitionJson = "{type:\"token\", partitions: 3, paths:[\"/home/cassandra/c\", \"/home/cassandra/f\", \"/home/cassandra/d\"]}"
val path = "/path/"
val paths = Array("/home/cassandra/").map(Paths.get(_))
val baseTablePath = Paths.get("/home/cassandra/search/table")
System.out.println(parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath))
val tuple = parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
tuple._1 shouldBe Some(Paths.get(path))
tuple._2 shouldBe PartitionerOnToken(3, Some(Array("/home/cassandra/c", "/home/cassandra/f", "/home/cassandra/d").map(Paths.get(_))))
}
test("test custom partitioner with all paths outside the cassandra directory") {
val partitionJson = "{type:\"token\", partitions: 3, paths:[\"/home/eduard/c\", \"/home/eduard/f\", \"/home/eduard/d\"]}"
val path = "/path/"
val paths = Array("/home/cassandra/").map(Paths.get(_))
val baseTablePath = Paths.get("/home/cassandra/search/table")
System.out.println(parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath))
val tuple = parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
tuple._1 shouldBe Some(Paths.get(path))
tuple._2 shouldBe PartitionerOnToken(3, Some(Array("/home/eduard/c", "/home/eduard/f", "/home/eduard/d").map(Paths.get(_))))
}
test("test directory_path inside the cassandra directory") {
val partitionJson = "{type:\"none\"}"
val path = "/home/cassandra/a"
val paths = Array("/home/cassandra/").map(Paths.get(_))
val baseTablePath = null
System.out.println(parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath))
val tuple = parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
tuple._1 shouldBe Some(Paths.get(path))
tuple._2 shouldBe PartitionerOnNone()
}
test("test directory_path outside the cassandra directory") {
val partitionJson = "{type:\"none\"}"
val path = "/home/eduard/"
val paths = Array("/home/cassandra/").map(Paths.get(_))
val baseTablePath = null
System.out.println( parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath))
val tuple = parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson, DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
tuple._1 shouldBe Some(Paths.get(path))
tuple._2 shouldBe PartitionerOnNone()
}
test("test custom partitioner with one path inside multiple cassandra directory") {
intercept[IndexException] {
val partitionJson = "{type:\"token\", partitions: 3, paths:[\"/home/cassandra/c\", \"/home/eduard/\", \"/home/jp\"]}"
val paths = Array("/home/cassandra/", "/home/cassandra2/").map(Paths.get(_))
val baseTablePath = null
parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson), null, paths, baseTablePath)
}.getMessage shouldBe "When cassandra is configured with more than one 'data_file_directory', custom partitioner paths must not be inside any of those 'data_file_directory','/home/cassandra/c' is inside: '/home/cassandra'"
}
test("test custom partitioner with every path inside multiple cassandra directory") {
intercept[IndexException] {
val partitionJson = "{type:\"token\", partitions: 3, paths:[\"/home/cassandra/c\", \"/home/cassandra/f\", \"/home/cassandra/d\"]}"
val paths = Array("/home/cassandra/", "/home/cassandra2/").map(Paths.get(_))
val baseTablePath = null
parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson), null, paths, baseTablePath)
}.getMessage shouldBe "When cassandra is configured with more than one 'data_file_directory', custom partitioner paths must not be inside any of those 'data_file_directory','/home/cassandra/c' is inside: '/home/cassandra'"
}
test("test custom partitioner with all paths outside multiple cassandra directory") {
val partitionJson = "{type:\"token\", partitions: 3, paths:[\"/home/eduard/c\", \"/home/eduard/f\", \"/home/eduard/d\"]}"
val paths = Array("/home/cassandra/", "/home/cassandra2/").map(Paths.get(_))
val baseTablePath = null
System.out.println(parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson), null, paths, baseTablePath))
val tuple = parsePathAndPartitioner(Map(PARTITIONER_OPTION -> partitionJson), null, paths, baseTablePath)
tuple._1 shouldBe None
tuple._2 shouldBe PartitionerOnToken(3, Some(Array("/home/eduard/c", "/home/eduard/f", "/home/eduard/d").map(Paths.get(_))))
}
test("test directory_path inside multiple cassandra directory") {
intercept[IndexException] {
val paths = Array("/home/cassandra/", "/home/cassandra2/").map(Paths.get(_))
val path = "/home/cassandra/a"
val baseTablePath = null
parsePathAndPartitioner(Map(DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
}.getMessage shouldBe "When cassandra is configured with more than one 'data_file_directory', 'directory_path' must not be inside any of those 'data_file_directory','/home/cassandra/a' is inside: '/home/cassandra'"
}
test("test directory_path outside multiple cassandra directory") {
val paths = Array("/home/cassandra/", "/home/cassandra2/").map(Paths.get(_))
val path = "/home/eduard"
val baseTablePath = null
System.out.println(parsePathAndPartitioner(Map(DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath))
val tuple = parsePathAndPartitioner(Map(DIRECTORY_PATH_OPTION -> path), null, paths, baseTablePath)
tuple._1 shouldBe Some(Paths.get("/home/eduard"))
tuple._2 shouldBe PartitionerOnNone()
}
test("test null directory_path") {
intercept[IndexException] {
val paths = Array("/home/cassandra/", "/home/cassandra2/").map(Paths.get(_))
val baseTablePath = null
parsePathAndPartitioner(Map(), null, paths, baseTablePath)
}.getMessage shouldBe "When cassandra is configured with more than one 'data_file_directory', 'directory_path' required"
}
} | Stratio/cassandra-lucene-index | plugin/src/test/scala/com/stratio/cassandra/lucene/IndexOptionsTest.scala | Scala | apache-2.0 | 17,567 |
/*
* User.java
*
* This file is part of the Sorcix Java IRC Library (sIRC).
*
* Copyright (C) 2008-2010 Vic Demuzere http://sorcix.com
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sorcix.sirc;
/**
* Represents a user on the IRC server.
*
* @author Sorcix
*/
public final class User {
/** Hostname of this user (or null if unknown). */
private final String hostName;
/** IrcConnection used to contact this user. */
private final IrcConnection irc;
/** Nickname of this user. */
private String nick;
/** Lowercase nickname of this user. */
private String nickLower;
/** The prefix. */
private char prefix;
/** Custom address to send messages to. */
private String address = null;
/** Username of this user (or null if unknown). */
private final String userName;
/** Mode character for voice. */
protected static final char MODE_VOICE = 'v';
/** Mode character for operator. */
protected static final char MODE_OPERATOR = 'o';
/** Mode character for half-op. (Not supported by RFC!) */
protected static final char MODE_HALF_OP = 'h';
/** Mode character for founder. (Not supported by RFC!) */
protected static final char MODE_FOUNDER = 'q';
/** Mode character for admin. (Not supported by RFC!) */
protected static final char MODE_ADMIN = 'a';
/** Prefix character for half-op. (Not supported by RFC!) */
protected static final char PREFIX_HALF_OP = '%';
/** Prefix character for founder. (Not supported by RFC!) */
protected static final char PREFIX_FOUNDER = '~';
/** Prefix character for admin. (Not supported by RFC!) */
protected static final char PREFIX_ADMIN = '&';
/** Prefix character for voice. */
protected static final char PREFIX_VOICE = '+';
/** Prefix character for operator. */
protected static final char PREFIX_OPERATOR = '@';
/** Possible user prefixes. */
protected static final String USER_PREFIX = "~@%+&";
private final String realName;
/**
* Creates a new {@code User}.
*
* @param nick The nickname.
* @param irc The IrcConnection used to send messages to this
* user.
*/
public User(final String nick, final IrcConnection irc) {
this(nick, null, null, null, irc);
}
/**
* Creates a new {@code User}.
*
* @param nick The nickname.
* @param user The username.
* @param host The hostname.
* @param irc The IrcConnection used to send messages to this
* user.
*/
protected User(final String nick, final String user, final String host, final String realName, final IrcConnection irc) {
this.setNick(nick);
this.realName = realName;
this.userName = user;
this.hostName = host;
this.irc = irc;
this.address = this.getNick();
}
@Override
public boolean equals(final Object user) {
try {
return ((User) user).getNick().equalsIgnoreCase(this.nick);
} catch (final Exception ex) {
return false;
}
}
/**
* Returns the address sIRC uses to send messages to this user.
* @return The address used to send messages to this user.
*/
private String getAddress() {
return this.address;
}
/**
* Returns the hostname for this user.
*
* @return The hostname, or null if unknown.
*/
public String getHostName() {
return this.hostName;
}
/**
* Returns the nickname for this user.
*
* @return The nickname.
*/
public String getNick() {
return this.nick;
}
/**
* Returns the lowercase nickname for this user.
*
* @return Lowercase nickname.
*/
public String getNickLower() {
return this.nickLower;
}
/**
* Returns this user's prefix.
*
* @return The prefix.
*/
public char getPrefix() {
return this.prefix;
}
/**
* Returns the username for this user.
*
* @return The username.
*/
public String getUserName() {
return this.userName;
}
public String getRealName() {
if (this.realName == null)
return this.nick;
return this.realName;
}
/**
* Checks whether this user has Admin privileges.
*
* @return True if this user is an admin.
* @since 1.1.0
*/
public boolean hasAdmin() {
return this.getPrefix() == User.PREFIX_ADMIN;
}
/**
* Checks whether this user has Founder privileges.
*
* @return True if this user is a founder.
* @since 1.1.0
*/
public boolean hasFounder() {
return this.getPrefix() == User.PREFIX_FOUNDER;
}
/**
* Checks whether this user has Halfop privileges.
*
* @return True if this user is a half operator.
* @since 1.1.0
*/
public boolean hasHalfOp() {
return this.getPrefix() == User.PREFIX_HALF_OP;
}
/**
* Checks whether this user has Operator privileges.
*
* @return True if this user is an operator.
* @since 1.1.0
*/
public boolean hasOperator() {
return this.getPrefix() == User.PREFIX_OPERATOR;
}
/**
* Checks whether this user has Voice privileges.
*
* @return True if this user has voice.
* @since 1.1.0
*/
public boolean hasVoice() {
return this.getPrefix() == User.PREFIX_VOICE;
}
/**
* Checks if this {@code User} represents us.
*
* @return True if this {@code User} represents us, false
* otherwise.
* @see IrcConnection#isUs(User)
*/
public boolean isUs() {
return this.irc.isUs(this);
}
/**
* Send message to user.
*
* @param message The message to send.
* @see #sendMessage(String)
*/
public void send(final String message) {
this.sendMessage(message);
}
/**
* Sends an action.
*
* @param action The action to send.
*/
public void sendAction(final String action) {
this.sendCtcpAction(action);
}
/**
* Sends CTCP request. This is a very primitive way to send CTCP
* commands, other methods are preferred.
*
* @param command Command to send.
*/
public void sendCtcp(final String command) {
this.irc.getOutput().send("PRIVMSG " + this.getAddress() + " :" + IrcPacket.CTCP + command + IrcPacket.CTCP);
}
/**
* Sends a CTCP ACTION command.
*
* @param action The action to send.
* @see #sendCtcp(String)
*/
protected void sendCtcpAction(final String action) {
if ((action != null) && (action.length() != 0)) {
this.sendCtcp("ACTION " + action);
}
}
/**
* Sends a CTCP CLIENTINFO command.
*/
public void sendCtcpClientInfo() {
this.sendCtcp("CLIENTINFO");
}
/**
* Sends a CTCP PING command.
*
* @return The timestamp sent to this user.
*/
public long sendCtcpPing() {
final Long time = System.currentTimeMillis();
this.sendCtcp("PING " + time.toString());
return time;
}
/**
* Sends CTCP reply using notices. Replies to CTCP requests should
* be sent using a notice.
*
* @param command Command to send.
*/
protected void sendCtcpReply(final String command) {
this.sendCtcpReply(command, false);
}
/**
* Sends CTCP reply using notices. Replies to CTCP requests should
* be sent using a notice.
*
* @param command Command to send.
* @param skipQueue Whether to skip the outgoing message queue.
*/
protected void sendCtcpReply(final String command, final boolean skipQueue) {
if (skipQueue) {
this.irc.getOutput().sendNow("NOTICE " + this.getAddress() + " :" + IrcPacket.CTCP + command + IrcPacket.CTCP);
} else {
this.irc.getOutput().send("NOTICE " + this.getAddress() + " :" + IrcPacket.CTCP + command + IrcPacket.CTCP);
}
}
/**
* Sends a CTCP VERSION command to this user.
*/
public void sendCtcpVersion() {
this.sendCtcp("VERSION");
}
/**
* Send message to this user.
*
* @param message The message to send.
*/
public void sendMessage(final String message) {
this.irc.getOutput().send("PRIVMSG " + this.getAddress() + " :" + message);
}
/**
* Send notice to this user.
*
* @param message The notice to send.
*/
public void sendNotice(final String message) {
this.irc.getOutput().send("NOTICE " + this.getAddress() + " :" + message);
}
/**
* Sets a custom address for this user. This address will be used
* to send messages to instead of simply the nickname. Use an
* address like {@code nick@server}. Setting the address to
* {@code @server} will prepend the nick automatically.
*
* @param address The address to use.
*/
public void setCustomAddress(final String address) {
if (address == null) {
this.address = this.getNick();
} else if (address.startsWith("@")) {
this.address = this.getNick() + address;
} else {
this.address = address;
}
}
/**
* Changes a user mode for given user.
*
* @param mode The mode character.
* @param toggle True to enable the mode, false to disable.
*/
public void setMode(final char mode, final boolean toggle) {
if (toggle) {
this.setMode("+" + mode);
} else {
this.setMode("-" + mode);
}
}
/**
* Changes a user mode. The address is automatically added.
*
* <pre>
* setMode("+m");
* </pre>
*
* @param mode The mode to change.
*/
public void setMode(final String mode) {
this.irc.getOutput().send("MODE " + this.getAddress() + " " + mode);
}
/**
* Changes the nickname of this user.
*
* @param nick The new nickname.
*/
protected void setNick(String nick) {
if (nick == null)
return;
if (User.USER_PREFIX.indexOf(nick.charAt(0)) >= 0) {
this.prefix = nick.charAt(0);
nick = nick.substring(1);
}
this.nick = nick;
this.nickLower = nick.toLowerCase();
// TODO: Check whether addresses like nick!user@server are
// allowed
if ((this.address != null) && this.address.contains("@")) {
this.address = this.nick + "@" + this.address.split("@", 2)[1];
} else {
this.address = this.nick;
}
}
@Override
public String toString() {
return this.getNick();
}
/**
* Updates this User object with data from given User.
*
* @param user The fresh User object.
*/
protected void updateUser(final User user) {
//TODO: Unfinished method?
}
}
| tcichowicz/MockMock | src/main/java/com/sorcix/sirc/User.java | Java | apache-2.0 | 10,895 |
use strict;
use warnings;
use Bio::EnsEMBL::Registry;
my $registry = 'Bio::EnsEMBL::Registry';
$registry->load_all('/hps/nobackup2/production/ensembl/anja/release_97/human/regulation_effect/ensembl.registry');
my $species = 'human';
my $sa = $registry->get_adaptor($species, 'core', 'slice');
my $rfa = $registry->get_adaptor($species, 'funcgen', 'RegulatoryFeature');
my $vdba = $registry->get_DBAdaptor($species, 'variation');
my $dbh = $vdba->dbc->db_handle;
#{"seq_region_end" => 44599149,"seq_region_name" => 10,"seq_region_start" => 39643689}
#{"seq_region_end" => 29384982,"seq_region_name" => 17,"seq_region_start" => 24487486}
#{"seq_region_end" => 53970840,"seq_region_name" => 5,"seq_region_start" => 49064401}
my $seq_region_name = 10;
my $seq_region_start = 39643689;
my $seq_region_end = 44599149;
my $slice = $sa->fetch_by_region('toplevel', $seq_region_name, $seq_region_start, $seq_region_end);
my @regulatory_features = grep { $_->seq_region_end <= $seq_region_end } @{$rfa->fetch_all_by_Slice($slice)||[]};
foreach my $regulatory_feature (@regulatory_features) {
my $stable_id = $regulatory_feature->stable_id;
my $sth = $dbh->prepare(qq{
SELECT COUNT(distinct variation_feature_id) FROM regulatory_feature_variation WHERE feature_stable_id=?;
});
$sth->execute($stable_id) or die 'Could not execute statement ' . $sth->errstr;
my @row = $sth->fetchrow_array;
my $count = $row[0];
$sth->finish();
$slice = $sa->fetch_by_Feature($regulatory_feature);
my @vfs = ();
push @vfs, @{ $slice->get_all_VariationFeatures };
push @vfs, @{ $slice->get_all_somatic_VariationFeatures };
my $count_vfs = scalar @vfs;
if ($count_vfs != $count) {
print STDERR $stable_id, ' ', $count, ' ', $count_vfs, "\n";
my @sorted = sort {$a->seq_region_end <=> $b->seq_region_end} @vfs;
my $smallest = $sorted[0];
my $largest = $sorted[$#sorted];
print STDERR $smallest->seq_region_start, ' ', $smallest->seq_region_end, "\n";
print STDERR $largest->seq_region_start, ' ', $largest->seq_region_end, "\n";
}
}
| at7/work | api/find_boundary_variations.pl | Perl | apache-2.0 | 2,069 |
#ifndef COMMON_H
#define COMMON_H
// #define USE_SUPER_SPECULAR
#include "shared\common.h"
//////////////////////////////////////////////////////////////////////////////////////////
// *** options
// #define USE_GAMMA_22
// #define USE_SJITTER
// #define USE_SUNFILTER
//
// #define USE_MBLUR //- HW-options defined
// #define USE_HWSMAP //- HW-options defined
// #define USE_BRANCHING //- HW-options defined
// #define USE_VTF //- HW-options defined, VertexTextureFetch
// #define FP16_FILTER //- HW-options defined
// #define FP16_BLEND //- HW-options defined
//
// #define USE_PARALLAX //- shader defined
// #define USE_TDETAIL //- shader defined
// #define USE_LM_HEMI //- shader defined
// #define USE_DISTORT //- shader defined
#define USE_SUNMASK //- shader defined
//#define DBG_TMAPPING
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef SMAP_size
#define SMAP_size 2048
#endif
#define PARALLAX_H 0.02
#define parallax float2(PARALLAX_H, -PARALLAX_H/2)
#ifdef USE_R2_STATIC_SUN
# define xmaterial half(1.0h/4.h)
#else
# define xmaterial half(L_material.w)
#endif
//////////////////////////////////////////////////////////////////////////////////////////
uniform half4 L_material; // 0,0,0,mid
uniform half4 Ldynamic_color; // dynamic light color (rgb1) - spot/point
uniform half4 Ldynamic_pos; // dynamic light pos+1/range(w) - spot/point
uniform half4 Ldynamic_dir; // dynamic light direction - sun
uniform half4 J_direct [6];
uniform half4 J_spot [6];
half calc_fogging (half4 w_pos) { return dot(w_pos,fog_plane); }
half2 calc_detail (half3 w_pos) {
float dtl = distance (w_pos,eye_position)*dt_params.w;
dtl = min (dtl*dtl, 1);
half dt_mul = 1 - dtl; // dt* [1 .. 0 ]
half dt_add = .5 * dtl; // dt+ [0 .. 0.5]
return half2 (dt_mul,dt_add);
}
float3 calc_reflection (float3 pos_w, float3 norm_w)
{
return reflect(normalize(pos_w-eye_position), norm_w);
}
float3 calc_sun_r1 (float3 norm_w) { return L_sun_color*saturate(dot((norm_w),-L_sun_dir_w)); }
float3 calc_model_hemi_r1 (float3 norm_w) { return max(0,norm_w.y)*L_hemi_color; }
float3 calc_model_lq_lighting (float3 norm_w) { return L_material.x*calc_model_hemi_r1(norm_w) + L_ambient + L_material.y*calc_sun_r1(norm_w); }
//////////////////////////////////////////////////////////////////////////////////////////
struct v_static {
float4 P : POSITION; // (float,float,float,1)
float4 Nh : NORMAL; // (nx,ny,nz,hemi occlusion)
float4 T : TANGENT; // tangent
float4 B : BINORMAL; // binormal
float2 tc : TEXCOORD0; // (u,v)
float2 lmh : TEXCOORD1; // (lmu,lmv)
float4 color : COLOR0; // (r,g,b,dir-occlusion)
};
struct v_tree {
float4 P : POSITION; // (float,float,float,1)
float4 Nh : NORMAL; // (nx,ny,nz)
float3 T : TANGENT; // tangent
float3 B : BINORMAL; // binormal
float4 tc : TEXCOORD0; // (u,v,frac,???)
};
struct v_model {
float4 P : POSITION; // (float,float,float,1)
float3 N : NORMAL; // (nx,ny,nz)
float3 T : TANGENT; // (nx,ny,nz)
float3 B : BINORMAL; // (nx,ny,nz)
float2 tc : TEXCOORD0; // (u,v)
};
struct v_detail {
float4 pos : POSITION; // (float,float,float,1)
int4 misc : TEXCOORD0; // (u(Q),v(Q),frac,matrix-id)
};
#ifdef USE_HWSMAP
struct v_shadow_direct_aref
{
float4 hpos: POSITION; // Clip-space position (for rasterization)
float2 tc0: TEXCOORD1; // Diffuse map for aref
};
struct v_shadow_direct
{
float4 hpos: POSITION; // Clip-space position (for rasterization)
};
#else
struct v_shadow_direct_aref
{
float4 hpos: POSITION; // Clip-space position (for rasterization)
float depth: TEXCOORD0; // Depth
float2 tc0: TEXCOORD1; // Diffuse map for aref
};
struct v_shadow_direct
{
float4 hpos: POSITION; // Clip-space position (for rasterization)
float depth: TEXCOORD0; // Depth
};
#endif
//////////////////////////////////////////////////////////////////////////////////////////
struct p_bumped {
float4 hpos : POSITION;
#if defined(USE_R2_STATIC_SUN) && !defined(USE_LM_HEMI)
float4 tcdh : TEXCOORD0; // Texture coordinates, w=sun_occlusion
#else
float2 tcdh : TEXCOORD0; // Texture coordinates
#endif
float4 position : TEXCOORD1; // position + hemi
half3 M1 : TEXCOORD2; // nmap 2 eye - 1
half3 M2 : TEXCOORD3; // nmap 2 eye - 2
half3 M3 : TEXCOORD4; // nmap 2 eye - 3
#ifdef USE_PARALLAX
half3 eye : TEXCOORD5; // vector to point in tangent space
#ifdef USE_TDETAIL
float2 tcdbump : TEXCOORD6; // d-bump
#ifdef USE_LM_HEMI
float2 lmh : TEXCOORD7; // lm-hemi
#endif
#else
#ifdef USE_LM_HEMI
float2 lmh : TEXCOORD6; // lm-hemi
#endif
#endif
#else
#ifdef USE_TDETAIL
float2 tcdbump : TEXCOORD5; // d-bump
#ifdef USE_LM_HEMI
float2 lmh : TEXCOORD6; // lm-hemi
#endif
#else
#ifdef USE_LM_HEMI
float2 lmh : TEXCOORD5; // lm-hemi
#endif
#endif
#endif
};
//////////////////////////////////////////////////////////////////////////////////////////
struct p_flat {
float4 hpos : POSITION;
#if defined(USE_R2_STATIC_SUN) && !defined(USE_LM_HEMI)
float4 tcdh : TEXCOORD0; // Texture coordinates, w=sun_occlusion
#else
float2 tcdh : TEXCOORD0; // Texture coordinates
#endif
float4 position : TEXCOORD1; // position + hemi
half3 N : TEXCOORD2; // Eye-space normal (for lighting)
#ifdef USE_TDETAIL
float2 tcdbump : TEXCOORD3; // d-bump
#ifdef USE_LM_HEMI
float2 lmh : TEXCOORD4; // lm-hemi
#endif
#else
#ifdef USE_LM_HEMI
float2 lmh : TEXCOORD3; // lm-hemi
#endif
#endif
};
//////////////////////////////////////////////////////////////////////////////////////////
struct f_deffer {
half4 position : COLOR0; // px,py,pz, m-id
half4 Ne : COLOR1; // nx,ny,nz, hemi
half4 C : COLOR2; // r, g, b, gloss
};
//////////////////////////////////////////////////////////////////////////////////////////
struct p_screen {
float4 hpos : POSITION;
float2 tc0 : TEXCOORD0; // Texture coordinates (for sampling maps)
};
//////////////////////////////////////////////////////////////////////////////////////////
// Geometry phase / deferring //
uniform sampler2D s_base; //
uniform sampler2D s_bump; //
uniform sampler2D s_bumpX; //
uniform sampler2D s_detail; //
uniform sampler2D s_bumpD; //
uniform sampler2D s_hemi; //
uniform sampler2D s_mask; //
uniform sampler2D s_dt_r; //
uniform sampler2D s_dt_g; //
uniform sampler2D s_dt_b; //
uniform sampler2D s_dt_a; //
uniform sampler2D s_dn_r; //
uniform sampler2D s_dn_g; //
uniform sampler2D s_dn_b; //
uniform sampler2D s_dn_a; //
//////////////////////////////////////////////////////////////////////////////////////////
// Lighting/shadowing phase //
uniform sampler2D s_depth; //
uniform sampler2D s_position; //
uniform sampler2D s_normal; //
uniform sampler s_smap; // 2D/cube shadowmap
uniform sampler s_lmap; // 2D/cube projector lightmap
uniform sampler3D s_material; //
uniform sampler1D s_attenuate; //
//////////////////////////////////////////////////////////////////////////////////////////
// Combine phase //
uniform sampler2D s_diffuse; // rgb.a = diffuse.gloss
uniform sampler2D s_accumulator; // rgb.a = diffuse.specular
uniform sampler2D s_generic; //
uniform sampler2D s_bloom; //
uniform sampler s_image; // used in various post-processing
uniform sampler2D s_tonemap; // actually MidleGray / exp(Lw + eps)
//////////////////////////////////////////////////////////////////////////////////////////
// Defines //
#define def_gloss half(2.f /255.f)
#define def_aref half(200.f/255.f)
#define def_dbumph half(0.333f)
#define def_virtualh half(.05f) // 5cm
#define def_distort half(0.05f) // we get -0.5 .. 0.5 range, this is -512 .. 512 for 1024, so scale it
#define def_hdr half(3.h) // hight luminance range half(3.h)
#define def_hdr_clip half(0.75h) //
//////////////////////////////////////////////////////////////////////////////////////////
#define LUMINANCE_VECTOR half3(0.3f, 0.48f, 0.22f)
void tonemap (out half4 low, out half4 high, half3 rgb, half scale)
{
rgb = rgb*scale ;
#ifdef USE_BRANCHING // ps_3_0
low = rgb.xyzz ;
high = low/def_hdr ; // 8x dynamic range
#else
low = half4 (rgb, 0 ) ;
high = half4 (rgb/def_hdr, 0 ) ; // 8x dynamic range
#endif
// low = half4 (rgb, 0);
// rgb /= def_hdr ;
// high = half4 (rgb, dot(rgb,0.333f)-def_hdr_clip) ;
}
half4 combine_bloom (half3 low, half4 high) {
return half4(low + high*high.a, 1.h);
}
float3 v_hemi (float3 n) { return L_hemi_color*(.5f + .5f*n.y); }
float3 v_hemi_wrap (float3 n, float w) { return L_hemi_color*(w + (1-w)*n.y); }
float3 v_sun (float3 n) { return L_sun_color*dot(n,-L_sun_dir_w); }
float3 v_sun_wrap (float3 n, float w) { return L_sun_color*(w+(1-w)*dot(n,-L_sun_dir_w)); }
half3 p_hemi (float2 tc) {
half3 t_lmh = tex2D (s_hemi, tc);
return dot (t_lmh,1.h/3.h);
}
#define FXPS technique _render{pass _code{PixelShader=compile ps_3_0 main();}}
#define FXVS technique _render{pass _code{VertexShader=compile vs_3_0 main();}}
#endif
| OLR-xray/XRay-NEW | gamedata/shaders/r2/common.h | C | apache-2.0 | 13,039 |
//Info-Content
function getBivesData(v1, v2, command, place){
$(".bivesNavi").hide();
$(".bivesResult").hide();
$('#loading').show();
d3.selectAll(place + ' > *').remove();
$("#bivesInfo").show ();
var dataCatch;
if(sessionStorage.getItem(v1.model+"_"+v1.versionid+"_"+v2.versionid) != null){
dataCatch = sessionStorage.getItem(v1.model+"_"+v1.versionid+"_"+v2.versionid);
fillGraphTabs(dataCatch);
return;
}
var bivesJob = {
files:
[
v1.url,
v2.url
],
commands:
command
};
// call the bives wrapper script
$.post (
"bives/bives.php",
"bivesJob=" + JSON.stringify (bivesJob),
function (data)
{
dataCatch = data;
}
).done(function(){
console.log(dataCatch);
fillGraphTabs(dataCatch);
//save diff in local storage
sessionStorage.setItem(v1.model+"_"+v1.versionid+"_"+v2.versionid, dataCatch);
console.log("saved in sessionStorage");
});
}
function fillGraphTabs(data){
//fill bives tabs
$("#bivesReport").html ($.parseJSON (data).reportHtml);
var annotations = $.parseJSON (data).separateAnnotations;
fillcomodiFig(annotations);
var sbgnJson = $.parseJSON (data).reactionsSbgnJson;
showSbgn(sbgnJson);
//highlight XmlDiff
$("#highlightXmlDiff").text($.parseJSON (data).xmlDiff);
$('#highlightXmlDiff').each(function(i, block) {
hljs.highlightBlock(block);
});
//hide loading gif, show bives tabs
$("#loading").hide();
$(".bivesNavi").show();
$('#bivesResult').show();
//set Hash to report tab
setHash('b', 'r');
}
| SemsProject/MOST | bives/bivesTool.js | JavaScript | apache-2.0 | 1,506 |
package com.github.florent37.camerafragment.internal.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaActionSound;
import android.os.Build;
import android.os.Bundle;
import android.os.FileObserver;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import com.github.florent37.camerafragment.CameraFragmentApi;
import com.github.florent37.camerafragment.R;
import com.github.florent37.camerafragment.configuration.Configuration;
import com.github.florent37.camerafragment.configuration.ConfigurationProvider;
import com.github.florent37.camerafragment.configuration.ConfigurationProviderImpl;
import com.github.florent37.camerafragment.internal.controller.CameraController;
import com.github.florent37.camerafragment.internal.controller.impl.Camera1Controller;
import com.github.florent37.camerafragment.internal.controller.impl.Camera2Controller;
import com.github.florent37.camerafragment.internal.controller.view.CameraView;
import com.github.florent37.camerafragment.internal.enums.Camera;
import com.github.florent37.camerafragment.internal.enums.Flash;
import com.github.florent37.camerafragment.internal.enums.MediaAction;
import com.github.florent37.camerafragment.internal.enums.Record;
import com.github.florent37.camerafragment.internal.timer.CountdownTask;
import com.github.florent37.camerafragment.internal.timer.TimerTask;
import com.github.florent37.camerafragment.internal.timer.TimerTaskBase;
import com.github.florent37.camerafragment.internal.ui.model.PhotoQualityOption;
import com.github.florent37.camerafragment.internal.ui.model.VideoQualityOption;
import com.github.florent37.camerafragment.internal.ui.view.AspectFrameLayout;
import com.github.florent37.camerafragment.internal.utils.CameraHelper;
import com.github.florent37.camerafragment.internal.utils.Size;
import com.github.florent37.camerafragment.internal.utils.Utils;
import com.github.florent37.camerafragment.listeners.CameraFragmentControlsListener;
import com.github.florent37.camerafragment.listeners.CameraFragmentResultListener;
import com.github.florent37.camerafragment.listeners.CameraFragmentStateListener;
import com.github.florent37.camerafragment.listeners.CameraFragmentVideoRecordTextListener;
import java.io.File;
/*
* Created by memfis on 12/1/16.
* Updated by Florent37
*/
public abstract class BaseAnncaFragment<CameraId> extends Fragment implements CameraFragmentApi {
public static final String ARG_CONFIGURATION = "configuration";
public static final int MIN_VERSION_ICECREAM = Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
protected CharSequence[] videoQualities;
protected CharSequence[] photoQualities;
protected AspectFrameLayout previewContainer;
protected ConfigurationProvider configurationProvider;
@Configuration.MediaQuality
protected int newQuality = -1;
private Configuration configuration;
private SensorManager sensorManager = null;
private CameraController cameraController;
private AlertDialog settingsDialog;
private CameraFragmentControlsListener cameraFragmentControlsListener;
private CameraFragmentVideoRecordTextListener cameraFragmentVideoRecordTextListener;
final TimerTaskBase.Callback timerCallBack = new TimerTaskBase.Callback() {
@Override
public void setText(String text) {
if (cameraFragmentVideoRecordTextListener != null) {
cameraFragmentVideoRecordTextListener.setRecordDurationText(text);
}
}
@Override
public void setTextVisible(boolean visible) {
if (cameraFragmentVideoRecordTextListener != null) {
cameraFragmentVideoRecordTextListener.setRecordDurationTextVisible(visible);
}
}
};
private CameraFragmentStateListener cameraFragmentStateListener;
@Flash.FlashMode
private int currentFlashMode = Flash.FLASH_AUTO;
@Camera.CameraType
private int currentCameraType = Camera.CAMERA_TYPE_REAR;
@MediaAction.MediaActionState
private int currentMediaActionState = MediaAction.ACTION_PHOTO;
@Record.RecordState
private int currentRecordState = Record.TAKE_PHOTO_STATE;
private String mediaFilePath;
private FileObserver fileObserver;
private long maxVideoFileSize = 0;
private TimerTaskBase countDownTimer;
private SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if (sensorEvent.values[0] < 4 && sensorEvent.values[0] > -4) {
if (sensorEvent.values[1] > 0) {
// UP
configurationProvider.setSensorPosition(Configuration.SENSOR_POSITION_UP);
configurationProvider.setDegrees(configurationProvider.getDeviceDefaultOrientation() == Configuration.ORIENTATION_PORTRAIT ? 0 : 90);
} else if (sensorEvent.values[1] < 0) {
// UP SIDE DOWN
configurationProvider.setSensorPosition(Configuration.SENSOR_POSITION_UP_SIDE_DOWN);
configurationProvider.setDegrees(configurationProvider.getDeviceDefaultOrientation() == Configuration.ORIENTATION_PORTRAIT ? 180 : 270);
}
} else if (sensorEvent.values[1] < 4 && sensorEvent.values[1] > -4) {
if (sensorEvent.values[0] > 0) {
// LEFT
configurationProvider.setSensorPosition(Configuration.SENSOR_POSITION_LEFT);
configurationProvider.setDegrees(configurationProvider.getDeviceDefaultOrientation() == Configuration.ORIENTATION_PORTRAIT ? 90 : 180);
} else if (sensorEvent.values[0] < 0) {
// RIGHT
configurationProvider.setSensorPosition(Configuration.SENSOR_POSITION_RIGHT);
configurationProvider.setDegrees(configurationProvider.getDeviceDefaultOrientation() == Configuration.ORIENTATION_PORTRAIT ? 270 : 0);
}
}
onScreenRotation(configurationProvider.getDegrees());
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
private CameraFragmentResultListener cameraFragmentResultListener;
protected static Fragment newInstance(Fragment fragment, Configuration configuration) {
Bundle args = new Bundle();
args.putSerializable(ARG_CONFIGURATION, configuration);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View decorView = ((Activity) container.getContext()).getWindow().getDecorView();
if (Build.VERSION.SDK_INT > MIN_VERSION_ICECREAM) {
int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
return inflater.inflate(R.layout.generic_camera_layout, container, false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle arguments = getArguments();
if (arguments != null) {
configuration = (Configuration) arguments.getSerializable(ARG_CONFIGURATION);
}
this.configurationProvider = new ConfigurationProviderImpl();
this.configurationProvider.setupWithAnnaConfiguration(configuration);
this.sensorManager = (SensorManager) getContext().getSystemService(Activity.SENSOR_SERVICE);
final CameraView cameraView = new CameraView() {
@Override
public void updateCameraPreview(Size size, View cameraPreview) {
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.unLockControls();
cameraFragmentControlsListener.allowRecord(true);
}
setCameraPreview(cameraPreview, size);
}
@Override
public void updateUiForMediaAction(@Configuration.MediaAction int mediaAction) {
}
@Override
public void updateCameraSwitcher(int numberOfCameras) {
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.allowCameraSwitching(numberOfCameras > 1);
}
}
@Override
public void onPhotoTaken(byte[] bytes, CameraFragmentResultListener callback) {
final String filePath = cameraController.getOutputFile().toString();
if (cameraFragmentResultListener != null) {
cameraFragmentResultListener.onPhotoTaken(bytes, filePath);
}
if (callback != null) {
callback.onPhotoTaken(bytes, filePath);
}
}
@Override
public void onVideoRecordStart(int width, int height) {
final File outputFile = cameraController.getOutputFile();
onStartVideoRecord(outputFile);
}
@Override
public void onVideoRecordStop(@Nullable CameraFragmentResultListener callback) {
//BaseAnncaFragment.this.onStopVideoRecord(callback);
}
@Override
public void releaseCameraPreview() {
clearCameraPreview();
}
};
if (CameraHelper.hasCamera2(getContext())) {
cameraController = new Camera2Controller(getContext(), cameraView, configurationProvider);
} else {
cameraController = new Camera1Controller(getContext(), cameraView, configurationProvider);
}
cameraController.onCreate(savedInstanceState);
//onProcessBundle
currentMediaActionState = configurationProvider.getMediaAction() == Configuration.MEDIA_ACTION_VIDEO ?
MediaAction.ACTION_VIDEO : MediaAction.ACTION_PHOTO;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
previewContainer = (AspectFrameLayout) view.findViewById(R.id.previewContainer);
final int defaultOrientation = Utils.getDeviceDefaultOrientation(getContext());
switch (defaultOrientation) {
case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
configurationProvider.setDeviceDefaultOrientation(Configuration.ORIENTATION_LANDSCAPE);
break;
default:
configurationProvider.setDeviceDefaultOrientation(Configuration.ORIENTATION_PORTRAIT);
break;
}
switch (configurationProvider.getFlashMode()) {
case Configuration.FLASH_MODE_AUTO:
setFlashMode(Flash.FLASH_AUTO);
break;
case Configuration.FLASH_MODE_ON:
setFlashMode(Flash.FLASH_ON);
break;
case Configuration.FLASH_MODE_OFF:
setFlashMode(Flash.FLASH_OFF);
break;
}
if (cameraFragmentControlsListener != null) {
setMaxVideoDuration(configurationProvider.getVideoDuration());
setMaxVideoFileSize(configurationProvider.getVideoFileSize());
}
setCameraTypeFrontBack(configurationProvider.getCameraFace());
notifyListeners();
}
public void notifyListeners() {
onFlashModeChanged();
onActionPhotoVideoChanged();
onCameraTypeFrontBackChanged();
}
@Override
public void takePhotoOrCaptureVideo(final CameraFragmentResultListener resultListener) {
takePhotoOrCaptureVideo(resultListener, null, null);
}
@Override
public void takePhotoOrCaptureVideo(final CameraFragmentResultListener resultListener, @Nullable String directoryPath, @Nullable String fileName) {
switch (currentMediaActionState) {
case MediaAction.ACTION_PHOTO:
takePhoto(resultListener, directoryPath, fileName);
break;
case MediaAction.ACTION_VIDEO:
switch (currentRecordState) {
case Record.RECORD_IN_PROGRESS_STATE:
stopRecording(resultListener);
break;
default:
startRecording(directoryPath, fileName);
break;
}
break;
}
}
@Override
public void onResume() {
super.onResume();
cameraController.onResume();
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.lockControls();
cameraFragmentControlsListener.allowRecord(false);
}
}
@Override
public void onPause() {
super.onPause();
cameraController.onPause();
sensorManager.unregisterListener(sensorEventListener);
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.lockControls();
cameraFragmentControlsListener.allowRecord(false);
}
}
@Override
public void onDestroy() {
super.onDestroy();
cameraController.onDestroy();
}
protected void setMaxVideoFileSize(long maxVideoFileSize) {
this.maxVideoFileSize = maxVideoFileSize;
}
protected void setMaxVideoDuration(int maxVideoDurationInMillis) {
if (maxVideoDurationInMillis > 0) {
this.countDownTimer = new CountdownTask(timerCallBack, maxVideoDurationInMillis);
} else {
this.countDownTimer = new TimerTask(timerCallBack);
}
}
@Override
public void openSettingDialog() {
final Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
if (currentMediaActionState == MediaAction.ACTION_VIDEO) {
builder.setSingleChoiceItems(videoQualities, getVideoOptionCheckedIndex(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int index) {
newQuality = ((VideoQualityOption) videoQualities[index]).getMediaQuality();
}
});
if (configurationProvider.getVideoFileSize() > 0)
builder.setTitle(String.format(getString(R.string.settings_video_quality_title),
"(Max " + String.valueOf(configurationProvider.getVideoFileSize() / (1024 * 1024) + " MB)")));
else
builder.setTitle(String.format(getString(R.string.settings_video_quality_title), ""));
} else {
builder.setSingleChoiceItems(photoQualities, getPhotoOptionCheckedIndex(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int index) {
newQuality = ((PhotoQualityOption) photoQualities[index]).getMediaQuality();
}
});
builder.setTitle(R.string.settings_photo_quality_title);
}
builder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (newQuality > 0 && newQuality != configurationProvider.getMediaQuality()) {
configurationProvider.setMediaQuality(newQuality);
dialogInterface.dismiss();
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.lockControls();
}
cameraController.switchQuality();
}
}
});
builder.setNegativeButton(R.string.cancel_label, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
settingsDialog = builder.create();
settingsDialog.show();
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(settingsDialog.getWindow().getAttributes());
layoutParams.width = Utils.convertDipToPixels(context, 350);
layoutParams.height = Utils.convertDipToPixels(context, 350);
settingsDialog.getWindow().setAttributes(layoutParams);
}
@Override
public void switchCameraTypeFrontBack() {
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.lockControls();
cameraFragmentControlsListener.allowRecord(false);
}
int cameraFace = Configuration.CAMERA_FACE_REAR;
switch (currentCameraType) {
case Camera.CAMERA_TYPE_FRONT:
currentCameraType = Camera.CAMERA_TYPE_REAR;
cameraFace = Configuration.CAMERA_FACE_REAR;
break;
case Camera.CAMERA_TYPE_REAR:
currentCameraType = Camera.CAMERA_TYPE_FRONT;
cameraFace = Configuration.CAMERA_FACE_FRONT;
break;
}
onCameraTypeFrontBackChanged();
this.cameraController.switchCamera(cameraFace);
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.unLockControls();
}
}
protected void setCameraTypeFrontBack(@Configuration.CameraFace int cameraFace) {
switch (cameraFace) {
case Configuration.CAMERA_FACE_FRONT:
currentCameraType = Camera.CAMERA_TYPE_FRONT;
cameraFace = Configuration.CAMERA_FACE_FRONT;
break;
case Configuration.CAMERA_FACE_REAR:
currentCameraType = Camera.CAMERA_TYPE_REAR;
cameraFace = Configuration.CAMERA_FACE_REAR;
break;
}
onCameraTypeFrontBackChanged();
this.cameraController.switchCamera(cameraFace);
}
protected void onCameraTypeFrontBackChanged() {
if (cameraFragmentStateListener != null) {
switch (currentCameraType) {
case Camera.CAMERA_TYPE_REAR:
cameraFragmentStateListener.onCurrentCameraBack();
break;
case Camera.CAMERA_TYPE_FRONT:
cameraFragmentStateListener.onCurrentCameraFront();
break;
}
}
}
@Override
public void switchActionPhotoVideo() {
switch (currentMediaActionState) {
case MediaAction.ACTION_PHOTO:
currentMediaActionState = MediaAction.ACTION_VIDEO;
break;
case MediaAction.ACTION_VIDEO:
currentMediaActionState = MediaAction.ACTION_PHOTO;
break;
}
onActionPhotoVideoChanged();
}
protected void onActionPhotoVideoChanged() {
if (cameraFragmentStateListener != null) {
switch (currentMediaActionState) {
case MediaAction.ACTION_VIDEO:
cameraFragmentStateListener.onCameraSetupForVideo();
break;
case MediaAction.ACTION_PHOTO:
cameraFragmentStateListener.onCameraSetupForPhoto();
break;
}
}
}
@Override
public void toggleFlashMode() {
switch (currentFlashMode) {
case Flash.FLASH_ON:
currentFlashMode = Flash.FLASH_OFF;
break;
case Flash.FLASH_OFF:
currentFlashMode = Flash.FLASH_ON;
break;
// case Flash.FLASH_ON:
// currentFlashMode = Flash.FLASH_AUTO;
// break;
}
onFlashModeChanged();
}
private void onFlashModeChanged() {
switch (currentFlashMode) {
// case Flash.FLASH_AUTO:
// if (cameraFragmentStateListener != null) cameraFragmentStateListener.onFlashAuto();
// configurationProvider.setFlashMode(Configuration.FLASH_MODE_AUTO);
// this.cameraController.setFlashMode(Configuration.FLASH_MODE_AUTO);
// break;
case Flash.FLASH_ON:
if (cameraFragmentStateListener != null) cameraFragmentStateListener.onFlashOn();
configurationProvider.setFlashMode(Configuration.FLASH_MODE_ON);
this.cameraController.setFlashMode(Configuration.FLASH_MODE_ON);
break;
case Flash.FLASH_OFF:
if (cameraFragmentStateListener != null) cameraFragmentStateListener.onFlashOff();
configurationProvider.setFlashMode(Configuration.FLASH_MODE_OFF);
this.cameraController.setFlashMode(Configuration.FLASH_MODE_OFF);
break;
}
}
protected void onScreenRotation(int degrees) {
if (cameraFragmentStateListener != null) {
cameraFragmentStateListener.shouldRotateControls(degrees);
}
rotateSettingsDialog(degrees);
}
protected void setRecordState(@Record.RecordState int recordState) {
this.currentRecordState = recordState;
}
//@Override
//public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if (resultCode == Activity.RESULT_OK) {
// if (requestCode == REQUEST_PREVIEW_CODE) {
// final FragmentActivity activity = getActivity();
// if (activity != null) {
// if (PreviewActivity.isResultConfirm(data)) {
// Intent resultIntent = new Intent();
// resultIntent.putExtra(Configuration.Arguments.FILE_PATH,
// PreviewActivity.getMediaFilePatch(data));
// activity.setResult(Activity.RESULT_OK, resultIntent);
// activity.finish();
// } else if (PreviewActivity.isResultCancel(data)) {
// activity.setResult(Activity.RESULT_CANCELED);
// activity.finish();
// } else if (PreviewActivity.isResultRetake(data)) {
// //ignore, just proceed the camera
// }
// }
// }
// }
//}
protected void setFlashMode(@Flash.FlashMode int mode) {
this.currentFlashMode = mode;
onFlashModeChanged();
}
protected void rotateSettingsDialog(int degrees) {
if (settingsDialog != null && settingsDialog.isShowing() && Build.VERSION.SDK_INT > 10) {
ViewGroup dialogView = (ViewGroup) settingsDialog.getWindow().getDecorView();
for (int i = 0; i < dialogView.getChildCount(); i++) {
dialogView.getChildAt(i).setRotation(degrees);
}
}
}
protected int getVideoOptionCheckedIndex() {
int checkedIndex = -1;
final int mediaQuality = configurationProvider.getMediaQuality();
final int passedMediaQuality = configurationProvider.getPassedMediaQuality();
if (mediaQuality == Configuration.MEDIA_QUALITY_AUTO) checkedIndex = 0;
else if (mediaQuality == Configuration.MEDIA_QUALITY_HIGH) checkedIndex = 1;
else if (mediaQuality == Configuration.MEDIA_QUALITY_MEDIUM) checkedIndex = 2;
else if (mediaQuality == Configuration.MEDIA_QUALITY_LOW) checkedIndex = 3;
if (passedMediaQuality != Configuration.MEDIA_QUALITY_AUTO) checkedIndex--;
return checkedIndex;
}
protected int getPhotoOptionCheckedIndex() {
int checkedIndex = -1;
final int mediaQuality = configurationProvider.getMediaQuality();
if (mediaQuality == Configuration.MEDIA_QUALITY_HIGHEST) checkedIndex = 0;
else if (mediaQuality == Configuration.MEDIA_QUALITY_HIGH) checkedIndex = 1;
else if (mediaQuality == Configuration.MEDIA_QUALITY_MEDIUM) checkedIndex = 2;
else if (mediaQuality == Configuration.MEDIA_QUALITY_LOWEST) checkedIndex = 3;
return checkedIndex;
}
protected void takePhoto(CameraFragmentResultListener callback, @Nullable String directoryPath, @Nullable String fileName) {
if (Build.VERSION.SDK_INT > MIN_VERSION_ICECREAM) {
new MediaActionSound().play(MediaActionSound.SHUTTER_CLICK);
}
setRecordState(Record.TAKE_PHOTO_STATE);
this.cameraController.takePhoto(callback, directoryPath, fileName);
if (cameraFragmentStateListener != null) {
cameraFragmentStateListener.onRecordStatePhoto();
}
}
protected void startRecording(@Nullable String directoryPath, @Nullable String fileName) {
if (Build.VERSION.SDK_INT > MIN_VERSION_ICECREAM) {
new MediaActionSound().play(MediaActionSound.START_VIDEO_RECORDING);
}
setRecordState(Record.RECORD_IN_PROGRESS_STATE);
this.cameraController.startVideoRecord(directoryPath, fileName);
if (cameraFragmentStateListener != null) {
cameraFragmentStateListener.onRecordStateVideoInProgress();
}
}
protected void stopRecording(CameraFragmentResultListener callback) {
if (Build.VERSION.SDK_INT > MIN_VERSION_ICECREAM) {
new MediaActionSound().play(MediaActionSound.STOP_VIDEO_RECORDING);
}
setRecordState(Record.READY_FOR_RECORD_STATE);
this.cameraController.stopVideoRecord(callback);
this.onStopVideoRecord(callback);
if (cameraFragmentStateListener != null) {
cameraFragmentStateListener.onRecordStateVideoReadyForRecord();
}
}
protected void clearCameraPreview() {
if (previewContainer != null)
previewContainer.removeAllViews();
}
protected void setCameraPreview(View preview, Size previewSize) {
//onCameraControllerReady()
videoQualities = cameraController.getVideoQualityOptions();
photoQualities = cameraController.getPhotoQualityOptions();
if (previewContainer == null || preview == null) return;
previewContainer.removeAllViews();
previewContainer.addView(preview);
previewContainer.setAspectRatio(previewSize.getHeight() / (double) previewSize.getWidth());
}
protected void setMediaFilePath(final File mediaFile) {
this.mediaFilePath = mediaFile.toString();
}
protected void onStartVideoRecord(final File mediaFile) {
setMediaFilePath(mediaFile);
if (maxVideoFileSize > 0) {
if (cameraFragmentVideoRecordTextListener != null) {
cameraFragmentVideoRecordTextListener.setRecordSizeText(maxVideoFileSize, "1Mb" + " / " + maxVideoFileSize / (1024 * 1024) + "Mb");
cameraFragmentVideoRecordTextListener.setRecordSizeTextVisible(true);
}
try {
fileObserver = new FileObserver(this.mediaFilePath) {
private long lastUpdateSize = 0;
@Override
public void onEvent(int event, String path) {
final long fileSize = mediaFile.length() / (1024 * 1024);
if ((fileSize - lastUpdateSize) >= 1) {
lastUpdateSize = fileSize;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (cameraFragmentVideoRecordTextListener != null) {
cameraFragmentVideoRecordTextListener.setRecordSizeText(maxVideoFileSize, fileSize + "Mb" + " / " + maxVideoFileSize / (1024 * 1024) + "Mb");
}
}
});
}
}
};
fileObserver.startWatching();
} catch (Exception e) {
Log.e("FileObserver", "setMediaFilePath: ", e);
}
}
if (countDownTimer == null) {
this.countDownTimer = new TimerTask(timerCallBack);
}
countDownTimer.start();
if (cameraFragmentStateListener != null) {
cameraFragmentStateListener.onStartVideoRecord(mediaFile);
}
}
protected void onStopVideoRecord(@Nullable CameraFragmentResultListener callback) {
if (cameraFragmentControlsListener != null) {
cameraFragmentControlsListener.allowRecord(false);
}
if (cameraFragmentStateListener != null) {
cameraFragmentStateListener.onStopVideoRecord();
}
setRecordState(Record.READY_FOR_RECORD_STATE);
if (fileObserver != null)
fileObserver.stopWatching();
if (countDownTimer != null) {
countDownTimer.stop();
}
final int mediaAction = configurationProvider.getMediaAction();
if (cameraFragmentControlsListener != null) {
if (mediaAction != Configuration.MEDIA_ACTION_UNSPECIFIED) {
cameraFragmentControlsListener.setMediaActionSwitchVisible(false);
} else {
cameraFragmentControlsListener.setMediaActionSwitchVisible(true);
}
}
final String filePath = this.cameraController.getOutputFile().toString();
if (cameraFragmentResultListener != null) {
cameraFragmentResultListener.onVideoRecorded(filePath);
}
if (callback != null) {
callback.onVideoRecorded(filePath);
}
}
@Override
public void setStateListener(CameraFragmentStateListener cameraFragmentStateListener) {
this.cameraFragmentStateListener = cameraFragmentStateListener;
}
@Override
public void setTextListener(CameraFragmentVideoRecordTextListener cameraFragmentVideoRecordTextListener) {
this.cameraFragmentVideoRecordTextListener = cameraFragmentVideoRecordTextListener;
}
@Override
public void setControlsListener(CameraFragmentControlsListener cameraFragmentControlsListener) {
this.cameraFragmentControlsListener = cameraFragmentControlsListener;
}
@Override
public void setResultListener(CameraFragmentResultListener cameraFragmentResultListener) {
this.cameraFragmentResultListener = cameraFragmentResultListener;
}
}
| mkrtchyanmnatsakan/DemoAppHelloWord | camerafragment/src/main/java/com/github/florent37/camerafragment/internal/ui/BaseAnncaFragment.java | Java | apache-2.0 | 31,725 |
---
author: admin
comments: true
date: 2012-11-09 09:56:00+00:00
layout: post
slug: '%e3%80%90html%e3%80%91%e5%89%8d%e5%8f%b0%e9%a1%b5%e9%9d%a2%e8%b0%83%e5%87%ba%e6%96%87%e4%bb%b6%e5%8f%a6%e5%ad%98%e4%b8%ba%e5%af%b9%e8%af%9d%e6%a1%86%e5%87%a0%e7%a7%8d%e6%96%b9%e6%b3%95'
title: 【HTML】前台页面调出文件另存为对话框几种方法
permalink: /2012/11/09/124.html
wordpress_id: 124
categories:
- JS
- 前端美工设计
tags:
- JS
- 前端美工设计
---
大家都知道,网页上传本地文件可以用<input type="file" value=""/>来实现,在前台页面调出另存为对话框、将服务器上存放的文件保存到本地那要怎么实现呢?以下便介绍几种实现的思路和方法。
1.调用document.execCommand方法
调用JS方法document.execCommand即可在前台页面调出另存为对话框,并将将服务器上存放的文件保存到本地。
这里有个很好的例子:
[HTML页面另存为对话框DEMO.rar](http://files.cnblogs.com/youuuu/code/HTML%E9%A1%B5%E9%9D%A2%E5%8F%A6%E5%AD%98%E4%B8%BA%E5%AF%B9%E8%AF%9D%E6%A1%86DEMO.rar)
代码:
[](http://www.cnblogs.com/youuuu/archive/2012/11/02/2750914.html)
<script
language='javascript'
type='text/javascript'>
function getimg()
//另存为存放在服务器上图片到本地的方法
{
event.returnValue=false;
show.window.location.href=imgSrc.src;
timer=setInterval(checkload,100)
}
function checkload()
{
if(show.readyState!="complete")
{
//调用document.execCommand方法,'Saveas'表示打开文件另存为对话框命令
show.document.execCommand('SaveAs');
clearInterval(timer)
}
}
</script>
<img
id="imgSrc" width="320px" height="200px"
src="test.bmp" alt=""/></br>
<input
id="btnSaveAs" type="button" value="另存为上图"
onclick="getimg()"/>
<iframe
src="" name="show" style="width:0;height:0"></iframe>
[](http://www.cnblogs.com/youuuu/archive/2012/11/02/2750914.html)
实现效果:

另外部分ie浏览器中,可能会阻止显示内容,点击上方"允许阻止的内容“即可正常运行
2. 调用ActiveX控件
实例化一个“MSComDlg.CommonDialog”对象,即可在前台页面调出另存为对话框,与先前Js方法不同,该ActiveX控件还能获取到你选择的本地保存路径。但缺点是客户端需要已经注册“COMDLG32.OCX”,且客户端浏览器对ActiveX安全级别要求不是很高,否则就无法调出另存为对话框。
实例代码:
[](http://www.cnblogs.com/youuuu/archive/2012/11/02/2750914.html)
try
{
OCXResult.Result.value = "";
//实例化一个ActiveX对象
var fd = new ActiveXObject("MSComDlg.CommonDialog");
//设置保存文件类型选项
fd.Filter = "BMP图片|*.bmp";
fd.FilterIndex = 2;
fd.fileName="你要保存的默认文件名";
// must setting
fd.MaxFileSize = 128;
//打开另存为文件对话框
fd.ShowSave();
}
catch(e)
{
confirm("当前您的系统尚未注册COMDLG32.OCXn请先下载注册此控件后);
}
[](http://www.cnblogs.com/youuuu/archive/2012/11/02/2750914.html)
附自动向客户端本地系统注册"COMDLG32.OCX"程序
[网页文件另存为对话框控件.rar](http://files.cnblogs.com/youuuu/dll/%E7%BD%91%E9%A1%B5%E6%96%87%E4%BB%B6%E5%8F%A6%E5%AD%98%E4%B8%BA%E5%AF%B9%E8%AF%9D%E6%A1%86%E6%8E%A7%E4%BB%B6.rar)
3.使用像第三方控件厂商提供的web控件(如硕正控件等)
以上就是本人目前所知的前台页面调出另存为对话框的三种方式,如有其它还望大家补充。。。
| akmumu/akmumu.github.io | _posts/2012-11-09-124.markdown | Markdown | apache-2.0 | 4,120 |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.devtools.v89;
import org.openqa.selenium.devtools.Command;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.Event;
import org.openqa.selenium.devtools.idealized.Javascript;
import org.openqa.selenium.devtools.v89.page.Page;
import org.openqa.selenium.devtools.v89.page.model.ScriptIdentifier;
import org.openqa.selenium.devtools.v89.runtime.Runtime;
import org.openqa.selenium.devtools.v89.runtime.model.BindingCalled;
import java.util.Optional;
public class V89Javascript extends Javascript<ScriptIdentifier, BindingCalled> {
public V89Javascript(DevTools devtools) {
super(devtools);
}
@Override
protected Command<Void> enableRuntime() {
return Runtime.enable();
}
@Override
protected Command<Void> disableRuntime() {
return Runtime.disable();
}
@Override
protected Command<Void> doAddJsBinding(String scriptName) {
return Runtime.addBinding(scriptName, Optional.empty(), Optional.empty());
}
@Override
protected Command<Void> doRemoveJsBinding(String scriptName) {
return Runtime.removeBinding(scriptName);
}
@Override
protected Command<Void> enablePage() {
return Page.enable();
}
@Override
protected Command<Void> disablePage() {
return Page.disable();
}
@Override
protected Command<ScriptIdentifier> addScriptToEvaluateOnNewDocument(String script) {
return Page.addScriptToEvaluateOnNewDocument(script, Optional.empty());
}
@Override
protected Command<Void> removeScriptToEvaluateOnNewDocument(ScriptIdentifier id) {
return Page.removeScriptToEvaluateOnNewDocument(id);
}
@Override
protected Event<BindingCalled> bindingCalledEvent() {
return Runtime.bindingCalled();
}
@Override
protected String extractPayload(BindingCalled event) {
return event.getPayload();
}
}
| Ardesco/selenium | java/client/src/org/openqa/selenium/devtools/v89/V89Javascript.java | Java | apache-2.0 | 2,659 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "database/src/desktop/persistence/prune_forest.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace firebase {
namespace database {
namespace internal {
namespace {
TEST(PruneForestTest, Equality) {
PruneForest forest;
forest.SetValueAt(Path("true"), true);
forest.SetValueAt(Path("false"), false);
PruneForest identical_forest;
identical_forest.SetValueAt(Path("true"), true);
identical_forest.SetValueAt(Path("false"), false);
PruneForest different_forest;
different_forest.SetValueAt(Path("true"), false);
different_forest.SetValueAt(Path("false"), true);
PruneForestRef ref(&forest);
PruneForestRef same_ref(&forest);
PruneForestRef identical_ref(&identical_forest);
PruneForestRef different_ref(&different_forest);
PruneForestRef null_ref(nullptr);
PruneForestRef another_null_ref(nullptr);
EXPECT_EQ(ref, ref);
EXPECT_EQ(ref, same_ref);
EXPECT_EQ(ref, identical_ref);
EXPECT_NE(ref, different_ref);
EXPECT_NE(ref, null_ref);
EXPECT_EQ(null_ref, null_ref);
EXPECT_EQ(null_ref, another_null_ref);
EXPECT_EQ(another_null_ref, null_ref);
}
TEST(PruneForestTest, PrunesAnything) {
{
PruneForest forest;
PruneForestRef ref(&forest);
EXPECT_FALSE(ref.PrunesAnything());
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Prune(Path("foo"));
EXPECT_TRUE(ref.PrunesAnything());
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Prune(Path("foo/bar/baz"));
EXPECT_TRUE(ref.PrunesAnything());
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Keep(Path("foo"));
EXPECT_FALSE(ref.PrunesAnything());
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Keep(Path("foo/bar/baz"));
EXPECT_FALSE(ref.PrunesAnything());
}
}
TEST(PruneForestTest, ShouldPruneUnkeptDescendants) {
{
PruneForest forest;
PruneForestRef ref(&forest);
EXPECT_FALSE(ref.ShouldPruneUnkeptDescendants(Path()));
EXPECT_FALSE(ref.ShouldPruneUnkeptDescendants(Path("aaa")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
forest.SetValueAt(Path("aaa"), true);
forest.SetValueAt(Path("bbb"), false);
EXPECT_FALSE(ref.ShouldPruneUnkeptDescendants(Path()));
EXPECT_TRUE(ref.ShouldPruneUnkeptDescendants(Path("aaa")));
EXPECT_FALSE(ref.ShouldPruneUnkeptDescendants(Path("bbb")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
forest.SetValueAt(Path("aaa"), false);
forest.SetValueAt(Path("aaa/bbb"), true);
forest.SetValueAt(Path("aaa/bbb/ccc"), false);
EXPECT_FALSE(ref.ShouldPruneUnkeptDescendants(Path("aaa")));
EXPECT_TRUE(ref.ShouldPruneUnkeptDescendants(Path("aaa/bbb")));
EXPECT_FALSE(ref.ShouldPruneUnkeptDescendants(Path("aaa/bbb/ccc")));
}
}
TEST(PruneForestTest, ShouldKeep) {
{
PruneForest forest;
PruneForestRef ref(&forest);
EXPECT_FALSE(ref.ShouldKeep(Path()));
EXPECT_FALSE(ref.ShouldKeep(Path("aaa")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
forest.SetValueAt(Path("aaa"), true);
forest.SetValueAt(Path("bbb"), false);
EXPECT_FALSE(ref.ShouldKeep(Path()));
EXPECT_FALSE(ref.ShouldKeep(Path("aaa")));
EXPECT_TRUE(ref.ShouldKeep(Path("bbb")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
forest.SetValueAt(Path("aaa"), true);
forest.SetValueAt(Path("aaa/bbb"), false);
EXPECT_FALSE(ref.ShouldKeep(Path("aaa")));
EXPECT_TRUE(ref.ShouldKeep(Path("aaa/bbb")));
}
}
TEST(PruneForestTest, AffectsPath) {
{
PruneForest forest;
PruneForestRef ref(&forest);
EXPECT_FALSE(ref.AffectsPath(Path()));
EXPECT_FALSE(ref.AffectsPath(Path("foo")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/baz")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/baz/quux")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/buzz")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/buzz/quuz")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Prune(Path("foo"));
EXPECT_TRUE(ref.AffectsPath(Path()));
EXPECT_TRUE(ref.AffectsPath(Path("foo")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz/quux")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/buzz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/buzz/quuz")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Prune(Path("foo/bar/baz"));
EXPECT_TRUE(ref.AffectsPath(Path()));
EXPECT_TRUE(ref.AffectsPath(Path("foo")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz/quux")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/buzz")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/buzz/quuz")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Keep(Path("foo"));
EXPECT_TRUE(ref.AffectsPath(Path()));
EXPECT_TRUE(ref.AffectsPath(Path("foo")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz/quux")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/buzz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/buzz/quuz")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Keep(Path("foo/bar/baz"));
EXPECT_TRUE(ref.AffectsPath(Path()));
EXPECT_TRUE(ref.AffectsPath(Path("foo")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz/quux")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/buzz")));
EXPECT_FALSE(ref.AffectsPath(Path("foo/bar/buzz/quuz")));
}
{
PruneForest forest;
PruneForestRef ref(&forest);
ref.Prune(Path("foo"));
ref.Keep(Path("foo/bar/baz"));
EXPECT_TRUE(ref.AffectsPath(Path()));
EXPECT_TRUE(ref.AffectsPath(Path("foo")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/baz/quux")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/buzz")));
EXPECT_TRUE(ref.AffectsPath(Path("foo/bar/buzz/quuz")));
}
}
TEST(PruneForestTest, GetChild) {
PruneForest forest;
PruneForestRef ref(&forest);
forest.SetValueAt(Path("aaa"), true);
forest.SetValueAt(Path("aaa/bbb"), true);
forest.SetValueAt(Path("aaa/bbb/ccc"), true);
forest.SetValueAt(Path("zzz"), false);
forest.SetValueAt(Path("zzz/yyy"), false);
forest.SetValueAt(Path("zzz/yyy/xxx"), false);
PruneForest* child_aaa = forest.GetChild(Path("aaa"));
PruneForest* child_aaa_bbb = forest.GetChild(Path("aaa/bbb"));
PruneForest* child_aaa_bbb_ccc = forest.GetChild(Path("aaa/bbb/ccc"));
PruneForest* child_zzz = forest.GetChild(Path("zzz"));
PruneForest* child_zzz_yyy = forest.GetChild(Path("zzz/yyy"));
PruneForest* child_zzz_yyy_xxx = forest.GetChild(Path("zzz/yyy/xxx"));
EXPECT_EQ(ref.GetChild(Path("aaa")), PruneForestRef(child_aaa));
EXPECT_EQ(ref.GetChild(Path("aaa/bbb")), PruneForestRef(child_aaa_bbb));
EXPECT_EQ(ref.GetChild(Path("aaa/bbb/ccc")),
PruneForestRef(child_aaa_bbb_ccc));
EXPECT_EQ(ref.GetChild(Path("zzz")), PruneForestRef(child_zzz));
EXPECT_EQ(ref.GetChild(Path("zzz/yyy")), PruneForestRef(child_zzz_yyy));
EXPECT_EQ(ref.GetChild(Path("zzz/yyy/xxx")),
PruneForestRef(child_zzz_yyy_xxx));
}
TEST(PruneForestTest, Prune) {
PruneForest forest;
PruneForestRef ref(&forest);
ref.Prune(Path("aaa/bbb/ccc"));
EXPECT_EQ(forest.GetValueAt(Path()), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb")), nullptr);
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/bbb/ccc")));
ref.Prune(Path("aaa/bbb"));
EXPECT_EQ(forest.GetValueAt(Path()), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa")), nullptr);
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/bbb")));
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb/ccc")), nullptr);
ref.Prune(Path("aaa"));
EXPECT_EQ(forest.GetValueAt(Path()), nullptr);
EXPECT_TRUE(*forest.GetValueAt(Path("aaa")));
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb/ccc")), nullptr);
ref.Prune(Path());
EXPECT_TRUE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("aaa")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb/ccc")), nullptr);
ref.Prune(Path("zzz"));
EXPECT_TRUE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("zzz")), nullptr);
ref.Prune(Path("zzz/yyy"));
EXPECT_TRUE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("zzz")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("zzz/yyy")), nullptr);
ref.Prune(Path("zzz/yyy/xxx"));
EXPECT_TRUE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("zzz")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("zzz/yyy")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("zzz/yyy/xxx")), nullptr);
}
TEST(PruneForestTest, Keep) {
PruneForest forest;
PruneForestRef ref(&forest);
ref.Keep(Path("aaa/bbb/ccc"));
EXPECT_EQ(forest.GetValueAt(Path()), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb")), nullptr);
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/bbb/ccc")));
ref.Keep(Path("aaa/bbb"));
EXPECT_EQ(forest.GetValueAt(Path()), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa")), nullptr);
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/bbb")));
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb/ccc")), nullptr);
ref.Keep(Path("aaa"));
EXPECT_EQ(forest.GetValueAt(Path()), nullptr);
EXPECT_FALSE(*forest.GetValueAt(Path("aaa")));
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb/ccc")), nullptr);
ref.Keep(Path());
EXPECT_FALSE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("aaa")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/bbb/ccc")), nullptr);
ref.Keep(Path("zzz"));
EXPECT_FALSE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("zzz")), nullptr);
ref.Keep(Path("zzz/yyy"));
EXPECT_FALSE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("zzz")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("zzz/yyy")), nullptr);
ref.Keep(Path("zzz/yyy/xxx"));
EXPECT_FALSE(*forest.GetValueAt(Path()));
EXPECT_EQ(forest.GetValueAt(Path("zzz")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("zzz/yyy")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("zzz/yyy/xxx")), nullptr);
}
TEST(PruneForestTest, KeepAll) {
// Set up a test case.
PruneForest default_forest;
default_forest.SetValueAt(Path("aaa/111"), true);
default_forest.SetValueAt(Path("aaa/222"), false);
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.KeepAll(Path("aaa"), std::set<std::string>({std::string("111")}));
// Only 111 should be affected, and it should now be false.
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/222")));
}
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.KeepAll(Path("aaa"), std::set<std::string>({std::string("222")}));
// Only 222 should be affected, but it was already false so it should not
// change.
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/222")));
}
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.KeepAll(Path("aaa"), std::set<std::string>(
{std::string("111"), std::string("222")}));
// Both children should now be false.
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/222")));
}
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.KeepAll(Path(), std::set<std::string>({std::string("aaa")}));
// aaa should now be false, and all children of it should be eliminated.
EXPECT_FALSE(*forest.GetValueAt(Path("aaa")));
// Children are now eliminated.
EXPECT_EQ(forest.GetValueAt(Path("aaa/111")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/222")), nullptr);
}
}
TEST(PruneForestTest, PruneAll) {
// Set up a test case.
PruneForest default_forest;
default_forest.SetValueAt(Path("aaa/111"), true);
default_forest.SetValueAt(Path("aaa/222"), false);
default_forest.SetValueAt(Path("bbb/111"), true);
default_forest.SetValueAt(Path("bbb/222"), false);
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.PruneAll(Path("aaa"), std::set<std::string>({std::string("111")}));
// Only 111 should be affected, but it was already true so it should not
// change.
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("aaa/222")));
// Should remain untouched.
EXPECT_TRUE(*forest.GetValueAt(Path("bbb/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("bbb/222")));
}
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.PruneAll(Path("aaa"), std::set<std::string>({std::string("222")}));
// Only 222 should be affected, and it should now be true
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/111")));
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/222")));
// Should remain untouched.
EXPECT_TRUE(*forest.GetValueAt(Path("bbb/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("bbb/222")));
}
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.PruneAll(Path("aaa"), std::set<std::string>(
{std::string("111"), std::string("222")}));
// Both children should now be true.
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/111")));
EXPECT_TRUE(*forest.GetValueAt(Path("aaa/222")));
// Should remain untouched.
EXPECT_TRUE(*forest.GetValueAt(Path("bbb/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("bbb/222")));
}
{
PruneForest forest = default_forest;
PruneForestRef ref(&forest);
ref.PruneAll(Path(), std::set<std::string>({std::string("aaa")}));
// aaa should now be true, and all children of it should be eliminated.
EXPECT_TRUE(*forest.GetValueAt(Path("aaa")));
// Children are now eliminated.
EXPECT_EQ(forest.GetValueAt(Path("aaa/111")), nullptr);
EXPECT_EQ(forest.GetValueAt(Path("aaa/222")), nullptr);
// Should remain untouched.
EXPECT_TRUE(*forest.GetValueAt(Path("bbb/111")));
EXPECT_FALSE(*forest.GetValueAt(Path("bbb/222")));
}
}
} // namespace
} // namespace internal
} // namespace database
} // namespace firebase
| firebase/firebase-cpp-sdk | database/tests/desktop/persistence/prune_forest_test.cc | C++ | apache-2.0 | 15,647 |
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802
// Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2015.12.01 alle 07:40:41 AM CET
//
package it.cnr.icar.biograph.models.uniprot;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Describes the subcellular location and optionally the topology and orientation of a molecule.
*
* <p>Classe Java per subcellularLocationType complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="subcellularLocationType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="location" type="{http://uniprot.org/uniprot}evidencedStringType" maxOccurs="unbounded"/>
* <element name="topology" type="{http://uniprot.org/uniprot}evidencedStringType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="orientation" type="{http://uniprot.org/uniprot}evidencedStringType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "subcellularLocationType", propOrder = {
"location",
"topology",
"orientation"
})
public class SubcellularLocationType {
@XmlElement(required = true)
protected List<EvidencedStringType> location;
protected List<EvidencedStringType> topology;
protected List<EvidencedStringType> orientation;
/**
* Gets the value of the location property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the location property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLocation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EvidencedStringType }
*
*
*/
public List<EvidencedStringType> getLocation() {
if (location == null) {
location = new ArrayList<EvidencedStringType>();
}
return this.location;
}
/**
* Gets the value of the topology property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the topology property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTopology().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EvidencedStringType }
*
*
*/
public List<EvidencedStringType> getTopology() {
if (topology == null) {
topology = new ArrayList<EvidencedStringType>();
}
return this.topology;
}
/**
* Gets the value of the orientation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the orientation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOrientation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EvidencedStringType }
*
*
*/
public List<EvidencedStringType> getOrientation() {
if (orientation == null) {
orientation = new ArrayList<EvidencedStringType>();
}
return this.orientation;
}
}
| IcarPA-TBlab/BioGraph | biograph-etl/src/main/java/it/cnr/icar/biograph/models/uniprot/SubcellularLocationType.java | Java | apache-2.0 | 4,510 |
using System.Threading;
namespace MediatR.Tests.Pipeline;
using System.Threading.Tasks;
using MediatR.Pipeline;
using Shouldly;
using StructureMap;
using Xunit;
public class RequestPreProcessorTests
{
public class Ping : IRequest<Pong>
{
public string Message { get; set; }
}
public class Pong
{
public string Message { get; set; }
}
public class PingHandler : IRequestHandler<Ping, Pong>
{
public Task<Pong> Handle(Ping request, CancellationToken cancellationToken)
{
return Task.FromResult(new Pong { Message = request.Message + " Pong" });
}
}
public class PingPreProcessor : IRequestPreProcessor<Ping>
{
public Task Process(Ping request, CancellationToken cancellationToken)
{
request.Message = request.Message + " Ping";
return Task.FromResult(0);
}
}
[Fact]
public async Task Should_run_preprocessors()
{
var container = new Container(cfg =>
{
cfg.Scan(scanner =>
{
scanner.AssemblyContainingType(typeof(PublishTests));
scanner.IncludeNamespaceContainingType<Ping>();
scanner.WithDefaultConventions();
scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
scanner.AddAllTypesOf(typeof(IRequestPreProcessor<>));
});
cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(RequestPreProcessorBehavior<,>));
cfg.For<ServiceFactory>().Use<ServiceFactory>(ctx => ctx.GetInstance);
cfg.For<IMediator>().Use<Mediator>();
});
var mediator = container.GetInstance<IMediator>();
var response = await mediator.Send(new Ping { Message = "Ping" });
response.Message.ShouldBe("Ping Ping Pong");
}
} | jbogard/MediatR | test/MediatR.Tests/Pipeline/RequestPreProcessorTests.cs | C# | apache-2.0 | 1,856 |
/**
* Copyright (c) 2013-2019 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.format.sentinel2;
import org.apache.commons.lang.ArrayUtils;
import org.geotools.data.DataUtilities;
import org.geotools.filter.visitor.DuplicatingFilterVisitor;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.PropertyIsBetween;
import org.opengis.filter.PropertyIsEqualTo;
import org.opengis.filter.PropertyIsGreaterThan;
import org.opengis.filter.PropertyIsGreaterThanOrEqualTo;
import org.opengis.filter.PropertyIsLessThan;
import org.opengis.filter.PropertyIsLessThanOrEqualTo;
import org.opengis.filter.PropertyIsLike;
import org.opengis.filter.PropertyIsNil;
import org.opengis.filter.PropertyIsNotEqualTo;
import org.opengis.filter.PropertyIsNull;
import org.opengis.filter.spatial.BBOX;
import org.opengis.filter.spatial.Beyond;
import org.opengis.filter.spatial.Contains;
import org.opengis.filter.spatial.Crosses;
import org.opengis.filter.spatial.DWithin;
import org.opengis.filter.spatial.Disjoint;
import org.opengis.filter.spatial.Equals;
import org.opengis.filter.spatial.Intersects;
import org.opengis.filter.spatial.Overlaps;
import org.opengis.filter.spatial.Touches;
import org.opengis.filter.spatial.Within;
import org.opengis.filter.temporal.After;
import org.opengis.filter.temporal.AnyInteracts;
import org.opengis.filter.temporal.Before;
import org.opengis.filter.temporal.Begins;
import org.opengis.filter.temporal.BegunBy;
import org.opengis.filter.temporal.During;
import org.opengis.filter.temporal.EndedBy;
import org.opengis.filter.temporal.Ends;
import org.opengis.filter.temporal.Meets;
import org.opengis.filter.temporal.MetBy;
import org.opengis.filter.temporal.OverlappedBy;
import org.opengis.filter.temporal.TContains;
import org.opengis.filter.temporal.TEquals;
import org.opengis.filter.temporal.TOverlaps;
public class PropertyIgnoringFilterVisitor extends DuplicatingFilterVisitor {
private final String[] validPropertyNames;
private final SimpleFeatureType type;
public PropertyIgnoringFilterVisitor(
final String[] validPropertyNames,
final SimpleFeatureType type) {
this.validPropertyNames = validPropertyNames;
this.type = type;
}
@Override
public Object visit(final PropertyIsBetween filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsEqualTo filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsNotEqualTo filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsGreaterThan filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsGreaterThanOrEqualTo filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsLessThan filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsLessThanOrEqualTo filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsLike filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsNull filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final PropertyIsNil filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final BBOX filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Beyond filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Contains filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Crosses filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Disjoint filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final DWithin filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Equals filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Intersects filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Overlaps filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Touches filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final Within filter, final Object extraData) {
if (!usesProperty(filter)) {
return Filter.INCLUDE;
}
return super.visit(filter, extraData);
}
@Override
public Object visit(final After after, final Object extraData) {
if (!usesProperty(after)) {
return Filter.INCLUDE;
}
return super.visit(after, extraData);
}
@Override
public Object visit(final AnyInteracts anyInteracts, final Object extraData) {
if (!usesProperty(anyInteracts)) {
return Filter.INCLUDE;
}
return super.visit(anyInteracts, extraData);
}
@Override
public Object visit(final Before before, final Object extraData) {
if (!usesProperty(before)) {
return Filter.INCLUDE;
}
return super.visit(before, extraData);
}
@Override
public Object visit(final Begins begins, final Object extraData) {
if (!usesProperty(begins)) {
return Filter.INCLUDE;
}
return super.visit(begins, extraData);
}
@Override
public Object visit(final BegunBy begunBy, final Object extraData) {
if (!usesProperty(begunBy)) {
return Filter.INCLUDE;
}
return super.visit(begunBy, extraData);
}
@Override
public Object visit(final During during, final Object extraData) {
if (!usesProperty(during)) {
return Filter.INCLUDE;
}
return super.visit(during, extraData);
}
@Override
public Object visit(final EndedBy endedBy, final Object extraData) {
if (!usesProperty(endedBy)) {
return Filter.INCLUDE;
}
return super.visit(endedBy, extraData);
}
@Override
public Object visit(final Ends ends, final Object extraData) {
if (!usesProperty(ends)) {
return Filter.INCLUDE;
}
return super.visit(ends, extraData);
}
@Override
public Object visit(final Meets meets, final Object extraData) {
if (!usesProperty(meets)) {
return Filter.INCLUDE;
}
return super.visit(meets, extraData);
}
@Override
public Object visit(final MetBy metBy, final Object extraData) {
if (!usesProperty(metBy)) {
return Filter.INCLUDE;
}
return super.visit(metBy, extraData);
}
@Override
public Object visit(final OverlappedBy overlappedBy, final Object extraData) {
if (!usesProperty(overlappedBy)) {
return Filter.INCLUDE;
}
return super.visit(overlappedBy, extraData);
}
@Override
public Object visit(final TContains contains, final Object extraData) {
if (!usesProperty(contains)) {
return Filter.INCLUDE;
}
return super.visit(contains, extraData);
}
@Override
public Object visit(final TEquals equals, final Object extraData) {
if (!usesProperty(equals)) {
return Filter.INCLUDE;
}
return super.visit(equals, extraData);
}
@Override
public Object visit(final TOverlaps contains, final Object extraData) {
if (!usesProperty(contains)) {
return Filter.INCLUDE;
}
return super.visit(contains, extraData);
}
private boolean usesProperty(final Filter filter) {
final String[] attributes = DataUtilities.attributeNames(filter, type);
// rely on best scene aggregation at a higher level if the filter is
// using attributes not contained in the scene
for (final String attribute : attributes) {
if (!ArrayUtils.contains(validPropertyNames, attribute)) {
return false;
}
}
return true;
}
}
| spohnan/geowave | extensions/cli/sentinel2/src/main/java/org/locationtech/geowave/format/sentinel2/PropertyIgnoringFilterVisitor.java | Java | apache-2.0 | 10,162 |
/**
* Copyright (c) 2008-2010 Andrey Somov
*
* 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 org.yaml.snakeyaml.error;
import org.yaml.snakeyaml.scanner.Constant;
/**
* It's just a record and its only use is producing nice error messages. Parser
* does not use it for any other purposes.
*
* @see <a href="http://pyyaml.org/wiki/PyYAML">PyYAML</a> for more information
*/
public final class Mark {
private String name;
private int line;
private int column;
private String buffer;
private int pointer;
public Mark(String name, int index, int line, int column, String buffer, int pointer) {
super();
this.name = name;
this.line = line;
this.column = column;
this.buffer = buffer;
this.pointer = pointer;
}
private boolean isLineBreak(char ch) {
return Constant.NULL_OR_LINEBR.has(ch);
}
public String get_snippet(int indent, int max_length) {
if (buffer == null) {
return null;
}
float half = max_length / 2 - 1;
int start = pointer;
String head = "";
while ((start > 0) && (!isLineBreak(buffer.charAt(start - 1)))) {
start -= 1;
if (pointer - start > half) {
head = " ... ";
start += 5;
break;
}
}
String tail = "";
int end = pointer;
while ((end < buffer.length()) && (!isLineBreak(buffer.charAt(end)))) {
end += 1;
if (end - pointer > half) {
tail = " ... ";
end -= 5;
break;
}
}
String snippet = buffer.substring(start, end);
StringBuilder result = new StringBuilder();
for (int i = 0; i < indent; i++) {
result.append(" ");
}
result.append(head);
result.append(snippet);
result.append(tail);
result.append("\n");
for (int i = 0; i < indent + pointer - start + head.length(); i++) {
result.append(" ");
}
result.append("^");
return result.toString();
}
public String get_snippet() {
return get_snippet(4, 75);
}
@Override
public String toString() {
String snippet = get_snippet();
StringBuilder where = new StringBuilder(" in \"");
where.append(name);
where.append("\", line ");
where.append(line + 1);
where.append(", column ");
where.append(column + 1);
if (snippet != null) {
where.append(":\n");
where.append(snippet);
}
return where.toString();
}
public String getName() {
return name;
}
/**
* starts with 0
*/
public int getLine() {
return line;
}
/**
* starts with 0
*/
public int getColumn() {
return column;
}
}
| spariev/snakeyaml | src/main/java/org/yaml/snakeyaml/error/Mark.java | Java | apache-2.0 | 3,582 |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>org.scalatest.matchers.HavePropertyMatcher</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link type="text/css" media="screen" rel="stylesheet" href="../../../lib/template.css" />
<script type="text/javascript" src="../../../lib/jquery.js"></script>
<script type="text/javascript" src="../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
</head>
<body class="value">
<div id="definition">
<a title="Go to companion" href="HavePropertyMatcher.html"><img src="../../../lib/object_to_trait_big.png" /></a>
<p id="owner"><a name="org" class="extype" href="../../package.html">org</a>.<a name="org.scalatest" class="extype" href="../package.html">scalatest</a>.<a name="org.scalatest.matchers" class="extype" href="package.html">matchers</a></p>
<h1><a title="Go to companion" href="HavePropertyMatcher.html">HavePropertyMatcher</a></h1>
</div>
<h4 class="signature" id="signature">
<span class="kind">object</span>
<span class="symbol">
<span class="name">HavePropertyMatcher</span>
<span class="result"> extends AnyRef</span>
</span>
</h4>
<div class="fullcommenttop" id="comment"><div class="comment cmt"><p>Companion object for trait <code>HavePropertyMatcher</code> that provides a
factory method that creates a <code>HavePropertyMatcher[T]</code> from a
passed function of type <code>(T => HavePropertyMatchResult)</code>.
</p></div><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent">AnyRef, <span name="scala.Any" class="extype">Any</span></div>
</div></div>
<div id="template">
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input accesskey="/" type="text" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol><li class="alpha in"><span>Alphabetic</span></li><li class="inherit out"><span>By inheritance</span></li></ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited</span>
<ol><li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li></ol>
<ol id="linearization"><li name="org.scalatest.matchers.HavePropertyMatcher" class="in"><span>HavePropertyMatcher</span></li><li name="scala.AnyRef" class="in"><span>AnyRef</span></li><li name="scala.Any" class="in"><span>Any</span></li></ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div class="values members" id="values">
<h3>Value Members</h3>
<ol><li visbl="pub" name="scala.AnyRef#!=" data-isabs="false">
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">!=</span>
<span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.Any#!=" data-isabs="false">
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">!=</span>
<span class="params">(<span name="arg0">arg0: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef###" data-isabs="false">
<a id="##():Int"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">##</span>
<span class="params">()</span><span class="result">: <span name="scala.Int" class="extype">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#==" data-isabs="false">
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">==</span>
<span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.Any#==" data-isabs="false">
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">==</span>
<span class="params">(<span name="arg0">arg0: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li visbl="pub" name="org.scalatest.matchers.HavePropertyMatcher#apply" data-isabs="false">
<a id="apply[T, P]((T) ⇒ HavePropertyMatchResult[P]):HavePropertyMatcher[T, P]"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">apply</span>
<span class="tparams">[<span name="T">T</span>, <span name="P">P</span>]</span>
<span class="params">(<span name="fun">fun: (T) ⇒ <a name="org.scalatest.matchers.HavePropertyMatchResult" class="extype" href="HavePropertyMatchResult.html">HavePropertyMatchResult</a>[P]</span>)</span><span class="result">: <a name="org.scalatest.matchers.HavePropertyMatcher" class="extype" href="HavePropertyMatcher.html">HavePropertyMatcher</a>[T, P]</span>
</span>
</h4>
<p class="shortcomment cmt">Factory method that creates a <code>HavePropertyMatcher[T]</code> from a
passed function of type <code>(T => HavePropertyMatchResult)</code>.</p><div class="fullcomment"><div class="comment cmt"><p>Factory method that creates a <code>HavePropertyMatcher[T]</code> from a
passed function of type <code>(T => HavePropertyMatchResult)</code>.</p><p>This allows you to create a <code>HavePropertyMatcher</code> in a slightly
more concise way, for example:</p><p><pre class="stHighlighted">
<span class="stReserved">case</span> <span class="stReserved">class</span> <span class="stType">Person</span>(name: <span class="stType">String</span>)
<span class="stReserved">def</span> name(expectedName: <span class="stType">String</span>) = {
<span class="stType">HavePropertyMatcher</span> {
(person: <span class="stType">Person</span>) => <span class="stType">HavePropertyMatchResult</span>(
person.name == expectedName,
<span class="stQuotedString">"name"</span>,
expectedName,
person.name
)
}
</pre>
</p></div></div>
</li><li visbl="pub" name="scala.Any#asInstanceOf" data-isabs="false">
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">asInstanceOf</span>
<span class="tparams">[<span name="T0">T0</span>]</span>
<span class="result">: T0</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li visbl="prt" name="scala.AnyRef#clone" data-isabs="false">
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">clone</span>
<span class="params">()</span><span class="result">: AnyRef</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a name="java.lang" class="extype" href="../../../java/lang/package.html">lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#eq" data-isabs="false">
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">eq</span>
<span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#equals" data-isabs="false">
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">equals</span>
<span class="params">(<span name="arg0">arg0: <span name="scala.Any" class="extype">Any</span></span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li visbl="prt" name="scala.AnyRef#finalize" data-isabs="false">
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">finalize</span>
<span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a name="java.lang" class="extype" href="../../../java/lang/package.html">lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#getClass" data-isabs="false">
<a id="getClass():java.lang.Class[_]"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">getClass</span>
<span class="params">()</span><span class="result">: java.lang.Class[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#hashCode" data-isabs="false">
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">hashCode</span>
<span class="params">()</span><span class="result">: <span name="scala.Int" class="extype">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li visbl="pub" name="scala.Any#isInstanceOf" data-isabs="false">
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">isInstanceOf</span>
<span class="tparams">[<span name="T0">T0</span>]</span>
<span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#ne" data-isabs="false">
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">ne</span>
<span class="params">(<span name="arg0">arg0: AnyRef</span>)</span><span class="result">: <span name="scala.Boolean" class="extype">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#notify" data-isabs="false">
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">notify</span>
<span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#notifyAll" data-isabs="false">
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">notifyAll</span>
<span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#synchronized" data-isabs="false">
<a id="synchronized[T0](⇒ T0):T0"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">synchronized</span>
<span class="tparams">[<span name="T0">T0</span>]</span>
<span class="params">(<span name="arg0">arg0: ⇒ T0</span>)</span><span class="result">: T0</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#toString" data-isabs="false">
<a id="toString():String"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">toString</span>
<span class="params">()</span><span class="result">: <span name="java.lang.String" class="extype">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#wait" data-isabs="false">
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">wait</span>
<span class="params">()</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#wait" data-isabs="false">
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">wait</span>
<span class="params">(<span name="arg0">arg0: <span name="scala.Long" class="extype">Long</span></span>, <span name="arg1">arg1: <span name="scala.Int" class="extype">Int</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li><li visbl="pub" name="scala.AnyRef#wait" data-isabs="false">
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="kind">def</span>
<span class="symbol">
<span class="name">wait</span>
<span class="params">(<span name="arg0">arg0: <span name="scala.Long" class="extype">Long</span></span>)</span><span class="result">: <span name="scala.Unit" class="extype">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>final </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">()</span>
</dd></dl></div>
</li></ol>
</div>
<div name="scala.AnyRef" class="parent">
<h3>Inherited from AnyRef</h3>
</div><div name="scala.Any" class="parent">
<h3>Inherited from <span name="scala.Any" class="extype">Any</span></h3>
</div>
</div>
<div id="tooltip"></div>
</body>
</html> | JimCallahan/Graphics | external/scalatest/doc/org/scalatest/matchers/HavePropertyMatcher$.html | HTML | apache-2.0 | 18,559 |
import { Template } from 'meteor/templating';
import { ReactiveDict } from 'meteor/reactive-dict';
import { _ } from 'meteor/underscore';
import { Beaches, BeachesSchema } from '/imports/api/items/beach/beach-item.js';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Profiles } from '/imports/api/profiles/ProfileCollection.js';
import { Meteor } from 'meteor/meteor';
/* eslint-disable no-param-reassign */
const displayErrorMessages = 'displayErrorMessages';
const displaySuccessMessage = 'displaySuccessMessage';
export const locationList = ['Aiea', 'Haleiwa', 'Hawaii Kai', 'Kahala', 'Kailua', 'Kaimuki', 'Kakaako', 'Kalihi', 'Kaneohe', 'Laie', 'Liliha', 'Manoa', 'Makiki', 'Mililani', 'Moanalua', 'Moilili', 'Pearl City', 'Waikiki'];
export const beachTagList = ['Busy', 'Dog-friendly', 'Good waves', 'Kid-friendly', 'No Lifeguard', 'No waves' , 'Private Access', 'Secluded'];
Template.Create_Beach_Form.onCreated(function onCreated() {
this.subscribe('Profiles');
this.subscribe('Beaches');
this.messageFlags = new ReactiveDict();
this.messageFlags.set(displaySuccessMessage, false);
this.messageFlags.set(displayErrorMessages, false);
this.context = BeachesSchema.namedContext('Create_Beach_Form');
});
Template.Create_Beach_Form.helpers({
errorClass() {
return Template.instance().messageFlags.get(displayErrorMessages) ? 'error' : '';
},
successClass() {
return Template.instance().messageFlags.get(displaySuccessMessage) ? 'success' : '';
},
displaySuccessMessage() {
return Template.instance().messageFlags.get(displaySuccessMessage);
},
fieldError(fieldName) {
const invalidKeys = Template.instance().context.invalidKeys();
const errorObject = _.find(invalidKeys, (keyObj) => keyObj.name === fieldName);
return errorObject && Template.instance().context.keyErrorMessage(errorObject.name);
},
locationChoice() {
return _.map(locationList, function makeLocationObject(location) {
return { label: location };
});
},
beachTagChoice() {
return _.map(beachTagList, function maketagObject(tag) {
return { label: tag };
});
},
});
Template.Create_Beach_Form.events({
'submit .create-beach-data'(event, instance) {
event.preventDefault();
// Get name (text field)
const title = event.target.Title.value;
const location = event.target.Location.value;
const about = event.target.About.value;
const selectedTags = _.filter(event.target.Tags.selectedOptions, (option) => option.selected);
const tags = _.map(selectedTags, (option) => option.value);
tags.push(location);
const createdAt = Date.now();
const picture = event.target.Picture.value;
const status = 'Pending';
const newItemData = { title, location, about, tags, status, picture, createdAt };
const currentTitle = title;
// Clear out any old validation errors.
instance.context.resetValidation();
// Invoke clean so that newStudentData reflects what will be inserted.
BeachesSchema.clean(newItemData);
// Determine validity.
instance.context.validate(newItemData);
if (instance.context.isValid()) {
Beaches.insert(newItemData);
instance.messageFlags.set(displayErrorMessages, false);
const usernameCurrent = Meteor.user().profile.name;
const profileId = Profiles.findOne({ username: usernameCurrent })._id;
const currentBeach = Beaches.findOne({ title: currentTitle })._id;
Profiles.update(profileId, { $push: { youritems: currentBeach } });
instance.messageFlags.set(displaySuccessMessage, true);
instance.messageFlags.set(displayErrorMessages, false);
FlowRouter.go('Item_Feed_Page');
} else {
instance.messageFlags.set(displaySuccessMessage, false);
instance.messageFlags.set(displayErrorMessages, true);
}
},
});
| chasehawaii/chasehawaii | app/imports/ui/components/items/create-beach-form.js | JavaScript | apache-2.0 | 3,843 |
// Copyright (c) 2017 Ernest Micklei
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package proto
import (
"strings"
"text/scanner"
)
// Comment one or more comment text lines, either in c- or c++ style.
type Comment struct {
Position scanner.Position
// Lines are comment text lines without prefixes //, ///, /* or suffix */
Lines []string
Cstyle bool // refers to /* ... */, C++ style is using //
ExtraSlash bool // is true if the comment starts with 3 slashes
}
// newComment returns a comment.
func newComment(pos scanner.Position, lit string) *Comment {
extraSlash := strings.HasPrefix(lit, "///")
isCstyle := strings.HasPrefix(lit, "/*") && strings.HasSuffix(lit, "*/")
var lines []string
if isCstyle {
withoutMarkers := strings.TrimRight(strings.TrimLeft(lit, "/*"), "*/")
lines = strings.Split(withoutMarkers, "\n")
} else {
lines = strings.Split(strings.TrimLeft(lit, "/"), "\n")
}
return &Comment{Position: pos, Lines: lines, Cstyle: isCstyle, ExtraSlash: extraSlash}
}
//type inlineComment struct {
// line string
// extraSlash bool
//}
// Accept dispatches the call to the visitor.
func (c *Comment) Accept(v Visitor) {
v.VisitComment(c)
}
// Merge appends all lines from the argument comment.
func (c *Comment) Merge(other *Comment) {
c.Lines = append(c.Lines, other.Lines...)
c.Cstyle = c.Cstyle || other.Cstyle
}
func (c Comment) hasTextOnLine(line int) bool {
if len(c.Lines) == 0 {
return false
}
return c.Position.Line <= line && line <= c.Position.Line+len(c.Lines)-1
}
// Message returns the first line or empty if no lines.
func (c Comment) Message() string {
if len(c.Lines) == 0 {
return ""
}
return c.Lines[0]
}
// commentInliner is for types that can have an inline comment.
type commentInliner interface {
inlineComment(c *Comment)
}
// maybeScanInlineComment tries to scan comment on the current line ; if present then set it for the last element added.
func maybeScanInlineComment(p *Parser, c elementContainer) {
currentPos := p.scanner.Position
// see if there is an inline Comment
pos, tok, lit := p.next()
esize := len(c.elements())
// seen comment and on same line and elements have been added
if tCOMMENT == tok && pos.Line == currentPos.Line && esize > 0 {
// if the last added element can have an inline comment then set it
last := c.elements()[esize-1]
if inliner, ok := last.(commentInliner); ok {
// TODO skip multiline?
inliner.inlineComment(newComment(pos, lit))
}
} else {
p.nextPut(pos, tok, lit)
}
}
// takeLastCommentIfEndsOnLine removes and returns the last element of the list if it is a Comment
func takeLastCommentIfEndsOnLine(list []Visitee, line int) (*Comment, []Visitee) {
if len(list) == 0 {
return nil, list
}
if last, ok := list[len(list)-1].(*Comment); ok && last.hasTextOnLine(line) {
return last, list[:len(list)-1]
}
return nil, list
}
// mergeOrReturnComment creates a new comment and tries to merge it with the last element (if is a comment and is on the next line).
func mergeOrReturnComment(elements []Visitee, lit string, pos scanner.Position) *Comment {
com := newComment(pos, lit)
esize := len(elements)
if esize == 0 {
return com
}
// last element must be a comment to merge
last, ok := elements[esize-1].(*Comment)
if !ok {
return com
}
// do not merge c-style comments
if last.Cstyle {
return com
}
// last comment has text on previous line
// TODO handle last line of file could be inline comment
if !last.hasTextOnLine(pos.Line - 1) {
return com
}
last.Merge(com)
return nil
}
// parent is part of elementContainer
func (c *Comment) parent(Visitee) {}
| LQJJ/demo | 126-go-common-master/app/admin/ep/melloi/service/proto/comment.go | GO | apache-2.0 | 4,695 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.