content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | update exampleredditapi.md to react 0.14 | 460a4dc9d7c959892a2b06c76a74f376f7799714 | <ide><path>docs/advanced/ExampleRedditAPI.md
<ide> This is the complete source code of the Reddit headline fetching example we buil
<ide> import 'babel-core/polyfill';
<ide>
<ide> import React from 'react';
<add>import { render } from 'react-dom';
<ide> import Root from './containers/Root';
<ide>
<del>React.render(
<add>render(
<ide> <Root />,
<ide> document.getElementById('root')
<ide> );
<ide> export default class Root extends Component {
<ide> render() {
<ide> return (
<ide> <Provider store={store}>
<del> {() => <AsyncApp />}
<add> <AsyncApp />
<ide> </Provider>
<ide> );
<ide> } | 1 |
PHP | PHP | use strict comparison | 9eb11508763024f150adefb17c0d8a6632e90a00 | <ide><path>src/Database/Schema/SqliteSchema.php
<ide> public function convertColumnDescription(Table $table, $row) {
<ide> 'null' => !$row['notnull'],
<ide> 'default' => $row['dflt_value'] === null ? null : trim($row['dflt_value'], "'"),
<ide> ];
<del> if ($row['pk'] == true) {
<add> if ($row['pk'] === true) {
<ide> $field['null'] = false;
<ide> $field['autoIncrement'] = true;
<ide> }
<ide> $table->addColumn($row['name'], $field);
<del> if ($row['pk'] == true) {
<add> if ($row['pk'] === true) {
<ide> $constraint = (array)$table->constraint('primary') + [
<ide> 'type' => Table::CONSTRAINT_PRIMARY,
<ide> 'columns' => []
<ide><path>src/Event/EventManagerTrait.php
<ide> trait EventManagerTrait {
<ide> * @return \Cake\Event\EventManager
<ide> */
<ide> public function eventManager(EventManager $eventManager = null) {
<del> if ($eventManager != null) {
<add> if ($eventManager !== null) {
<ide> $this->_eventManager = $eventManager;
<ide> } elseif (empty($this->_eventManager)) {
<ide> $this->_eventManager = new EventManager();
<ide> public function eventManager(EventManager $eventManager = null) {
<ide> }
<ide>
<ide> /**
<del> * Wrapper for creating and dispatching events.
<add> * Wrapper for creating and dispatching events.
<ide> *
<ide> * Returns a dispatched event.
<ide> *
<ide> * @param string $name Name of the event.
<ide> * @param array $data Any value you wish to be transported with this event to
<ide> * it can be read by listeners.
<ide> *
<del> * @param object $subject The object that this event applies to
<add> * @param object $subject The object that this event applies to
<ide> * ($this by default).
<ide> *
<ide> * @return \Cake\Event\Event
<ide><path>src/Routing/RouteBuilder.php
<ide> public function __construct($collection, $path, array $params = [], array $optio
<ide> * @return string|void
<ide> */
<ide> public function routeClass($routeClass = null) {
<del> if ($routeClass == null) {
<add> if ($routeClass === null) {
<ide> return $this->_routeClass;
<ide> }
<ide> $this->_routeClass = $routeClass;
<ide><path>src/Routing/Router.php
<ide> class Router {
<ide> * @return string|void
<ide> */
<ide> public static function defaultRouteClass($routeClass = null) {
<del> if ($routeClass == null) {
<add> if ($routeClass === null) {
<ide> return static::$_defaultRouteClass;
<ide> }
<ide> static::$_defaultRouteClass = $routeClass;
<ide><path>src/View/ViewVarsTrait.php
<ide> public function viewOptions($options = null, $merge = true) {
<ide> $this->_validViewOptions = [];
<ide> }
<ide>
<del> if ($options == null) {
<add> if ($options === null) {
<ide> return $this->_validViewOptions;
<ide> }
<ide> | 5 |
PHP | PHP | remove unused variables | c06ea522ca7e553584e7fb0f3726d2c979c25ec5 | <ide><path>tests/Log/LogLoggerTest.php
<ide> public function testListenShortcutFailsWithNoDispatcher()
<ide> $this->expectException(RuntimeException::class);
<ide> $this->expectExceptionMessage('Events dispatcher has not been set.');
<ide>
<del> $writer = new Logger($monolog = m::mock(Monolog::class));
<add> $writer = new Logger(m::mock(Monolog::class));
<ide> $writer->listen(function () {
<ide> //
<ide> });
<ide> }
<ide>
<ide> public function testListenShortcut()
<ide> {
<del> $writer = new Logger($monolog = m::mock(Monolog::class), $events = m::mock(DispatcherContract::class));
<add> $writer = new Logger(m::mock(Monolog::class), $events = m::mock(DispatcherContract::class));
<ide>
<ide> $callback = function () {
<ide> return 'success'; | 1 |
Ruby | Ruby | add tests for unless build.with? | ec2b0df10e62152529386cf2a696f9aaece405ea | <ide><path>Library/Homebrew/rubocops/lines_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> problem "Use if #{correct} instead of unless #{m.source}"
<ide> end
<ide>
<del> # find_instance_method_call(body_node, :build, :with?) do |m|
<del> # next unless unless_modifier?(m.parent)
<del> # correct = m.source.gsub("?", "out?").gsub("unless", "if")
<del> # problem "Use #{correct} instead of unless #{m.source}"
<del> # end
<del> #
<add> find_instance_method_call(body_node, :build, :with?) do |m|
<add> next unless unless_modifier?(m.parent)
<add> correct = m.source.gsub("?", "out?")
<add> problem "Use if #{correct} instead of unless #{m.source}"
<add> end
<add>
<ide> # find_instance_method_call(body_node, :build, :with?) do |m|
<ide> # next unless negation?(m)
<ide> # problem "Don't negate 'build.with?': use 'build.without?'"
<ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb
<ide> def post_install
<ide> expect_offense(expected, actual)
<ide> end
<ide> end
<add>
<add> it "with unless build.with?" do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> desc "foo"
<add> url 'http://example.com/foo-1.0.tgz'
<add> def post_install
<add> return unless build.with? "bar"
<add> end
<add> end
<add> EOS
<add>
<add> expected_offenses = [{ message: 'Use if build.without? "bar" instead of unless build.with? "bar"',
<add> severity: :convention,
<add> line: 5,
<add> column: 18,
<add> source: source }]
<add>
<add> inspect_source(cop, source)
<add>
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<ide> end
<ide> def expect_offense(expected, actual)
<ide> expect(actual.message).to eq(expected[:message]) | 2 |
Go | Go | check all required fields | 4c69d0dd8ade90b6602147b8dfb8c1f4c267d3bc | <ide><path>integration-cli/docker_cli_info_test.go
<ide> func TestInfoEnsureSucceeds(t *testing.T) {
<ide> t.Fatalf("failed to execute docker info: %s, %v", out, err)
<ide> }
<ide>
<del> stringsToCheck := []string{"Containers:", "Execution Driver:", "Logging Driver:", "Kernel Version:"}
<add> // always shown fields
<add> stringsToCheck := []string{
<add> "ID:",
<add> "Containers:",
<add> "Images:",
<add> "Execution Driver:",
<add> "Logging Driver:",
<add> "Operating System:",
<add> "CPUs:",
<add> "Total Memory:",
<add> "Kernel Version:",
<add> "Storage Driver:"}
<ide>
<ide> for _, linePrefix := range stringsToCheck {
<ide> if !strings.Contains(out, linePrefix) { | 1 |
Java | Java | update copyright date | 88af24c1cb5cb0325c2322e0efdc109e4eceb487 | <ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactory.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. | 1 |
PHP | PHP | explain modulus 0 | a3178708884f73448d215d5a06db57166a6412c4 | <ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function counter($options = [])
<ide> * - `after` Content to be inserted after the numbers, but before the last links.
<ide> * - `model` Model to create numbers for, defaults to PaginatorHelper::defaultModel()
<ide> * - `modulus` How many numbers to include on either side of the current page, defaults to 8.
<del> * Set to `false` to disable.
<add> * Set to `false` to disable and to show all numbers.
<ide> * - `first` Whether you want first links generated, set to an integer to define the number of 'first'
<ide> * links to generate.
<ide> * - `last` Whether you want last links generated, set to an integer to define the number of 'last' | 1 |
Javascript | Javascript | fix uniforms that need unsharing for outline pass | b01a230aa98d74d2b6bd1d903623a86194b2b767 | <ide><path>examples/js/postprocessing/OutlinePass.js
<ide> THREE.OutlinePass = function ( resolution, scene, camera, selectedObjects ) {
<ide> var MAX_EDGE_GLOW = 4;
<ide>
<ide> this.separableBlurMaterial1 = this.getSeperableBlurMaterial(MAX_EDGE_THICKNESS);
<del> this.separableBlurMaterial1.uniforms[ "texSize" ].value = new THREE.Vector2(resx, resy);
<del> this.separableBlurMaterial1.uniforms[ "kernelRadius" ].value = 1;
<add> this.separableBlurMaterial1.uniforms[ "texSize" ] = new THREE.Uniform( new THREE.Vector2(resx, resy) );
<add> this.separableBlurMaterial1.uniforms[ "kernelRadius" ] = new THREE.Uniform( 1 );
<ide> this.separableBlurMaterial2 = this.getSeperableBlurMaterial(MAX_EDGE_GLOW);
<del> this.separableBlurMaterial2.uniforms[ "texSize" ].value = new THREE.Vector2(Math.round(resx/2), Math.round(resy/2));
<del> this.separableBlurMaterial2.uniforms[ "kernelRadius" ].value = MAX_EDGE_GLOW;
<add> this.separableBlurMaterial2.uniforms[ "texSize" ] = new THREE.Uniform(new THREE.Vector2(Math.round(resx/2), Math.round(resy/2) ) );
<add> this.separableBlurMaterial2.uniforms[ "kernelRadius" ] = new THREE.Uniform( MAX_EDGE_GLOW) ;
<ide>
<ide> // Overlay material
<ide> this.overlayMaterial = this.getOverlayMaterial();
<ide> THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype
<ide> this.renderTargetMaskDownSampleBuffer.setSize(resx, resy );
<ide> this.renderTargetBlurBuffer1.setSize(resx, resy );
<ide> this.renderTargetEdgeBuffer1.setSize(resx, resy );
<del> this.separableBlurMaterial1.uniforms[ "texSize" ].value = new THREE.Vector2(resx, resy);
<add> this.separableBlurMaterial1.uniforms[ "texSize" ] = new THREE.Uniform( new THREE.Vector2(resx, resy) );
<ide>
<del> resx = Math.round(resx/2);
<del> resy = Math.round(resy/2);
<add> resx = Math.round(resx/2);
<add> resy = Math.round(resy/2);
<ide>
<ide> this.renderTargetBlurBuffer2.setSize(resx, resy );
<ide> this.renderTargetEdgeBuffer2.setSize(resx, resy );
<ide>
<del> this.separableBlurMaterial2.uniforms[ "texSize" ].value = new THREE.Vector2(resx, resy);
<add> this.separableBlurMaterial2.uniforms[ "texSize" ] = new THREE.Uniform( new THREE.Vector2(resx, resy) );
<ide> },
<ide>
<ide> changeVisibilityOfSelectedObjects: function( bVisible ) { | 1 |
Java | Java | fix timing issue with obtaining async result | 705efc5bdf7971cde7a1de1b05b437cea557eee9 | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/DefaultMvcResult.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> class DefaultMvcResult implements MvcResult {
<ide>
<add> private static final Object RESULT_NONE = new Object();
<add>
<add>
<ide> private final MockHttpServletRequest mockRequest;
<ide>
<ide> private final MockHttpServletResponse mockResponse;
<ide> class DefaultMvcResult implements MvcResult {
<ide>
<ide> private Exception resolvedException;
<ide>
<del> private Object asyncResult;
<add> private Object asyncResult = RESULT_NONE;
<ide>
<ide> private CountDownLatch asyncResultLatch;
<ide>
<ide> public Object getAsyncResult() {
<ide>
<ide> @Override
<ide> public Object getAsyncResult(long timeout) {
<del> // MockHttpServletRequest type doesn't have async methods
<del> HttpServletRequest request = this.mockRequest;
<del> if ((timeout != 0) && request.isAsyncStarted()) {
<del> if (timeout == -1) {
<del> timeout = request.getAsyncContext().getTimeout();
<del> }
<del> if (!awaitAsyncResult(timeout)) {
<del> throw new IllegalStateException(
<del> "Gave up waiting on async result from handler [" + this.handler + "] to complete");
<add> if (this.asyncResult == RESULT_NONE) {
<add> if ((timeout != 0) && this.mockRequest.isAsyncStarted()) {
<add> if (timeout == -1) {
<add> timeout = this.mockRequest.getAsyncContext().getTimeout();
<add> }
<add> if (!awaitAsyncResult(timeout) && this.asyncResult == RESULT_NONE) {
<add> throw new IllegalStateException(
<add> "Gave up waiting on async result from handler [" + this.handler + "] to complete");
<add> }
<ide> }
<ide> }
<del> return this.asyncResult;
<add> return (this.asyncResult == RESULT_NONE ? null : this.asyncResult);
<ide> }
<ide>
<ide> private boolean awaitAsyncResult(long timeout) {
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void testDeferredResult() throws Exception {
<ide> .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
<ide> }
<ide>
<add> @Test
<add> @Ignore
<add> public void testDeferredResultWithSetValue() throws Exception {
<add> MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResultWithSetValue", "true"))
<add> .andExpect(request().asyncStarted())
<add> .andExpect(request().asyncResult(new Person("Joe")))
<add> .andReturn();
<add>
<add> this.mockMvc.perform(asyncDispatch(mvcResult))
<add> .andExpect(status().isOk())
<add> .andExpect(content().contentType(MediaType.APPLICATION_JSON))
<add> .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
<add> }
<add>
<ide>
<ide> @Controller
<ide> private static class AsyncController {
<ide> public DeferredResult<Person> getDeferredResult() {
<ide> return deferredResult;
<ide> }
<ide>
<add> @RequestMapping(value="/{id}", params="deferredResultWithSetValue", produces="application/json")
<add> @ResponseBody
<add> public DeferredResult<Person> getDeferredResultWithSetValue() {
<add> DeferredResult<Person> deferredResult = new DeferredResult<Person>();
<add> deferredResult.setResult(new Person("Joe"));
<add> return deferredResult;
<add> }
<add>
<ide> public void onMessage(String name) {
<ide> for (DeferredResult<Person> deferredResult : this.deferredResults) {
<ide> deferredResult.setResult(new Person(name)); | 2 |
Ruby | Ruby | ensure cmake uses the desired sdk | 2592b937706a4393ad2f275da32ae9dab48e594d | <ide><path>Library/Homebrew/formula.rb
<ide> def std_cmake_args
<ide> # CMake cache entries for other weak symbols may be added here as needed.
<ide> args << "-DHAVE_CLOCK_GETTIME:INTERNAL=0" if MacOS.version == "10.11" && MacOS::Xcode.version >= "8.0"
<ide>
<add> # Ensure CMake is using the same SDK we are using.
<add> sdk = MacOS.sdk_path_if_needed
<add> args << "-DCMAKE_OSX_SYSROOT=#{sdk}" if sdk
<add>
<ide> args
<ide> end
<ide> | 1 |
Python | Python | fix formatting errors | 0bac2ade9154b4c1a267990238e2ab84931a0cb4 | <ide><path>tests/test_user_error_handler.py
<ide>
<ide>
<ide> def test_error_handler_subclass():
<del> app = flask.Flask(__name__)
<add> app = flask.Flask(__name__)
<ide>
<del> class ParentException(Exception):
<del> pass
<add> class ParentException(Exception):
<add> pass
<ide>
<del> class ChildExceptionUnregistered(ParentException):
<del> pass
<add> class ChildExceptionUnregistered(ParentException):
<add> pass
<ide>
<del> class ChildExceptionRegistered(ParentException):
<del> pass
<add> class ChildExceptionRegistered(ParentException):
<add> pass
<ide>
<del> @app.errorhandler(ParentException)
<del> def parent_exception_handler(e):
<del> assert isinstance(e, ParentException)
<del> return 'parent'
<add> @app.errorhandler(ParentException)
<add> def parent_exception_handler(e):
<add> assert isinstance(e, ParentException)
<add> return 'parent'
<ide>
<del> @app.errorhandler(ChildExceptionRegistered)
<del> def child_exception_handler(e):
<del> assert isinstance(e, ChildExceptionRegistered)
<del> return 'child-registered'
<add> @app.errorhandler(ChildExceptionRegistered)
<add> def child_exception_handler(e):
<add> assert isinstance(e, ChildExceptionRegistered)
<add> return 'child-registered'
<ide>
<del> @app.route('/parent')
<del> def parent_test():
<del> raise ParentException()
<add> @app.route('/parent')
<add> def parent_test():
<add> raise ParentException()
<ide>
<del> @app.route('/child-unregistered')
<del> def unregistered_test():
<del> raise ChildExceptionUnregistered()
<add> @app.route('/child-unregistered')
<add> def unregistered_test():
<add> raise ChildExceptionUnregistered()
<ide>
<del> @app.route('/child-registered')
<del> def registered_test():
<del> raise ChildExceptionRegistered()
<add> @app.route('/child-registered')
<add> def registered_test():
<add> raise ChildExceptionRegistered()
<ide>
<add> c = app.test_client()
<ide>
<del> c = app.test_client()
<del>
<del> assert c.get('/parent').data == b'parent'
<del> assert c.get('/child-unregistered').data == b'parent'
<del> assert c.get('/child-registered').data == b'child-registered'
<add> assert c.get('/parent').data == b'parent'
<add> assert c.get('/child-unregistered').data == b'parent'
<add> assert c.get('/child-registered').data == b'child-registered'
<ide>
<ide>
<ide> def test_error_handler_http_subclass():
<del> app = flask.Flask(__name__)
<del>
<del> class ForbiddenSubclassRegistered(Forbidden):
<del> pass
<add> app = flask.Flask(__name__)
<ide>
<del> class ForbiddenSubclassUnregistered(Forbidden):
<del> pass
<add> class ForbiddenSubclassRegistered(Forbidden):
<add> pass
<ide>
<del> @app.errorhandler(403)
<del> def code_exception_handler(e):
<del> assert isinstance(e, Forbidden)
<del> return 'forbidden'
<add> class ForbiddenSubclassUnregistered(Forbidden):
<add> pass
<ide>
<del> @app.errorhandler(ForbiddenSubclassRegistered)
<del> def subclass_exception_handler(e):
<del> assert isinstance(e, ForbiddenSubclassRegistered)
<del> return 'forbidden-registered'
<add> @app.errorhandler(403)
<add> def code_exception_handler(e):
<add> assert isinstance(e, Forbidden)
<add> return 'forbidden'
<ide>
<del> @app.route('/forbidden')
<del> def forbidden_test():
<del> raise Forbidden()
<add> @app.errorhandler(ForbiddenSubclassRegistered)
<add> def subclass_exception_handler(e):
<add> assert isinstance(e, ForbiddenSubclassRegistered)
<add> return 'forbidden-registered'
<ide>
<del> @app.route('/forbidden-registered')
<del> def registered_test():
<del> raise ForbiddenSubclassRegistered()
<add> @app.route('/forbidden')
<add> def forbidden_test():
<add> raise Forbidden()
<ide>
<del> @app.route('/forbidden-unregistered')
<del> def unregistered_test():
<del> raise ForbiddenSubclassUnregistered()
<add> @app.route('/forbidden-registered')
<add> def registered_test():
<add> raise ForbiddenSubclassRegistered()
<ide>
<add> @app.route('/forbidden-unregistered')
<add> def unregistered_test():
<add> raise ForbiddenSubclassUnregistered()
<ide>
<del> c = app.test_client()
<add> c = app.test_client()
<ide>
<del> assert c.get('/forbidden').data == b'forbidden'
<del> assert c.get('/forbidden-unregistered').data == b'forbidden'
<del> assert c.get('/forbidden-registered').data == b'forbidden-registered'
<add> assert c.get('/forbidden').data == b'forbidden'
<add> assert c.get('/forbidden-unregistered').data == b'forbidden'
<add> assert c.get('/forbidden-registered').data == b'forbidden-registered'
<ide>
<ide>
<ide> def test_error_handler_blueprint():
<del> bp = flask.Blueprint('bp', __name__)
<del>
<del> @bp.errorhandler(500)
<del> def bp_exception_handler(e):
<del> return 'bp-error'
<del>
<del> @bp.route('/error')
<del> def bp_test():
<del> raise InternalServerError()
<del>
<del> app = flask.Flask(__name__)
<del>
<del> @app.errorhandler(500)
<del> def app_exception_handler(e):
<del> return 'app-error'
<del>
<del> @app.route('/error')
<del> def app_test():
<del> raise InternalServerError()
<del>
<del> app.register_blueprint(bp, url_prefix='/bp')
<del>
<del> c = app.test_client()
<del>
<del> assert c.get('/error').data == b'app-error'
<del> assert c.get('/bp/error').data == b'bp-error'
<ide>\ No newline at end of file
<add> bp = flask.Blueprint('bp', __name__)
<add>
<add> @bp.errorhandler(500)
<add> def bp_exception_handler(e):
<add> return 'bp-error'
<add>
<add> @bp.route('/error')
<add> def bp_test():
<add> raise InternalServerError()
<add>
<add> app = flask.Flask(__name__)
<add>
<add> @app.errorhandler(500)
<add> def app_exception_handler(e):
<add> return 'app-error'
<add>
<add> @app.route('/error')
<add> def app_test():
<add> raise InternalServerError()
<add>
<add> app.register_blueprint(bp, url_prefix='/bp')
<add>
<add> c = app.test_client()
<add>
<add> assert c.get('/error').data == b'app-error'
<add> assert c.get('/bp/error').data == b'bp-error' | 1 |
PHP | PHP | remove unnecessary comments from input class | 0e02a8a53df9a11d8fa88ca5ebfde8615e96605e | <ide><path>system/input.php
<ide> public static function had($key)
<ide> /**
<ide> * Get input data from the previous request.
<ide> *
<del> * Since input data is flashed to the session, a session driver must be specified
<del> * in order to use this method.
<del> *
<ide> * @param string $key
<ide> * @param mixed $default
<ide> * @return string
<ide> public static function old($key = null, $default = null)
<ide> /**
<ide> * Get an item from the uploaded file data.
<ide> *
<del> * If a "dot" is present in the key. A specific element will be returned from
<del> * the specified file array.
<del> *
<del> * Example: Input::file('picture.size');
<del> *
<del> * The statement above will return the value of $_FILES['picture']['size'].
<del> *
<ide> * @param string $key
<ide> * @param mixed $default
<ide> * @return array
<ide> public static function file($key = null, $default = null)
<ide> /**
<ide> * Hydrate the input data for the request.
<ide> *
<del> * Typically, browsers do not support PUT and DELETE methods on HTML forms. So, they are simulated
<del> * by Laravel using a hidden POST element. If the request method is being "spoofed", the POST
<del> * array will be moved into the PUT / DELETE array. True "PUT" or "DELETE" rqeuests will be read
<del> * from the php://input file.
<del> *
<ide> * @return void
<ide> */
<ide> public static function hydrate()
<ide> public static function hydrate()
<ide>
<ide> case 'PUT':
<ide> case 'DELETE':
<add> // The request method can be spoofed by specifying a "REQUEST_METHOD" in the $_POST array.
<add> // If the method is being spoofed, the $_POST array will be considered the input.
<ide> if (isset($_POST['REQUEST_METHOD']) and in_array($_POST['REQUEST_METHOD'], array('PUT', 'DELETE')))
<ide> {
<ide> static::$input =& $_POST; | 1 |
Javascript | Javascript | change some magic numbers to hoist exports | a952bb99a6830804d06c5b8e04b75c66100fbae9 | <ide><path>lib/dependencies/HarmonyCompatibilityDependency.js
<ide> HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate
<ide> if(usedExports && !Array.isArray(usedExports)) {
<ide> const exportName = dep.originModule.exportsArgument || "exports";
<ide> const content = `Object.defineProperty(${exportName}, \"__esModule\", { value: true });\n`;
<del> source.insert(-1, content);
<add> source.insert(-10, content);
<ide> }
<ide> }
<ide> };
<ide><path>lib/dependencies/HarmonyExportDependencyParserPlugin.js
<ide> module.exports = class HarmonyExportDependencyParserPlugin {
<ide> } else {
<ide> const immutable = statement.declaration && isImmutableStatement(statement.declaration);
<ide> const hoisted = statement.declaration && isHoistedStatement(statement.declaration);
<del> dep = new HarmonyExportSpecifierDependency(parser.state.module, id, name, !immutable || hoisted ? -0.5 : (statement.range[1] + 0.5), immutable);
<add> dep = new HarmonyExportSpecifierDependency(parser.state.module, id, name, !immutable || hoisted ? -2 : (statement.range[1] + 0.5), immutable);
<ide> }
<ide> dep.loc = Object.create(statement.loc);
<ide> dep.loc.index = idx;
<ide><path>test/cases/parsing/harmony-export-hoist/bar.js
<add>import { foo, foo2 } from "./foo";
<add>
<add>export default {
<add> foo: foo,
<add> foo2: foo2
<add>};
<ide><path>test/cases/parsing/harmony-export-hoist/foo.js
<add>import {bar} from "./bar";
<add>
<add>export function foo() {
<add> return "ok";
<add>}
<add>
<add>function foo2() {
<add> return "ok";
<add>}
<add>export { foo2 }
<add>
<add>export { default } from "./bar";
<ide><path>test/cases/parsing/harmony-export-hoist/index.js
<add>"use strict";
<add>
<add>it("should hoist exports", function() {
<add> var result = require("./foo").default;
<add> (typeof result.foo).should.have.eql("function");
<add> (typeof result.foo2).should.have.eql("function");
<add> result.foo().should.be.eql("ok");
<add> result.foo2().should.be.eql("ok");
<add>}); | 5 |
Javascript | Javascript | allow periods in doc shortnames | 95102a5afef6a6f36aefd3d3590e305cc972881d | <ide><path>docs/src/ngdoc.js
<ide> function scenarios(docs){
<ide> function metadata(docs){
<ide> var pages = [];
<ide> docs.forEach(function(doc){
<del> var path = (doc.name || '').split(/(\.|\:\s*)/);
<add> var path = (doc.name || '').split(/(\:\s*)/);
<ide> for ( var i = 1; i < path.length; i++) {
<ide> path.splice(i, 1);
<ide> } | 1 |
Ruby | Ruby | update connection_pool docs | b00fc77f772260eb23d120b2c4d19b346293ad69 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> def async_executor; end
<ide> # handle cases in which there are more threads than connections: if all
<ide> # connections have been checked out, and a thread tries to checkout a
<ide> # connection anyway, then ConnectionPool will wait until some other thread
<del> # has checked in a connection.
<add> # has checked in a connection, or the +checkout_timeout+ has expired.
<ide> #
<ide> # == Obtaining (checking out) a connection
<ide> #
<ide> def async_executor; end
<ide> # Connections in the pool are actually AbstractAdapter objects (or objects
<ide> # compatible with AbstractAdapter's interface).
<ide> #
<add> # While a thread has a connection checked out from the pool using one of the
<add> # above three methods, that connection will automatically be the one used
<add> # by ActiveRecord queries executing on that thread. It is not required to
<add> # explicitly pass the checked out connection to Rails models or queries, for
<add> # example.
<add> #
<ide> # == Options
<ide> #
<ide> # There are several connection-pooling-related options that you can add to
<ide> def release_connection(owner_thread = ActiveSupport::IsolatedExecutionState.cont
<ide> end
<ide> end
<ide>
<del> # If a connection obtained through #connection or #with_connection methods
<del> # already exists yield it to the block. If no such connection
<del> # exists checkout a connection, yield it to the block, and checkin the
<del> # connection when finished.
<add> # Yields a connection from the connection pool to the block. If no connection
<add> # is already checked out by the current thread, a connection will be checked
<add> # out from the pool, yielded to the block, and then returned to the pool when
<add> # the block is finished. If a connection has already been checked out on the
<add> # current thread, such as via #connection or #with_connection, that existing
<add> # connection will be the one yielded and it will not be returned to the pool
<add> # automatically at the end of the block; it is expected that such an existing
<add> # connection will be properly returned to the pool by the code that checked
<add> # it out.
<ide> def with_connection
<ide> unless conn = @thread_cached_conns[connection_cache_key(ActiveSupport::IsolatedExecutionState.context)]
<ide> conn = connection | 1 |
Javascript | Javascript | increase coverage internal readline | f77bb3cb0043f1f7908fa668b40052c331e5af50 | <ide><path>test/parallel/test-readline-keys.js
<ide> addTest('\n\r\t', [
<ide> ]);
<ide>
<ide> // space and backspace
<del>addTest('\b\x7f\x1b\b\x1b\x7f \x1b ', [
<add>addTest('\b\x7f\x1b\b\x1b\x7f\x1b\x1b \x1b ', [
<ide> { name: 'backspace', sequence: '\b' },
<ide> { name: 'backspace', sequence: '\x7f' },
<ide> { name: 'backspace', sequence: '\x1b\b', meta: true },
<ide> { name: 'backspace', sequence: '\x1b\x7f', meta: true },
<add> { name: 'space', sequence: '\x1b\x1b ', meta: true },
<ide> { name: 'space', sequence: ' ' },
<ide> { name: 'space', sequence: '\x1b ', meta: true },
<ide> ]); | 1 |
Ruby | Ruby | move tests to namespace | 79173314dea2fa02f54fb1cc9316a9ce1838b86c | <ide><path>activerecord/test/cases/encryption/concurrency_test.rb
<ide> require "cases/encryption/helper"
<ide> require "models/post"
<ide>
<del>module ActiveRecord::Encryption
<del> class ConcurrencyTest < ActiveRecord::TestCase
<del> setup do
<del> ActiveRecord::Encryption.config.support_unencrypted_data = true
<del> end
<add>class ActiveRecord::Encryption::ConcurrencyTest < ActiveRecord::TestCase
<add> setup do
<add> ActiveRecord::Encryption.config.support_unencrypted_data = true
<add> end
<ide>
<del> test "models can be encrypted and decrypted in different threads concurrently" do
<del> 4.times.collect { |index| thread_encrypting_and_decrypting("thread #{index}") }.each(&:join)
<del> end
<add> test "models can be encrypted and decrypted in different threads concurrently" do
<add> 4.times.collect { |index| thread_encrypting_and_decrypting("thread #{index}") }.each(&:join)
<add> end
<ide>
<del> def thread_encrypting_and_decrypting(thread_label)
<del> posts = 200.times.collect { |index| EncryptedPost.create! title: "Article #{index} (#{thread_label})", body: "Body #{index} (#{thread_label})" }
<add> def thread_encrypting_and_decrypting(thread_label)
<add> posts = 200.times.collect { |index| EncryptedPost.create! title: "Article #{index} (#{thread_label})", body: "Body #{index} (#{thread_label})" }
<ide>
<del> Thread.new do
<del> posts.each.with_index do |article, index|
<del> assert_encrypted_attribute article, :title, "Article #{index} (#{thread_label})"
<del> article.decrypt
<del> assert_not_encrypted_attribute article, :title, "Article #{index} (#{thread_label})"
<del> end
<add> Thread.new do
<add> posts.each.with_index do |article, index|
<add> assert_encrypted_attribute article, :title, "Article #{index} (#{thread_label})"
<add> article.decrypt
<add> assert_not_encrypted_attribute article, :title, "Article #{index} (#{thread_label})"
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/encryption/configurable_test.rb
<ide> require "cases/encryption/helper"
<ide> require "models/book"
<ide>
<del>class ActiveRecord::ConfigurableTest < ActiveRecord::TestCase
<add>class ActiveRecord::Encryption::ConfigurableTest < ActiveRecord::TestCase
<ide> test 'can access context properties with top level getters' do
<ide> assert_equal ActiveRecord::Encryption.key_provider, ActiveRecord::Encryption.context.key_provider
<ide> end
<ide><path>activerecord/test/cases/encryption/contexts_test.rb
<ide> require "models/book"
<ide> require "models/post"
<ide>
<del>class ActiveRecord::ContextsTest < ActiveRecord::TestCase
<add>class ActiveRecord::Encryption::ContextsTest < ActiveRecord::TestCase
<ide> fixtures :posts
<ide>
<ide> setup do
<ide><path>activerecord/test/cases/encryption/encrypted_attribute_type_test.rb
<del>require "cases/encryption/helper"
<del>
<del>class EncryptedAttributeTypeTest < ActiveSupport::TestCase
<del> test "deterministic is true when some iv is set" do
<del> assert_not ActiveRecord::Encryption::EncryptedAttributeType.new.deterministic?
<del>
<del> assert ActiveRecord::Encryption::EncryptedAttributeType.new(deterministic: true).deterministic?
<del> assert_not ActiveRecord::Encryption::EncryptedAttributeType.new(deterministic: false).deterministic?
<del> end
<del>end
<ide><path>activerecord/test/cases/encryption/encrypted_fixtures_test.rb
<ide> require "cases/encryption/helper"
<ide> require "models/book"
<ide>
<del>class EncryptableFixtureTest < ActiveRecord::TestCase
<add>class ActiveRecord::Encryption::EncryptableFixtureTest < ActiveRecord::TestCase
<ide> fixtures :encrypted_books, :encrypted_book_that_ignores_cases
<ide>
<ide> test "fixtures get encrypted automatically" do
<ide><path>activerecord/test/cases/encryption/extended_deterministic_queries_test.rb
<ide> require "cases/encryption/helper"
<ide> require "models/book"
<ide>
<del>class ExtendedDeterministicQueriesTest < ActiveRecord::TestCase
<add>class ActiveRecord::Encryption::ExtendedDeterministicQueriesTest < ActiveRecord::TestCase
<ide> test "Finds records when data is unencrypted" do
<ide> ActiveRecord::Encryption.without_encryption { Book.create! name: "Dune" }
<ide> assert EncryptedBook.find_by(name: "Dune") # core
<ide><path>activerecord/test/cases/encryption/helper.rb
<ide> class ActiveRecord::Fixture
<ide> prepend ActiveRecord::Encryption::EncryptedFixtures
<ide> end
<ide>
<del>module EncryptionHelpers
<del> def assert_encrypted_attribute(model, attribute_name, expected_value)
<del> encrypted_content = model.ciphertext_for(attribute_name)
<del> assert_not_equal expected_value, encrypted_content
<del> assert_equal expected_value, model.public_send(attribute_name)
<del> assert_equal expected_value, model.reload.public_send(attribute_name) unless model.new_record?
<del> end
<del>
<del> def assert_invalid_key_cant_read_attribute(model, attribute_name)
<del> if model.type_for_attribute(attribute_name).key_provider.present?
<del> assert_invalid_key_cant_read_attribute_with_custom_key_provider(model, attribute_name)
<del> else
<del> assert_invalid_key_cant_read_attribute_with_default_key_provider(model, attribute_name)
<add>module ActiveRecord::Encryption
<add> module EncryptionHelpers
<add> def assert_encrypted_attribute(model, attribute_name, expected_value)
<add> encrypted_content = model.ciphertext_for(attribute_name)
<add> assert_not_equal expected_value, encrypted_content
<add> assert_equal expected_value, model.public_send(attribute_name)
<add> assert_equal expected_value, model.reload.public_send(attribute_name) unless model.new_record?
<ide> end
<del> end
<del>
<del> def assert_not_encrypted_attribute(model, attribute_name, expected_value)
<del> assert_equal expected_value, model.send(attribute_name)
<del> assert_equal expected_value, model.ciphertext_for(attribute_name)
<del> end
<del>
<del> def assert_encrypted_record(model)
<del> encrypted_attributes = model.class.encrypted_attributes.find_all { |attribute_name| model.send(attribute_name).present? }
<del> assert_not encrypted_attributes.empty?, "The model has no encrypted attributes with content to check (they are all blank)"
<ide>
<del> encrypted_attributes.each do |attribute_name|
<del> assert_encrypted_attribute model, attribute_name, model.send(attribute_name)
<add> def assert_invalid_key_cant_read_attribute(model, attribute_name)
<add> if model.type_for_attribute(attribute_name).key_provider.present?
<add> assert_invalid_key_cant_read_attribute_with_custom_key_provider(model, attribute_name)
<add> else
<add> assert_invalid_key_cant_read_attribute_with_default_key_provider(model, attribute_name)
<add> end
<ide> end
<del> end
<ide>
<del> def assert_encryptor_works_with(key_provider)
<del> encryptor = ActiveRecord::Encryption::Encryptor.new
<add> def assert_not_encrypted_attribute(model, attribute_name, expected_value)
<add> assert_equal expected_value, model.send(attribute_name)
<add> assert_equal expected_value, model.ciphertext_for(attribute_name)
<add> end
<ide>
<del> encrypted_message = encryptor.encrypt("some text", key_provider: key_provider)
<del> assert_equal "some text", encryptor.decrypt(encrypted_message, key_provider: key_provider)
<del> end
<add> def assert_encrypted_record(model)
<add> encrypted_attributes = model.class.encrypted_attributes.find_all { |attribute_name| model.send(attribute_name).present? }
<add> assert_not encrypted_attributes.empty?, "The model has no encrypted attributes with content to check (they are all blank)"
<ide>
<del> private
<del> def build_keys(count = 3)
<del> count.times.collect do |index|
<del> password = "some secret #{index}"
<del> secret = ActiveRecord::Encryption.key_generator.derive_key_from(password)
<del> ActiveRecord::Encryption::Key.new(secret)
<add> encrypted_attributes.each do |attribute_name|
<add> assert_encrypted_attribute model, attribute_name, model.send(attribute_name)
<ide> end
<ide> end
<ide>
<del> def with_key_provider(key_provider, &block)
<del> ActiveRecord::Encryption.with_encryption_context key_provider: key_provider, &block
<del> end
<add> def assert_encryptor_works_with(key_provider)
<add> encryptor = ActiveRecord::Encryption::Encryptor.new
<ide>
<del> def with_envelope_encryption(&block)
<del> @envelope_encryption_key_provider ||= ActiveRecord::Encryption::EnvelopeEncryptionKeyProvider.new
<del> with_key_provider @envelope_encryption_key_provider, &block
<add> encrypted_message = encryptor.encrypt("some text", key_provider: key_provider)
<add> assert_equal "some text", encryptor.decrypt(encrypted_message, key_provider: key_provider)
<ide> end
<ide>
<del> def create_unencrypted_book_ignoring_case(name:)
<del> book = ActiveRecord::Encryption.without_encryption do
<del> EncryptedBookThatIgnoresCase.create!(name: name)
<add> private
<add> def build_keys(count = 3)
<add> count.times.collect do |index|
<add> password = "some secret #{index}"
<add> secret = ActiveRecord::Encryption.key_generator.derive_key_from(password)
<add> ActiveRecord::Encryption::Key.new(secret)
<add> end
<add> end
<add>
<add> def with_key_provider(key_provider, &block)
<add> ActiveRecord::Encryption.with_encryption_context key_provider: key_provider, &block
<ide> end
<ide>
<del> # Skip type casting to simulate an upcase value. Not supported in AR without using private apis
<del> EncryptedBookThatIgnoresCase.connection.execute <<~SQL
<del> UPDATE books SET name = '#{name}' WHERE id = #{book.id};
<del> SQL
<add> def with_envelope_encryption(&block)
<add> @envelope_encryption_key_provider ||= ActiveRecord::Encryption::EnvelopeEncryptionKeyProvider.new
<add> with_key_provider @envelope_encryption_key_provider, &block
<add> end
<ide>
<del> book.reload
<del> end
<add> def create_unencrypted_book_ignoring_case(name:)
<add> book = ActiveRecord::Encryption.without_encryption do
<add> EncryptedBookThatIgnoresCase.create!(name: name)
<add> end
<ide>
<del> def assert_invalid_key_cant_read_attribute_with_default_key_provider(model, attribute_name)
<del> model.reload
<add> # Skip type casting to simulate an upcase value. Not supported in AR without using private apis
<add> EncryptedBookThatIgnoresCase.connection.execute <<~SQL
<add> UPDATE books SET name = '#{name}' WHERE id = #{book.id};
<add> SQL
<ide>
<del> ActiveRecord::Encryption.with_encryption_context key_provider: ActiveRecord::Encryption::DerivedSecretKeyProvider.new("a different 256 bits key for now") do
<del> assert_raises ActiveRecord::Encryption::Errors::Decryption do
<del> model.public_send(attribute_name)
<add> book.reload
<add> end
<add>
<add> def assert_invalid_key_cant_read_attribute_with_default_key_provider(model, attribute_name)
<add> model.reload
<add>
<add> ActiveRecord::Encryption.with_encryption_context key_provider: ActiveRecord::Encryption::DerivedSecretKeyProvider.new("a different 256 bits key for now") do
<add> assert_raises ActiveRecord::Encryption::Errors::Decryption do
<add> model.public_send(attribute_name)
<add> end
<ide> end
<ide> end
<del> end
<ide>
<del> def assert_invalid_key_cant_read_attribute_with_custom_key_provider(model, attribute_name)
<del> attribute_type = model.type_for_attribute(attribute_name)
<add> def assert_invalid_key_cant_read_attribute_with_custom_key_provider(model, attribute_name)
<add> attribute_type = model.type_for_attribute(attribute_name)
<ide>
<del> model.reload
<add> model.reload
<ide>
<del> attribute_type.key_provider.key = ActiveRecord::Encryption::Key.derive_from "other custom attribute secret"
<add> attribute_type.key_provider.key = ActiveRecord::Encryption::Key.derive_from "other custom attribute secret"
<ide>
<del> assert_raises ActiveRecord::Encryption::Errors::Decryption do
<del> model.public_send(attribute_name)
<add> assert_raises ActiveRecord::Encryption::Errors::Decryption do
<add> model.public_send(attribute_name)
<add> end
<ide> end
<del> end
<del>end
<add> end
<ide>
<del>module PerformanceHelpers
<del> BENCHMARK_DURATION = 1
<del> BENCHMARK_WARMUP = 1
<del> BASELINE_LABEL = "Baseline"
<del> CODE_TO_TEST_LABEL = "Code"
<del>
<del>
<del> # Usage:
<del> #
<del> # baseline = -> { <some baseline code> }
<del> #
<del> # assert_slower_by_at_most 2, baseline: baseline do
<del> # <the code you want to compare against the baseline>
<del> # end
<del> def assert_slower_by_at_most(threshold_factor, baseline:, baseline_label: BASELINE_LABEL, code_to_test_label: CODE_TO_TEST_LABEL, duration: BENCHMARK_DURATION, &block_to_test)
<del> GC.start
<del>
<del> result = Benchmark.ips do |x|
<del> x.config(time: duration, warmup: BENCHMARK_WARMUP)
<del> x.report(code_to_test_label, &block_to_test)
<del> x.report(baseline_label, &baseline)
<del> x.compare!
<del> end
<add> module PerformanceHelpers
<add> BENCHMARK_DURATION = 1
<add> BENCHMARK_WARMUP = 1
<add> BASELINE_LABEL = "Baseline"
<add> CODE_TO_TEST_LABEL = "Code"
<add>
<add> # Usage:
<add> #
<add> # baseline = -> { <some baseline code> }
<add> #
<add> # assert_slower_by_at_most 2, baseline: baseline do
<add> # <the code you want to compare against the baseline>
<add> # end
<add> def assert_slower_by_at_most(threshold_factor, baseline:, baseline_label: BASELINE_LABEL, code_to_test_label: CODE_TO_TEST_LABEL, duration: BENCHMARK_DURATION, &block_to_test)
<add> GC.start
<add>
<add> result = Benchmark.ips do |x|
<add> x.config(time: duration, warmup: BENCHMARK_WARMUP)
<add> x.report(code_to_test_label, &block_to_test)
<add> x.report(baseline_label, &baseline)
<add> x.compare!
<add> end
<ide>
<del> baseline_result = result.entries.find { |entry| entry.label == baseline_label }
<del> code_to_test_result = result.entries.find { |entry| entry.label == code_to_test_label }
<add> baseline_result = result.entries.find { |entry| entry.label == baseline_label }
<add> code_to_test_result = result.entries.find { |entry| entry.label == code_to_test_label }
<ide>
<del> times_slower = baseline_result.ips / code_to_test_result.ips
<add> times_slower = baseline_result.ips / code_to_test_result.ips
<ide>
<del> assert times_slower < threshold_factor, "Expecting #{threshold_factor} times slower at most, but got #{times_slower} times slower"
<add> assert times_slower < threshold_factor, "Expecting #{threshold_factor} times slower at most, but got #{times_slower} times slower"
<add> end
<ide> end
<ide> end
<ide>
<ide> class ActiveRecord::TestCase
<del> include EncryptionHelpers, PerformanceHelpers
<add> include ActiveRecord::Encryption::EncryptionHelpers, ActiveRecord::Encryption::PerformanceHelpers
<ide> #, PerformanceHelpers
<ide>
<ide> ENCRYPTION_ERROR_FLAGS = %i[ master_key store_key_references key_derivation_salt support_unencrypted_data
<ide><path>activerecord/test/cases/encryption/performance/extended_deterministic_queries_performance_test.rb
<ide> require "cases/encryption/helper"
<ide> require "models/book"
<ide>
<del>class ExtendedDeterministicQueriesPerformanceTest < ActiveRecord::TestCase
<add>class ActiveRecord::Encryption::ExtendedDeterministicQueriesPerformanceTest < ActiveRecord::TestCase
<ide> # TODO: Is this failing only with SQLite/in memory adapter?
<ide> test "finding with prepared statement caching by deterministically encrypted columns" do
<ide> baseline = -> { EncryptedBook.find_by(format: "paperback") } # not encrypted
<ide><path>activerecord/test/cases/encryption/properties_test.rb
<ide> require "cases/encryption/helper"
<ide>
<del>module ActiveRecord::Encryption
<del> class PropertiesTest < ActiveSupport::TestCase
<del> setup do
<del> @properties = ActiveRecord::Encryption::Properties.new
<del> end
<add>class ActiveRecord::EncryptionPropertiesTest < ActiveSupport::TestCase
<add> setup do
<add> @properties = ActiveRecord::Encryption::Properties.new
<add> end
<ide>
<del> test "behaves like a hash" do
<del> @properties[:key_1] = "value 1"
<del> @properties[:key_2] = "value 2"
<add> test "behaves like a hash" do
<add> @properties[:key_1] = "value 1"
<add> @properties[:key_2] = "value 2"
<ide>
<del> assert_equal "value 1", @properties[:key_1]
<del> assert_equal "value 2", @properties[:key_2]
<del> end
<add> assert_equal "value 1", @properties[:key_1]
<add> assert_equal "value 2", @properties[:key_2]
<add> end
<ide>
<del> test "defines custom accessors for some default properties" do
<del> auth_tag = "some auth tag"
<add> test "defines custom accessors for some default properties" do
<add> auth_tag = "some auth tag"
<ide>
<del> @properties.auth_tag = auth_tag
<del> assert_equal auth_tag, @properties.auth_tag
<del> assert_equal auth_tag, @properties[:at]
<del> end
<add> @properties.auth_tag = auth_tag
<add> assert_equal auth_tag, @properties.auth_tag
<add> assert_equal auth_tag, @properties[:at]
<add> end
<ide>
<del> test "raises EncryptedContentIntegrity when trying to override properties" do
<del> @properties[:key_1] = "value 1"
<add> test "raises EncryptedContentIntegrity when trying to override properties" do
<add> @properties[:key_1] = "value 1"
<ide>
<del> assert_raises ActiveRecord::Encryption::Errors::EncryptedContentIntegrity do
<del> @properties[:key_1] = "value 1"
<del> end
<add> assert_raises ActiveRecord::Encryption::Errors::EncryptedContentIntegrity do
<add> @properties[:key_1] = "value 1"
<ide> end
<add> end
<ide>
<del> test "add will add all the properties passed" do
<del> @properties.add(key_1: "value 1", key_2: "value 2")
<add> test "add will add all the properties passed" do
<add> @properties.add(key_1: "value 1", key_2: "value 2")
<ide>
<del> assert_equal "value 1", @properties[:key_1]
<del> assert_equal "value 2", @properties[:key_2]
<del> end
<add> assert_equal "value 1", @properties[:key_1]
<add> assert_equal "value 2", @properties[:key_2]
<add> end
<ide>
<del> test "validate allowed types on creation" do
<del> example_of_valid_values.each do |value|
<del> ActiveRecord::Encryption::Properties.new(some_value: value)
<del> end
<add> test "validate allowed types on creation" do
<add> example_of_valid_values.each do |value|
<add> ActiveRecord::Encryption::Properties.new(some_value: value)
<add> end
<ide>
<del> assert_raises ActiveRecord::Encryption::Errors::ForbiddenClass do
<del> ActiveRecord::Encryption::Properties.new(my_class: MyClass.new)
<del> end
<add> assert_raises ActiveRecord::Encryption::Errors::ForbiddenClass do
<add> ActiveRecord::Encryption::Properties.new(my_class: MyClass.new)
<ide> end
<add> end
<ide>
<del> test "validate allowed_types setting headers" do
<del> example_of_valid_values.each.with_index do |value, index|
<del> @properties["some_value_#{index}"] = value
<del> end
<add> test "validate allowed_types setting headers" do
<add> example_of_valid_values.each.with_index do |value, index|
<add> @properties["some_value_#{index}"] = value
<add> end
<ide>
<del> assert_raises ActiveRecord::Encryption::Errors::ForbiddenClass do
<del> @properties["some_value"] = MyClass.new
<del> end
<add> assert_raises ActiveRecord::Encryption::Errors::ForbiddenClass do
<add> @properties["some_value"] = MyClass.new
<ide> end
<add> end
<ide>
<del> MyClass = Struct.new(:some_value)
<add> MyClass = Struct.new(:some_value)
<ide>
<del> def example_of_valid_values
<del> [ "a string", 123, 123.5, true, false, nil, :a_symbol, ActiveRecord::Encryption::Message.new ]
<del> end
<add> def example_of_valid_values
<add> ["a string", 123, 123.5, true, false, nil, :a_symbol, ActiveRecord::Encryption::Message.new]
<ide> end
<ide> end | 9 |
Text | Text | use vercel.app for blog starter url | 817cffdcbe6149b78d52a43d6d28da3b0e4ab3dd | <ide><path>docs/basic-features/data-fetching.md
<ide> description: 'Next.js has 2 pre-rendering modes: Static Generation and Server-si
<ide> <summary><b>Examples</b></summary>
<ide> <ul>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress">WordPress Example</a> (<a href="https://next-blog-wordpress.now.sh">Demo</a>)</li>
<del> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/blog-starter">Blog Starter using markdown files</a> (<a href="https://next-blog-starter.now.sh/">Demo</a>)</li>
<add> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/blog-starter">Blog Starter using markdown files</a> (<a href="https://next-blog-starter.vercel.app/">Demo</a>)</li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-datocms">DatoCMS Example</a> (<a href="https://next-blog-datocms.now.sh/">Demo</a>)</li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-takeshape">TakeShape Example</a> (<a href="https://next-blog-takeshape.now.sh/">Demo</a>)</li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-sanity">Sanity Example</a> (<a href="https://next-blog-sanity.now.sh/">Demo</a>)</li>
<ide><path>docs/basic-features/pages.md
<ide> You can also use **Client-side Rendering** along with Static Generation or Serve
<ide> <summary><b>Examples</b></summary>
<ide> <ul>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress">WordPress Example</a> (<a href="https://next-blog-wordpress.now.sh">Demo</a>)</li>
<del> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/blog-starter">Blog Starter using markdown files</a> (<a href="https://next-blog-starter.now.sh/">Demo</a>)</li>
<add> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/blog-starter">Blog Starter using markdown files</a> (<a href="https://next-blog-starter.vercel.app/">Demo</a>)</li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-datocms">DatoCMS Example</a> (<a href="https://next-blog-datocms.now.sh/">Demo</a>)</li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-takeshape">TakeShape Example</a> (<a href="https://next-blog-takeshape.now.sh/">Demo</a>)</li>
<ide> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/cms-sanity">Sanity Example</a> (<a href="https://next-blog-sanity.now.sh/">Demo</a>)</li>
<ide><path>examples/blog-starter/README.md
<ide> To create the blog posts we use [`remark`](https://github.com/remarkjs/remark) a
<ide>
<ide> ## Demo
<ide>
<del>[https://next-blog-starter.now.sh/](https://next-blog-starter.now.sh/)
<add>[https://next-blog-starter.vercel.app/](https://next-blog-starter.vercel.app/)
<ide>
<ide> ## Deploy your own
<ide> | 3 |
Text | Text | use shields.io image | 18c93912180aa93d1120495d4f7e47d7bed025f4 | <ide><path>README.md
<ide> Send a description of the issue via email to [rest-framework-security@googlegrou
<ide>
<ide> [build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.svg?branch=master
<ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
<del>[coverage-status-image]: http://codecov.io/github/tomchristie/django-rest-framework/coverage.svg?branch=master
<del>[codecov]: https://img.shields.io/codecov/c/github/tomchristie/django-rest-framework/master.svg
<add>[coverage-status-image]: https://img.shields.io/codecov/c/github/tomchristie/django-rest-framework/master.svg
<add>[codecov]: http://codecov.io/github/tomchristie/django-rest-framework?branch=master
<ide> [pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
<ide> [pypi]: https://pypi.python.org/pypi/djangorestframework
<ide> [twitter]: https://twitter.com/_tomchristie | 1 |
Java | Java | support multiple sources | c61aafe95db4ad26b78650c4156250a6e730f736 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawImage.java
<ide> import android.content.Context;
<ide>
<ide> import com.facebook.drawee.drawable.ScalingUtils.ScaleType;
<add>import com.facebook.react.bridge.ReadableArray;
<ide>
<ide> /**
<ide> * Common interface for DrawImageWithPipeline and DrawImageWithDrawee.
<ide> /**
<ide> * Assigns a new image source to the DrawImage, or null to clear the image request.
<ide> */
<del> void setSource(Context context, @Nullable String source);
<add> void setSource(Context context, @Nullable ReadableArray sources);
<ide>
<ide> /**
<ide> * Assigns a tint color to apply to the image drawn.
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawImageWithDrawee.java
<ide>
<ide> import javax.annotation.Nullable;
<ide>
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>
<ide> import android.content.Context;
<ide> import android.graphics.Canvas;
<ide> import android.graphics.PorterDuff;
<ide> import com.facebook.drawee.generic.RoundingParams;
<ide> import com.facebook.imagepipeline.request.ImageRequest;
<ide> import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.bridge.ReadableArray;
<add>import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.views.image.ImageLoadEvent;
<ide> import com.facebook.react.views.image.ImageResizeMode;
<ide> import com.facebook.react.views.image.ReactImageView;
<ide> /* package */ final class DrawImageWithDrawee extends AbstractDrawCommand
<ide> implements DrawImage, ControllerListener {
<ide>
<del> private @Nullable String mSource;
<add> private @Nullable Map<String, Double> mSources;
<add> private @Nullable String mImageSource;
<ide> private @Nullable Context mContext;
<ide> private @Nullable DraweeRequestHelper mRequestHelper;
<ide> private @Nullable PorterDuffColorFilter mColorFilter;
<ide>
<ide> @Override
<ide> public boolean hasImageRequest() {
<del> return mSource != null;
<add> return mSources != null && !mSources.isEmpty();
<ide> }
<ide>
<ide> @Override
<del> public void setSource(Context context, @Nullable String source) {
<del> mSource = source;
<add> public void setSource(Context context, @Nullable ReadableArray sources) {
<add> if (mSources == null) {
<add> mSources = new HashMap<>();
<add> }
<add> mSources.clear();
<add> if (sources != null && sources.size() != 0) {
<add> // Optimize for the case where we have just one uri, case in which we don't need the sizes
<add> if (sources.size() == 1) {
<add> mSources.put(sources.getMap(0).getString("uri"), 0.0d);
<add> } else {
<add> for (int idx = 0; idx < sources.size(); idx++) {
<add> ReadableMap source = sources.getMap(idx);
<add> mSources.put(
<add> source.getString("uri"),
<add> source.getDouble("width") * source.getDouble("height"));
<add> }
<add> }
<add> }
<ide> mContext = context;
<ide> }
<ide>
<ide> public void onRelease(String id) {
<ide> @Override
<ide> protected void onBoundsChanged() {
<ide> super.onBoundsChanged();
<del> maybeComputeRequestHelper();
<add> computeRequestHelper();
<ide> }
<ide>
<del> private void maybeComputeRequestHelper() {
<del> if (mRequestHelper != null) {
<del> return;
<del> }
<del>
<del> if (mSource == null) {
<add> private void computeRequestHelper() {
<add> mImageSource = getSourceImage();
<add> if (mImageSource == null) {
<ide> mRequestHelper = null;
<ide> return;
<ide> }
<ide> ImageRequest imageRequest =
<del> ImageRequestHelper.createImageRequest(Assertions.assertNotNull(mContext), mSource);
<add> ImageRequestHelper.createImageRequest(Assertions.assertNotNull(mContext),
<add> mImageSource);
<ide> mRequestHelper = new DraweeRequestHelper(Assertions.assertNotNull(imageRequest), this);
<ide> }
<ide>
<add> private @Nullable String getSourceImage() {
<add> if (mSources == null || mSources.isEmpty()) {
<add> return null;
<add> }
<add> if (hasMultipleSources()) {
<add> final double targetImageSize = (getRight() - getLeft()) * (getBottom() - getTop());
<add> return MultiSourceImageHelper.getImageSourceFromMultipleSources(targetImageSize, mSources);
<add> }
<add> return mSources.keySet().iterator().next();
<add> }
<add>
<add> private boolean hasMultipleSources() {
<add> return Assertions.assertNotNull(mSources).size() > 1;
<add> }
<add>
<ide> private boolean shouldDisplayBorder() {
<ide> return mBorderColor != 0 || mBorderRadius >= 0.5f;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawImageWithPipeline.java
<ide>
<ide> import javax.annotation.Nullable;
<ide>
<add>import java.util.HashMap;
<add>import java.util.Map;
<add>
<ide> import android.content.Context;
<ide> import android.graphics.Bitmap;
<ide> import android.graphics.BitmapShader;
<ide> import com.facebook.drawee.drawable.ScalingUtils.ScaleType;
<ide> import com.facebook.imagepipeline.request.ImageRequest;
<ide> import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.bridge.ReadableArray;
<add>import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.views.image.ImageResizeMode;
<ide> import com.facebook.react.views.image.ReactImageView;
<ide>
<ide> private static final Paint PAINT = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
<ide> private static final int BORDER_BITMAP_PATH_DIRTY = 1 << 1;
<ide>
<del> private @Nullable String mSource;
<add> private @Nullable Map<String, Double> mSources;
<add> private @Nullable String mImageSource;
<ide> private @Nullable Context mContext;
<ide> private final Matrix mTransform = new Matrix();
<ide> private ScaleType mScaleType = ImageResizeMode.defaultValue();
<ide> public boolean hasImageRequest() {
<ide> }
<ide>
<ide> @Override
<del> public void setSource(Context context, @Nullable String source) {
<del> mSource = source;
<add> public void setSource(Context context, @Nullable ReadableArray sources) {
<add> if (mSources == null) {
<add> mSources = new HashMap<>();
<add> }
<add> mSources.clear();
<add> if (sources != null && sources.size() != 0) {
<add> // Optimize for the case where we have just one uri, case in which we don't need the sizes
<add> if (sources.size() == 1) {
<add> mSources.put(sources.getMap(0).getString("uri"), 0.0d);
<add> } else {
<add> for (int idx = 0; idx < sources.size(); idx++) {
<add> ReadableMap source = sources.getMap(idx);
<add> mSources.put(
<add> source.getString("uri"),
<add> source.getDouble("width") * source.getDouble("height"));
<add> }
<add> }
<add> }
<ide> mContext = context;
<ide> mBitmapShader = null;
<ide> }
<ide> public void onDetached() {
<ide> protected void onBoundsChanged() {
<ide> super.onBoundsChanged();
<ide> setFlag(BORDER_BITMAP_PATH_DIRTY);
<del> maybeComputeRequestHelper();
<add> computeRequestHelper();
<ide> }
<ide>
<ide> @Override
<ide> public void onImageLoadEvent(int imageLoadEvent) {
<ide> }
<ide> }
<ide>
<del> private void maybeComputeRequestHelper() {
<del> if (mRequestHelper == null) {
<del> return;
<del> }
<del>
<del> if (mSource == null) {
<add> private void computeRequestHelper() {
<add> mImageSource = getSourceImage();
<add> if (mImageSource == null) {
<ide> mRequestHelper = null;
<ide> return;
<ide> }
<ide> ImageRequest imageRequest =
<del> ImageRequestHelper.createImageRequest(Assertions.assertNotNull(mContext), mSource);
<add> ImageRequestHelper.createImageRequest(Assertions.assertNotNull(mContext),
<add> mImageSource);
<ide> mRequestHelper = new PipelineRequestHelper(Assertions.assertNotNull(imageRequest));
<ide> }
<ide>
<add> private String getSourceImage() {
<add> if (mSources == null || mSources.isEmpty()) {
<add> return null;
<add> }
<add> if (hasMultipleSources()) {
<add> final double targetImageSize = (getRight() - getLeft()) * (getBottom() - getTop());
<add> return MultiSourceImageHelper.getImageSourceFromMultipleSources(targetImageSize, mSources);
<add> }
<add> return mSources.keySet().iterator().next();
<add> }
<add>
<add> private boolean hasMultipleSources() {
<add> return Assertions.assertNotNull(mSources).size() > 1;
<add> }
<add>
<ide> /* package */ void updateBounds(Bitmap bitmap) {
<ide> Assertions.assumeNotNull(mCallback).invalidate();
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/MultiSourceImageHelper.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import java.util.Map;
<add>
<add>/**
<add> * Helper class for computing the source to be used for an Image.
<add> */
<add>/* package */ class MultiSourceImageHelper {
<add>
<add> /**
<add> * Chooses the image source with the size closest to the target image size. Must be called only
<add> * after the layout pass when the sizes of the target image have been computed, and when there
<add> * are at least two sources to choose from.
<add> */
<add> public static @Nullable String getImageSourceFromMultipleSources(
<add> double targetImageSize,
<add> Map<String, Double> sources) {
<add> double bestPrecision = Double.MAX_VALUE;
<add> String imageSource = null;
<add> for (Map.Entry<String, Double> source : sources.entrySet()) {
<add> final double precision = Math.abs(1.0 - (source.getValue()) / targetImageSize);
<add> if (precision < bestPrecision) {
<add> bestPrecision = precision;
<add> imageSource = source.getKey();
<add> }
<add> }
<add> return imageSource;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTImageView.java
<ide> public void setShouldNotifyLoadEvents(boolean shouldNotifyLoadEvents) {
<ide>
<ide> @ReactProp(name = "src")
<ide> public void setSource(@Nullable ReadableArray sources) {
<del> final String source =
<del> (sources == null || sources.size() == 0) ? null : sources.getMap(0).getString("uri");
<del> getMutableDrawImage().setSource(getThemedContext(), source);
<add> getMutableDrawImage().setSource(getThemedContext(), sources);
<ide> }
<ide>
<ide> @ReactProp(name = "tintColor") | 5 |
Javascript | Javascript | reduce sortableset memory consumption | a4fec7932e45ad357ca44ae869f7f9c29c926e2e | <ide><path>lib/util/SortableSet.js
<ide> "use strict";
<ide>
<del>module.exports = class SortableSet extends Set {
<add>class SortableSet extends Set {
<ide>
<ide> constructor(initialIterable, defaultSort) {
<ide> super(initialIterable);
<ide> this._sortFn = defaultSort;
<ide> this._lastActiveSortFn = null;
<del> this._cache = null;
<del> this._cacheOrderIndependent = null;
<add> this._cache = undefined;
<add> this._cacheOrderIndependent = undefined;
<ide> }
<ide>
<ide> /**
<ide> module.exports = class SortableSet extends Set {
<ide> */
<ide> add(value) {
<ide> this._lastActiveSortFn = null;
<del> this._cache = null;
<del> this._cacheOrderIndependent = null;
<add> this._invalidateCache();
<add> this._invalidateOrderedCache();
<ide> super.add(value);
<ide> return this;
<ide> }
<ide>
<ide> delete(value) {
<del> this._cache = null;
<del> this._cacheOrderIndependent = null;
<add> this._invalidateCache();
<add> this._invalidateOrderedCache();
<ide> return super.delete(value);
<ide> }
<ide>
<ide> clear() {
<del> this._cache = null;
<del> this._cacheOrderIndependent = null;
<add> this._invalidateCache();
<add> this._invalidateOrderedCache();
<ide> return super.clear();
<ide> }
<ide>
<ide> module.exports = class SortableSet extends Set {
<ide> super.add(sortedArray[i]);
<ide> }
<ide> this._lastActiveSortFn = sortFn;
<del> this._cache = null;
<add> this._invalidateCache();
<ide> }
<ide>
<ide> /**
<ide> module.exports = class SortableSet extends Set {
<ide> * @returns {any} - returns result of fn(this), cached until set changes
<ide> */
<ide> getFromCache(fn) {
<del> if(this._cache === null) {
<add> if(this._cache === undefined) {
<ide> this._cache = new Map();
<ide> } else {
<ide> const data = this._cache.get(fn);
<ide> module.exports = class SortableSet extends Set {
<ide> this._cache.set(fn, newData);
<ide> return newData;
<ide> }
<add>
<ide> /**
<ide> * @param {Function} fn - function to calculate value
<ide> * @returns {any} - returns result of fn(this), cached until set changes
<ide> */
<ide> getFromUnorderedCache(fn) {
<del> if(this._cacheOrderIndependent === null) {
<add> if(this._cacheOrderIndependent === undefined) {
<ide> this._cacheOrderIndependent = new Map();
<ide> } else {
<ide> const data = this._cacheOrderIndependent.get(fn);
<ide> module.exports = class SortableSet extends Set {
<ide> this._cacheOrderIndependent.set(fn, newData);
<ide> return newData;
<ide> }
<del>};
<add>
<add> _invalidateCache() {
<add> if(this._cache !== undefined)
<add> this._cache.clear();
<add> }
<add>
<add> _invalidateOrderedCache() {
<add> if(this._cacheOrderIndependent !== undefined)
<add> this._cacheOrderIndependent.clear();
<add> }
<add>}
<add>
<add>module.exports = SortableSet; | 1 |
Javascript | Javascript | fix jpx colors | 9457095c9c89b7362b4847b83449719b374547cb | <ide><path>src/core/jpx.js
<ide> var JpxImage = (function JpxImageClosure() {
<ide> 'HL': 1,
<ide> 'HH': 2
<ide> };
<add> var TransformType = {
<add> IRREVERSIBLE: 0,
<add> REVERSIBLE: 1
<add> };
<ide> function JpxImage() {
<ide> this.failOnCorruptedImage = false;
<ide> }
<ide> var JpxImage = (function JpxImageClosure() {
<ide> function copyCoefficients(coefficients, x0, y0, width, height,
<ide> delta, mb, codeblocks, transformation,
<ide> segmentationSymbolUsed) {
<del> var r = 0.5; // formula (E-6)
<ide> for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
<ide> var codeblock = codeblocks[i];
<ide> var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide>
<ide> var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
<del> var position = 0;
<add> var n, nb, correction, position = 0;
<add> var irreversible = (transformation === TransformType.IRREVERSIBLE);
<add> var sign = bitModel.coefficentsSign;
<add> var magnitude = bitModel.coefficentsMagnitude;
<add> var bitsDecoded = bitModel.bitsDecoded;
<ide> for (var j = 0; j < blockHeight; j++) {
<ide> for (var k = 0; k < blockWidth; k++) {
<del> var n = (bitModel.coefficentsSign[position] ? -1 : 1) *
<del> bitModel.coefficentsMagnitude[position];
<del> var nb = bitModel.bitsDecoded[position], correction;
<del> if (transformation === 0 || mb > nb) {
<del> // use r only if transformation is irreversible or
<del> // not all bitplanes were decoded for reversible transformation
<del> n += n < 0 ? n - r : n > 0 ? n + r : 0;
<del> correction = 1 << (mb - nb);
<del> } else {
<del> correction = 1;
<del> }
<add> n = (sign[position] ? -1 : 1) * magnitude[position];
<add> nb = bitsDecoded[position];
<add> correction = (irreversible || mb > nb) ? 1 << (mb - nb) : 1;
<ide> coefficients[offset++] = n * correction * delta;
<ide> position++;
<ide> }
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
<ide> var precision = context.components[c].precision;
<ide>
<add> var transformation = codingStyleParameters.transformation;
<add> var transform = transformation === TransformType.IRREVERSIBLE ?
<add> new IrreversibleTransform() : new ReversibleTransform();
<add>
<ide> var subbandCoefficients = [];
<ide> var k = 0, b = 0;
<ide> for (var i = 0; i <= decompositionLevelsCount; i++) {
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var gainLog2 = SubbandsGainLog2[subband.type];
<ide>
<ide> // calulate quantization coefficient (Section E.1.1.1)
<del> var delta = Math.pow(2, (precision + gainLog2) - epsilon) *
<del> (1 + mu / 2048);
<add> var delta = transformation === TransformType.IRREVERSIBLE ?
<add> Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048) : 1;
<ide> var mb = (guardBits + epsilon - 1);
<ide>
<ide> var coefficients = new Float32Array(width * height);
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide> }
<ide>
<del> var transformation = codingStyleParameters.transformation;
<del> var transform = transformation === 0 ? new IrreversibleTransform() :
<del> new ReversibleTransform();
<ide> var result = transform.calculate(subbandCoefficients,
<ide> component.tcx0, component.tcy0);
<ide> return {
<ide> var JpxImage = (function JpxImageClosure() {
<ide>
<ide> // Section G.2.2 Inverse multi component transform
<ide> if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
<del> var y0items = result[0].items;
<del> var y1items = result[1].items;
<del> var y2items = result[2].items;
<del> for (var j = 0, jj = y0items.length; j < jj; j++) {
<del> var y0 = y0items[j], y1 = y1items[j], y2 = y2items[j];
<del> var i1 = y0 - ((y2 + y1) >> 2);
<del> y1items[j] = i1;
<del> y0items[j] = y2 + i1;
<del> y2items[j] = y1 + i1;
<add> var component0 = tile.components[0];
<add> var transformation = component0.codingStyleParameters.transformation;
<add> if (transformation === TransformType.IRREVERSIBLE) {
<add> // inverse irreversible multiple component transform
<add> var y0items = result[0].items;
<add> var y1items = result[1].items;
<add> var y2items = result[2].items;
<add> for (var j = 0, jj = y0items.length; j < jj; ++j) {
<add> var y0 = y0items[j], y1 = y1items[j], y2 = y2items[j];
<add> y0items[j] = y0 + 1.402 * y2 + 0.5;
<add> y1items[j] = y0 - 0.34413 * y1 - 0.71414 * y2 + 0.5;
<add> y2items[j] = y0 + 1.772 * y1 + 0.5;
<add> }
<add> } else {
<add> // inverse reversible multiple component transform
<add> var y0items = result[0].items;
<add> var y1items = result[1].items;
<add> var y2items = result[2].items;
<add> for (var j = 0, jj = y0items.length; j < jj; ++j) {
<add> var y0 = y0items[j], y1 = y1items[j], y2 = y2items[j];
<add> var i1 = y0 - ((y2 + y1) >> 2);
<add> y1items[j] = i1;
<add> y0items[j] = y2 + i1;
<add> y2items[j] = y1 + i1;
<add> }
<ide> }
<ide> }
<ide> | 1 |
Python | Python | set version to v2.1.0.dev0 | f55a52a2ddb8adbb2be23d0e0c77e367829a0038 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a13"
<add>__version__ = "2.1.0.dev0"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Ruby | Ruby | fix cross-references in httphelper methods | 49744bdaee899d64f8c70f65b2c1d63ace41cafa | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def define_generate_prefix(app, name)
<ide>
<ide> module HttpHelpers
<ide> # Define a route that only recognizes HTTP GET.
<del> # For supported arguments, see +match+.
<add> # For supported arguments, see <tt>Base#match</tt>.
<ide> #
<ide> # Example:
<ide> #
<ide> def get(*args, &block)
<ide> end
<ide>
<ide> # Define a route that only recognizes HTTP POST.
<del> # For supported arguments, see +match+.
<add> # For supported arguments, see <tt>Base#match</tt>.
<ide> #
<ide> # Example:
<ide> #
<ide> def post(*args, &block)
<ide> end
<ide>
<ide> # Define a route that only recognizes HTTP PUT.
<del> # For supported arguments, see +match+.
<add> # For supported arguments, see <tt>Base#match</tt>.
<ide> #
<ide> # Example:
<ide> #
<ide> def put(*args, &block)
<ide> end
<ide>
<ide> # Define a route that only recognizes HTTP PUT.
<del> # For supported arguments, see +match+.
<add> # For supported arguments, see <tt>Base#match</tt>.
<ide> #
<ide> # Example:
<ide> # | 1 |
Python | Python | import abc from collections.abc | 46e34ab4fbfa6a861920b7870e95f370df4c70bc | <ide><path>airflow/utils/email.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>import collections
<add>import collections.abc
<ide> import logging
<ide> import os
<ide> import smtplib | 1 |
Python | Python | fix pretrain script | 2ddd4288349db030e33335dfadc218b950b0e45e | <ide><path>spacy/cli/pretrain.py
<ide>
<ide> import spacy
<ide> from spacy.attrs import ID
<del>from spacy.util import minibatch_by_words, use_gpu, compounding, ensure_path
<add>from spacy.util import minibatch, minibatch_by_words, use_gpu, compounding, ensure_path
<ide> from spacy._ml import Tok2Vec, flatten, chain, zero_init, create_default_optimizer
<ide> from thinc.v2v import Affine
<ide>
<ide> def get_vectors_loss(ops, docs, prediction):
<ide> ids = ops.flatten([doc.to_array(ID).ravel() for doc in docs])
<ide> target = docs[0].vocab.vectors.data[ids]
<ide> d_scores = (prediction - target) / prediction.shape[0]
<del> loss = (d_scores**2).sum()
<add> # Don't want to return a cupy object here
<add> loss = float((d_scores**2).sum())
<ide> return loss, d_scores
<ide>
<ide>
<ide> def create_pretraining_model(nlp, tok2vec):
<ide> '''
<ide> output_size = nlp.vocab.vectors.data.shape[1]
<ide> output_layer = zero_init(Affine(output_size, drop_factor=0.0))
<add> # This is annoying, but the parser etc have the flatten step after
<add> # the tok2vec. To load the weights in cleanly, we need to match
<add> # the shape of the models' components exactly. So what we cann
<add> # "tok2vec" has to be the same set of processes as what the components do.
<add> tok2vec = chain(tok2vec, flatten)
<ide> model = chain(
<ide> tok2vec,
<del> flatten,
<ide> output_layer
<ide> )
<add> model.tok2vec = tok2vec
<ide> model.output_layer = output_layer
<ide> model.begin_training([nlp.make_doc('Give it a doc to infer shapes')])
<ide> return model
<ide> def update(self, epoch, loss, docs):
<ide> nr_iter=("Number of iterations to pretrain", "option", "i", int),
<ide> )
<ide> def pretrain(texts_loc, vectors_model, output_dir, width=128, depth=4,
<del> embed_rows=1000, dropout=0.2, nr_iter=1, seed=0):
<add> embed_rows=1000, dropout=0.2, nr_iter=10, seed=0):
<ide> """
<ide> Pre-train the 'token-to-vector' (tok2vec) layer of pipeline components,
<ide> using an approximate language-modelling objective. Specifically, we load
<ide> def pretrain(texts_loc, vectors_model, output_dir, width=128, depth=4,
<ide> file_.write(json.dumps(config))
<ide> has_gpu = prefer_gpu()
<ide> nlp = spacy.load(vectors_model)
<del> tok2vec = Tok2Vec(width, embed_rows,
<del> conv_depth=depth,
<del> pretrained_vectors=nlp.vocab.vectors.name,
<del> bilstm_depth=0, # Requires PyTorch. Experimental.
<del> cnn_maxout_pieces=2, # You can try setting this higher
<del> subword_features=True) # Set to False for character models, e.g. Chinese
<del> model = create_pretraining_model(nlp, tok2vec)
<add> model = create_pretraining_model(nlp,
<add> Tok2Vec(width, embed_rows,
<add> conv_depth=depth,
<add> pretrained_vectors=nlp.vocab.vectors.name,
<add> bilstm_depth=0, # Requires PyTorch. Experimental.
<add> cnn_maxout_pieces=2, # You can try setting this higher
<add> subword_features=True)) # Set to False for character models, e.g. Chinese
<ide> optimizer = create_default_optimizer(model.ops)
<ide> tracker = ProgressTracker()
<ide> print('Epoch', '#Words', 'Loss', 'w/s')
<ide> texts = stream_texts() if texts_loc == '-' else load_texts(texts_loc)
<ide> for epoch in range(nr_iter):
<del> for batch in minibatch_by_words(texts, tuples=False, size=50000):
<add> for batch in minibatch(texts, size=64):
<ide> docs = [nlp.make_doc(text) for text in batch]
<ide> loss = make_update(model, docs, optimizer, drop=dropout)
<ide> progress = tracker.update(epoch, loss, docs)
<ide> if progress:
<ide> print(*progress)
<del> if texts_loc == '-' and tracker.words_per_epoch[epoch] >= 10**7:
<add> if texts_loc == '-' and tracker.words_per_epoch[epoch] >= 10**6:
<ide> break
<ide> with model.use_params(optimizer.averages):
<ide> with (output_dir / ('model%d.bin' % epoch)).open('wb') as file_:
<del> file_.write(tok2vec.to_bytes())
<add> file_.write(model.tok2vec.to_bytes())
<ide> with (output_dir / 'log.jsonl').open('a') as file_:
<ide> file_.write(json.dumps({'nr_word': tracker.nr_word,
<ide> 'loss': tracker.loss, 'epoch': epoch})) | 1 |
Javascript | Javascript | use document from store context | d263ed4ed7fe2c992477889753c7ec8bc7305a27 | <ide><path>client/src/redux/createStore.js
<ide> import { isBrowser } from '../../utils';
<ide>
<ide> const clientSide = isBrowser();
<ide>
<del>const sagaMiddleware = createSagaMiddleware();
<add>const sagaMiddleware = createSagaMiddleware({
<add> context: {
<add> document: clientSide ? document : {}
<add> }
<add>});
<ide> const epicMiddleware = createEpicMiddleware({
<ide> dependencies: {
<ide> window: clientSide ? window : {},
<ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js
<ide> import {
<ide> call,
<ide> takeLatest,
<ide> takeEvery,
<del> fork
<add> fork,
<add> getContext
<ide> } from 'redux-saga/effects';
<ide> import { delay, channel } from 'redux-saga';
<ide>
<ide> function* executeJSChallengeSaga(state, proxyLogger) {
<ide> }
<ide> }
<ide>
<del>function createTestFrame(ctx, proxyLogger) {
<add>function createTestFrame(document, ctx, proxyLogger) {
<ide> return new Promise(resolve =>
<ide> createTestFramer(document, resolve, proxyLogger)(ctx)
<ide> );
<ide> }
<ide>
<ide> function* executeDOMChallengeSaga(state, proxyLogger) {
<add> const document = yield getContext('document');
<ide> const ctx = yield call(buildDOMChallenge, state);
<del> yield call(createTestFrame, ctx, proxyLogger);
<add> yield call(createTestFrame, document, ctx, proxyLogger);
<ide> // wait for a code execution on a "ready" event in jQuery challenges
<ide> yield delay(100);
<ide>
<ide> function* executeDOMChallengeSaga(state, proxyLogger) {
<ide>
<ide> // TODO: use a web worker
<ide> function* executeBackendChallengeSaga(state, proxyLogger) {
<add> const document = yield getContext('document');
<ide> const ctx = yield call(buildBackendChallenge, state);
<del> yield call(createTestFrame, ctx, proxyLogger);
<add> yield call(createTestFrame, document, ctx, proxyLogger);
<ide>
<ide> return yield call(executeTests, (testString, testTimeout) =>
<ide> runTestInTestFrame(document, testString, testTimeout)
<ide> function* updateMainSaga() {
<ide> }
<ide> const state = yield select();
<ide> const ctx = yield call(buildDOMChallenge, state);
<add> const document = yield getContext('document');
<ide> const frameMain = yield call(createMainFramer, document);
<ide> yield call(frameMain, ctx);
<ide> } catch (err) { | 2 |
Javascript | Javascript | fix finger print, remove unused code | eba8f5a22cc8997a73947ba5cc023edf8c50cc9d | <ide><path>src/worker.js
<ide> var WorkerMessageHandler = {
<ide> pdfModel = new PDFDocument(new Stream(data));
<ide> var doc = {
<ide> numPages: pdfModel.numPages,
<del> fingerprint: pdfModel.fingerprint,
<add> fingerprint: pdfModel.getFingerprint(),
<ide> destinations: pdfModel.catalog.destinations,
<ide> outline: pdfModel.catalog.documentOutline,
<ide> info: pdfModel.info,
<ide><path>web/viewer.js
<ide> var PageView = function pageView(container, pdfPage, id, scale,
<ide> }
<ide>
<ide> this.getPagePoint = function pageViewGetPagePoint(x, y) {
<del> var scale = PDFView.currentScale;
<ide> return this.viewport.convertToPdfPoint(x, y);
<ide> };
<ide> | 2 |
PHP | PHP | fix job release on exception | b27f967b43e9b1bb54fc68bb07e65023e866d0c7 | <ide><path>src/Illuminate/Queue/Worker.php
<ide> protected function handleJobException($connectionName, $job, WorkerOptions $opti
<ide> // If we catch an exception, we will attempt to release the job back onto the queue
<ide> // so it is not lost entirely. This'll let the job be retried at a later time by
<ide> // another listener (or this same one). We will re-throw this exception after.
<del> if (! $job->isDeleted()) {
<add> // Do not release the job back onto the queue if the job is either deleted, failed
<add> // or if the job has already been released from the JobExceptionOccurred event listener.
<add> if (! ($job->isReleased() || $job->isDeleted() || $job->hasFailed())) {
<ide> $job->release($options->delay);
<ide> }
<ide> }
<ide><path>tests/Queue/QueueWorkerTest.php
<ide> class WorkerFakeJob
<ide> public $callback;
<ide> public $deleted = false;
<ide> public $releaseAfter;
<add> public $released = false;
<ide> public $maxTries;
<ide> public $attempts = 0;
<ide> public $failedWith;
<add> public $failed = false;
<ide> public $connectionName;
<ide>
<ide> public function __construct($callback = null)
<ide> public function isDeleted()
<ide>
<ide> public function release($delay)
<ide> {
<add> $this->released = true;
<add>
<ide> $this->releaseAfter = $delay;
<ide> }
<ide>
<add> public function isReleased()
<add> {
<add> return $this->released;
<add> }
<add>
<ide> public function attempts()
<ide> {
<ide> return $this->attempts;
<ide> }
<ide>
<ide> public function markAsFailed()
<ide> {
<del> //
<add> $this->failed = true;
<ide> }
<ide>
<ide> public function failed($e)
<ide> {
<add> $this->markAsFailed();
<add>
<ide> $this->failedWith = $e;
<ide> }
<ide>
<add> public function hasFailed()
<add> {
<add> return $this->failed;
<add> }
<add>
<ide> public function setConnectionName($name)
<ide> {
<ide> $this->connectionName = $name; | 2 |
Java | Java | fix checkstyle violation | b5fba14ab8396fb50b9ec3e6b19dea9f1c74b350 | <ide><path>spring-test/src/test/java/org/springframework/test/context/support/TestConstructorUtilsTests.java
<ide> import org.springframework.test.context.TestConstructor;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<del>import static org.springframework.test.context.TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME;
<ide> import static org.springframework.test.context.TestConstructor.AutowireMode.ALL;
<ide> import static org.springframework.test.context.TestConstructor.AutowireMode.ANNOTATED;
<ide>
<ide> private void setGlobalFlag() {
<ide> }
<ide>
<ide> private void setGlobalFlag(String flag) {
<del> SpringProperties.setProperty(TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME, flag);
<add> SpringProperties.setProperty(TestConstructor.TEST_CONSTRUCTOR_AUTOWIRE_MODE_PROPERTY_NAME, flag);
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | use a proper lognormal cdf approximation | cdbb9b78384e9a7cfae8f26630cad322afd0d339 | <ide><path>test/math/random-test.js
<ide> var suite = vows.describe("d3.random");
<ide> * @see http://www.johndcook.com/Beautiful_Testing_ch10.pdf
<ide> */
<ide>
<del>// Arbitrarily chosen parameters for the normal RNG. It's good practice to set
<del>// |STDDEV| << |MEAN| to help catch bugs involving accidental swapping of
<del>// stddev and mean.
<del>var STDDEV = 38.8;
<del>var MEAN = -349234;
<del>
<ide> // Overwrites Math.random to a seeded random function.
<ide> // (by default Math.random is seeded with current time)
<ide> Math.seedrandom('a random seed.');
<ide> suite.addBatch({
<ide> "random": {
<ide> topic: load("math/random").expression("d3.random"),
<ide> "normal": {
<del> "topic": function(random) { return random.normal(MEAN, STDDEV); },
<add> "topic": function(random) { return random.normal(-43289, 38.8); },
<ide>
<ide> // P = 98%
<del> "has normal distribution" : KSTest(normalCDF(MEAN, STDDEV))
<add> "has normal distribution" : KSTest(normalCDF(-43289, 38.8))
<ide> },
<ide> "logNormal": {
<del> "topic": function(random) { return random.logNormal(MEAN, STDDEV); },
<add> // Use reasonable values for mean here because random.logNormal() grows
<add> // exponentially with the mean.
<add> "topic": function(random) { return random.logNormal(10, 2.5); },
<ide>
<ide> // P = 98%
<del> "has log-normal distribution" : KSTest(logNormalCDF(MEAN, STDDEV))
<add> "has log-normal distribution" : KSTest(logNormalCDF(10, 2.5))
<ide> },
<ide> "irwinHall": {
<ide> "topic": function(random) { return random.irwinHall(10); },
<ide> suite.addBatch({
<ide> });
<ide>
<ide> /**
<del> * A macro that that takes a RNG and performs a Kolmogorov-Smirnov test: asserts
<del> * that the values generated by the RNG could be generated by the distribution
<del> * with cumulative distribution function `cdf'.
<add> * A macro that that takes a RNG and performs a Kolmogorov-Smirnov test:
<add> * asserts that the values generated by the RNG could be generated by the
<add> * distribution with cumulative distribution function `cdf'. Each test runs in
<add> * O(n log n) * O(cdf).
<ide> *
<ide> * Passes with P≈98%.
<ide> *
<ide> function normalCDF(mean, stddev) {
<ide> }
<ide>
<ide> function logNormalCDF(mean, stddev) {
<del> var normal = normalCDF(1, 1);
<add> // @see http://en.wikipedia.org/wiki/Log-normal_distribution#Similar_distributions
<add> var exponent = Math.PI / (stddev * Math.sqrt(3));
<add> var numerator = Math.exp(mean);
<ide> return function(x) {
<del> return normal((Math.exp(x) - mean) / stddev);
<add> return 1 / (Math.pow(numerator / x, exponent) + 1);
<ide> }
<ide> }
<ide>
<ide> function irwinHallCDF(n) {
<del> var multiplier = 1 / factorial(n);
<add> var normalisingFactor = factorial(n);
<ide>
<ide> // Precompute binom(n, k), k=0..n for efficiency. (this array gets stored
<ide> // inside the closure, so it is only computed once) | 1 |
PHP | PHP | make contains() non-recursive | 885d5dfd802a699fbb2f4813f64cebb1815307a9 | <ide><path>lib/Cake/Test/Case/Utility/Set2Test.php
<ide> public function testNormalize() {
<ide> */
<ide> public function testContains() {
<ide> $data = array('apple', 'bee', 'cyclops');
<del> // $this->assertTrue(Set2::contains($data, array('apple')));
<del> // $this->assertFalse(Set2::contains($data, array('data')));
<add> $this->assertTrue(Set2::contains($data, array('apple')));
<add> $this->assertFalse(Set2::contains($data, array('data')));
<ide>
<ide> $a = array(
<ide> 0 => array('name' => 'main'),
<ide> public function testContains() {
<ide> $this->assertTrue(Set2::contains($a, $a));
<ide> $this->assertFalse(Set2::contains($a, $b));
<ide> $this->assertTrue(Set2::contains($b, $a));
<add>
<add> $a = array(
<add> array('User' => array('id' => 1)),
<add> array('User' => array('id' => 2)),
<add> );
<add> $b = array(
<add> array('User' => array('id' => 1)),
<add> array('User' => array('id' => 2)),
<add> array('User' => array('id' => 3))
<add> );
<add> $this->assertTrue(Set2::contains($b, $a));
<add> $this->assertFalse(Set2::contains($a, $b));
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Utility/Set2.php
<ide> public static function contains(array $data, array $needle) {
<ide> if (empty($data) || empty($needle)) {
<ide> return false;
<ide> }
<add> $stack = array();
<add>
<add> $i = 1;
<add> while (!empty($needle)) {
<add> $key = key($needle);
<add> $val = $needle[$key];
<add> unset($needle[$key]);
<ide>
<del> foreach ($needle as $key => $val) {
<ide> if (isset($data[$key]) && is_array($val)) {
<del> if (!Set2::contains($data[$key], $val)) {
<del> return false;
<add> $next = $data[$key];
<add> unset($data[$key]);
<add>
<add> if (!empty($val)) {
<add> $stack[] = array($val, $next);
<ide> }
<ide> } elseif (!isset($data[$key]) || $data[$key] != $val) {
<ide> return false;
<ide> }
<add>
<add> if (empty($needle) && !empty($stack)) {
<add> list($needle, $data) = array_pop($stack);
<add> }
<ide> }
<ide> return true;
<ide> } | 2 |
Text | Text | update examples in builder.md | 744cf2c9718a43aad21c6dee53a07856ef06fc79 | <ide><path>docs/reference/builder.md
<ide> of this dockerfile is that second and third lines are considered a single
<ide> instruction:
<ide>
<ide> ```Dockerfile
<del>FROM windowsservercore
<add>FROM microsoft/nanoserver
<ide> COPY testfile.txt c:\\
<ide> RUN dir c:\
<ide> ```
<ide> Results in:
<ide>
<ide> PS C:\John> docker build -t cmd .
<ide> Sending build context to Docker daemon 3.072 kB
<del> Step 1 : FROM windowsservercore
<del> ---> dbfee88ee9fd
<del> Step 2 : COPY testfile.txt c:RUN dir c:
<add> Step 1/2 : FROM microsoft/nanoserver
<add> ---> 22738ff49c6d
<add> Step 2/2 : COPY testfile.txt c:\RUN dir c:
<ide> GetFileAttributesEx c:RUN: The system cannot find the file specified.
<ide> PS C:\John>
<ide>
<ide> expected with the use of natural platform semantics for file paths on `Windows`:
<ide>
<ide> # escape=`
<ide>
<del> FROM windowsservercore
<add> FROM microsoft/nanoserver
<ide> COPY testfile.txt c:\
<ide> RUN dir c:\
<ide>
<ide> Results in:
<ide>
<ide> PS C:\John> docker build -t succeeds --no-cache=true .
<ide> Sending build context to Docker daemon 3.072 kB
<del> Step 1 : FROM windowsservercore
<del> ---> dbfee88ee9fd
<del> Step 2 : COPY testfile.txt c:\
<del> ---> 99ceb62e90df
<del> Removing intermediate container 62afbe726221
<del> Step 3 : RUN dir c:\
<del> ---> Running in a5ff53ad6323
<add> Step 1/3 : FROM microsoft/nanoserver
<add> ---> 22738ff49c6d
<add> Step 2/3 : COPY testfile.txt c:\
<add> ---> 96655de338de
<add> Removing intermediate container 4db9acbb1682
<add> Step 3/3 : RUN dir c:\
<add> ---> Running in a2c157f842f5
<ide> Volume in drive C has no label.
<del> Volume Serial Number is 1440-27FA
<del>
<add> Volume Serial Number is 7E6D-E0F7
<add>
<ide> Directory of c:\
<del>
<del> 03/25/2016 05:28 AM <DIR> inetpub
<del> 03/25/2016 04:22 AM <DIR> PerfLogs
<del> 04/22/2016 10:59 PM <DIR> Program Files
<del> 03/25/2016 04:22 AM <DIR> Program Files (x86)
<del> 04/18/2016 09:26 AM 4 testfile.txt
<del> 04/22/2016 10:59 PM <DIR> Users
<del> 04/22/2016 10:59 PM <DIR> Windows
<del> 1 File(s) 4 bytes
<del> 6 Dir(s) 21,252,689,920 bytes free
<del> ---> 2569aa19abef
<del> Removing intermediate container a5ff53ad6323
<del> Successfully built 2569aa19abef
<add>
<add> 10/05/2016 05:04 PM 1,894 License.txt
<add> 10/05/2016 02:22 PM <DIR> Program Files
<add> 10/05/2016 02:14 PM <DIR> Program Files (x86)
<add> 10/28/2016 11:18 AM 62 testfile.txt
<add> 10/28/2016 11:20 AM <DIR> Users
<add> 10/28/2016 11:20 AM <DIR> Windows
<add> 2 File(s) 1,956 bytes
<add> 4 Dir(s) 21,259,096,064 bytes free
<add> ---> 01c7f3bef04f
<add> Removing intermediate container a2c157f842f5
<add> Successfully built 01c7f3bef04f
<ide> PS C:\John>
<ide>
<ide> ## Environment replacement
<ide> well as alternate shells available including `sh`.
<ide> The `SHELL` instruction can appear multiple times. Each `SHELL` instruction overrides
<ide> all previous `SHELL` instructions, and affects all subsequent instructions. For example:
<ide>
<del> FROM windowsservercore
<add> FROM microsoft/windowsservercore
<ide>
<ide> # Executed as cmd /S /C echo default
<ide> RUN echo default
<ide> the `escape` parser directive:
<ide>
<ide> # escape=`
<ide>
<del> FROM windowsservercore
<add> FROM microsoft/nanoserver
<ide> SHELL ["powershell","-command"]
<ide> RUN New-Item -ItemType Directory C:\Example
<ide> ADD Execute-MyCmdlet.ps1 c:\example\
<ide> the `escape` parser directive:
<ide> Resulting in:
<ide>
<ide> PS E:\docker\build\shell> docker build -t shell .
<del> Sending build context to Docker daemon 3.584 kB
<del> Step 1 : FROM windowsservercore
<del> ---> 5bc36a335344
<del> Step 2 : SHELL powershell -command
<del> ---> Running in 87d7a64c9751
<del> ---> 4327358436c1
<del> Removing intermediate container 87d7a64c9751
<del> Step 3 : RUN New-Item -ItemType Directory C:\Example
<del> ---> Running in 3e6ba16b8df9
<del>
<del>
<add> Sending build context to Docker daemon 4.096 kB
<add> Step 1/5 : FROM microsoft/nanoserver
<add> ---> 22738ff49c6d
<add> Step 2/5 : SHELL powershell -command
<add> ---> Running in 6fcdb6855ae2
<add> ---> 6331462d4300
<add> Removing intermediate container 6fcdb6855ae2
<add> Step 3/5 : RUN New-Item -ItemType Directory C:\Example
<add> ---> Running in d0eef8386e97
<add>
<add>
<ide> Directory: C:\
<del>
<del>
<add>
<add>
<ide> Mode LastWriteTime Length Name
<ide> ---- ------------- ------ ----
<del> d----- 6/2/2016 2:59 PM Example
<del>
<del>
<del> ---> 1f1dfdcec085
<del> Removing intermediate container 3e6ba16b8df9
<del> Step 4 : ADD Execute-MyCmdlet.ps1 c:\example\
<del> ---> 6770b4c17f29
<del> Removing intermediate container b139e34291dc
<del> Step 5 : RUN c:\example\Execute-MyCmdlet -sample 'hello world'
<del> ---> Running in abdcf50dfd1f
<del> Hello from Execute-MyCmdlet.ps1 - passed hello world
<del> ---> ba0e25255fda
<del> Removing intermediate container abdcf50dfd1f
<del> Successfully built ba0e25255fda
<add> d----- 10/28/2016 11:26 AM Example
<add>
<add>
<add> ---> 3f2fbf1395d9
<add> Removing intermediate container d0eef8386e97
<add> Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\
<add> ---> a955b2621c31
<add> Removing intermediate container b825593d39fc
<add> Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world'
<add> ---> Running in be6d8e63fe75
<add> hello world
<add> ---> 8e559e9bf424
<add> Removing intermediate container be6d8e63fe75
<add> Successfully built 8e559e9bf424
<ide> PS E:\docker\build\shell>
<ide>
<ide> The `SHELL` instruction could also be used to modify the way in which | 1 |
Ruby | Ruby | fix issue with params in url_for | e492c446d520e8941624564b157b297cfd0aeaa9 | <ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def url_for(options = {})
<ide> path = options.delete(:script_name).to_s.chomp("/")
<ide> path << options.delete(:path).to_s
<ide>
<del> params = options[:params] || {}
<add> params = options[:params].is_a?(Hash) ? options[:params] : {}
<ide> params.reject! { |_,v| v.to_param.nil? }
<ide>
<ide> result = build_host_url(options)
<ide><path>actionpack/test/dispatch/request_test.rb
<ide> def url_for(options = {})
<ide> end
<ide> end
<ide>
<add> test "url_for options[:params]" do
<add> assert_equal 'http://www.example.com?params=', url_for(:params => '')
<add> assert_equal 'http://www.example.com?params=1', url_for(:params => 1)
<add> assert_equal 'http://www.example.com', url_for
<add> assert_equal 'http://www.example.com', url_for(:params => {})
<add> assert_equal 'http://www.example.com?name=tumayun', url_for(:params => { :name => 'tumayun' })
<add> end
<add>
<ide> protected
<ide>
<ide> def stub_request(env = {}) | 2 |
Javascript | Javascript | revert two missed files | 197f989c1ade6da99d5c1a21d1c1eaf4bbe26b21 | <ide><path>src/test/locale/de-at.js
<ide> test('weeks year starting sunday formatted', function (assert) {
<ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2');
<ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2');
<ide> });
<del>
<del>test('valid localeData', function (assert) {
<del> assert.equal(moment().localeData().months().length, 12, 'months should return 12 months');
<del> assert.equal(moment().localeData().monthsShort().length, 12, 'monthsShort should return 12 months');
<del> assert.equal(moment().localeData().weekdays().length, 7, 'weekdays should return 7 days');
<del> assert.equal(moment().localeData().weekdaysShort().length, 7, 'weekdaysShort should return 7 days');
<del> assert.equal(moment().localeData().weekdaysMin().length, 7, 'monthsShort should return 7 days');
<del>});
<ide><path>src/test/locale/dv.js
<ide> test('weeks year starting sunday formatted', function (assert) {
<ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2');
<ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3');
<ide> });
<del>
<del>test('valid localeData', function (assert) {
<del> assert.equal(moment().localeData().months().length, 12, 'months should return 12 months');
<del> assert.equal(moment().localeData().monthsShort().length, 12, 'monthsShort should return 12 months');
<del> assert.equal(moment().localeData().weekdays().length, 7, 'weekdays should return 7 days');
<del> assert.equal(moment().localeData().weekdaysShort().length, 7, 'weekdaysShort should return 7 days');
<del> assert.equal(moment().localeData().weekdaysMin().length, 7, 'monthsShort should return 7 days');
<del>}); | 2 |
Python | Python | improve test slightly | 7e5f63a59596a7951af4ccfb286cc831c3972822 | <ide><path>spacy/tests/regression/test_issue587.py
<ide> import spacy
<ide> import spacy.matcher
<add>from spacy.attrs import IS_PUNCT, ORTH
<ide>
<ide> import pytest
<ide>
<ide> def test_matcher_segfault():
<ide> nlp = spacy.load('en', parser=False, entity=False)
<ide> matcher = spacy.matcher.Matcher(nlp.vocab)
<ide> content = u'''a b; c'''
<del> matcher.add(entity_key='1', label='TEST', attrs={}, specs=[[{65: 'a'}, {65: 'b'}]])
<add> matcher.add(entity_key='1', label='TEST', attrs={}, specs=[[{ORTH: 'a'}, {ORTH: 'b'}]])
<ide> matcher(nlp(content))
<del> matcher.add(entity_key='2', label='TEST', attrs={}, specs=[[{65: 'a'}, {65: 'b'}, {5: True}, {65: 'c'}]])
<add> matcher.add(entity_key='2', label='TEST', attrs={}, specs=[[{ORTH: 'a'}, {ORTH: 'b'}, {IS_PUNCT: True}, {ORTH: 'c'}]])
<ide> matcher(nlp(content))
<del> matcher.add(entity_key='3', label='TEST', attrs={}, specs=[[{65: 'a'}, {65: 'b'}, {5: True}, {65: 'd'}]])
<add> matcher.add(entity_key='3', label='TEST', attrs={}, specs=[[{ORTH: 'a'}, {ORTH: 'b'}, {IS_PUNCT: True}, {ORTH: 'd'}]])
<ide> matcher(nlp(content)) | 1 |
Javascript | Javascript | fix greek characters | 0d67dea6b1a0fbf3eb26c432c41a680c1124f85e | <ide><path>examples/js/loaders/SVGLoader.js
<ide> THREE.SVGLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype
<ide> var cxp = q * rx * y1p / ry;
<ide> var cyp = - q * ry * x1p / rx;
<ide>
<del> // Step 3: Compute (cx, cy) from (cxâ², cyâ²)
<add> // Step 3: Compute (cx, cy) from (cx', cy')
<ide> var cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;
<ide> var cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;
<ide>
<del> // Step 4: Compute θ1 and Îθ
<add> // Step 4: Compute θ1 and Δθ
<ide> var theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );
<ide> var delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );
<ide> | 1 |
Python | Python | fix crash on 0d return value in apply_along_axis | 52988ea98120c10a927325401257eb3715a51b15 | <ide><path>numpy/lib/shape_base.py
<ide> from numpy.core.numeric import (
<ide> asarray, zeros, outer, concatenate, isscalar, array, asanyarray
<ide> )
<del>from numpy.core.fromnumeric import product, reshape
<add>from numpy.core.fromnumeric import product, reshape, transpose
<ide> from numpy.core import vstack, atleast_3d
<ide>
<ide>
<ide> def apply_along_axis(func1d, axis, arr, *args, **kwargs):
<ide> -------
<ide> apply_along_axis : ndarray
<ide> The output array. The shape of `outarr` is identical to the shape of
<del> `arr`, except along the `axis` dimension, where the length of `outarr`
<del> is equal to the size of the return value of `func1d`. If `func1d`
<del> returns a scalar `outarr` will have one fewer dimensions than `arr`.
<add> `arr`, except along the `axis` dimension. This axis is removed, and
<add> replaced with new dimensions equal to the shape of the return value
<add> of `func1d`. So if `func1d` returns a scalar `outarr` will have one
<add> fewer dimensions than `arr`.
<ide>
<ide> See Also
<ide> --------
<ide> def apply_along_axis(func1d, axis, arr, *args, **kwargs):
<ide> >>> np.apply_along_axis(my_func, 1, b)
<ide> array([ 2., 5., 8.])
<ide>
<del> For a function that doesn't return a scalar, the number of dimensions in
<add> For a function that returns a 1D array, the number of dimensions in
<ide> `outarr` is the same as `arr`.
<ide>
<ide> >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
<ide> def apply_along_axis(func1d, axis, arr, *args, **kwargs):
<ide> [3, 4, 9],
<ide> [2, 5, 6]])
<ide>
<add> For a function that returns a higher dimensional array, those dimensions
<add> are inserted in place of the `axis` dimension.
<add>
<add> >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
<add> >>> np.apply_along_axis(np.diag, -1, b)
<add> array([[[1, 0, 0],
<add> [0, 2, 0],
<add> [0, 0, 3]],
<add>
<add> [[4, 0, 0],
<add> [0, 5, 0],
<add> [0, 0, 6]],
<add>
<add> [[7, 0, 0],
<add> [0, 8, 0],
<add> [0, 0, 9]]])
<ide> """
<add> # handle negative axes
<ide> arr = asanyarray(arr)
<ide> nd = arr.ndim
<ide> if axis < 0:
<ide> axis += nd
<del> if (axis >= nd):
<add> if axis >= nd:
<ide> raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d."
<ide> % (axis, nd))
<del> ind = [0]*(nd-1)
<del> i = zeros(nd, 'O')
<del> indlist = list(range(nd))
<del> indlist.remove(axis)
<del> i[axis] = slice(None, None)
<del> outshape = asarray(arr.shape).take(indlist)
<del> i.put(indlist, ind)
<del> res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
<del> # if res is a number, then we have a smaller output array
<del> if isscalar(res):
<del> outarr = zeros(outshape, asarray(res).dtype)
<del> outarr[tuple(ind)] = res
<del> Ntot = product(outshape)
<del> k = 1
<del> while k < Ntot:
<del> # increment the index
<del> ind[-1] += 1
<del> n = -1
<del> while (ind[n] >= outshape[n]) and (n > (1-nd)):
<del> ind[n-1] += 1
<del> ind[n] = 0
<del> n -= 1
<del> i.put(indlist, ind)
<del> res = func1d(arr[tuple(i.tolist())], *args, **kwargs)
<del> outarr[tuple(ind)] = res
<del> k += 1
<del> return outarr
<del> else:
<del> res = asanyarray(res)
<del> Ntot = product(outshape)
<del> holdshape = outshape
<del> outshape = list(arr.shape)
<del> outshape[axis] = res.size
<del> outarr = zeros(outshape, res.dtype)
<del> outarr = res.__array_wrap__(outarr)
<del> outarr[tuple(i.tolist())] = res
<del> k = 1
<del> while k < Ntot:
<del> # increment the index
<del> ind[-1] += 1
<del> n = -1
<del> while (ind[n] >= holdshape[n]) and (n > (1-nd)):
<del> ind[n-1] += 1
<del> ind[n] = 0
<del> n -= 1
<del> i.put(indlist, ind)
<del> res = asanyarray(func1d(arr[tuple(i.tolist())], *args, **kwargs))
<del> outarr[tuple(i.tolist())] = res
<del> k += 1
<del> if res.shape == ():
<del> outarr = outarr.squeeze(axis)
<del> return outarr
<add>
<add> # arr, with the iteration axis at the end
<add> dims_in = list(range(nd))
<add> inarr_view = transpose(arr, dims_in[:axis] + dims_in[axis+1:] + [axis])
<add>
<add> # number of iterations
<add> Ntot = product(inarr_view.shape[:nd-1])
<add>
<add> # current index
<add> ind = [0]*(nd - 1)
<add>
<add> # invoke the function on the first item
<add> res = func1d(inarr_view[tuple(ind)], *args, **kwargs)
<add> res = asanyarray(res)
<add>
<add> # insert as many axes as necessary to create the output
<add> outshape = arr.shape[:axis] + res.shape + arr.shape[axis+1:]
<add> outarr = zeros(outshape, res.dtype)
<add> outarr = res.__array_wrap__(outarr)
<add>
<add> # outarr, with inserted dimensions at the end
<add> # this means that outarr_view[i] = func1d(inarr_view[i])
<add> dims_out = list(range(outarr.ndim))
<add> outarr_view = transpose(outarr, dims_out[:axis] + dims_out[axis+res.ndim:] + dims_out[axis:axis+res.ndim])
<add>
<add> # save the first result
<add> outarr_view[tuple(ind)] = res
<add> k = 1
<add> while k < Ntot:
<add> # increment the index
<add> ind[-1] += 1
<add> n = -1
<add> while (ind[n] >= outshape[n]) and (n > (1-nd)):
<add> ind[n-1] += 1
<add> ind[n] = 0
<add> n -= 1
<add> outarr_view[tuple(ind)] = asanyarray(func1d(inarr_view[tuple(ind)], *args, **kwargs))
<add> k += 1
<add> return outarr
<ide>
<ide>
<ide> def apply_over_axes(func, a, axes):
<ide><path>numpy/lib/tests/test_shape_base.py
<ide> def double(row):
<ide> return row * 2
<ide> m = np.matrix([[0, 1], [2, 3]])
<ide> result = apply_along_axis(double, 0, m)
<del> assert isinstance(result, np.matrix)
<add> assert_(isinstance(result, np.matrix))
<ide> assert_array_equal(
<ide> result, np.matrix([[0, 2], [4, 6]])
<ide> )
<ide> def minimal_function(array):
<ide> apply_along_axis(minimal_function, 0, a), np.array([1, 1, 1])
<ide> )
<ide>
<del> def test_scalar_array(self):
<add> def test_scalar_array(self, cls=np.ndarray):
<add> a = np.ones((6, 3)).view(cls)
<add> res = apply_along_axis(np.sum, 0, a)
<add> assert_(isinstance(res, cls))
<add> assert_array_equal(res, np.array([6, 6, 6]).view(cls))
<add>
<add> def test_0d_array(self, cls=np.ndarray):
<add> def sum_to_0d(x):
<add> """ Sum x, returning a 0d array of the same class """
<add> assert_equal(x.ndim, 1)
<add> return np.squeeze(np.sum(x, keepdims=True))
<add> a = np.ones((6, 3)).view(cls)
<add> res = apply_along_axis(sum_to_0d, 0, a)
<add> assert_(isinstance(res, cls))
<add> assert_array_equal(res, np.array([6, 6, 6]).view(cls))
<add>
<add> res = apply_along_axis(sum_to_0d, 1, a)
<add> assert_(isinstance(res, cls))
<add> assert_array_equal(res, np.array([3, 3, 3, 3, 3, 3]).view(cls))
<add>
<add> def test_axis_insertion(self, cls=np.ndarray):
<add> def f1to2(x):
<add> """produces an assymmetric non-square matrix from x"""
<add> assert_equal(x.ndim, 1)
<add> return (x[::-1] * x[1:,None]).view(cls)
<add>
<add> a2d = np.arange(6*3).reshape((6, 3))
<add>
<add> # 2d insertion along first axis
<add> actual = apply_along_axis(f1to2, 0, a2d)
<add> expected = np.stack([
<add> f1to2(a2d[:,i]) for i in range(a2d.shape[1])
<add> ], axis=-1).view(cls)
<add> assert_equal(type(actual), type(expected))
<add> assert_equal(actual, expected)
<add>
<add> # 2d insertion along last axis
<add> actual = apply_along_axis(f1to2, 1, a2d)
<add> expected = np.stack([
<add> f1to2(a2d[i,:]) for i in range(a2d.shape[0])
<add> ], axis=0).view(cls)
<add> assert_equal(type(actual), type(expected))
<add> assert_equal(actual, expected)
<add>
<add> # 3d insertion along middle axis
<add> a3d = np.arange(6*5*3).reshape((6, 5, 3))
<add>
<add> actual = apply_along_axis(f1to2, 1, a3d)
<add> expected = np.stack([
<add> np.stack([
<add> f1to2(a3d[i,:,j]) for i in range(a3d.shape[0])
<add> ], axis=0)
<add> for j in range(a3d.shape[2])
<add> ], axis=-1).view(cls)
<add> assert_equal(type(actual), type(expected))
<add> assert_equal(actual, expected)
<add>
<add> def test_subclass_preservation(self):
<ide> class MinimalSubclass(np.ndarray):
<ide> pass
<del> a = np.ones((6, 3)).view(MinimalSubclass)
<del> res = apply_along_axis(np.sum, 0, a)
<del> assert isinstance(res, MinimalSubclass)
<del> assert_array_equal(res, np.array([6, 6, 6]).view(MinimalSubclass))
<add> self.test_scalar_array(MinimalSubclass)
<add> self.test_0d_array(MinimalSubclass)
<add> self.test_axis_insertion(MinimalSubclass)
<ide>
<ide> def test_tuple_func1d(self):
<ide> def sample_1d(x): | 2 |
Ruby | Ruby | fix uninitialized ivar | 8234ac22e9c797a6f50ff9bf496bf789fa7bf901 | <ide><path>Library/Homebrew/formula_lock.rb
<ide> class FormulaLock
<ide> def initialize(name)
<ide> @name = name
<ide> @path = LOCKDIR.join("#{@name}.brewing")
<add> @lockfile = nil
<ide> end
<ide>
<ide> def lock | 1 |
Javascript | Javascript | reuse local "hash" variable | 5cbb34a841ed22c495761e6a924f36a7051ee7bc | <ide><path>packages/ember-handlebars/lib/helpers/action.js
<ide> ActionHelper.registerAction = function(actionName, eventName, target, view, cont
<ide>
<ide> EmberHandlebars.registerHelper('action', function(actionName, options) {
<ide> var hash = options.hash || {},
<del> eventName = options.hash.on || "click",
<add> eventName = hash.on || "click",
<ide> view = options.data.view,
<ide> target, context;
<ide>
<ide> if (view.isVirtual) { view = view.get('parentView'); }
<del> target = options.hash.target ? getPath(this, options.hash.target) : view;
<add> target = hash.target ? getPath(this, hash.target) : view;
<ide> context = options.contexts[0];
<ide>
<ide> var actionId = ActionHelper.registerAction(actionName, eventName, target, view, context); | 1 |
Ruby | Ruby | prepare inline patch specs | 644ae115f56de90a72ab0fac68d5bdac906cf82e | <ide><path>Library/Homebrew/test/rubocops/patches_spec.rb
<ide> def patches
<ide> end
<ide> end
<ide>
<add> context "When auditing inline patches" do
<add> it "reports no offenses for valid inline patches" do
<add> expect_no_offenses(<<~RUBY)
<add> class Foo < Formula
<add> url 'https://brew.sh/foo-1.0.tgz'
<add> patch :DATA
<add> end
<add> __END__
<add> patch content here
<add> RUBY
<add> end
<add>
<add> it "reports an offense when DATA is found with no __END__" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> url 'https://brew.sh/foo-1.0.tgz'
<add> patch :DATA
<add> ^^^^^^^^^^^ patch is missing '__END__'
<add> end
<add> RUBY
<add> end
<add>
<add> it "reports an offense when __END__ is found with no DATA" do
<add> expect_offense(<<~RUBY)
<add> class Foo < Formula
<add> url 'https://brew.sh/foo-1.0.tgz'
<add> end
<add> __END__
<add> ^^^^^^^ patch is missing 'DATA'
<add> patch content here
<add> RUBY
<add> end
<add> end
<add>
<ide> context "When auditing external patches" do
<ide> it "Patch URLs" do
<ide> patch_urls = [ | 1 |
PHP | PHP | add macros to tables | 906d0d851e182ee832100af207a555e6919acf65 | <ide><path>laravel/database/schema/table.php
<ide> class Table {
<ide> */
<ide> public $commands = array();
<ide>
<add> /**
<add> * The registered custom macros.
<add> *
<add> * @var array
<add> */
<add> public static $macros = array();
<add>
<add> /**
<add> * Registers a custom macro.
<add> *
<add> * @param string $name
<add> * @param Closure $macro
<add> * @return void
<add> */
<add> public static function macro($name, $macro)
<add> {
<add> static::$macros[$name] = $macro;
<add> }
<add>
<ide> /**
<ide> * Create a new schema table instance.
<ide> *
<ide> protected function column($type, $parameters = array())
<ide> return $this->columns[] = new Fluent($parameters);
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add> /**
<add> * Dynamically handle calls to custom macros.
<add> *
<add> * @param string $method
<add> * @param array $parameters
<add> * @return mixed
<add> */
<add> public function __call($method, $parameters)
<add> {
<add> if (isset(static::$macros[$method]))
<add> {
<add> array_unshift($parameters, $this);
<add> return call_user_func_array(static::$macros[$method], $parameters);
<add> }
<add>
<add> throw new \Exception("Method [$method] does not exist.");
<add> }
<add>
<add>} | 1 |
Text | Text | fix "summary" block titles | 7e949501d60eb201194277668ef052f9f06904c1 | <ide><path>docs/tutorials/essentials/part-1-overview-concepts.md
<ide> Here's what that data flow looks like visually:
<ide>
<ide> Redux does have a number of new terms and concepts to remember. As a reminder, here's what we just covered:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux is a library for managing global application state**
<ide> - Redux is typically used with the React-Redux library for integrating Redux and React together
<ide><path>docs/tutorials/essentials/part-2-app-structure.md
<ide> Now, any React components that call `useSelector` or `useDispatch` will be talki
<ide>
<ide> Even though the counter example app is pretty small, it showed all the key pieces of a React + Redux app working together. Here's what we covered:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **We can create a Redux store using the Redux Toolkit `configureStore` API**
<ide> - `configureStore` accepts a `reducer` function as a named argument
<ide><path>docs/tutorials/essentials/part-3-data-flow.md
<ide> Notice that our `AddPostForm` component has some React `useState` hooks inside,
<ide>
<ide> Let's recap what you've learned in this section:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux state is updated by "reducer functions"**:
<ide> - Reducers always calculate a new state _immutably_, by copying existing state values and modifying the copies with the new data
<ide><path>docs/tutorials/essentials/part-4-using-data.md
<ide> It's actually starting to look more useful and interesting!
<ide>
<ide> We've covered a lot of information and concepts in this section. Let's recap the important things to remember:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Any React component can use data from the Redux store as needed**
<ide> - Any component can read any data that is in the Redux store
<ide><path>docs/tutorials/essentials/part-5-async-logic.md
<ide> Here's what our app looks like now that we're fetching data from that fake API:
<ide>
<ide> As a reminder, here's what we covered in this section:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **You can write reusable "selector" functions to encapsulate reading values from the Redux state**
<ide> - Selectors are functions that get the Redux `state` as an argument, and return some data
<ide><path>docs/tutorials/essentials/part-6-performance-normalization.md
<ide> Congratulations, you've completed the Redux Essentials tutorial! Let's see what
<ide>
<ide> Here's what we covered in this section:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Memoized selector functions can be used to optimize performance**
<ide> - Redux Toolkit re-exports the `createSelector` function from Reselect, which generates memoized selectors
<ide><path>docs/tutorials/fundamentals/part-1-overview.md
<ide> That counter example was small, but it does show all the working pieces of a rea
<ide>
<ide> With that in mind, let's review what we've learned so far:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux is a library for managing global application state**
<ide> - Redux is typically used with the React-Redux library for integrating Redux and React together
<ide><path>docs/tutorials/fundamentals/part-2-concepts-data-flow.md
<ide> Here's what that data flow looks like visually:
<ide>
<ide> ## What You've Learned
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux's intent can be summarized in three principles**
<ide> - Global app state is kept in a single store
<ide><path>docs/tutorials/fundamentals/part-3-state-actions-reducers.md
<ide> Here's the contents of our app so far:
<ide> sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
<ide> ></iframe>
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux apps use plain JS objects, arrays, and primitives as the state values**
<ide> - The root state value should be a plain JS object
<ide><path>docs/tutorials/fundamentals/part-4-store.md
<ide> Let's see how our example app looks now:
<ide>
<ide> And as a reminder, here's what we covered in this section:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux apps always have a single store**
<ide> - Stores are created with the Redux `createStore` API
<ide><path>docs/tutorials/fundamentals/part-5-ui-and-react.md
<ide> Let's see how the app looks now, including the components and sections we skippe
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> ></iframe>
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux stores can be used with any UI layer**
<ide> - UI code always subscribes to the store, gets the latest state, and redraws itself
<ide><path>docs/tutorials/fundamentals/part-6-async-logic.md
<ide> Here's what the current app looks like:
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> ></iframe>
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux middleware were designed to enable writing logic that has side effects**
<ide> - "Side effects" are code that changes state/behavior outside a function, like AJAX calls, modifying function arguments, or generating random values
<ide><path>docs/tutorials/fundamentals/part-7-standard-patterns.md
<ide> Here's how our app looks after it's been fully converted to use these patterns:
<ide> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<ide> ></iframe>
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Action creator functions encapsulate preparing action objects and thunks**
<ide> - Action creators can accept arguments and contain setup logic, and return the final action object or thunk function
<ide><path>docs/tutorials/fundamentals/part-8-modern-redux.md
<ide> Let's take one final look at the completed todo application, including all the c
<ide>
<ide> And we'll do a final recap of the key points you learned in this section:
<ide>
<del>:::Summary
<add>:::tip Summary
<ide>
<ide> - **Redux Toolkit (RTK) is the standard way to write Redux logic**
<ide> - RTK includes APIs that simplify most Redux code | 14 |
Ruby | Ruby | fix info --github | faaac9482efdc35268382b65dcea41a274ea4846 | <ide><path>Library/Homebrew/cmd/info.rb
<ide> def github_info f
<ide> path = "Library/Formula/#{path.basename}"
<ide> end
<ide>
<del> "From: https://github.com/#{user}/#{repo}/commits/master/#{path}"
<add> "https://github.com/#{user}/#{repo}/commits/master/#{path}"
<ide> end
<ide>
<ide> def info_formula f
<ide> def info_formula f
<ide> end
<ide>
<ide> history = github_info(f)
<del> puts history if history
<add> puts "From: #{history}" if history
<ide>
<ide> unless f.deps.empty?
<ide> ohai "Dependencies" | 1 |
Text | Text | adjust text to code example | 2400fcb432d4bce68abfbe54cbc9cc8c930c381f | <ide><path>docs/general/fonts.md
<ide>
<ide> There are special global settings that can change all of the fonts on the chart. These options are in `Chart.defaults.font`. The global font settings only apply when more specific options are not included in the config.
<ide>
<del>For example, in this chart the text will all be red except for the labels in the legend.
<add>For example, in this chart the text will have a font size of 16px except for the labels in the legend.
<ide>
<ide> ```javascript
<ide> Chart.defaults.font.size = 16; | 1 |
Javascript | Javascript | incapsulate tag variable | 432d338f9a457551591cfdceef71de95ce0b096f | <ide><path>lib/optimize/InnerGraph.js
<ide> exports.getExportDependentDependencies = state => {
<ide> };
<ide>
<ide> /**
<del> * @param {ParserState} state parser state
<add> * @param {TODO} parser parser
<ide> * @param {string} name symbol name
<ide> * @returns {TopLevelSymbol} usage data
<ide> */
<del>exports.createTopLevelSymbol = (state, name) => {
<del> const innerGraphState = getState(state);
<add>exports.tagTopLevelSymbol = (parser, name) => {
<add> const innerGraphState = getState(parser.state);
<ide> const { innerGraph } = innerGraphState || {};
<ide>
<del> return new TopLevelSymbol(name, innerGraph);
<add> parser.defineVariable(name);
<add>
<add> const existingTag = parser.getTagData(name, topLevelSymbolTag);
<add> if (existingTag) {
<add> return existingTag;
<add> }
<add>
<add> const fn = new TopLevelSymbol(name, innerGraph);
<add> parser.tagVariable(name, topLevelSymbolTag, fn);
<add> return fn;
<ide> };
<ide>
<ide> class TopLevelSymbol {
<ide><path>lib/optimize/InnerGraphPlugin.js
<ide> class InnerGraphPlugin {
<ide> if (parser.scope.topLevelScope === true) {
<ide> if (statement.type === "FunctionDeclaration") {
<ide> const name = statement.id ? statement.id.name : "*default*";
<del> parser.defineVariable(name);
<del> const fn = InnerGraph.createTopLevelSymbol(parser.state, name);
<del> parser.tagVariable(name, topLevelSymbolTag, fn);
<add> const fn = InnerGraph.tagTopLevelSymbol(parser, name);
<ide> statementWithTopLevelSymbol.set(statement, fn);
<ide> return true;
<ide> }
<ide> class InnerGraphPlugin {
<ide> if (parser.scope.topLevelScope === true) {
<ide> if (statement.type === "ClassDeclaration") {
<ide> const name = statement.id ? statement.id.name : "*default*";
<del> parser.defineVariable(name);
<del> const fn = InnerGraph.createTopLevelSymbol(parser.state, name);
<del> parser.tagVariable(name, topLevelSymbolTag, fn);
<add> const fn = InnerGraph.tagTopLevelSymbol(parser, name);
<ide> statementWithTopLevelSymbol.set(statement, fn);
<ide> return true;
<ide> }
<ide> class InnerGraphPlugin {
<ide> decl.type === "Identifier"
<ide> ) {
<ide> const name = "*default*";
<del> parser.defineVariable(name);
<del> const fn = InnerGraph.createTopLevelSymbol(
<del> parser.state,
<del> name
<del> );
<del> parser.tagVariable(name, topLevelSymbolTag, fn);
<add> const fn = InnerGraph.tagTopLevelSymbol(parser, name);
<ide> statementWithTopLevelSymbol.set(statement, fn);
<ide> }
<ide> }
<ide> }
<ide> });
<del> const tagVar = name => {
<del> parser.defineVariable(name);
<del> const existingTag = parser.getTagData(name, topLevelSymbolTag);
<del> const fn =
<del> existingTag ||
<del> InnerGraph.createTopLevelSymbol(parser.state, name);
<del> if (!existingTag) {
<del> parser.tagVariable(name, topLevelSymbolTag, fn);
<del> }
<del> return fn;
<del> };
<ide> /** @type {WeakMap<{}, TopLevelSymbol>} */
<ide> const declWithTopLevelSymbol = new WeakMap();
<ide> const pureDeclarators = new WeakSet();
<ide> class InnerGraphPlugin {
<ide> decl.init.type === "ClassExpression"
<ide> ) {
<ide> const name = decl.id.name;
<del> const fn = tagVar(name);
<add> const fn = InnerGraph.tagTopLevelSymbol(parser, name);
<ide> declWithTopLevelSymbol.set(decl, fn);
<ide> return true;
<ide> }
<ide> if (isPure(decl.init, parser, decl.id.range[1])) {
<ide> const name = decl.id.name;
<del> const fn = tagVar(name);
<add> const fn = InnerGraph.tagTopLevelSymbol(parser, name);
<ide> declWithTopLevelSymbol.set(decl, fn);
<ide> pureDeclarators.add(decl);
<ide> return true; | 2 |
Text | Text | add a guide for the live ui and live api | c1475819b2e2983ece6e0c42ae7a29daaf4ae51b | <ide><path>docs/guides/live.md
<add># The live user interface and API in Video.js
<add>> Note the the "old" live user interface is currently the default, see the section on [the new user interface](#the-new-user-interface) for information on setting that up.
<add>
<add>
<add>## The default live user interface
<add>The default user interface hides the `ProgressControl` component on the controlbar and shows the `LiveDisplay` component when Video.js detects that the video that it is playing is live (via a `durationchange` event).
<add>
<add>> Note: It does this by adding the `vjs-live` class to the player and the showing/hiding of components is all handled in css.
<add>
<add>This makes the player have hide the progress bar, seek bar, and display text indicating that the player is live. All of those will be shown again if a non-live video is switched to (via another `durationchange` event).
<add>
<add>To view a sample of this user interface please:
<add>1. clone the repository, and move into that directory
<add>2. run `npm install` or `npm ci` to install all necessary packages
<add>3. run `npm start` to start the local server
<add>4. open `http://localhost:9999/sandbox/live.html` in a web browser
<add>
<add>## The new user interface
<add>> Note: This user interface is will not work on Android due to the live HLS implementation not supporting seekable ranges during live streams. We reccommend overriding the native hls implementation with @videojs/http-streaming this will make the new liveui work.
<add>
<add>The new user interface is currently opt-in to prevent breaking backwards compatiblity. We feel that the new user interface is much better and it will likely become the new default in the next major version. If you want to use the new user interface you will have to pass `{liveui: true}` during player setup. This can be done in two ways:
<add>
<add>Using `data-setup`
<add>```html
<add> <video-js data-setup='{"liveui": true}'>
<add> </video-js>
<add>```
<add>
<add>Using the `videojs` function
<add>
<add>```js
<add>var player = videojs('some-player-id', {liveui: true});
<add>```
<add>
<add>The new user interface shows the `ProgressControl` component on the control bar, hides the `LiveDisplay` component, and shows the new `SeekToLive` component when Video.js detects that the video that it is playing is live (via a `durationchange` event). Along with the `ProgressControl` update we also updated all the time tooltips on the player to indicate a negative number from the live current time, rather than seeking to a specific time.
<add>
<add>> Note: It does this by adding the `vjs-live` and `vjs-liveui` class to the player and the showing/hiding of components is all handled in css.
<add>
<add>The new live user interface shows the progress/seek bar and lets the user seek backwards/forwards within the live window. Next it adds a button, via the `SeekToLive` component that can be clicked when the user is behind live that will seek to the live current time. That same button indicates if the `currentTime` of the player is live via a grey circle when not live and a red circle when live.
<add>
<add>To view a sample of this user interface please:
<add>1. clone the repository, and move into that directory
<add>2. run `npm install` or `npm ci` to install all necessary packages
<add>3. run `npm start` to start the local server
<add>4. open `http://localhost:9999/sandbox/liveui.html` in a web browser
<add>
<add>
<add>## LiveTracker
<add>> Note: this component can be turned off by passing `liveTracker: false` to the player during initialization.
<add>
<add>Along with the new liveui we implemented an API that can be used regardless of which user interface is in use. This API is a child of the player and should be on the player at `player.liveTracker`. `LiveTracker` provides several useful helper functions and events for dealing with live playback, all of which are used and tested internally. Internally this component keeps track of the live current time through a function that runs on a 30ms interval.
<add>
<add>### The seekableendchange event
<add>The live tracker will fire this event every time that the `seekableEnd` for the player changes. This is used internally to keep our `pastSeekEnd()` function up to date.
<add>
<add>### The liveedgechange event
<add>As the name implies the live tracker will fire this event when it detects that the current time is no longer at the live edge.
<add>
<add>### startTracking() and stopTracking()
<add>These functions can be called to arbitrarily start/stop tracking live playback. Normally these are handled by automatically when the player triggers a `durationchange` with a duration of `Infinity`. You won't want to call them unless you are doing something fairly specific.
<add>
<add>### seekableEnd()
<add>seekableEnd gets the time in seconds of the furthest seekable end. For instance if we have an array of seekable `TimeRanges` where the first element in the array is the `start()` second and the last is the `end()` second:
<add>
<add>```js
<add>// seekable index 0: 0 is start, 1 is end
<add>// seekable index 1: 2 is the start, 3 is the end
<add>const seekableExample = [[0, 1], [2, 3]];
<add>```
<add>
<add>seekableEnd would return `3` as that is the furthest seekable point for the current media.
<add>
<add>> Note: that if Infinity is anywhere in seekable end, this will return Infinity
<add>
<add>### seekableStart()
<add>seekableStart gets the time in seconds of the earliest seekable start. For instance if we have an array of seekable `TimeRanges` where the first element in the array is the `start()` second and the last is the `end()` second:
<add>
<add>
<add>```js
<add>// seekable index 0: 0 is start, 1 is end
<add>// seekable index 1: 2 is the start, 3 is the end
<add>const seekableExample = [[0, 1], [2, 3]];
<add>```
<add>
<add>seekableStart would return `0` as that is the first seekable point for the current media.
<add>
<add>> Note: that if Infinity is anywhere in seekable start, this will return Infinity
<add>
<add>### liveWindow()
<add>This function gets the amount of time between the `seekableStart()` and the `liveCurrentTime()`. We use this internally to update the total length of our bars, such as the progress/seek bar.
<add>
<add>### atLiveEdge() and behindLiveEdge()
<add>Determines if the currentTime of the player is close enough to live to be considered live. We make sure its close enough, rather than absolutely live, because there are too many factors to determine when live actually is. We consider the currentTime live when it is within two seekable increments and 70ms (two ticks of the live tracking interval). The seekable increment is a number that is determined by the amount that seekable end changes as playback continues. See the `seekableendchange` event and the `pastSeekEnd()` function for more info.
<add>
<add>### liveCurrentTime()
<add>live current time is our best approximation of what the live current time is. Internally it uses the `pastSeekEnd()` function and adds that to the `seekableEnd()` function. It is possible for this function to return `Infinity`.
<add>
<add>### pastSeekEnd()
<add>This is the main value that we use to track if the player is live or not. Every `30ms` we add `0.03` seconds to this value and every `seekableendchange` it is reset to 0 and `0.03` is added to it right away.
<add>
<add>### isTracking() and isLive()
<add>`isTracking` and `isLive` do the same thing they tell you if the `LiveTracker` is currently tracking live playback and since we assume that live tracking will only be done during live they should be the same.
<add>
<add>### seekToLiveEdge()
<add>This function sets the players `currentTime` to the result of the `liveCurrentTime()` function. It will also start playback if playback is currently paused. It starts playback because it is easy to fall behind the live edge if the player is not playing.
<add> | 1 |
Text | Text | fix typo in with-unstated/readme.md | a1dc5588c2bbbecf2ee164206879562a387c7f89 | <ide><path>examples/with-unstated/README.md
<ide>
<ide> This example shows how to integrate [Unstated Next](https://github.com/jamiebuilds/unstated-next) with Next.js.
<ide>
<del>There are two pages, `/` and `/about`, both render a counter and a timer, the state is saved for the current page and resetted when switching to a different page. To keep a shared state between pages you can add the state providers to `pages/_app.js` instead of using the page.
<add>There are two pages, `/` and `/about`, both render a counter and a timer, the state is saved for the current page and reset when switching to a different page. To keep a shared state between pages you can add the state providers to `pages/_app.js` instead of using the page.
<ide>
<ide> ## Preview
<ide> | 1 |
Go | Go | fix the regexp for matching an ip address | e5d44569fb15a0a0b66437104615ccc97bdde076 | <ide><path>libnetwork/resolvconf/dns/resolvconf.go
<ide> import (
<ide> )
<ide>
<ide> // IPLocalhost is a regex patter for localhost IP address range.
<del>const IPLocalhost = `((127\.([0-9]{1,3}.){2}[0-9]{1,3})|(::1))`
<add>const IPLocalhost = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1))`
<ide>
<ide> var localhostIPRegexp = regexp.MustCompile(IPLocalhost)
<ide> | 1 |
Java | Java | update copyright of change file | 87c0e9b48a3e2219de75fb517a700d360acc3b32 | <ide><path>spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License. | 1 |
PHP | PHP | use config instead of middleware property | 860ec9f2a48c65d30998942263a4f9a849e9b0a0 | <ide><path>app/Http/Middleware/HandleCors.php
<ide>
<ide> class HandleCors extends Middleware
<ide> {
<del> /**
<del> * The paths to enable CORS on.
<del> * Example: ['api/*']
<del> *
<del> * @var array
<del> */
<del> protected $paths = [];
<add>
<ide> }
<ide><path>config/cors.php
<add><?php
<add>
<add>return [
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Laravel CORS Options
<add> |--------------------------------------------------------------------------
<add> |
<add> | The allowed_methods and allowed_headers options are case-insensitive.
<add> |
<add> | You don't need to provide both allowed_origins and allowed_origins_patterns.
<add> | If one of the strings passed matches, it is considered a valid origin.
<add> |
<add> | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
<add> | all methods / origins / headers are allowed.
<add> |
<add> */
<add>
<add> /*
<add> * You can enable CORS for 1 or multiple paths.
<add> * Example: ['api/*']
<add> */
<add> 'paths' => [],
<add>
<add> /*
<add> * Matches the request method. `[*]` allows all methods.
<add> */
<add> 'allowed_methods' => ['*'],
<add>
<add> /*
<add> * Matches the request origin. `[*]` allows all origins.
<add> */
<add> 'allowed_origins' => ['*'],
<add>
<add> /**
<add> * Matches the request origin with, similar to `Request::is()`
<add> */
<add> 'allowed_origins_patterns' => [],
<add>
<add> /**
<add> * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
<add> */
<add> 'allowed_headers' => ['*'],
<add>
<add> /**
<add> * Sets the Access-Control-Expose-Headers response header.
<add> */
<add> 'exposed_headers' => false,
<add>
<add> /**
<add> * Sets the Access-Control-Max-Age response header.
<add> */
<add> 'max_age' => false,
<add>
<add> /**
<add> * Sets the Access-Control-Allow-Credentials header.
<add> */
<add> 'supports_credentials' => false,
<add>];
<ide><path>routes/api.php
<ide> | is assigned the "api" middleware group. Enjoy building your API!
<ide> |
<ide> */
<add>Route::any('/test', function (Request $request) {
<add> $a++;
<add> return $request->user();
<add>});
<add>
<ide>
<del>Route::middleware('auth:api')->get('/user', function (Request $request) {
<add>Route::middleware('auth:api')->any('/user', function (Request $request) {
<ide> return $request->user();
<ide> }); | 3 |
Javascript | Javascript | fix move gesture handling | e0d53e1c48d34419ea9a0622bd9b360c51ec3b78 | <ide><path>Libraries/CustomComponents/Navigator/Navigator.js
<ide> var Navigator = React.createClass({
<ide> });
<ide> this.panGesture = PanResponder.create({
<ide> onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
<del> onPanResponderGrant: this._handlePanResponderGrant,
<ide> onPanResponderRelease: this._handlePanResponderRelease,
<ide> onPanResponderMove: this._handlePanResponderMove,
<ide> onPanResponderTerminate: this._handlePanResponderTerminate,
<ide> var Navigator = React.createClass({
<ide> if (!sceneConfig) {
<ide> return false;
<ide> }
<del> this._expectingGestureGrant = this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState);
<add> this._expectingGestureGrant =
<add> this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState);
<ide> return !!this._expectingGestureGrant;
<ide> },
<ide>
<ide> var Navigator = React.createClass({
<ide> return wouldOverswipeForward || wouldOverswipeBack;
<ide> },
<ide>
<del> _handlePanResponderGrant: function(e, gestureState) {
<del> invariant(
<del> this._expectingGestureGrant,
<del> 'Responder granted unexpectedly.'
<del> );
<del> this._attachGesture(this._expectingGestureGrant);
<del> this._onAnimationStart();
<del> this._expectingGestureGrant = null;
<del> },
<del>
<ide> _deltaForGestureAction: function(gestureAction) {
<ide> switch (gestureAction) {
<ide> case 'pop':
<ide> var Navigator = React.createClass({
<ide> },
<ide>
<ide> _handlePanResponderMove: function(e, gestureState) {
<add> if (this._isMoveGestureAttached !== undefined) {
<add> invariant(
<add> this._expectingGestureGrant,
<add> 'Responder granted unexpectedly.'
<add> );
<add> this._attachGesture(this._expectingGestureGrant);
<add> this._onAnimationStart();
<add> this._expectingGestureGrant = undefined;
<add> }
<add>
<ide> var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
<ide> if (this.state.activeGesture) {
<ide> var gesture = sceneConfig.gestures[this.state.activeGesture];
<ide> var Navigator = React.createClass({
<ide> this._eligibleGestures = this._eligibleGestures.slice().splice(gestureIndex, 1);
<ide> }
<ide> });
<del> return matchedGesture;
<add> return matchedGesture || null;
<ide> },
<ide>
<ide> _transitionSceneStyle: function(fromIndex, toIndex, progress, index) { | 1 |
Text | Text | add changes " define " to article. | 7bd91ddffdcd63dc81b09472f61c3c6f3c2f838e | <ide><path>guide/english/product-design/brand-identity/index.md
<ide> title: Brand Identity
<ide>
<ide> ## Brand Identity
<ide>
<add>Brand identity is how a business presents itself to, and wants to be perceived by, its consumers.
<add>
<ide> Brand identity is the face of a brand. While a brand is an emotional and even philosophical concept, brand identity is the visual component of a brand that represents those larger ideas.
<ide>
<ide> Brand identity includes logos, typography, colors, packaging, and messaging, and it complements and reinforces the existing reputation of a brand. Successful brand identity attracts new customers while making existing customers feel at home. It’s both outward- and inward-facing. | 1 |
Ruby | Ruby | add glibc to os.version on linux | 4e94f75bcb10971ef421e075f297a4e35d52fcd1 | <ide><path>Library/Homebrew/github_packages.rb
<ide> def upload_bottle(user, token, skopeo, formula_full_name, bottle_hash, dry_run:)
<ide> end
<ide> raise TypeError, "unknown tab['built_on']['os']: #{tab["built_on"]["os"]}" if os.blank?
<ide>
<del> os_version = if tab["built_on"].present? && tab["built_on"]["os_version"].present?
<del> tab["built_on"]["os_version"]
<add> os_version = tab["built_on"]["os_version"] if tab["built_on"].present?
<add> os_version = case os
<add> when "darwin"
<add> os_version || "macOS #{MacOS::Version.from_symbol(bottle_tag)}"
<add> when "linux"
<add> glibc_version = tab["built_on"]["glibc_version"] if tab["built_on"].present?
<add> os_version ||= "Ubuntu 16.04.7"
<add> glibc_version ||= "2.23"
<add> os_version = os_version.delete_suffix " LTS"
<add> "#{os_version} glibc #{glibc_version}"
<ide> else
<del> MacOS::Version.from_symbol(bottle_tag).to_s
<add> os_version
<ide> end
<ide>
<ide> platform_hash = { | 1 |
Ruby | Ruby | remove unneeded objectwrapper class | df36a6f7598a7e963fb3d79fb48fd1c073045a43 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def render(options = nil, extra_options = {}, &block) #:doc:
<ide> else
<ide> render_for_text(
<ide> @template.send!(:render_partial, partial,
<del> ActionView::Base::ObjectWrapper.new(options[:object]), options[:locals]), options[:status]
<add> options[:object], options[:locals]), options[:status]
<ide> )
<ide> end
<ide>
<ide><path>actionpack/lib/action_view/base.rb
<ide> module CompiledTemplates #:nodoc:
<ide> cattr_reader :computed_public_paths
<ide> @@computed_public_paths = {}
<ide>
<del> class ObjectWrapper < Struct.new(:value) #:nodoc:
<del> end
<del>
<ide> def self.helper_modules #:nodoc:
<ide> helpers = []
<ide> Dir.entries(File.expand_path("#{File.dirname(__FILE__)}/helpers")).sort.each do |file|
<ide> def render(options = {}, local_assigns = {}, &block) #:nodoc:
<ide> elsif options[:partial] && options[:collection]
<ide> render_partial_collection(options[:partial], options[:collection], options[:spacer_template], options[:locals], options[:as])
<ide> elsif options[:partial]
<del> render_partial(options[:partial], ActionView::Base::ObjectWrapper.new(options[:object]), options[:locals])
<add> render_partial(options[:partial], options[:object], options[:locals])
<ide> elsif options[:inline]
<ide> render_inline(options[:inline], options[:locals], options[:type])
<ide> end
<ide><path>actionpack/lib/action_view/partial_template.rb
<ide> def counter=(num)
<ide> private
<ide> def add_object_to_local_assigns!(object)
<ide> @locals[:object] ||=
<del> @locals[@variable_name] ||=
<del> if object.is_a?(ActionView::Base::ObjectWrapper)
<del> object.value
<del> else
<del> object
<del> end || @view_controller.instance_variable_get("@#{variable_name}")
<add> @locals[@variable_name] ||= object || @view_controller.instance_variable_get("@#{variable_name}")
<ide> @locals[as] ||= @locals[:object] if as
<ide> end
<ide> | 3 |
Java | Java | implement cloning for all reactshadownodes | 62efff8ab8e05d27da24e50d1751660138a8ac76 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java
<ide> private static class MutableYogaValue {
<ide> float value;
<ide> YogaUnit unit;
<ide>
<add> private MutableYogaValue() { }
<add>
<add> private MutableYogaValue(MutableYogaValue mutableYogaValue) {
<add> this.value = mutableYogaValue.value;
<add> this.unit = mutableYogaValue.unit;
<add> }
<add>
<ide> void setFromDynamic(Dynamic dynamic) {
<ide> if (dynamic.isNull()) {
<ide> unit = YogaUnit.UNDEFINED;
<ide> void setFromDynamic(Dynamic dynamic) {
<ide> }
<ide> }
<ide>
<del> private final MutableYogaValue mTempYogaValue = new MutableYogaValue();
<add> private final MutableYogaValue mTempYogaValue;
<add>
<add> public LayoutShadowNode() {
<add> mTempYogaValue = new MutableYogaValue();
<add> }
<add>
<add> protected LayoutShadowNode(LayoutShadowNode node) {
<add> super(node);
<add> mTempYogaValue = new MutableYogaValue(node.mTempYogaValue);
<add> }
<add>
<add> @Override
<add> public LayoutShadowNode mutableCopy() {
<add> return new LayoutShadowNode(this);
<add> }
<ide>
<ide> @ReactProp(name = ViewProps.WIDTH)
<ide> public void setWidth(Dynamic width) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ModalHostShadowNode.java
<ide> */
<ide> class ModalHostShadowNode extends LayoutShadowNode {
<ide>
<add> public ModalHostShadowNode() {}
<add>
<add> private ModalHostShadowNode(ModalHostShadowNode node) {
<add> super(node);
<add> }
<add>
<add> @Override
<add> public ModalHostShadowNode mutableCopy() {
<add> return new ModalHostShadowNode(this);
<add> }
<add>
<ide> /**
<ide> * We need to set the styleWidth and styleHeight of the one child (represented by the <View/>
<ide> * within the <RCTModalHostView/> in Modal.js. This needs to fill the entire window.
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/progressbar/ProgressBarShadowNode.java
<ide> public class ProgressBarShadowNode extends LayoutShadowNode implements YogaMeasu
<ide>
<ide> private String mStyle = ReactProgressBarViewManager.DEFAULT_STYLE;
<ide>
<del> private final SparseIntArray mHeight = new SparseIntArray();
<del> private final SparseIntArray mWidth = new SparseIntArray();
<del> private final Set<Integer> mMeasured = new HashSet<>();
<add> private final SparseIntArray mHeight;
<add> private final SparseIntArray mWidth;
<add> private final Set<Integer> mMeasured;
<ide>
<ide> public ProgressBarShadowNode() {
<add> mHeight = new SparseIntArray();
<add> mWidth = new SparseIntArray();
<add> mMeasured = new HashSet<>();
<ide> setMeasureFunction(this);
<ide> }
<ide>
<add> public ProgressBarShadowNode(ProgressBarShadowNode node) {
<add> super(node);
<add> mWidth = node.mWidth.clone();
<add> mHeight = node.mHeight.clone();
<add> mMeasured = new HashSet<>(node.mMeasured);
<add> setMeasureFunction(this);
<add> }
<add>
<add> @Override
<add> public ProgressBarShadowNode mutableCopy() {
<add> return new ProgressBarShadowNode(this);
<add> }
<add>
<ide> public @Nullable String getStyle() {
<ide> return mStyle;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderManager.java
<ide> static class ReactSliderShadowNode extends LayoutShadowNode implements
<ide> private boolean mMeasured;
<ide>
<ide> private ReactSliderShadowNode() {
<add> initMeasureFunction();
<add> }
<add>
<add> private ReactSliderShadowNode(ReactSliderShadowNode node) {
<add> super(node);
<add> mWidth = node.mWidth;
<add> mHeight = node.mHeight;
<add> mMeasured = node.mMeasured;
<add> initMeasureFunction();
<add> }
<add>
<add> private void initMeasureFunction() {
<ide> setMeasureFunction(this);
<ide> }
<ide>
<add> @Override
<add> public ReactSliderShadowNode mutableCopy() {
<add> return new ReactSliderShadowNode(this);
<add> }
<add>
<ide> @Override
<ide> public long measure(
<ide> YogaNode node,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitchManager.java
<ide> static class ReactSwitchShadowNode extends LayoutShadowNode implements
<ide> private boolean mMeasured;
<ide>
<ide> private ReactSwitchShadowNode() {
<add> initMeasureFunction();
<add> }
<add>
<add> private ReactSwitchShadowNode(ReactSwitchShadowNode node) {
<add> super(node);
<add> mWidth = node.mWidth;
<add> mHeight = node.mHeight;
<add> mMeasured = node.mMeasured;
<add> initMeasureFunction();
<add> }
<add>
<add> private void initMeasureFunction() {
<ide> setMeasureFunction(this);
<ide> }
<ide>
<add> @Override
<add> public ReactSwitchShadowNode mutableCopy() {
<add> return new ReactSwitchShadowNode(this);
<add> }
<add>
<ide> @Override
<ide> public long measure(
<ide> YogaNode node,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java
<ide> private static int parseNumericFontWeight(String fontWeightString) {
<ide> protected boolean mContainsImages = false;
<ide> protected float mHeightOfTallestInlineImage = Float.NaN;
<ide>
<add> public ReactBaseTextShadowNode() {}
<add>
<add> public ReactBaseTextShadowNode(ReactBaseTextShadowNode node) {
<add> super(node);
<add> mLineHeight = node.mLineHeight;
<add> mIsColorSet = node.mIsColorSet;
<add> mAllowFontScaling = node.mAllowFontScaling;
<add> mColor = node.mColor;
<add> mIsBackgroundColorSet = node.mIsBackgroundColorSet;
<add> mBackgroundColor = node.mBackgroundColor;
<add>
<add> mNumberOfLines = node.mNumberOfLines;
<add> mFontSize = node.mFontSize;
<add> mFontSizeInput = node.mFontSizeInput;
<add> mLineHeightInput = node.mLineHeightInput;
<add> mTextAlign = node.mTextAlign;
<add> mTextBreakStrategy = node.mTextBreakStrategy;
<add>
<add> mTextShadowOffsetDx = node.mTextShadowOffsetDx;
<add> mTextShadowOffsetDy = node.mTextShadowOffsetDy;
<add> mTextShadowRadius = node.mTextShadowRadius;
<add> mTextShadowColor = node.mTextShadowColor;
<add>
<add> mIsUnderlineTextDecorationSet = node.mIsUnderlineTextDecorationSet;
<add> mIsLineThroughTextDecorationSet = node.mIsLineThroughTextDecorationSet;
<add> mIncludeFontPadding = node.mIncludeFontPadding;
<add> mFontStyle = node.mFontStyle;
<add> mFontWeight = node.mFontWeight;
<add> mFontFamily = node.mFontFamily;
<add> mContainsImages = node.mContainsImages;
<add> mHeightOfTallestInlineImage = node.mHeightOfTallestInlineImage;
<add> }
<add>
<ide> // Returns a line height which takes into account the requested line height
<ide> // and the height of the inline images.
<ide> public float getEffectiveLineHeight() {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactRawTextShadowNode.java
<ide> public class ReactRawTextShadowNode extends ReactShadowNodeImpl {
<ide>
<ide> private @Nullable String mText = null;
<ide>
<add> public ReactRawTextShadowNode() { }
<add>
<add> private ReactRawTextShadowNode(ReactRawTextShadowNode node) {
<add> super(node);
<add> this.mText = node.mText;
<add> }
<add>
<add> @Override
<add> public ReactShadowNodeImpl mutableCopy() {
<add> return new ReactRawTextShadowNode(this);
<add> }
<add>
<ide> @ReactProp(name = PROP_TEXT)
<ide> public void setText(@Nullable String text) {
<ide> mText = text;
<ide> public void setText(@Nullable String text) {
<ide> public boolean isVirtual() {
<ide> return true;
<ide> }
<add>
<add>
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextInlineImageShadowNode.java
<ide> public abstract class ReactTextInlineImageShadowNode extends LayoutShadowNode {
<ide> * place of this node.
<ide> */
<ide> public abstract TextInlineImageSpan buildInlineImageSpan();
<add>
<add> public ReactTextInlineImageShadowNode() {}
<add>
<add> protected ReactTextInlineImageShadowNode(ReactTextInlineImageShadowNode node) {
<add> super(node);
<add> }
<add>
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java
<ide> import android.view.Gravity;
<ide> import android.widget.TextView;
<ide> import com.facebook.infer.annotation.Assertions;
<add>import com.facebook.react.uimanager.LayoutShadowNode;
<ide> import com.facebook.react.uimanager.Spacing;
<ide> import com.facebook.react.uimanager.UIViewOperationQueue;
<ide> import com.facebook.yoga.YogaConstants;
<ide> public long measure(
<ide> };
<ide>
<ide> public ReactTextShadowNode() {
<add> initMeasureFunction();
<add> }
<add>
<add> private ReactTextShadowNode(ReactTextShadowNode node) {
<add> super(node);
<add> this.mPreparedSpannableText = node.mPreparedSpannableText;
<add> initMeasureFunction();
<add> }
<add>
<add> private void initMeasureFunction() {
<ide> if (!isVirtual()) {
<ide> setMeasureFunction(mTextMeasureFunction);
<ide> }
<ide> }
<ide>
<add> @Override
<add> public LayoutShadowNode mutableCopy() {
<add> return new ReactTextShadowNode(this);
<add> }
<add>
<ide> // Return text alignment according to LTR or RTL style
<ide> private int getTextAlign() {
<ide> int textAlign = mTextAlign;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactVirtualTextShadowNode.java
<ide> public class ReactVirtualTextShadowNode extends ReactBaseTextShadowNode {
<ide> public boolean isVirtual() {
<ide> return true;
<ide> }
<add>
<add> public ReactVirtualTextShadowNode() { }
<add>
<add> private ReactVirtualTextShadowNode(ReactVirtualTextShadowNode node) {
<add> super(node);
<add> }
<add>
<add> @Override
<add> public ReactVirtualTextShadowNode mutableCopy() {
<add> return new ReactVirtualTextShadowNode(this);
<add> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/FrescoBasedReactTextInlineImageShadowNode.java
<ide>
<ide> package com.facebook.react.views.text.frescosupport;
<ide>
<add>import com.facebook.react.uimanager.LayoutShadowNode;
<ide> import javax.annotation.Nullable;
<ide>
<ide> import java.util.Locale;
<ide> public FrescoBasedReactTextInlineImageShadowNode(
<ide> mCallerContext = callerContext;
<ide> }
<ide>
<add> private FrescoBasedReactTextInlineImageShadowNode(FrescoBasedReactTextInlineImageShadowNode node) {
<add> super(node);
<add> mHeaders = node.mHeaders; // mHeaders is immutable
<add> mWidth = node.mWidth;
<add> mHeight = node.mHeight;
<add> mDraweeControllerBuilder = node.mDraweeControllerBuilder;
<add> mCallerContext = node.mCallerContext;
<add> mUri = node.mUri;
<add> }
<add>
<add> @Override
<add> public FrescoBasedReactTextInlineImageShadowNode mutableCopy() {
<add> return new FrescoBasedReactTextInlineImageShadowNode(this);
<add> }
<add>
<ide> @ReactProp(name = "src")
<ide> public void setSource(@Nullable ReadableArray sources) {
<ide> final String source =
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputShadowNode.java
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.common.annotations.VisibleForTesting;
<add>import com.facebook.react.uimanager.LayoutShadowNode;
<ide> import com.facebook.react.uimanager.Spacing;
<ide> import com.facebook.react.uimanager.ThemedReactContext;
<ide> import com.facebook.react.uimanager.UIViewOperationQueue;
<ide> public ReactTextInputShadowNode() {
<ide> setMeasureFunction(this);
<ide> }
<ide>
<add> private ReactTextInputShadowNode(ReactTextInputShadowNode node) {
<add> super(node);
<add> mMostRecentEventCount = node.mMostRecentEventCount;
<add> mText = node.mText;
<add> mLocalData = node.mLocalData;
<add> setMeasureFunction(this);
<add> ThemedReactContext themedContext = getThemedContext();
<add> if (themedContext != null) {
<add> setThemedContext(themedContext);
<add> }
<add> }
<add>
<add> @Override
<add> public ReactTextInputShadowNode mutableCopy() {
<add> return new ReactTextInputShadowNode(this);
<add> }
<add>
<ide> @Override
<ide> public void setThemedContext(ThemedReactContext themedContext) {
<ide> super.setThemedContext(themedContext); | 12 |
Mixed | Python | update a3c_cartpole.py to tf2.x | 8722f59f87acc4c386c10bb7bf5c0f73c6469812 | <ide><path>research/a3c_blogpost/README.md
<ide> In order to run this code, you will need the following prerequisites:
<ide>
<ide> * [OpenAI Gym](https://github.com/openai/gym) - `pip install gym`
<ide> * [pyglet](https://bitbucket.org/pyglet/pyglet/wiki/Home) - `pip install pyglet`
<del>* [TensorFlow](https://www.tensorflow.org/install/) - `pip install tensorflow==v1.14.0`
<add>* [TensorFlow](https://www.tensorflow.org/install/) - `pip install tensorflow==2.2.0`
<ide><path>research/a3c_blogpost/a3c_cartpole.py
<ide> from tensorflow.python import keras
<ide> from tensorflow.python.keras import layers
<ide>
<del>tf.enable_eager_execution()
<del>
<ide> parser = argparse.ArgumentParser(description='Run A3C algorithm on the game '
<ide> 'Cartpole.')
<ide> parser.add_argument('--algorithm', default='a3c', type=str,
<ide> def __init__(self):
<ide> env = gym.make(self.game_name)
<ide> self.state_size = env.observation_space.shape[0]
<ide> self.action_size = env.action_space.n
<del> self.opt = tf.train.AdamOptimizer(args.lr, use_locking=True)
<add> self.opt = tf.compat.v1.train.AdamOptimizer(args.lr, use_locking=True)
<ide> print(self.state_size, self.action_size)
<ide>
<ide> self.global_model = ActorCriticModel(self.state_size, self.action_size) # global network
<ide> def compute_loss(self,
<ide>
<ide> # Calculate our policy loss
<ide> policy = tf.nn.softmax(logits)
<del> entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=policy, logits=logits)
<add> entropy = tf.nn.softmax_cross_entropy_with_logits(labels=policy, logits=logits)
<ide>
<ide> policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions,
<ide> logits=logits) | 2 |
Text | Text | fix changelog entry [ci skip] | d7d228402efd1ddbbdb2b15d2e91ec22693b9298 | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<del>* `CollectionAssociation#count` returns 0 without querying if the
<del> parent record is new.
<add>* `CollectionAssociation#count` returns `0` without querying if the
<add> parent record is not persisted.
<ide>
<ide> Before:
<ide>
<del> person.pets
<add> person.pets.count
<ide> # SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" IS NULL
<ide> # => 0
<ide>
<ide> After:
<ide>
<del> person.pets
<add> person.pets.count
<ide> # fires without sql query
<ide> # => 0
<ide> | 1 |
Ruby | Ruby | remove @secure ivar | aad33d5808a8c5fd10732db1045fb3367a4e72f4 | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> def exists?
<ide> class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc:
<ide> def self.build(request)
<ide> host = request.host
<del> secure = request.ssl?
<ide>
<del> new(host, secure, request)
<add> new(host, request)
<ide> end
<ide>
<ide> def write(*)
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> class CookieJar #:nodoc:
<ide>
<ide> def self.build(req, cookies)
<ide> host = req.host
<del> secure = req.ssl?
<del> new(host, secure, req).tap do |hash|
<add> new(host, req).tap do |hash|
<ide> hash.update(cookies)
<ide> end
<ide> end
<ide>
<del> def initialize(host = nil, secure = false, request)
<add> def initialize(host = nil, request)
<ide> @set_cookies = {}
<ide> @delete_cookies = {}
<ide> @host = host
<del> @secure = secure
<ide> @request = request
<ide> @cookies = {}
<ide> @committed = false
<ide> def recycle! #:nodoc:
<ide>
<ide> private
<ide> def write_cookie?(cookie)
<del> @secure || !cookie[:secure] || always_write_cookie
<add> @request.ssl? || !cookie[:secure] || always_write_cookie
<ide> end
<ide> end
<ide> | 2 |
Javascript | Javascript | use d3.quantile in d3.chart.box | c6c70d4730e182cae80277f0dc7ba1fb04cf296e | <ide><path>d3.chart.js
<ide> function d3_chart_boxWhiskers(d) {
<ide> }
<ide>
<ide> function d3_chart_boxQuartiles(d) {
<del> // TODO avoid sorting data twice?
<del> var n = d.length;
<del> return [.25, .5, .75].map(function(q) {
<del> q *= n;
<del> return ~~q === q ? (d[q] + d[q + 1]) / 2 : d[Math.round(q)];
<del> });
<add> return [
<add> d3.quantile(d, .25),
<add> d3.quantile(d, .5),
<add> d3.quantile(d, .75)
<add> ];
<ide> }
<ide> // Chart design based on the recommendations of Stephen Few. Implementation
<ide> // based on the work of Clint Ivy, Jamie Love, and Jason Davies.
<ide><path>d3.chart.min.js
<del>(function(){function n(a){return a.y}function m(a){return a.x}function l(a,b){var c=b.length-1;b=b.slice().sort(d3.ascending);return d3.range(a).map(function(d){return b[~~(d*c/a)]})}function k(a){return a[1]}function j(a){return a[0]}function g(a){var b=a(0);return function(c){return Math.abs(a(c)-b)}}function f(a){return function(b){return"translate("+a(b)+",0)"}}function e(a){return a.measures}function d(a){return a.markers}function c(a){return a.ranges}function b(a){var b=a.length;return[.25,.5,.75].map(function(c){c*=b;return~~c===c?(a[c]+a[c+1])/2:a[Math.round(c)]})}function a(a){return[0,a.length-1]}d3.chart={},d3.chart.box=function(){function k(a){a.each(function(a,b){a=a.map(g).sort(d3.ascending);var k=d3.select(this),l=a.length,m=a[0],n=a[l-1],o=a.quartiles=i(a),p=h&&h.call(this,a,b),q=p&&p.map(function(b){return a[b]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(f&&f.call(this,a,b)||[m,n]).range([d,0]),t=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(s.range());this.__chart__=s;var u=k.selectAll("line.center").data(q?[q]:[]);u.enter().insert("svg:line","rect").attr("class","center").attr("x1",c/2).attr("y1",function(a){return t(a[0])}).attr("x2",c/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(e).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=k.selectAll("rect.box").data([o]);v.enter().append("svg:rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",c).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=k.selectAll("line.median").data([o[1]]);w.enter().append("svg:line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).transition().duration(e).attr("y1",s).attr("y2",s),w.transition().duration(e).attr("y1",s).attr("y2",s);var x=k.selectAll("line.whisker").data(q||[]);x.enter().insert("svg:line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).style("opacity",1e-6).transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=k.selectAll("circle.outlier").data(r,Number);y.enter().insert("svg:circle","text").attr("class","outlier").attr("r",5).attr("cx",c/2).attr("cy",function(b){return t(a[b])}).style("opacity",1e-6).transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.exit().transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1e-6).remove();var z=j||s.tickFormat(8),A=k.selectAll("text.box").data(o);A.enter().append("svg:text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return b&1?6:-6}).attr("x",function(a,b){return b&1?c:0}).attr("y",t).attr("text-anchor",function(a,b){return b&1?"start":"end"}).text(z).transition().duration(e).attr("y",s),A.transition().duration(e).text(z).attr("y",s);var B=k.selectAll("text.whisker").data(q||[]);B.enter().append("svg:text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",c).attr("y",t).text(z).style("opacity",1e-6).transition().duration(e).attr("y",s).style("opacity",1),B.transition().duration(e).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(e).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var c=1,d=1,e=0,f=null,g=Number,h=a,i=b,j=null;k.width=function(a){if(!arguments.length)return c;c=a;return k},k.height=function(a){if(!arguments.length)return d;d=a;return k},k.tickFormat=function(a){if(!arguments.length)return j;j=a;return k},k.duration=function(a){if(!arguments.length)return e;e=a;return k},k.domain=function(a){if(!arguments.length)return f;f=a==null?a:d3.functor(a);return k},k.value=function(a){if(!arguments.length)return g;g=a;return k},k.whiskers=function(a){if(!arguments.length)return h;h=a;return k},k.quartiles=function(a){if(!arguments.length)return i;i=a;return k};return k},d3.chart.bullet=function(){function o(a){a.each(function(a,c){var d=i.call(this,a,c).slice().sort(d3.descending),e=j.call(this,a,c).slice().sort(d3.descending),o=k.call(this,a,c).slice().sort(d3.descending),p=d3.select(this),q=d3.scale.linear().domain([0,Math.max(d[0],e[0],o[0])]).range(b?[l,0]:[0,l]),r=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(q.range());this.__chart__=q;var s=g(r),t=g(q),u=p.selectAll("rect.range").data(d);u.enter().append("svg:rect").attr("class",function(a,b){return"range s"+b}).attr("width",s).attr("height",m).attr("x",b?r:0).transition().duration(h).attr("width",t).attr("x",b?q:0),u.transition().duration(h).attr("x",b?q:0).attr("width",t).attr("height",m);var v=p.selectAll("rect.measure").data(o);v.enter().append("svg:rect").attr("class",function(a,b){return"measure s"+b}).attr("width",s).attr("height",m/3).attr("x",b?r:0).attr("y",m/3).transition().duration(h).attr("width",t).attr("x",b?q:0),v.transition().duration(h).attr("width",t).attr("height",m/3).attr("x",b?q:0).attr("y",m/3);var w=p.selectAll("line.marker").data(e);w.enter().append("svg:line").attr("class","marker").attr("x1",r).attr("x2",r).attr("y1",m/6).attr("y2",m*5/6).transition().duration(h).attr("x1",q).attr("x2",q),w.transition().duration(h).attr("x1",q).attr("x2",q).attr("y1",m/6).attr("y2",m*5/6);var x=n||q.tickFormat(8),y=p.selectAll("g.tick").data(q.ticks(8),function(a){return this.textContent||x(a)}),z=y.enter().append("svg:g").attr("class","tick").attr("transform",f(r)).style("opacity",1e-6);z.append("svg:line").attr("y1",m).attr("y2",m*7/6),z.append("svg:text").attr("text-anchor","middle").attr("dy","1em").attr("y",m*7/6).text(x),z.transition().duration(h).attr("transform",f(q)).style("opacity",1);var A=y.transition().duration(h).attr("transform",f(q)).style("opacity",1);A.select("line").attr("y1",m).attr("y2",m*7/6),A.select("text").attr("y",m*7/6),y.exit().transition().duration(h).attr("transform",f(q)).style("opacity",1e-6).remove()}),d3.timer.flush()}var a="left",b=!1,h=0,i=c,j=d,k=e,l=380,m=30,n=null;o.orient=function(c){if(!arguments.length)return a;a=c,b=a=="right"||a=="bottom";return o},o.ranges=function(a){if(!arguments.length)return i;i=a;return o},o.markers=function(a){if(!arguments.length)return j;j=a;return o},o.measures=function(a){if(!arguments.length)return k;k=a;return o},o.width=function(a){if(!arguments.length)return l;l=a;return o},o.height=function(a){if(!arguments.length)return m;m=a;return o},o.tickFormat=function(a){if(!arguments.length)return n;n=a;return o},o.duration=function(a){if(!arguments.length)return h;h=a;return o};return o},d3.chart.horizon=function(){function n(j){j.each(function(j,k){var n=d3.select(this),o=2*a+1,p=Infinity,q=-Infinity,r=-Infinity,s,t,u,v=j.map(function(a,b){var c=d.call(this,a,b),f=e.call(this,a,b);c<p&&(p=c),c>q&&(q=c),-f>r&&(r=-f),f>r&&(r=f);return[c,f]}),z=d3.scale.linear().domain([p,q]).range([0,f]),A=d3.scale.linear().domain([0,r]).range([0,g*a]);this.__chart__?(s=this.__chart__.x,t=this.__chart__.y,u=this.__chart__.id):(s=d3.scale.linear().domain([0,Infinity]).range(z.range()),t=d3.scale.linear().domain([0,Infinity]).range(A.range()),u=++i);var B=n.selectAll("defs").data([v]),C=B.enter().append("svg:defs");C.append("svg:clipPath").attr("id","d3_chart_horizon_clip"+u).append("svg:rect").attr("width",f).attr("height",g),B.select("rect").transition().duration(l).attr("width",f).attr("height",g),C.append("svg:path").attr("id","d3_chart_horizon_path"+u).attr("d",h.interpolate(c).x(function(a){return s(a[0])}).y0(g*a).y1(function(b){return g*a-t(b[1])})).transition().duration(l).attr("d",h.x(function(a){return z(a[0])}).y1(function(b){return g*a-A(b[1])})),B.select("path").transition().duration(l).attr("d",h),n.selectAll("g").data([null]).enter().append("svg:g").attr("clip-path","url(#d3_chart_horizon_clip"+u+")");var D=b=="offset"?function(b){return"translate(0,"+(b+(b<0)-a)*g+")"}:function(b){return(b<0?"scale(1,-1)":"")+"translate(0,"+(b-a)*g+")"},E=n.select("g").selectAll("use").data(d3.range(-1,-a-1,-1).concat(d3.range(1,a+1)),Number);E.enter().append("svg:use").attr("xlink:href","#d3_chart_horizon_path"+u).attr("transform",function(a){return D(a+(a>0?1:-1))}).style("fill",m).transition().duration(l).attr("transform",D),E.transition().duration(l).attr("transform",D).style("fill",m),E.exit().transition().duration(l).attr("transform",D).remove(),this.__chart__={x:z,y:A,id:u}}),d3.timer.flush()}var a=1,b="offset",c="linear",d=j,e=k,f=960,g=40,l=0,m=d3.scale.linear().domain([-1,0,1]).range(["#d62728","#fff","#1f77b4"]);n.duration=function(a){if(!arguments.length)return l;l=+a;return n},n.bands=function(b){if(!arguments.length)return a;a=+b,m.domain([-a,0,a]);return n},n.mode=function(a){if(!arguments.length)return b;b=a+"";return n},n.colors=function(a){if(!arguments.length)return m.range();m.range(a);return n},n.interpolate=function(a){if(!arguments.length)return c;c=a+"";return n},n.x=function(a){if(!arguments.length)return d;d=a;return n},n.y=function(a){if(!arguments.length)return e;e=a;return n},n.width=function(a){if(!arguments.length)return width;f=+a;return n},n.height=function(a){if(!arguments.length)return height;g=+a;return n};return n};var h=d3.svg.area(),i=0;d3.chart.qq=function(){function i(i){i.each(function(i,j){var k=d3.select(this),m=l(f,g.call(this,i,j)),n=l(f,h.call(this,i,j)),o=d&&d.call(this,i,j)||[d3.min(m),d3.max(m)],p=d&&d.call(this,i,j)||[d3.min(n),d3.max(n)],q,r,s=d3.scale.linear().domain(o).range([0,a]),t=d3.scale.linear().domain(p).range([b,0]);this.__chart__?(q=this.__chart__.x,r=this.__chart__.y):(q=d3.scale.linear().domain([0,Infinity]).range(s.range()),r=d3.scale.linear().domain([0,Infinity]).range(t.range())),this.__chart__={x:s,y:t};var u=k.selectAll("line.diagonal").data([null]);u.enter().append("svg:line").attr("class","diagonal").attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1])),u.transition().duration(c).attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1]));var v=k.selectAll("circle").data(d3.range(f).map(function(a){return{x:m[a],y:n[a]}}));v.enter().append("svg:circle").attr("class","quantile").attr("r",4.5).attr("cx",function(a){return q(a.x)}).attr("cy",function(a){return r(a.y)}).style("opacity",1e-6).transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.exit().transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1e-6).remove();var w=e||s.tickFormat(4),z=e||t.tickFormat(4),A=function(a){return"translate("+s(a)+","+b+")"},B=function(a){return"translate(0,"+t(a)+")"},C=k.selectAll("g.x.tick").data(s.ticks(4),function(a){return this.textContent||w(a)}),D=C.enter().append("svg:g").attr("class","x tick").attr("transform",function(a){return"translate("+q(a)+","+b+")"}).style("opacity",1e-6);D.append("svg:line").attr("y1",0).attr("y2",-6),D.append("svg:text").attr("text-anchor","middle").attr("dy","1em").text(w),D.transition().duration(c).attr("transform",A).style("opacity",1),C.transition().duration(c).attr("transform",A).style("opacity",1),C.exit().transition().duration(c).attr("transform",A).style("opacity",1e-6).remove();var E=k.selectAll("g.y.tick").data(t.ticks(4),function(a){return this.textContent||z(a)}),F=E.enter().append("svg:g").attr("class","y tick").attr("transform",function(a){return"translate(0,"+r(a)+")"}).style("opacity",1e-6);F.append("svg:line").attr("x1",0).attr("x2",6),F.append("svg:text").attr("text-anchor","end").attr("dx","-.5em").attr("dy",".3em").text(z),F.transition().duration(c).attr("transform",B).style("opacity",1),E.transition().duration(c).attr("transform",B).style("opacity",1),E.exit().transition().duration(c).attr("transform",B).style("opacity",1e-6).remove()})}var a=1,b=1,c=0,d=null,e=null,f=100,g=m,h=n;i.width=function(b){if(!arguments.length)return a;a=b;return i},i.height=function(a){if(!arguments.length)return b;b=a;return i},i.duration=function(a){if(!arguments.length)return c;c=a;return i},i.domain=function(a){if(!arguments.length)return d;d=a==null?a:d3.functor(a);return i},i.count=function(a){if(!arguments.length)return f;f=a;return i},i.x=function(a){if(!arguments.length)return g;g=a;return i},i.y=function(a){if(!arguments.length)return h;h=a;return i},i.tickFormat=function(a){if(!arguments.length)return e;e=a;return i};return i}})()
<ide>\ No newline at end of file
<add>(function(){function n(a){return a.y}function m(a){return a.x}function l(a,b){var c=b.length-1;b=b.slice().sort(d3.ascending);return d3.range(a).map(function(d){return b[~~(d*c/a)]})}function k(a){return a[1]}function j(a){return a[0]}function g(a){var b=a(0);return function(c){return Math.abs(a(c)-b)}}function f(a){return function(b){return"translate("+a(b)+",0)"}}function e(a){return a.measures}function d(a){return a.markers}function c(a){return a.ranges}function b(a){return[d3.quantile(a,.25),d3.quantile(a,.5),d3.quantile(a,.75)]}function a(a){return[0,a.length-1]}d3.chart={},d3.chart.box=function(){function k(a){a.each(function(a,b){a=a.map(g).sort(d3.ascending);var k=d3.select(this),l=a.length,m=a[0],n=a[l-1],o=a.quartiles=i(a),p=h&&h.call(this,a,b),q=p&&p.map(function(b){return a[b]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(f&&f.call(this,a,b)||[m,n]).range([d,0]),t=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(s.range());this.__chart__=s;var u=k.selectAll("line.center").data(q?[q]:[]);u.enter().insert("svg:line","rect").attr("class","center").attr("x1",c/2).attr("y1",function(a){return t(a[0])}).attr("x2",c/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(e).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=k.selectAll("rect.box").data([o]);v.enter().append("svg:rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",c).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=k.selectAll("line.median").data([o[1]]);w.enter().append("svg:line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).transition().duration(e).attr("y1",s).attr("y2",s),w.transition().duration(e).attr("y1",s).attr("y2",s);var x=k.selectAll("line.whisker").data(q||[]);x.enter().insert("svg:line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).style("opacity",1e-6).transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=k.selectAll("circle.outlier").data(r,Number);y.enter().insert("svg:circle","text").attr("class","outlier").attr("r",5).attr("cx",c/2).attr("cy",function(b){return t(a[b])}).style("opacity",1e-6).transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.exit().transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1e-6).remove();var z=j||s.tickFormat(8),A=k.selectAll("text.box").data(o);A.enter().append("svg:text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return b&1?6:-6}).attr("x",function(a,b){return b&1?c:0}).attr("y",t).attr("text-anchor",function(a,b){return b&1?"start":"end"}).text(z).transition().duration(e).attr("y",s),A.transition().duration(e).text(z).attr("y",s);var B=k.selectAll("text.whisker").data(q||[]);B.enter().append("svg:text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",c).attr("y",t).text(z).style("opacity",1e-6).transition().duration(e).attr("y",s).style("opacity",1),B.transition().duration(e).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(e).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var c=1,d=1,e=0,f=null,g=Number,h=a,i=b,j=null;k.width=function(a){if(!arguments.length)return c;c=a;return k},k.height=function(a){if(!arguments.length)return d;d=a;return k},k.tickFormat=function(a){if(!arguments.length)return j;j=a;return k},k.duration=function(a){if(!arguments.length)return e;e=a;return k},k.domain=function(a){if(!arguments.length)return f;f=a==null?a:d3.functor(a);return k},k.value=function(a){if(!arguments.length)return g;g=a;return k},k.whiskers=function(a){if(!arguments.length)return h;h=a;return k},k.quartiles=function(a){if(!arguments.length)return i;i=a;return k};return k},d3.chart.bullet=function(){function o(a){a.each(function(a,c){var d=i.call(this,a,c).slice().sort(d3.descending),e=j.call(this,a,c).slice().sort(d3.descending),o=k.call(this,a,c).slice().sort(d3.descending),p=d3.select(this),q=d3.scale.linear().domain([0,Math.max(d[0],e[0],o[0])]).range(b?[l,0]:[0,l]),r=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(q.range());this.__chart__=q;var s=g(r),t=g(q),u=p.selectAll("rect.range").data(d);u.enter().append("svg:rect").attr("class",function(a,b){return"range s"+b}).attr("width",s).attr("height",m).attr("x",b?r:0).transition().duration(h).attr("width",t).attr("x",b?q:0),u.transition().duration(h).attr("x",b?q:0).attr("width",t).attr("height",m);var v=p.selectAll("rect.measure").data(o);v.enter().append("svg:rect").attr("class",function(a,b){return"measure s"+b}).attr("width",s).attr("height",m/3).attr("x",b?r:0).attr("y",m/3).transition().duration(h).attr("width",t).attr("x",b?q:0),v.transition().duration(h).attr("width",t).attr("height",m/3).attr("x",b?q:0).attr("y",m/3);var w=p.selectAll("line.marker").data(e);w.enter().append("svg:line").attr("class","marker").attr("x1",r).attr("x2",r).attr("y1",m/6).attr("y2",m*5/6).transition().duration(h).attr("x1",q).attr("x2",q),w.transition().duration(h).attr("x1",q).attr("x2",q).attr("y1",m/6).attr("y2",m*5/6);var x=n||q.tickFormat(8),y=p.selectAll("g.tick").data(q.ticks(8),function(a){return this.textContent||x(a)}),z=y.enter().append("svg:g").attr("class","tick").attr("transform",f(r)).style("opacity",1e-6);z.append("svg:line").attr("y1",m).attr("y2",m*7/6),z.append("svg:text").attr("text-anchor","middle").attr("dy","1em").attr("y",m*7/6).text(x),z.transition().duration(h).attr("transform",f(q)).style("opacity",1);var A=y.transition().duration(h).attr("transform",f(q)).style("opacity",1);A.select("line").attr("y1",m).attr("y2",m*7/6),A.select("text").attr("y",m*7/6),y.exit().transition().duration(h).attr("transform",f(q)).style("opacity",1e-6).remove()}),d3.timer.flush()}var a="left",b=!1,h=0,i=c,j=d,k=e,l=380,m=30,n=null;o.orient=function(c){if(!arguments.length)return a;a=c,b=a=="right"||a=="bottom";return o},o.ranges=function(a){if(!arguments.length)return i;i=a;return o},o.markers=function(a){if(!arguments.length)return j;j=a;return o},o.measures=function(a){if(!arguments.length)return k;k=a;return o},o.width=function(a){if(!arguments.length)return l;l=a;return o},o.height=function(a){if(!arguments.length)return m;m=a;return o},o.tickFormat=function(a){if(!arguments.length)return n;n=a;return o},o.duration=function(a){if(!arguments.length)return h;h=a;return o};return o},d3.chart.horizon=function(){function n(j){j.each(function(j,k){var n=d3.select(this),o=2*a+1,p=Infinity,q=-Infinity,r=-Infinity,s,t,u,v=j.map(function(a,b){var c=d.call(this,a,b),f=e.call(this,a,b);c<p&&(p=c),c>q&&(q=c),-f>r&&(r=-f),f>r&&(r=f);return[c,f]}),z=d3.scale.linear().domain([p,q]).range([0,f]),A=d3.scale.linear().domain([0,r]).range([0,g*a]);this.__chart__?(s=this.__chart__.x,t=this.__chart__.y,u=this.__chart__.id):(s=d3.scale.linear().domain([0,Infinity]).range(z.range()),t=d3.scale.linear().domain([0,Infinity]).range(A.range()),u=++i);var B=n.selectAll("defs").data([v]),C=B.enter().append("svg:defs");C.append("svg:clipPath").attr("id","d3_chart_horizon_clip"+u).append("svg:rect").attr("width",f).attr("height",g),B.select("rect").transition().duration(l).attr("width",f).attr("height",g),C.append("svg:path").attr("id","d3_chart_horizon_path"+u).attr("d",h.interpolate(c).x(function(a){return s(a[0])}).y0(g*a).y1(function(b){return g*a-t(b[1])})).transition().duration(l).attr("d",h.x(function(a){return z(a[0])}).y1(function(b){return g*a-A(b[1])})),B.select("path").transition().duration(l).attr("d",h),n.selectAll("g").data([null]).enter().append("svg:g").attr("clip-path","url(#d3_chart_horizon_clip"+u+")");var D=b=="offset"?function(b){return"translate(0,"+(b+(b<0)-a)*g+")"}:function(b){return(b<0?"scale(1,-1)":"")+"translate(0,"+(b-a)*g+")"},E=n.select("g").selectAll("use").data(d3.range(-1,-a-1,-1).concat(d3.range(1,a+1)),Number);E.enter().append("svg:use").attr("xlink:href","#d3_chart_horizon_path"+u).attr("transform",function(a){return D(a+(a>0?1:-1))}).style("fill",m).transition().duration(l).attr("transform",D),E.transition().duration(l).attr("transform",D).style("fill",m),E.exit().transition().duration(l).attr("transform",D).remove(),this.__chart__={x:z,y:A,id:u}}),d3.timer.flush()}var a=1,b="offset",c="linear",d=j,e=k,f=960,g=40,l=0,m=d3.scale.linear().domain([-1,0,1]).range(["#d62728","#fff","#1f77b4"]);n.duration=function(a){if(!arguments.length)return l;l=+a;return n},n.bands=function(b){if(!arguments.length)return a;a=+b,m.domain([-a,0,a]);return n},n.mode=function(a){if(!arguments.length)return b;b=a+"";return n},n.colors=function(a){if(!arguments.length)return m.range();m.range(a);return n},n.interpolate=function(a){if(!arguments.length)return c;c=a+"";return n},n.x=function(a){if(!arguments.length)return d;d=a;return n},n.y=function(a){if(!arguments.length)return e;e=a;return n},n.width=function(a){if(!arguments.length)return width;f=+a;return n},n.height=function(a){if(!arguments.length)return height;g=+a;return n};return n};var h=d3.svg.area(),i=0;d3.chart.qq=function(){function i(i){i.each(function(i,j){var k=d3.select(this),m=l(f,g.call(this,i,j)),n=l(f,h.call(this,i,j)),o=d&&d.call(this,i,j)||[d3.min(m),d3.max(m)],p=d&&d.call(this,i,j)||[d3.min(n),d3.max(n)],q,r,s=d3.scale.linear().domain(o).range([0,a]),t=d3.scale.linear().domain(p).range([b,0]);this.__chart__?(q=this.__chart__.x,r=this.__chart__.y):(q=d3.scale.linear().domain([0,Infinity]).range(s.range()),r=d3.scale.linear().domain([0,Infinity]).range(t.range())),this.__chart__={x:s,y:t};var u=k.selectAll("line.diagonal").data([null]);u.enter().append("svg:line").attr("class","diagonal").attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1])),u.transition().duration(c).attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1]));var v=k.selectAll("circle").data(d3.range(f).map(function(a){return{x:m[a],y:n[a]}}));v.enter().append("svg:circle").attr("class","quantile").attr("r",4.5).attr("cx",function(a){return q(a.x)}).attr("cy",function(a){return r(a.y)}).style("opacity",1e-6).transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.exit().transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1e-6).remove();var w=e||s.tickFormat(4),z=e||t.tickFormat(4),A=function(a){return"translate("+s(a)+","+b+")"},B=function(a){return"translate(0,"+t(a)+")"},C=k.selectAll("g.x.tick").data(s.ticks(4),function(a){return this.textContent||w(a)}),D=C.enter().append("svg:g").attr("class","x tick").attr("transform",function(a){return"translate("+q(a)+","+b+")"}).style("opacity",1e-6);D.append("svg:line").attr("y1",0).attr("y2",-6),D.append("svg:text").attr("text-anchor","middle").attr("dy","1em").text(w),D.transition().duration(c).attr("transform",A).style("opacity",1),C.transition().duration(c).attr("transform",A).style("opacity",1),C.exit().transition().duration(c).attr("transform",A).style("opacity",1e-6).remove();var E=k.selectAll("g.y.tick").data(t.ticks(4),function(a){return this.textContent||z(a)}),F=E.enter().append("svg:g").attr("class","y tick").attr("transform",function(a){return"translate(0,"+r(a)+")"}).style("opacity",1e-6);F.append("svg:line").attr("x1",0).attr("x2",6),F.append("svg:text").attr("text-anchor","end").attr("dx","-.5em").attr("dy",".3em").text(z),F.transition().duration(c).attr("transform",B).style("opacity",1),E.transition().duration(c).attr("transform",B).style("opacity",1),E.exit().transition().duration(c).attr("transform",B).style("opacity",1e-6).remove()})}var a=1,b=1,c=0,d=null,e=null,f=100,g=m,h=n;i.width=function(b){if(!arguments.length)return a;a=b;return i},i.height=function(a){if(!arguments.length)return b;b=a;return i},i.duration=function(a){if(!arguments.length)return c;c=a;return i},i.domain=function(a){if(!arguments.length)return d;d=a==null?a:d3.functor(a);return i},i.count=function(a){if(!arguments.length)return f;f=a;return i},i.x=function(a){if(!arguments.length)return g;g=a;return i},i.y=function(a){if(!arguments.length)return h;h=a;return i},i.tickFormat=function(a){if(!arguments.length)return e;e=a;return i};return i}})()
<ide>\ No newline at end of file
<ide><path>src/chart/box.js
<ide> function d3_chart_boxWhiskers(d) {
<ide> }
<ide>
<ide> function d3_chart_boxQuartiles(d) {
<del> // TODO avoid sorting data twice?
<del> var n = d.length;
<del> return [.25, .5, .75].map(function(q) {
<del> q *= n;
<del> return ~~q === q ? (d[q] + d[q + 1]) / 2 : d[Math.round(q)];
<del> });
<add> return [
<add> d3.quantile(d, .25),
<add> d3.quantile(d, .5),
<add> d3.quantile(d, .75)
<add> ];
<ide> } | 3 |
Java | Java | add a compiler for spel | 2eeb2e92359381328789585233e54c9bbd41e6dc | <ide><path>spring-expression/src/main/java/org/springframework/expression/CompilablePropertyAccessor.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression;
<add>
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.asm.Opcodes;
<add>import org.springframework.expression.spel.ast.PropertyOrFieldReference;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<add>
<add>
<add>/**
<add> * A compilable property accessor is able to generate bytecode that represents
<add> * the access operation, facilitating compilation to bytecode of expressions
<add> * that use the accessor.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>public interface CompilablePropertyAccessor extends PropertyAccessor, Opcodes {
<add>
<add> /**
<add> * @return true if this property accessor is currently suitable for compilation.
<add> */
<add> boolean isCompilable();
<add>
<add> /**
<add> * Generate the bytecode the performs the access operation into the specified MethodVisitor using
<add> * context information from the codeflow where necessary.
<add> * @param propertyReference the property reference for which code is being generated
<add> * @param mv the Asm method visitor into which code should be generated
<add> * @param codeflow the current state of the expression compiler
<add> */
<add> void generateCode(PropertyOrFieldReference propertyReference, MethodVisitor mv, CodeFlow codeflow);
<add>
<add> /**
<add> * @return the type of the accessed property - may only be known once an access has occurred.
<add> */
<add> Class<?> getPropertyType();
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/CompiledExpression.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel;
<add>
<add>import org.springframework.expression.EvaluationContext;
<add>import org.springframework.expression.EvaluationException;
<add>
<add>/**
<add> * Base superclass for compiled expressions. Each generated compiled expression class will
<add> * extend this class and implement one of the getValue() methods. It is not intended
<add> * to subclassed by user code.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>public abstract class CompiledExpression {
<add>
<add> /**
<add> * Subclasses of CompiledExpression generated by SpelCompiler will provide an implementation of
<add> * this method.
<add> */
<add> public abstract Object getValue(Object target, EvaluationContext context) throws EvaluationException;
<add>
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelCompilerMode.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel;
<add>
<add>/**
<add> * Captures the possible configuration settings for a compiler that can be
<add> * used when evaluating expressions.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>public enum SpelCompilerMode {
<add> /**
<add> * The compiler is switched off, this is the default.
<add> */
<add> off,
<add>
<add> /**
<add> * In immediate mode, expressions are compiled as soon as possible (usually after 1 interpreted run).
<add> * If a compiled expression fails it will throw an exception to the caller.
<add> */
<add> immediate,
<add>
<add> /**
<add> * In mixed mode, expression evaluate silently switches between interpreted and compiled over time.
<add> * After a number of runs the expression gets compiled. If it later fails (possibly due to inferred
<add> * type information changing) then that will be caught internally and the system switches back to
<add> * interpreted mode. It may subsequently compile it again later.
<add> */
<add> mixed
<add>}
<ide>\ No newline at end of file
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java
<ide> public enum SpelMessage {
<ide> "Problem parsing left operand"),
<ide>
<ide> MISSING_SELECTION_EXPRESSION(Kind.ERROR, 1071,
<del> "A required selection expression has not been specified");
<add> "A required selection expression has not been specified"),
<add>
<add> EXCEPTION_RUNNING_COMPILED_EXPRESSION(Kind.ERROR,1072,
<add> "An exception occurred whilst evaluating a compiled expression");
<ide>
<ide>
<ide> private final Kind kind;
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelParserConfiguration.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel;
<ide>
<add>import org.springframework.core.SpringProperties;
<add>
<add>
<ide> /**
<ide> * Configuration object for the SpEL expression parser.
<ide> *
<ide> * @author Juergen Hoeller
<ide> * @author Phillip Webb
<add> * @author Andy Clement
<ide> * @since 3.0
<ide> * @see org.springframework.expression.spel.standard.SpelExpressionParser#SpelExpressionParser(SpelParserConfiguration)
<ide> */
<ide> public class SpelParserConfiguration {
<ide> private final boolean autoGrowNullReferences;
<ide>
<ide> private final boolean autoGrowCollections;
<add>
<add> private static SpelCompilerMode defaultCompilerMode = SpelCompilerMode.off;
<add>
<add> private SpelCompilerMode compilerMode;
<ide>
<ide> private final int maximumAutoGrowSize;
<ide>
<del>
<add> static {
<add> String compilerMode = SpringProperties.getProperty("spring.expression.compiler.mode");
<add> if (compilerMode != null) {
<add> defaultCompilerMode = SpelCompilerMode.valueOf(compilerMode.toLowerCase());
<add> // System.out.println("SpelCompiler: switched to "+defaultCompilerMode+" mode");
<add> }
<add> }
<add>
<ide> /**
<ide> * Create a new {@link SpelParserConfiguration} instance.
<ide> * @param autoGrowNullReferences if null references should automatically grow
<ide> public SpelParserConfiguration(boolean autoGrowNullReferences, boolean autoGrowC
<ide> this.autoGrowNullReferences = autoGrowNullReferences;
<ide> this.autoGrowCollections = autoGrowCollections;
<ide> this.maximumAutoGrowSize = maximumAutoGrowSize;
<add> this.compilerMode = defaultCompilerMode;
<add> }
<add>
<add> /**
<add> * @param compilerMode the compiler mode that parsers using this configuration object should use
<add> */
<add> public void setCompilerMode(SpelCompilerMode compilerMode) {
<add> this.compilerMode = compilerMode;
<ide> }
<ide>
<add> /**
<add> * @return the configuration mode for parsers using this configuration object
<add> */
<add> public SpelCompilerMode getCompilerMode() {
<add> return this.compilerMode;
<add> }
<ide>
<ide> /**
<ide> * @return {@code true} if {@code null} references should be automatically grown
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/BooleanLiteral.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<ide> /**
<ide> public class BooleanLiteral extends Literal {
<ide> public BooleanLiteral(String payload, int pos, boolean value) {
<ide> super(payload, pos);
<ide> this.value = BooleanTypedValue.forValue(value);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public BooleanTypedValue getLiteralValue() {
<ide> return this.value;
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> if (this.value == BooleanTypedValue.TRUE) {
<add> mv.visitLdcInsn(1);
<add> }
<add> else {
<add> mv.visitLdcInsn(0);
<add> }
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Represents a DOT separated expression sequence, such as 'property1.property2.methodOne()'
<ide> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException
<ide> */
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<del> return getValueRef(state).getValue();
<add> ValueRef ref = getValueRef(state);
<add> TypedValue result = ref.getValue();
<add> this.exitTypeDescriptor = this.children[this.children.length-1].getExitDescriptor();
<add> return result;
<add> }
<add>
<add> @Override
<add> public String getExitDescriptor() {
<add> return this.exitTypeDescriptor;
<ide> }
<ide>
<ide> @Override
<ide> public String toStringAST() {
<ide> }
<ide> return sb.toString();
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> for (SpelNodeImpl child: children) {
<add> if (!child.isCompilable()) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv,CodeFlow codeflow) {
<add> // TODO could optimize T(SomeType).staticMethod - no need to generate the T() part
<add> for (int i=0;i<children.length;i++) {
<add> SpelNodeImpl child = children[i];
<add> if (child instanceof TypeReference &&
<add> (i+1) < children.length &&
<add> children[i+1] instanceof MethodReference) {
<add> continue;
<add> }
<add> child.generateCode(mv, codeflow);
<add> }
<add> codeflow.pushDescriptor(this.getExitDescriptor());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/ConstructorReference.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.expression.spel.ast;
<ide>
<ide> import java.lang.reflect.Array;
<add>import java.lang.reflect.Constructor;
<ide> import java.lang.reflect.InvocationTargetException;
<add>import java.lang.reflect.Modifier;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.AccessException;
<ide> import org.springframework.expression.ConstructorExecutor;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<ide> import org.springframework.expression.spel.SpelNode;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<add>import org.springframework.expression.spel.support.ReflectiveConstructorExecutor;
<ide>
<ide> /**
<ide> * Represents the invocation of a constructor. Either a constructor on a regular type or
<ide> private TypedValue createNewInstance(ExpressionState state) throws EvaluationExc
<ide> executorToUse = findExecutorForConstructor(typename, argumentTypes, state);
<ide> try {
<ide> this.cachedExecutor = executorToUse;
<add> if (this.cachedExecutor instanceof ReflectiveConstructorExecutor) {
<add> this.exitTypeDescriptor = CodeFlow.toDescriptor(((ReflectiveConstructorExecutor)this.cachedExecutor).getConstructor().getDeclaringClass());
<add>
<add> }
<ide> return executorToUse.execute(state.getEvaluationContext(), arguments);
<ide> }
<ide> catch (AccessException ae) {
<ide> private void populateIntArray(ExpressionState state, Object newArray, TypeConver
<ide> private boolean hasInitializer() {
<ide> return getChildCount() > 1;
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> if (!(this.cachedExecutor instanceof ReflectiveConstructorExecutor) ||
<add> this.exitTypeDescriptor == null) {
<add> return false;
<add> }
<add> if (getChildCount() > 1) {
<add> for (int c = 1, max = getChildCount();c < max; c++) {
<add> if (!children[c].isCompilable()) {
<add> return false;
<add> }
<add> }
<add> }
<add> ReflectiveConstructorExecutor executor = (ReflectiveConstructorExecutor)this.cachedExecutor;
<add> Constructor<?> constructor = executor.getConstructor();
<add> if (!Modifier.isPublic(constructor.getModifiers()) ||
<add> !Modifier.isPublic(constructor.getDeclaringClass().getModifiers())) {
<add> return false;
<add> }
<add> if (constructor.isVarArgs()) {
<add> return false;
<add> }
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> ReflectiveConstructorExecutor executor = ((ReflectiveConstructorExecutor) this.cachedExecutor);
<add> Constructor<?> constructor = executor.getConstructor();
<add>
<add> String classSlashedDescriptor = constructor.getDeclaringClass().getName().replace('.','/');
<add> String[] paramDescriptors = CodeFlow.toParamDescriptors(constructor);
<add> mv.visitTypeInsn(NEW,classSlashedDescriptor);
<add> mv.visitInsn(DUP);
<add> for (int c = 1; c < children.length; c++) { // children[0] is the type of the constructor
<add> SpelNodeImpl child = children[c];
<add> codeflow.enterCompilationScope();
<add> child.generateCode(mv, codeflow);
<add> // Check if need to box it for the method reference?
<add> if (CodeFlow.isPrimitive(codeflow.lastDescriptor()) && (paramDescriptors[c-1].charAt(0)=='L')) {
<add> CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
<add> }
<add> codeflow.exitCompilationScope();
<add> }
<add> mv.visitMethodInsn(INVOKESPECIAL,classSlashedDescriptor,"<init>",CodeFlow.createSignatureDescriptor(constructor),false);
<add> codeflow.pushDescriptor(exitTypeDescriptor);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Elvis.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Represents the elvis operator ?:. For an expression "a?:b" if a is not null, the value
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> return value;
<ide> }
<ide> else {
<del> return this.children[1].getValueInternal(state);
<add> TypedValue result = this.children[1].getValueInternal(state);
<add> if (exitTypeDescriptor == null) {
<add> String testDescriptor = this.children[0].exitTypeDescriptor;
<add> String ifNullDescriptor = this.children[1].exitTypeDescriptor;
<add> if (testDescriptor.equals(ifNullDescriptor)) {
<add> this.exitTypeDescriptor = testDescriptor;
<add> }
<add> else {
<add> this.exitTypeDescriptor = "Ljava/lang/Object";
<add> }
<add> }
<add> return result;
<ide> }
<ide> }
<ide>
<ide> public String toStringAST() {
<ide> getChild(1).toStringAST()).toString();
<ide> }
<ide>
<add> private void computeExitTypeDescriptor() {
<add> if (exitTypeDescriptor == null &&
<add> this.children[0].getExitDescriptor()!=null &&
<add> this.children[1].getExitDescriptor()!=null) {
<add> String conditionDescriptor = this.children[0].exitTypeDescriptor;
<add> String ifNullValueDescriptor = this.children[1].exitTypeDescriptor;
<add> if (conditionDescriptor.equals(ifNullValueDescriptor)) {
<add> this.exitTypeDescriptor = conditionDescriptor;
<add> }
<add> else if (conditionDescriptor.equals("Ljava/lang/Object") && !CodeFlow.isPrimitive(ifNullValueDescriptor)) {
<add> this.exitTypeDescriptor = ifNullValueDescriptor;
<add> }
<add> else if (ifNullValueDescriptor.equals("Ljava/lang/Object") && !CodeFlow.isPrimitive(conditionDescriptor)) {
<add> this.exitTypeDescriptor = conditionDescriptor;
<add> }
<add> else {
<add> // Use the easiest to compute common super type
<add> this.exitTypeDescriptor = "Ljava/lang/Object";
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl condition = this.children[0];
<add> SpelNodeImpl ifNullValue = this.children[1];
<add> if (!(condition.isCompilable() && ifNullValue.isCompilable())) {
<add> return false;
<add> }
<add> return
<add> condition.getExitDescriptor()!=null &&
<add> ifNullValue.getExitDescriptor()!=null;
<add> }
<add>
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> // exit type descriptor can be null if both components are literal expressions
<add> computeExitTypeDescriptor();
<add> this.children[0].generateCode(mv, codeflow);
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> mv.visitInsn(DUP);
<add> mv.visitJumpInsn(IFNULL, elseTarget);
<add> mv.visitJumpInsn(GOTO, endOfIf);
<add> mv.visitLabel(elseTarget);
<add> mv.visitInsn(POP);
<add> this.children[1].generateCode(mv, codeflow);
<add> if (!CodeFlow.isPrimitive(getExitDescriptor())) {
<add> CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
<add> }
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/FloatLiteral.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Expression language AST node that represents a float literal.
<ide> *
<ide> * @author Satyapal Reddy
<add> * @author Andy Clement
<ide> * @since 3.2
<ide> */
<ide> public class FloatLiteral extends Literal {
<ide> public class FloatLiteral extends Literal {
<ide> FloatLiteral(String payload, int pos, float value) {
<ide> super(payload, pos);
<ide> this.value = new TypedValue(value);
<add> this.exitTypeDescriptor = "F";
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public TypedValue getLiteralValue() {
<ide> return this.value;
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> mv.visitLdcInsn(this.value.getValue());
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/FunctionReference.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.lang.reflect.Method;
<ide> import java.lang.reflect.Modifier;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.ReflectionHelper;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<ide> public class FunctionReference extends SpelNodeImpl {
<ide>
<ide> private final String name;
<ide>
<add> // Captures the most recently used method for the function invocation *if*
<add> // the method can safely be used for compilation (i.e. no argument conversion is
<add> // going on)
<add> private Method method;
<ide>
<ide> public FunctionReference(String functionName, int pos, SpelNodeImpl... arguments) {
<ide> super(pos,arguments);
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> * @throws EvaluationException if there is any problem invoking the method
<ide> */
<ide> private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method) throws EvaluationException {
<add> this.method = null;
<ide> Object[] functionArgs = getArguments(state);
<ide>
<ide> if (!method.isVarArgs() && method.getParameterTypes().length != functionArgs.length) {
<ide> private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method
<ide> SpelMessage.FUNCTION_MUST_BE_STATIC,
<ide> method.getDeclaringClass().getName() + "." + method.getName(), this.name);
<ide> }
<del>
<add> boolean argumentConversionOccurred = false;
<ide> // Convert arguments if necessary and remap them for varargs if required
<ide> if (functionArgs != null) {
<ide> TypeConverter converter = state.getEvaluationContext().getTypeConverter();
<del> ReflectionHelper.convertAllArguments(converter, functionArgs, method);
<add> argumentConversionOccurred |= ReflectionHelper.convertAllArguments(converter, functionArgs, method);
<ide> }
<ide> if (method.isVarArgs()) {
<ide> functionArgs = ReflectionHelper.setupArgumentsForVarargsInvocation(
<ide> private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method
<ide> try {
<ide> ReflectionUtils.makeAccessible(method);
<ide> Object result = method.invoke(method.getClass(), functionArgs);
<add> if (!argumentConversionOccurred) {
<add> this.method = method;
<add> this.exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
<add> }
<ide> return new TypedValue(result, new TypeDescriptor(new MethodParameter(method,-1)).narrow(result));
<ide> }
<ide> catch (Exception ex) {
<ide> private Object[] getArguments(ExpressionState state) throws EvaluationException
<ide> }
<ide> return arguments;
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> // Don't yet support non-static method compilation.
<add> return method!=null && Modifier.isStatic(method.getModifiers());
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv,CodeFlow codeflow) {
<add> String methodDeclaringClassSlashedDescriptor = method.getDeclaringClass().getName().replace('.','/');
<add> String[] paramDescriptors = CodeFlow.toParamDescriptors(method);
<add> for (int c = 0; c < children.length; c++) {
<add> SpelNodeImpl child = children[c];
<add> codeflow.enterCompilationScope();
<add> child.generateCode(mv, codeflow);
<add> // Check if need to box it for the method reference?
<add> if (CodeFlow.isPrimitive(codeflow.lastDescriptor()) && (paramDescriptors[c].charAt(0)=='L')) {
<add> CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
<add> }
<add> else if (!codeflow.lastDescriptor().equals(paramDescriptors[c])) {
<add> // This would be unnecessary in the case of subtyping (e.g. method takes a Number but passed in is an Integer)
<add> CodeFlow.insertCheckCast(mv, paramDescriptors[c]);
<add> }
<add> codeflow.exitCompilationScope();
<add> }
<add> mv.visitMethodInsn(INVOKESTATIC,methodDeclaringClassSlashedDescriptor,method.getName(),CodeFlow.createSignatureDescriptor(method),false);
<add> codeflow.pushDescriptor(exitTypeDescriptor);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import java.lang.reflect.Field;
<add>import java.lang.reflect.Member;
<add>import java.lang.reflect.Method;
<add>import java.lang.reflect.Modifier;
<ide> import java.util.Collection;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.AccessException;
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
<ide>
<ide> /**
<ide> public class Indexer extends SpelNodeImpl {
<ide>
<ide> private PropertyAccessor cachedWriteAccessor;
<ide>
<add> private static enum IndexedType { map, array, list, string, object; }
<add>
<add> private IndexedType indexedType;
<add>
<ide>
<ide> public Indexer(int pos, SpelNodeImpl expr) {
<ide> super(pos, expr);
<ide> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException
<ide> if (targetObjectTypeDescriptor.getMapKeyTypeDescriptor() != null) {
<ide> key = state.convertValue(key, targetObjectTypeDescriptor.getMapKeyTypeDescriptor());
<ide> }
<add> this.indexedType = IndexedType.map;
<ide> return new MapIndexingValueRef(state.getTypeConverter(), (Map<?, ?>) targetObject, key,
<ide> targetObjectTypeDescriptor);
<ide> }
<ide> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException
<ide> if (targetObject.getClass().isArray() || targetObject instanceof Collection || targetObject instanceof String) {
<ide> int idx = (Integer) state.convertValue(index, TypeDescriptor.valueOf(Integer.class));
<ide> if (targetObject.getClass().isArray()) {
<add> this.indexedType = IndexedType.array;
<ide> return new ArrayIndexingValueRef(state.getTypeConverter(), targetObject, idx, targetObjectTypeDescriptor);
<ide> }
<ide> else if (targetObject instanceof Collection) {
<add> if (targetObject instanceof List) {
<add> this.indexedType = IndexedType.list;
<add> }
<ide> return new CollectionIndexingValueRef((Collection<?>) targetObject, idx, targetObjectTypeDescriptor,
<ide> state.getTypeConverter(), state.getConfiguration().isAutoGrowCollections(),
<ide> state.getConfiguration().getMaximumAutoGrowSize());
<ide> }
<ide> else if (targetObject instanceof String) {
<add> this.indexedType = IndexedType.string;
<ide> return new StringIndexingLValue((String) targetObject, idx, targetObjectTypeDescriptor);
<ide> }
<ide> }
<ide>
<ide> // Try and treat the index value as a property of the context object
<ide> // TODO could call the conversion service to convert the value to a String
<ide> if (indexValue.getTypeDescriptor().getType() == String.class) {
<add> this.indexedType = IndexedType.object;
<ide> return new PropertyIndexingValueRef(targetObject, (String) indexValue.getValue(),
<ide> state.getEvaluationContext(), targetObjectTypeDescriptor);
<ide> }
<ide>
<ide> throw new SpelEvaluationException(getStartPosition(), SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE,
<ide> targetObjectTypeDescriptor.toString());
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> if (this.indexedType == IndexedType.array) {
<add> return exitTypeDescriptor != null;
<add> }
<add> else if (this.indexedType == IndexedType.list || this.indexedType == IndexedType.map) {
<add> return true;
<add> }
<add> else if (this.indexedType == IndexedType.object) {
<add> // If the string name is changing the accessor is clearly going to change (so compilation is not possible)
<add> if (this.cachedReadAccessor != null &&
<add> (this.cachedReadAccessor instanceof ReflectivePropertyAccessor.OptimalPropertyAccessor) &&
<add> (getChild(0) instanceof StringLiteral)) {
<add> return true;
<add> };
<add> }
<add> return false;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> String s = codeflow.lastDescriptor();
<add>
<add> if (s == null) {
<add> // stack is empty, should use context object
<add> codeflow.loadTarget(mv);
<add> }
<add>
<add> if (this.indexedType == IndexedType.array) {
<add> if (exitTypeDescriptor == "I") {
<add> mv.visitTypeInsn(CHECKCAST,"[I");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(IALOAD);
<add> }
<add> else if (exitTypeDescriptor == "D") {
<add> mv.visitTypeInsn(CHECKCAST,"[D");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(DALOAD);
<add> }
<add> else if (exitTypeDescriptor == "J") {
<add> mv.visitTypeInsn(CHECKCAST,"[J");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(LALOAD);
<add> }
<add> else if (exitTypeDescriptor == "F") {
<add> mv.visitTypeInsn(CHECKCAST,"[F");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(FALOAD);
<add> }
<add> else if (exitTypeDescriptor == "S") {
<add> mv.visitTypeInsn(CHECKCAST,"[S");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(SALOAD);
<add> }
<add> else if (exitTypeDescriptor == "B") {
<add> mv.visitTypeInsn(CHECKCAST,"[B");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(BALOAD);
<add> }
<add> else if (exitTypeDescriptor == "C") {
<add> mv.visitTypeInsn(CHECKCAST,"[C");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(CALOAD);
<add> }
<add> else {
<add> mv.visitTypeInsn(CHECKCAST,"["+exitTypeDescriptor+(CodeFlow.isPrimitiveArray(exitTypeDescriptor)?"":";"));//depthPlusOne(exitTypeDescriptor)+"Ljava/lang/Object;");
<add> SpelNodeImpl index = this.children[0];
<add> index.generateCode(mv, codeflow);
<add> mv.visitInsn(AALOAD);
<add> }
<add> }
<add> else if (this.indexedType == IndexedType.list) {
<add> mv.visitTypeInsn(CHECKCAST,"java/util/List");
<add> this.children[0].generateCode(mv, codeflow);
<add> mv.visitMethodInsn(INVOKEINTERFACE,"java/util/List","get","(I)Ljava/lang/Object;", true);
<add> CodeFlow.insertCheckCast(mv,exitTypeDescriptor);
<add> }
<add> else if (this.indexedType == IndexedType.map) {
<add> mv.visitTypeInsn(CHECKCAST,"java/util/Map");
<add> this.children[0].generateCode(mv, codeflow);
<add> mv.visitMethodInsn(INVOKEINTERFACE,"java/util/Map","get","(Ljava/lang/Object;)Ljava/lang/Object;", true);
<add> CodeFlow.insertCheckCast(mv,exitTypeDescriptor);
<add> }
<add> else if (this.indexedType == IndexedType.object) {
<add> ReflectivePropertyAccessor.OptimalPropertyAccessor accessor =
<add> (ReflectivePropertyAccessor.OptimalPropertyAccessor)this.cachedReadAccessor;
<add> Member member = accessor.member;
<add> boolean isStatic = Modifier.isStatic(member.getModifiers());
<add>
<add> String descriptor = codeflow.lastDescriptor();
<add> String memberDeclaringClassSlashedDescriptor = member.getDeclaringClass().getName().replace('.','/');
<add> if (!isStatic) {
<add> if (descriptor == null) {
<add> codeflow.loadTarget(mv);
<add> }
<add> if (descriptor == null || !memberDeclaringClassSlashedDescriptor.equals(descriptor.substring(1))) {
<add> mv.visitTypeInsn(CHECKCAST, memberDeclaringClassSlashedDescriptor);
<add> }
<add> }
<add> if (member instanceof Field) {
<add> mv.visitFieldInsn(isStatic?GETSTATIC:GETFIELD,memberDeclaringClassSlashedDescriptor,member.getName(),CodeFlow.toJVMDescriptor(((Field) member).getType()));
<add> } else {
<add> mv.visitMethodInsn(isStatic?INVOKESTATIC:INVOKEVIRTUAL, memberDeclaringClassSlashedDescriptor, member.getName(),CodeFlow.createSignatureDescriptor((Method)member),false);
<add> }
<add> }
<add> codeflow.pushDescriptor(exitTypeDescriptor);
<add> }
<ide>
<ide> @Override
<ide> public String toStringAST() {
<ide> private Object accessArrayElement(Object ctx, int idx) throws SpelEvaluationExce
<ide> if (arrayComponentType == Integer.TYPE) {
<ide> int[] array = (int[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "I";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Boolean.TYPE) {
<ide> boolean[] array = (boolean[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "Z";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Character.TYPE) {
<ide> char[] array = (char[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "C";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Long.TYPE) {
<ide> long[] array = (long[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "J";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Short.TYPE) {
<ide> short[] array = (short[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "S";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Double.TYPE) {
<ide> double[] array = (double[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "D";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Float.TYPE) {
<ide> float[] array = (float[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "F";
<ide> return array[idx];
<ide> }
<ide> else if (arrayComponentType == Byte.TYPE) {
<ide> byte[] array = (byte[]) ctx;
<ide> checkAccess(array.length, idx);
<add> this.exitTypeDescriptor = "B";
<ide> return array[idx];
<ide> }
<ide> else {
<ide> Object[] array = (Object[]) ctx;
<ide> checkAccess(array.length, idx);
<del> return array[idx];
<add> Object retValue = array[idx];
<add> this.exitTypeDescriptor = CodeFlow.toDescriptor(arrayComponentType);
<add> return retValue;
<ide> }
<ide> }
<ide>
<ide> public boolean isWritable() {
<ide>
<ide>
<ide> @SuppressWarnings({"rawtypes", "unchecked"})
<del> private static class MapIndexingValueRef implements ValueRef {
<add> private class MapIndexingValueRef implements ValueRef {
<ide>
<ide> private final TypeConverter typeConverter;
<ide>
<ide> public MapIndexingValueRef(TypeConverter typeConverter, Map map, Object key, Typ
<ide> @Override
<ide> public TypedValue getValue() {
<ide> Object value = this.map.get(this.key);
<add> exitTypeDescriptor = CodeFlow.toDescriptorFromObject(value);
<ide> return new TypedValue(value,
<ide> this.mapEntryTypeDescriptor.getMapValueTypeDescriptor(value));
<ide> }
<ide> public TypedValue getValue() {
<ide> Indexer.this.cachedReadAccessor = accessor;
<ide> Indexer.this.cachedReadName = this.name;
<ide> Indexer.this.cachedReadTargetType = targetObjectRuntimeClass;
<del> return accessor.read(this.evaluationContext, this.targetObject, this.name);
<add> if (accessor instanceof ReflectivePropertyAccessor.OptimalPropertyAccessor) {
<add> ReflectivePropertyAccessor.OptimalPropertyAccessor optimalAccessor = (ReflectivePropertyAccessor.OptimalPropertyAccessor)accessor;
<add> Member member = optimalAccessor.member;
<add> if (member instanceof Field) {
<add> Indexer.this.exitTypeDescriptor = CodeFlow.toDescriptor(((Field)member).getType());
<add> } else {
<add> Indexer.this.exitTypeDescriptor = CodeFlow.toDescriptor(((Method)member).getReturnType());
<add> }
<add> }
<add> TypedValue value = accessor.read(this.evaluationContext, this.targetObject, this.name);
<add> return value;
<ide> }
<ide> }
<ide> }
<ide> public TypedValue getValue() {
<ide> growCollectionIfNecessary();
<ide> if (this.collection instanceof List) {
<ide> Object o = ((List) this.collection).get(this.index);
<add> exitTypeDescriptor = CodeFlow.toDescriptorFromObject(o);
<ide> return new TypedValue(o, this.collectionEntryDescriptor.elementTypeDescriptor(o));
<ide> }
<ide> int pos = 0;
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/IntLiteral.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Expression language AST node that represents an integer literal.
<ide> public class IntLiteral extends Literal {
<ide>
<ide> private final TypedValue value;
<ide>
<del>
<ide> IntLiteral(String payload, int pos, int value) {
<ide> super(payload, pos);
<ide> this.value = new TypedValue(value);
<add> this.exitTypeDescriptor = "I";
<ide> }
<ide>
<ide>
<ide> public TypedValue getLiteralValue() {
<ide> return this.value;
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> int intValue = ((Integer)this.value.getValue()).intValue();
<add> if (intValue==-1) {
<add> // Not sure we can get here because -1 is OpMinus
<add> mv.visitInsn(ICONST_M1);
<add> }
<add> else if (intValue >= 0 && intValue < 6) {
<add> mv.visitInsn(ICONST_0+intValue);
<add> }
<add> else {
<add> mv.visitLdcInsn(intValue);
<add> }
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/LongLiteral.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Expression language AST node that represents a long integer literal.
<ide> public class LongLiteral extends Literal {
<ide> LongLiteral(String payload, int pos, long value) {
<ide> super(payload, pos);
<ide> this.value = new TypedValue(value);
<add> this.exitTypeDescriptor = "J";
<ide> }
<ide>
<del>
<ide> @Override
<ide> public TypedValue getLiteralValue() {
<ide> return this.value;
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> mv.visitLdcInsn(this.value.getValue());
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/MethodReference.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.expression.spel.ast;
<ide>
<ide> import java.lang.reflect.InvocationTargetException;
<add>import java.lang.reflect.Method;
<add>import java.lang.reflect.Modifier;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.AccessException;
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<add>import org.springframework.expression.spel.support.ReflectiveMethodExecutor;
<ide> import org.springframework.expression.spel.support.ReflectiveMethodResolver;
<ide>
<ide> /**
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> Object value = state.getActiveContextObject().getValue();
<ide> TypeDescriptor targetType = state.getActiveContextObject().getTypeDescriptor();
<ide> Object[] arguments = getArguments(state);
<del> return getValueInternal(evaluationContext, value, targetType, arguments);
<add> TypedValue result = getValueInternal(evaluationContext, value, targetType, arguments);
<add> if (cachedExecutor.get() instanceof ReflectiveMethodExecutor) {
<add> ReflectiveMethodExecutor executor = (ReflectiveMethodExecutor) cachedExecutor.get();
<add> Method method = executor.getMethod();
<add> exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
<add> }
<add> return result;
<add> }
<add>
<add> @Override
<add> public String getExitDescriptor() {
<add> return exitTypeDescriptor;
<ide> }
<ide>
<ide> private TypedValue getValueInternal(EvaluationContext evaluationContext,
<ide> private List<TypeDescriptor> getArgumentTypes(Object... arguments) {
<ide> return Collections.unmodifiableList(descriptors);
<ide> }
<ide>
<del> private MethodExecutor getCachedExecutor(EvaluationContext evaluationContext, Object value,
<del> TypeDescriptor target, List<TypeDescriptor> argumentTypes) {
<del>
<add> private MethodExecutor getCachedExecutor(EvaluationContext evaluationContext, Object value, TypeDescriptor target, List<TypeDescriptor> argumentTypes) {
<ide> List<MethodResolver> methodResolvers = evaluationContext.getMethodResolvers();
<ide> if (methodResolvers == null || methodResolvers.size() != 1 ||
<ide> !(methodResolvers.get(0) instanceof ReflectiveMethodResolver)) {
<ide> public MethodValueRef(ExpressionState state, Object[] arguments) {
<ide>
<ide> @Override
<ide> public TypedValue getValue() {
<del> return getValueInternal(this.evaluationContext, this.value, this.targetType, this.arguments);
<add> TypedValue result = MethodReference.this.getValueInternal(this.evaluationContext, this.value, this.targetType, this.arguments);
<add> if (MethodReference.this.cachedExecutor.get() instanceof ReflectiveMethodExecutor) {
<add> ReflectiveMethodExecutor executor = (ReflectiveMethodExecutor) MethodReference.this.cachedExecutor.get();
<add> Method method = executor.getMethod();
<add> MethodReference.this.exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
<add> }
<add> return result;
<ide> }
<ide>
<ide> @Override
<ide> public MethodExecutor get() {
<ide> }
<ide> }
<ide>
<add> /**
<add> * A method reference is compilable if it has been resolved to a reflectively accessible method
<add> * and the child nodes (arguments to the method) are also compilable.
<add> */
<add> @Override
<add> public boolean isCompilable() {
<add> if (this.cachedExecutor == null || !(this.cachedExecutor.get() instanceof ReflectiveMethodExecutor)) {
<add> return false;
<add> }
<add> for (SpelNodeImpl child: children) {
<add> if (!child.isCompilable()) {
<add> return false;
<add> }
<add> }
<add> ReflectiveMethodExecutor executor = (ReflectiveMethodExecutor) this.cachedExecutor.get();
<add> Method method = executor.getMethod();
<add> if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
<add> return false;
<add> }
<add> if (method.isVarArgs()) {
<add> return false;
<add> }
<add> if (executor.didArgumentConversionOccur()) {
<add> return false;
<add> }
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv,CodeFlow codeflow) {
<add> ReflectiveMethodExecutor executor = (ReflectiveMethodExecutor) this.cachedExecutor.get();
<add> Method method = executor.getMethod();
<add> boolean isStaticMethod = Modifier.isStatic(method.getModifiers());
<add> String descriptor = codeflow.lastDescriptor();
<add>
<add> if (descriptor == null && !isStaticMethod) {
<add> codeflow.loadTarget(mv);
<add> }
<add>
<add> boolean itf = method.getDeclaringClass().isInterface();
<add> String methodDeclaringClassSlashedDescriptor = method.getDeclaringClass().getName().replace('.','/');
<add> if (!isStaticMethod) {
<add> if (descriptor == null || !descriptor.equals(method.getDeclaringClass())) {
<add> mv.visitTypeInsn(CHECKCAST, method.getDeclaringClass().getName().replace('.','/'));
<add> }
<add> }
<add> String[] paramDescriptors = CodeFlow.toParamDescriptors(method);
<add> for (int c=0;c<children.length;c++) {
<add> SpelNodeImpl child = children[c];
<add> codeflow.enterCompilationScope();
<add> child.generateCode(mv, codeflow);
<add> // Check if need to box it for the method reference?
<add> if (CodeFlow.isPrimitive(codeflow.lastDescriptor()) && (paramDescriptors[c].charAt(0)=='L')) {
<add> CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
<add> }
<add> else if (!codeflow.lastDescriptor().equals(paramDescriptors[c])) {
<add> // This would be unnecessary in the case of subtyping (e.g. method takes a Number but passed in is an Integer)
<add> CodeFlow.insertCheckCast(mv, paramDescriptors[c]);
<add> }
<add> codeflow.exitCompilationScope();
<add> }
<add> mv.visitMethodInsn(isStaticMethod?INVOKESTATIC:INVOKEVIRTUAL,methodDeclaringClassSlashedDescriptor,method.getName(),CodeFlow.createSignatureDescriptor(method), itf);
<add> codeflow.pushDescriptor(exitTypeDescriptor);
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/NullLiteral.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Expression language AST node that represents null.
<ide> public class NullLiteral extends Literal {
<ide>
<ide> public NullLiteral(int pos) {
<ide> super(null,pos);
<add> this.exitTypeDescriptor = "Ljava/lang/Object";
<ide> }
<ide>
<ide>
<ide> public String toString() {
<ide> return "null";
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> mv.visitInsn(ACONST_NULL);
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpAnd.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<ide> /**
<ide> public class OpAnd extends Operator {
<ide>
<ide> public OpAnd(int pos, SpelNodeImpl... operands) {
<ide> super("and", pos, operands);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide>
<ide> private void assertValueNotNull(Boolean value) {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl left = getLeftOperand();
<add> SpelNodeImpl right= getRightOperand();
<add> if (!left.isCompilable() || !right.isCompilable()) {
<add> return false;
<add> }
<add> return
<add> CodeFlow.isBooleanCompatible(left.getExitDescriptor()) &&
<add> CodeFlow.isBooleanCompatible(right.getExitDescriptor());
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> // pseudo: if (!leftOperandValue) { result=false; } else { result=rightOperandValue; }
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> codeflow.enterCompilationScope();
<add> getLeftOperand().generateCode(mv, codeflow);
<add> codeflow.unboxBooleanIfNecessary(mv);
<add> codeflow.exitCompilationScope();
<add> mv.visitJumpInsn(IFNE, elseTarget);
<add> mv.visitLdcInsn(0); // FALSE
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add> mv.visitLabel(elseTarget);
<add> codeflow.enterCompilationScope();
<add> getRightOperand().generateCode(mv, codeflow);
<add> codeflow.unboxBooleanIfNecessary(mv);
<add> codeflow.exitCompilationScope();
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor(this.exitTypeDescriptor);
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDivide.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>
<ide> import java.math.BigDecimal;
<ide> import java.math.RoundingMode;
<ide>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.Operation;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> /**
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> }
<ide>
<ide> if (leftNumber instanceof Double || rightNumber instanceof Double) {
<add> if (leftNumber instanceof Double && rightNumber instanceof Double) {
<add> this.exitTypeDescriptor = "D";
<add> }
<ide> return new TypedValue(leftNumber.doubleValue() / rightNumber.doubleValue());
<ide> }
<del> if (leftNumber instanceof Float || rightNumber instanceof Float) {
<add> else if (leftNumber instanceof Float || rightNumber instanceof Float) {
<add> if (leftNumber instanceof Float && rightNumber instanceof Float) {
<add> this.exitTypeDescriptor = "F";
<add> }
<ide> return new TypedValue(leftNumber.floatValue() / rightNumber.floatValue());
<ide> }
<del> if (leftNumber instanceof Long || rightNumber instanceof Long) {
<add> else if (leftNumber instanceof Long || rightNumber instanceof Long) {
<add> if (leftNumber instanceof Long && rightNumber instanceof Long) {
<add> this.exitTypeDescriptor = "J";
<add> }
<ide> return new TypedValue(leftNumber.longValue() / rightNumber.longValue());
<ide> }
<del>
<del> // TODO what about non-int result of the division?
<del> return new TypedValue(leftNumber.intValue() / rightNumber.intValue());
<add> else {
<add> if (leftNumber instanceof Integer && rightNumber instanceof Integer) {
<add> this.exitTypeDescriptor = "I";
<add> }
<add> // TODO what about non-int result of the division?
<add> return new TypedValue(leftNumber.intValue() / rightNumber.intValue());
<add> }
<ide> }
<ide>
<ide> return state.operate(Operation.DIVIDE, leftOperand, rightOperand);
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> if (!getLeftOperand().isCompilable()) {
<add> return false;
<add> }
<add> if (this.children.length>1) {
<add> if (!getRightOperand().isCompilable()) {
<add> return false;
<add> }
<add> }
<add> return this.exitTypeDescriptor!=null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> String leftdesc = getLeftOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(leftdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> if (this.children.length > 1) {
<add> getRightOperand().generateCode(mv, codeflow);
<add> String rightdesc = getRightOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(rightdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> switch (this.exitTypeDescriptor.charAt(0)) {
<add> case 'I':
<add> mv.visitInsn(IDIV);
<add> break;
<add> case 'J':
<add> mv.visitInsn(LDIV);
<add> break;
<add> case 'F':
<add> mv.visitInsn(FDIV);
<add> break;
<add> case 'D':
<add> mv.visitInsn(DDIV);
<add> break;
<add> default:
<add> throw new IllegalStateException("Unrecognized exit descriptor: '"+this.exitTypeDescriptor+"'");
<add> }
<add> }
<add> codeflow.pushDescriptor(this.exitTypeDescriptor);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpEQ.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<ide> /**
<ide> public class OpEQ extends Operator {
<ide>
<ide> public OpEQ(int pos, SpelNodeImpl... operands) {
<ide> super("==", pos, operands);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide> @Override
<ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati
<ide> Object right = getRightOperand().getValueInternal(state).getValue();
<ide> return BooleanTypedValue.forValue(equalityCheck(state, left, right));
<ide> }
<add>
<add> // This check is different to the one in the other numeric operators (OpLt/etc)
<add> // because it allows for simple object comparison
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl left = getLeftOperand();
<add> SpelNodeImpl right= getRightOperand();
<add> if (!left.isCompilable() || !right.isCompilable()) {
<add> return false;
<add> }
<add> String leftdesc = left.getExitDescriptor();
<add> String rightdesc = right.getExitDescriptor();
<add> if ((CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(leftdesc) ||
<add> CodeFlow.isPrimitiveOrUnboxableSupportedNumber(rightdesc))) {
<add> if (!CodeFlow.areBoxingCompatible(leftdesc, rightdesc)) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> String leftDesc = getLeftOperand().getExitDescriptor();
<add> String rightDesc = getRightOperand().getExitDescriptor();
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> boolean leftPrim = CodeFlow.isPrimitive(leftDesc);
<add> boolean rightPrim = CodeFlow.isPrimitive(rightDesc);
<add>
<add> if ((CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(leftDesc) ||
<add> CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(rightDesc)) &&
<add> CodeFlow.areBoxingCompatible(leftDesc,rightDesc)) {
<add> char targetType = CodeFlow.toPrimitiveTargetDesc(leftDesc);
<add>
<add> getLeftOperand().generateCode(mv, codeflow);
<add> if (!leftPrim) {
<add> CodeFlow.insertUnboxInsns(mv, targetType, false);
<add> }
<add>
<add> getRightOperand().generateCode(mv, codeflow);
<add> if (!rightPrim) {
<add> CodeFlow.insertUnboxInsns(mv, targetType, false);
<add> }
<add> // assert: SpelCompiler.boxingCompatible(leftDesc, rightDesc)
<add> if (targetType=='D') {
<add> mv.visitInsn(DCMPL);
<add> mv.visitJumpInsn(IFNE, elseTarget);
<add> }
<add> else if (targetType=='F') {
<add> mv.visitInsn(FCMPL);
<add> mv.visitJumpInsn(IFNE, elseTarget);
<add> }
<add> else if (targetType=='J') {
<add> mv.visitInsn(LCMP);
<add> mv.visitJumpInsn(IFNE, elseTarget);
<add> }
<add> else if (targetType=='I' || targetType=='Z') {
<add> mv.visitJumpInsn(IF_ICMPNE, elseTarget);
<add> }
<add> else {
<add> throw new IllegalStateException("Unexpected descriptor "+leftDesc);
<add> }
<add> } else {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> getRightOperand().generateCode(mv, codeflow);
<add> Label leftNotNull = new Label();
<add> mv.visitInsn(DUP_X1); // Dup right on the top of the stack
<add> mv.visitJumpInsn(IFNONNULL,leftNotNull);
<add> // Right is null!
<add> mv.visitInsn(SWAP);
<add> mv.visitInsn(POP); // remove it
<add> Label rightNotNull = new Label();
<add> mv.visitJumpInsn(IFNONNULL, rightNotNull);
<add> // Left is null too
<add> mv.visitInsn(ICONST_1);
<add> mv.visitJumpInsn(GOTO, endOfIf);
<add> mv.visitLabel(rightNotNull);
<add> mv.visitInsn(ICONST_0);
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add>
<add>
<add> mv.visitLabel(leftNotNull);
<add> mv.visitMethodInsn(INVOKEVIRTUAL,"java/lang/Object","equals","(Ljava/lang/Object;)Z",false);
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor("Z");
<add> return;
<add> }
<add> mv.visitInsn(ICONST_1);
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add> mv.visitLabel(elseTarget);
<add> mv.visitInsn(ICONST_0);
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor("Z");
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpGE.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import java.math.BigDecimal;
<del>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> public class OpGE extends Operator {
<ide>
<ide> public OpGE(int pos, SpelNodeImpl... operands) {
<ide> super(">=", pos, operands);
<add> this.exitTypeDescriptor="Z";
<ide> }
<ide>
<ide>
<ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati
<ide> }
<ide> return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) >= 0);
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return isCompilableOperatorUsingNumerics();
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> generateComparisonCode(mv, codeflow, IFLT, IF_ICMPLT);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpGT.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import java.math.BigDecimal;
<del>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> public class OpGT extends Operator {
<ide>
<ide> public OpGT(int pos, SpelNodeImpl... operands) {
<ide> super(">", pos, operands);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide> @Override
<ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati
<ide> return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) > 0);
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> return isCompilableOperatorUsingNumerics();
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> generateComparisonCode(mv, codeflow, IFLE, IF_ICMPLE);
<add> }
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLE.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import java.math.BigDecimal;
<del>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> public class OpLE extends Operator {
<ide>
<ide> public OpLE(int pos, SpelNodeImpl... operands) {
<ide> super("<=", pos, operands);
<add> this.exitTypeDescriptor="Z";
<ide> }
<ide>
<ide>
<ide> public BooleanTypedValue getValueInternal(ExpressionState state)
<ide>
<ide> return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) <= 0);
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return isCompilableOperatorUsingNumerics();
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> generateComparisonCode(mv, codeflow, IFGT, IF_ICMPGT);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpLT.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import java.math.BigDecimal;
<del>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> public class OpLT extends Operator {
<ide>
<ide> public OpLT(int pos, SpelNodeImpl... operands) {
<ide> super("<", pos, operands);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide> @Override
<ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati
<ide>
<ide> return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) < 0);
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return isCompilableOperatorUsingNumerics();
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> generateComparisonCode(mv, codeflow, IFGE, IF_ICMPGE);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMinus.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>
<ide> import java.math.BigDecimal;
<ide>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.Operation;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> /**
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> }
<ide>
<ide> if (operand instanceof Double) {
<add> this.exitTypeDescriptor = "D";
<ide> return new TypedValue(0 - n.doubleValue());
<ide> }
<ide>
<ide> if (operand instanceof Float) {
<add> this.exitTypeDescriptor = "F";
<ide> return new TypedValue(0 - n.floatValue());
<ide> }
<ide>
<ide> if (operand instanceof Long) {
<add> this.exitTypeDescriptor = "J";
<ide> return new TypedValue(0 - n.longValue());
<ide> }
<del>
<add> this.exitTypeDescriptor = "I";
<ide> return new TypedValue(0 - n.intValue());
<ide> }
<ide>
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
<ide> return new TypedValue(leftBigDecimal.subtract(rightBigDecimal));
<ide> }
<del>
<add>
<ide> if (leftNumber instanceof Double || rightNumber instanceof Double) {
<add> if (leftNumber instanceof Double && rightNumber instanceof Double) {
<add> this.exitTypeDescriptor = "D";
<add> }
<ide> return new TypedValue(leftNumber.doubleValue() - rightNumber.doubleValue());
<ide> }
<ide>
<ide> if (leftNumber instanceof Float || rightNumber instanceof Float) {
<add> if (leftNumber instanceof Float && rightNumber instanceof Float) {
<add> this.exitTypeDescriptor = "F";
<add> }
<ide> return new TypedValue(leftNumber.floatValue() - rightNumber.floatValue());
<ide> }
<ide>
<ide> if (leftNumber instanceof Long || rightNumber instanceof Long) {
<add> if (leftNumber instanceof Long && rightNumber instanceof Long) {
<add> this.exitTypeDescriptor = "J";
<add> }
<ide> return new TypedValue(leftNumber.longValue() - rightNumber.longValue());
<ide> }
<del>
<add> this.exitTypeDescriptor = "I";
<ide> return new TypedValue(leftNumber.intValue() - rightNumber.intValue());
<ide> }
<ide> else if (left instanceof String && right instanceof Integer
<ide> public String toStringAST() {
<ide> }
<ide> return super.toStringAST();
<ide> }
<add>
<ide> @Override
<ide> public SpelNodeImpl getRightOperand() {
<ide> if (this.children.length<2) {return null;}
<ide> return this.children[1];
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> if (!getLeftOperand().isCompilable()) {
<add> return false;
<add> }
<add> if (this.children.length>1) {
<add> if (!getRightOperand().isCompilable()) {
<add> return false;
<add> }
<add> }
<add> return this.exitTypeDescriptor!=null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> String leftdesc = getLeftOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(leftdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> if (this.children.length>1) {
<add> getRightOperand().generateCode(mv, codeflow);
<add> String rightdesc = getRightOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(rightdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> switch (this.exitTypeDescriptor.charAt(0)) {
<add> case 'I':
<add> mv.visitInsn(ISUB);
<add> break;
<add> case 'J':
<add> mv.visitInsn(LSUB);
<add> break;
<add> case 'F':
<add> mv.visitInsn(FSUB);
<add> break;
<add> case 'D':
<add> mv.visitInsn(DSUB);
<add> break;
<add> default:
<add> throw new IllegalStateException("Unrecognized exit descriptor: '"+this.exitTypeDescriptor+"'");
<add> }
<add> } else {
<add> switch (this.exitTypeDescriptor.charAt(0)) {
<add> case 'I':
<add> mv.visitInsn(INEG);
<add> break;
<add> case 'J':
<add> mv.visitInsn(LNEG);
<add> break;
<add> case 'F':
<add> mv.visitInsn(FNEG);
<add> break;
<add> case 'D':
<add> mv.visitInsn(DNEG);
<add> break;
<add> default:
<add> throw new IllegalStateException("Unrecognized exit descriptor: '"+this.exitTypeDescriptor+"'");
<add> }
<add> }
<add> codeflow.pushDescriptor(this.exitTypeDescriptor);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMultiply.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>
<ide> import java.math.BigDecimal;
<ide>
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.Operation;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> /**
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> }
<ide>
<ide> if (leftNumber instanceof Double || rightNumber instanceof Double) {
<del> return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue());
<add> if (leftNumber instanceof Double && rightNumber instanceof Double) {
<add> this.exitTypeDescriptor = "D";
<add> }
<add> return new TypedValue(leftNumber.doubleValue()
<add> * rightNumber.doubleValue());
<ide> }
<ide>
<ide> if (leftNumber instanceof Float || rightNumber instanceof Float) {
<add> if (leftNumber instanceof Float && rightNumber instanceof Float) {
<add> this.exitTypeDescriptor = "F";
<add> }
<ide> return new TypedValue(leftNumber.floatValue() * rightNumber.floatValue());
<ide> }
<ide>
<ide> if (leftNumber instanceof Long || rightNumber instanceof Long) {
<add> if (leftNumber instanceof Long && rightNumber instanceof Long) {
<add> this.exitTypeDescriptor = "J";
<add> }
<ide> return new TypedValue(leftNumber.longValue() * rightNumber.longValue());
<ide> }
<del>
<add> if (leftNumber instanceof Integer && rightNumber instanceof Integer) {
<add> this.exitTypeDescriptor = "I";
<add> }
<ide> return new TypedValue(leftNumber.intValue() * rightNumber.intValue());
<ide> }
<ide> else if (leftOperand instanceof String && rightOperand instanceof Integer) {
<ide> else if (leftOperand instanceof String && rightOperand instanceof Integer) {
<ide>
<ide> return state.operate(Operation.MULTIPLY, leftOperand, rightOperand);
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> if (!getLeftOperand().isCompilable()) {
<add> return false;
<add> }
<add> if (this.children.length>1) {
<add> if (!getRightOperand().isCompilable()) {
<add> return false;
<add> }
<add> }
<add> return this.exitTypeDescriptor!=null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> String leftdesc = getLeftOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(leftdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> if (this.children.length>1) {
<add> getRightOperand().generateCode(mv, codeflow);
<add> String rightdesc = getRightOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(rightdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> switch (this.exitTypeDescriptor.charAt(0)) {
<add> case 'I':
<add> mv.visitInsn(IMUL);
<add> break;
<add> case 'J':
<add> mv.visitInsn(LMUL);
<add> break;
<add> case 'F':
<add> mv.visitInsn(FMUL);
<add> break;
<add> case 'D':
<add> mv.visitInsn(DMUL);
<add> break;
<add> default:
<add> throw new IllegalStateException("Unrecognized exit descriptor: '"+this.exitTypeDescriptor+"'");
<add> }
<add> }
<add> codeflow.pushDescriptor(this.exitTypeDescriptor);
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpNE.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<ide> /**
<ide> public class OpNE extends Operator {
<ide>
<ide> public OpNE(int pos, SpelNodeImpl... operands) {
<ide> super("!=", pos, operands);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide> @Override
<ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati
<ide> return BooleanTypedValue.forValue(!equalityCheck(state, left, right));
<ide> }
<ide>
<add> // This check is different to the one in the other numeric operators (OpLt/etc)
<add> // because we allow simple object comparison
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl left = getLeftOperand();
<add> SpelNodeImpl right= getRightOperand();
<add> if (!left.isCompilable() || !right.isCompilable()) {
<add> return false;
<add> }
<add> String leftdesc = left.getExitDescriptor();
<add> String rightdesc = right.getExitDescriptor();
<add> if ((CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(leftdesc) ||
<add> CodeFlow.isPrimitiveOrUnboxableSupportedNumber(rightdesc))) {
<add> if (!CodeFlow.areBoxingCompatible(leftdesc, rightdesc)) {
<add> return false;
<add> }
<add> }
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> String leftDesc = getLeftOperand().getExitDescriptor();
<add> String rightDesc = getRightOperand().getExitDescriptor();
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> boolean leftPrim = CodeFlow.isPrimitive(leftDesc);
<add> boolean rightPrim = CodeFlow.isPrimitive(rightDesc);
<add>
<add> if ((CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(leftDesc) ||
<add> CodeFlow.isPrimitiveOrUnboxableSupportedNumberOrBoolean(rightDesc)) &&
<add> CodeFlow.areBoxingCompatible(leftDesc,rightDesc)) {
<add> char targetType = CodeFlow.toPrimitiveTargetDesc(leftDesc);
<add>
<add> getLeftOperand().generateCode(mv, codeflow);
<add> if (!leftPrim) {
<add> CodeFlow.insertUnboxInsns(mv, targetType, false);
<add> }
<add>
<add> getRightOperand().generateCode(mv, codeflow);
<add> if (!rightPrim) {
<add> CodeFlow.insertUnboxInsns(mv, targetType, false);
<add> }
<add> // assert: SpelCompiler.boxingCompatible(leftDesc, rightDesc)
<add> if (targetType == 'D') {
<add> mv.visitInsn(DCMPL);
<add> mv.visitJumpInsn(IFEQ, elseTarget);
<add> }
<add> else if (targetType == 'F') {
<add> mv.visitInsn(FCMPL);
<add> mv.visitJumpInsn(IFEQ, elseTarget);
<add> }
<add> else if (targetType == 'J') {
<add> mv.visitInsn(LCMP);
<add> mv.visitJumpInsn(IFEQ, elseTarget);
<add> }
<add> else if (targetType == 'I' || targetType == 'Z') {
<add> mv.visitJumpInsn(IF_ICMPEQ, elseTarget);
<add> }
<add> else {
<add> throw new IllegalStateException("Unexpected descriptor "+leftDesc);
<add> }
<add> } else {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> getRightOperand().generateCode(mv, codeflow);
<add> mv.visitJumpInsn(IF_ACMPEQ, elseTarget);
<add> }
<add> mv.visitInsn(ICONST_1);
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add> mv.visitLabel(elseTarget);
<add> mv.visitInsn(ICONST_0);
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor("Z");
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpOr.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<ide> /**
<ide> public class OpOr extends Operator {
<ide>
<ide> public OpOr(int pos, SpelNodeImpl... operands) {
<ide> super("or", pos, operands);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide>
<ide> private void assertValueNotNull(Boolean value) {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl left = getLeftOperand();
<add> SpelNodeImpl right= getRightOperand();
<add> if (!left.isCompilable() || !right.isCompilable()) {
<add> return false;
<add> }
<add> return
<add> CodeFlow.isBooleanCompatible(left.getExitDescriptor()) &&
<add> CodeFlow.isBooleanCompatible(right.getExitDescriptor());
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> // pseudo: if (leftOperandValue) { result=true; } else { result=rightOperandValue; }
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> codeflow.enterCompilationScope();
<add> getLeftOperand().generateCode(mv, codeflow);
<add> codeflow.unboxBooleanIfNecessary(mv);
<add> codeflow.exitCompilationScope();
<add> mv.visitJumpInsn(IFEQ, elseTarget);
<add> mv.visitLdcInsn(1); // TRUE
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add> mv.visitLabel(elseTarget);
<add> codeflow.enterCompilationScope();
<add> getRightOperand().generateCode(mv, codeflow);
<add> codeflow.unboxBooleanIfNecessary(mv);
<add> codeflow.exitCompilationScope();
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>
<ide> import java.math.BigDecimal;
<ide>
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.TypeConverter;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.NumberUtils;
<ide>
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> Object operandOne = leftOp.getValueInternal(state).getValue();
<ide> if (operandOne instanceof Number) {
<ide> if (operandOne instanceof Double || operandOne instanceof Long || operandOne instanceof BigDecimal) {
<add> if (operandOne instanceof Double || operandOne instanceof Long) {
<add> this.exitTypeDescriptor = (operandOne instanceof Double)?"D":"J";
<add> }
<ide> return new TypedValue(operandOne);
<ide> }
<ide> if (operandOne instanceof Float) {
<add> this.exitTypeDescriptor = "F";
<ide> return new TypedValue(((Number) operandOne).floatValue());
<ide> }
<add> this.exitTypeDescriptor = "I";
<ide> return new TypedValue(((Number) operandOne).intValue());
<ide> }
<ide> return state.operate(Operation.ADD, operandOne, null);
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class);
<ide> return new TypedValue(leftBigDecimal.add(rightBigDecimal));
<ide> }
<del>
<ide> if (leftNumber instanceof Double || rightNumber instanceof Double) {
<add> if (leftNumber instanceof Double && rightNumber instanceof Double) {
<add> this.exitTypeDescriptor = "D";
<add> }
<ide> return new TypedValue(leftNumber.doubleValue() + rightNumber.doubleValue());
<ide> }
<del>
<ide> if (leftNumber instanceof Float || rightNumber instanceof Float) {
<add> if (leftNumber instanceof Float && rightNumber instanceof Float) {
<add> this.exitTypeDescriptor = "F";
<add> }
<ide> return new TypedValue(leftNumber.floatValue() + rightNumber.floatValue());
<ide> }
<del>
<ide> if (leftNumber instanceof Long || rightNumber instanceof Long) {
<add> if (leftNumber instanceof Long && rightNumber instanceof Long) {
<add> this.exitTypeDescriptor = "J";
<add> }
<ide> return new TypedValue(leftNumber.longValue() + rightNumber.longValue());
<ide> }
<ide>
<ide> // TODO what about overflow?
<add> this.exitTypeDescriptor = "I";
<ide> return new TypedValue(leftNumber.intValue() + rightNumber.intValue());
<ide> }
<ide>
<ide> private static String convertTypedValueToString(TypedValue value, ExpressionStat
<ide> return String.valueOf(value.getValue());
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> if (!getLeftOperand().isCompilable()) {
<add> return false;
<add> }
<add> if (this.children.length>1) {
<add> if (!getRightOperand().isCompilable()) {
<add> return false;
<add> }
<add> }
<add> return this.exitTypeDescriptor!=null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> String leftdesc = getLeftOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(leftdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> if (this.children.length>1) {
<add> getRightOperand().generateCode(mv, codeflow);
<add> String rightdesc = getRightOperand().getExitDescriptor();
<add> if (!CodeFlow.isPrimitive(rightdesc)) {
<add> CodeFlow.insertUnboxInsns(mv, this.exitTypeDescriptor.charAt(0), false);
<add> }
<add> switch (this.exitTypeDescriptor.charAt(0)) {
<add> case 'I':
<add> mv.visitInsn(IADD);
<add> break;
<add> case 'J':
<add> mv.visitInsn(LADD);
<add> break;
<add> case 'F':
<add> mv.visitInsn(FADD);
<add> break;
<add> case 'D':
<add> mv.visitInsn(DADD);
<add> break;
<add> default:
<add> throw new IllegalStateException("Unrecognized exit descriptor: '"+this.exitTypeDescriptor+"'");
<add> }
<add> }
<add> codeflow.pushDescriptor(this.exitTypeDescriptor);
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<add>
<ide> import java.math.BigDecimal;
<ide>
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> public String toStringAST() {
<ide> return sb.toString();
<ide> }
<ide>
<add> protected boolean isCompilableOperatorUsingNumerics() {
<add> SpelNodeImpl left = getLeftOperand();
<add> SpelNodeImpl right= getRightOperand();
<add> if (!left.isCompilable() || !right.isCompilable()) {
<add> return false;
<add> }
<add> // Supported operand types for equals (at the moment)
<add> String leftDesc = left.getExitDescriptor();
<add> String rightDesc= right.getExitDescriptor();
<add> if (CodeFlow.isPrimitiveOrUnboxableSupportedNumber(leftDesc) && CodeFlow.isPrimitiveOrUnboxableSupportedNumber(rightDesc)) {
<add> if (CodeFlow.areBoxingCompatible(leftDesc, rightDesc)) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * Numeric comparison operators share very similar generated code, only differing in
<add> * two comparison instructions.
<add> */
<add> protected void generateComparisonCode(MethodVisitor mv, CodeFlow codeflow, int compareInstruction1,
<add> int compareInstruction2) {
<add> String leftDesc = getLeftOperand().getExitDescriptor();
<add> String rightDesc = getRightOperand().getExitDescriptor();
<add>
<add> boolean unboxLeft = !CodeFlow.isPrimitive(leftDesc);
<add> boolean unboxRight = !CodeFlow.isPrimitive(rightDesc);
<add> char targetType = CodeFlow.toPrimitiveTargetDesc(leftDesc);
<add>
<add> getLeftOperand().generateCode(mv, codeflow);
<add> if (unboxLeft) {
<add> CodeFlow.insertUnboxInsns(mv, targetType, false);
<add> }
<add>
<add> getRightOperand().generateCode(mv, codeflow);
<add> if (unboxRight) {
<add> CodeFlow.insertUnboxInsns(mv, targetType, false);
<add> }
<add> // assert: SpelCompiler.boxingCompatible(leftDesc, rightDesc)
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> if (targetType=='D') {
<add> mv.visitInsn(DCMPG);
<add> mv.visitJumpInsn(compareInstruction1, elseTarget);
<add> }
<add> else if (targetType=='F') {
<add> mv.visitInsn(FCMPG);
<add> mv.visitJumpInsn(compareInstruction1, elseTarget);
<add> }
<add> else if (targetType=='J') {
<add> mv.visitInsn(LCMP);
<add> mv.visitJumpInsn(compareInstruction1, elseTarget);
<add> }
<add> else if (targetType=='I') {
<add> mv.visitJumpInsn(compareInstruction2, elseTarget);
<add> }
<add> else {
<add> throw new IllegalStateException("Unexpected descriptor "+leftDesc);
<add> }
<add> // Other numbers are not yet supported (isCompilable will not have returned true)
<add> mv.visitInsn(ICONST_1);
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add> mv.visitLabel(elseTarget);
<add> mv.visitInsn(ICONST_0);
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor("Z");
<add> }
<ide>
<ide> protected boolean equalityCheck(ExpressionState state, Object left, Object right) {
<ide> if (left instanceof Number && right instanceof Number) {
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OperatorInstanceof.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.asm.Type;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<add>
<ide> /**
<ide> * The operator 'instanceof' checks if an object is of the class specified in the right
<ide> * hand operand, in the same way that {@code instanceof} does in Java.
<ide> */
<ide> public class OperatorInstanceof extends Operator {
<ide>
<add> private Class<?> type;
<add>
<ide> public OperatorInstanceof(int pos, SpelNodeImpl... operands) {
<ide> super("instanceof", pos, operands);
<ide> }
<ide> public BooleanTypedValue getValueInternal(ExpressionState state) throws Evaluati
<ide> TypedValue right = getRightOperand().getValueInternal(state);
<ide> Object leftValue = left.getValue();
<ide> Object rightValue = right.getValue();
<del> if (leftValue == null) {
<del> return BooleanTypedValue.FALSE; // null is not an instanceof anything
<del> }
<add> BooleanTypedValue result = null;
<ide> if (rightValue == null || !(rightValue instanceof Class<?>)) {
<ide> throw new SpelEvaluationException(getRightOperand().getStartPosition(),
<ide> SpelMessage.INSTANCEOF_OPERATOR_NEEDS_CLASS_OPERAND,
<ide> (rightValue == null ? "null" : rightValue.getClass().getName()));
<ide> }
<ide> Class<?> rightClass = (Class<?>) rightValue;
<del> return BooleanTypedValue.forValue(rightClass.isAssignableFrom(leftValue.getClass()));
<add> if (leftValue == null) {
<add> result = BooleanTypedValue.FALSE; // null is not an instanceof anything
<add> } else {
<add> result = BooleanTypedValue.forValue(rightClass.isAssignableFrom(leftValue.getClass()));
<add> }
<add> this.type = rightClass;
<add> this.exitTypeDescriptor = "Z";
<add> return result;
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> return this.exitTypeDescriptor != null && getLeftOperand().isCompilable();
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> getLeftOperand().generateCode(mv, codeflow);
<add> mv.visitTypeInsn(INSTANCEOF,Type.getInternalName(this.type));
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/OperatorNot.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.BooleanTypedValue;
<ide>
<ide> /**
<ide> public class OperatorNot extends SpelNodeImpl { // Not is a unary operator so do
<ide>
<ide> public OperatorNot(int pos, SpelNodeImpl operand) {
<ide> super(pos, operand);
<add> this.exitTypeDescriptor = "Z";
<ide> }
<ide>
<ide>
<ide> public String toStringAST() {
<ide> sb.append("!").append(getChild(0).toStringAST());
<ide> return sb.toString();
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl child = this.children[0];
<add> return child.isCompilable() && CodeFlow.isBooleanCompatible(child.getExitDescriptor());
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> this.children[0].generateCode(mv, codeflow);
<add> codeflow.unboxBooleanIfNecessary(mv);
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> mv.visitJumpInsn(IFNE,elseTarget);
<add> mv.visitInsn(ICONST_1); // TRUE
<add> mv.visitJumpInsn(GOTO,endOfIf);
<add> mv.visitLabel(elseTarget);
<add> mv.visitInsn(ICONST_0); // FALSE
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.expression.AccessException;
<add>import org.springframework.expression.CompilablePropertyAccessor;
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.PropertyAccessor;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
<ide>
<ide> /**
<ide> public ValueRef getValueRef(ExpressionState state) throws EvaluationException {
<ide>
<ide> @Override
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
<del> return getValueInternal(state.getActiveContextObject(), state.getEvaluationContext(),
<del> state.getConfiguration().isAutoGrowNullReferences());
<add> TypedValue tv = getValueInternal(state.getActiveContextObject(), state.getEvaluationContext(), state.getConfiguration().isAutoGrowNullReferences());
<add> if (cachedReadAccessor instanceof CompilablePropertyAccessor) {
<add> CompilablePropertyAccessor accessor = (CompilablePropertyAccessor)cachedReadAccessor;
<add> exitTypeDescriptor = CodeFlow.toDescriptor(accessor.getPropertyType());
<add> }
<add> return tv;
<add> }
<add>
<add> @Override
<add> public String getExitDescriptor() {
<add> return exitTypeDescriptor;
<ide> }
<ide>
<ide> private TypedValue getValueInternal(TypedValue contextObject, EvaluationContext eContext,
<ide> else if (clazz.isAssignableFrom(targetType)) {
<ide> resolvers.addAll(generalAccessors);
<ide> return resolvers;
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> if (this.cachedReadAccessor == null) {
<add> return false;
<add> }
<add> if (this.cachedReadAccessor instanceof CompilablePropertyAccessor) {
<add> return ((CompilablePropertyAccessor)this.cachedReadAccessor).isCompilable();
<add> }
<add> return false;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv,CodeFlow codeflow) {
<add> ((CompilablePropertyAccessor)this.cachedReadAccessor).generateCode(this, mv, codeflow);
<add> codeflow.pushDescriptor(exitTypeDescriptor);
<add> }
<ide>
<ide>
<ide> private static class AccessorLValue implements ValueRef {
<ide> public AccessorLValue(PropertyOrFieldReference propertyOrFieldReference, TypedVa
<ide>
<ide> @Override
<ide> public TypedValue getValue() {
<del> return this.ref.getValueInternal(this.contextObject, this.eContext, this.autoGrowNullReferences);
<add> TypedValue value = this.ref.getValueInternal(this.contextObject, this.eContext, this.autoGrowNullReferences);
<add> if (ref.cachedReadAccessor instanceof CompilablePropertyAccessor) {
<add> CompilablePropertyAccessor accessor = (CompilablePropertyAccessor)this.ref.cachedReadAccessor;
<add> this.ref.exitTypeDescriptor = CodeFlow.toDescriptor(accessor.getPropertyType());
<add> }
<add> return value;
<ide> }
<ide>
<ide> @Override
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/RealLiteral.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Expression language AST node that represents a real literal.
<ide> public class RealLiteral extends Literal {
<ide> public RealLiteral(String payload, int pos, double value) {
<ide> super(payload, pos);
<ide> this.value = new TypedValue(value);
<add> this.exitTypeDescriptor = "D";
<ide> }
<ide>
<ide>
<ide> public TypedValue getLiteralValue() {
<ide> return this.value;
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> mv.visitLdcInsn(this.value.getValue());
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.asm.Opcodes;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.common.ExpressionUtils;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<ide> import org.springframework.expression.spel.SpelNode;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.expression.spel.support.StandardEvaluationContext;
<ide> import org.springframework.util.Assert;
<ide>
<ide> * @author Andy Clement
<ide> * @since 3.0
<ide> */
<del>public abstract class SpelNodeImpl implements SpelNode {
<add>public abstract class SpelNodeImpl implements SpelNode, Opcodes {
<ide>
<ide> private static SpelNodeImpl[] NO_CHILDREN = new SpelNodeImpl[0];
<ide>
<ide> public abstract class SpelNodeImpl implements SpelNode {
<ide>
<ide> private SpelNodeImpl parent;
<ide>
<add> /**
<add> * Indicates the type descriptor for the result of this expression node. This is
<add> * set as soon as it is known. For a literal node it is known immediately. For
<add> * a property access or method invocation it is known after one evaluation of
<add> * that node.
<add> * The descriptor is like the bytecode form but is slightly easier to work with. It
<add> * does not include the trailing semicolon (for non array reference types). Some examples:
<add> * Ljava/lang/String, I, [I
<add> */
<add> protected String exitTypeDescriptor;
<ide>
<ide> public SpelNodeImpl(int pos, SpelNodeImpl... operands) {
<ide> this.pos = pos;
<ide> protected ValueRef getValueRef(ExpressionState state) throws EvaluationException
<ide> throw new SpelEvaluationException(this.pos, SpelMessage.NOT_ASSIGNABLE, toStringAST());
<ide> }
<ide>
<add> /**
<add> * Check whether a node can be compiled to bytecode. The reasoning in each node may
<add> * be different but will typically involve checking whether the exit type descriptor
<add> * of the node is known and any relevant child nodes are compilable.
<add> *
<add> * @return true if this node can be compiled to bytecode
<add> */
<add> public boolean isCompilable() {
<add> return false;
<add> }
<add>
<add> /**
<add> * Generate the bytecode for this node into the supplied visitor. Context info about
<add> * the current expression being compiled is available in the codeflow object. For
<add> * example it will include information about the type of the object currently
<add> * on the stack.
<add> *
<add> * @param mv the ASM MethodVisitor into which code should be generated
<add> * @param codeflow a context object with info about what is on the stack
<add> */
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> throw new IllegalStateException(this.getClass().getName()+" has no generateCode(..) method");
<add> }
<add>
<add> public String getExitDescriptor() {
<add> return this.exitTypeDescriptor;
<add> }
<ide>
<ide> public abstract TypedValue getValueInternal(ExpressionState expressionState) throws EvaluationException;
<ide>
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/StringLiteral.java
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Expression language AST node that represents a string literal.
<ide> public class StringLiteral extends Literal {
<ide>
<ide> public StringLiteral(String payload, int pos, String value) {
<ide> super(payload,pos);
<del> // TODO should these have been skipped being created by the parser rules? or not?
<ide> value = value.substring(1, value.length() - 1);
<ide> this.value = new TypedValue(value.replaceAll("''", "'").replaceAll("\"\"", "\""));
<add> this.exitTypeDescriptor = "Ljava/lang/String";
<ide> }
<ide>
<ide>
<ide> public TypedValue getLiteralValue() {
<ide> public String toString() {
<ide> return "'" + getLiteralValue().getValue() + "'";
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> mv.visitLdcInsn(this.value.getValue());
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Ternary.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.Label;
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<ide> import org.springframework.expression.spel.SpelMessage;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Represents a ternary expression, for example: "someCheck()?true:false".
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> throw new SpelEvaluationException(getChild(0).getStartPosition(),
<ide> SpelMessage.TYPE_CONVERSION_ERROR, "null", "boolean");
<ide> }
<add> TypedValue result = null;
<ide> if (value.booleanValue()) {
<del> return this.children[1].getValueInternal(state);
<add> result = this.children[1].getValueInternal(state);
<ide> }
<ide> else {
<del> return this.children[2].getValueInternal(state);
<add> result = this.children[2].getValueInternal(state);
<ide> }
<add> computeExitTypeDescriptor();
<add> return result;
<ide> }
<del>
<add>
<ide> @Override
<ide> public String toStringAST() {
<ide> return new StringBuilder().append(getChild(0).toStringAST()).append(" ? ").append(getChild(1).toStringAST())
<ide> .append(" : ").append(getChild(2).toStringAST()).toString();
<ide> }
<ide>
<add> private void computeExitTypeDescriptor() {
<add> if (exitTypeDescriptor == null && this.children[1].getExitDescriptor()!=null && this.children[2].getExitDescriptor()!=null) {
<add> String leftDescriptor = this.children[1].exitTypeDescriptor;
<add> String rightDescriptor = this.children[2].exitTypeDescriptor;
<add> if (leftDescriptor.equals(rightDescriptor)) {
<add> this.exitTypeDescriptor = leftDescriptor;
<add> }
<add> else if (leftDescriptor.equals("Ljava/lang/Object") && !CodeFlow.isPrimitive(rightDescriptor)) {
<add> this.exitTypeDescriptor = rightDescriptor;
<add> }
<add> else if (rightDescriptor.equals("Ljava/lang/Object") && !CodeFlow.isPrimitive(leftDescriptor)) {
<add> this.exitTypeDescriptor = leftDescriptor;
<add> }
<add> else {
<add> // Use the easiest to compute common super type
<add> this.exitTypeDescriptor = "Ljava/lang/Object";
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> SpelNodeImpl condition = this.children[0];
<add> SpelNodeImpl left = this.children[1];
<add> SpelNodeImpl right = this.children[2];
<add> if (!(condition.isCompilable() && left.isCompilable() && right.isCompilable())) {
<add> return false;
<add> }
<add> return CodeFlow.isBooleanCompatible(condition.exitTypeDescriptor) &&
<add> left.getExitDescriptor()!=null &&
<add> right.getExitDescriptor()!=null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> // May reach here without it computed if all elements are literals
<add> computeExitTypeDescriptor();
<add> codeflow.enterCompilationScope();
<add> this.children[0].generateCode(mv, codeflow);
<add> codeflow.exitCompilationScope();
<add> Label elseTarget = new Label();
<add> Label endOfIf = new Label();
<add> mv.visitJumpInsn(IFEQ, elseTarget);
<add> codeflow.enterCompilationScope();
<add> this.children[1].generateCode(mv, codeflow);
<add> if (!CodeFlow.isPrimitive(getExitDescriptor())) {
<add> CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
<add> }
<add> codeflow.exitCompilationScope();
<add> mv.visitJumpInsn(GOTO, endOfIf);
<add> mv.visitLabel(elseTarget);
<add> codeflow.enterCompilationScope();
<add> this.children[2].generateCode(mv, codeflow);
<add> if (!CodeFlow.isPrimitive(getExitDescriptor())) {
<add> CodeFlow.insertBoxIfNecessary(mv, codeflow.lastDescriptor().charAt(0));
<add> }
<add> codeflow.exitCompilationScope();
<add> mv.visitLabel(endOfIf);
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/TypeReference.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import java.lang.reflect.Array;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.asm.Type;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Represents a reference to a type, for example "T(String)" or "T(com.somewhere.Foo)"
<ide> public class TypeReference extends SpelNodeImpl {
<ide>
<ide> private final int dimensions;
<ide>
<add> private transient Class<?> type;
<ide>
<ide> public TypeReference(int pos, SpelNodeImpl qualifiedId) {
<ide> this(pos,qualifiedId,0);
<ide> public TypedValue getValueInternal(ExpressionState state) throws EvaluationExcep
<ide> // it is a primitive type
<ide> Class<?> clazz = tc.getType();
<ide> clazz = makeArrayIfNecessary(clazz);
<add> this.exitTypeDescriptor = "Ljava/lang/Class";
<add> this.type = clazz;
<ide> return new TypedValue(clazz);
<ide> }
<ide> }
<ide> Class<?> clazz = state.findType(typename);
<ide> clazz = makeArrayIfNecessary(clazz);
<add> this.exitTypeDescriptor = "Ljava/lang/Class";
<add> this.type = clazz;
<ide> return new TypedValue(clazz);
<ide> }
<ide>
<ide> public String toStringAST() {
<ide> sb.append(")");
<ide> return sb.toString();
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return this.exitTypeDescriptor != null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> // TODO Future optimization - if followed by a static method call, skip generating code here
<add> if (type.isPrimitive()) {
<add> if (type == Integer.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Integer", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Boolean.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Byte.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Byte", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Short.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Short", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Double.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Double", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Character.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Character", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Float.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Float", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Long.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Long", "TYPE", "Ljava/lang/Class;");
<add> } else if (type == Boolean.TYPE) {
<add> mv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
<add> }
<add> }
<add> else {
<add> mv.visitLdcInsn(Type.getType(type));
<add> }
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/VariableReference.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.expression.spel.ast;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.spel.ExpressionState;
<ide> import org.springframework.expression.spel.SpelEvaluationException;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide>
<ide> /**
<ide> * Represents a variable reference, eg. #someVar. Note this is different to a *local*
<ide> public TypedValue getValueInternal(ExpressionState state) throws SpelEvaluationE
<ide> return state.getActiveContextObject();
<ide> }
<ide> if (this.name.equals(ROOT)) {
<del> return state.getRootContextObject();
<add> TypedValue result = state.getRootContextObject();
<add> this.exitTypeDescriptor = CodeFlow.toDescriptorFromObject(result.getValue());
<add> return result;
<ide> }
<ide> TypedValue result = state.lookupVariable(this.name);
<add> this.exitTypeDescriptor = CodeFlow.toDescriptorFromObject(result.getValue());
<ide> // a null value will mean either the value was null or the variable was not found
<ide> return result;
<ide> }
<ide> public boolean isWritable() {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public boolean isCompilable() {
<add> return getExitDescriptor()!=null;
<add> }
<add>
<add> @Override
<add> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<add> if (this.name.equals(ROOT)) {
<add> mv.visitVarInsn(ALOAD,1);
<add> } else {
<add> mv.visitVarInsn(ALOAD, 2);
<add> mv.visitLdcInsn(name);
<add> mv.visitMethodInsn(INVOKEINTERFACE, "org/springframework/expression/EvaluationContext", "lookupVariable", "(Ljava/lang/String;)Ljava/lang/Object;",true);
<add> }
<add> CodeFlow.insertCheckCast(mv,getExitDescriptor());
<add> codeflow.pushDescriptor(getExitDescriptor());
<add> }
<add>
<ide>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/CodeFlow.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel.standard;
<add>
<add>import java.lang.reflect.Constructor;
<add>import java.lang.reflect.Method;
<add>import java.util.ArrayList;
<add>import java.util.Stack;
<add>
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.asm.Opcodes;
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Records intermediate compilation state as the bytecode is generated for a parsed
<add> * expression. Also contains bytecode generation helper functions.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>public class CodeFlow implements Opcodes {
<add>
<add> /**
<add> * Record the type of what is on top of the bytecode stack (i.e. the type of the
<add> * output from the previous expression component). New scopes are used to evaluate
<add> * sub-expressions like the expressions for the argument values in a method invocation
<add> * expression.
<add> */
<add> private Stack<ArrayList<String>> compilationScopes;
<add>
<add> public CodeFlow() {
<add> compilationScopes = new Stack<ArrayList<String>>();
<add> compilationScopes.add(new ArrayList<String>());
<add> }
<add>
<add> /**
<add> * Push the byte code to load the target (i.e. what was passed as the first argument
<add> * to CompiledExpression.getValue(target, context))
<add> * @param mv the visitor into which the load instruction should be inserted
<add> */
<add> public void loadTarget(MethodVisitor mv) {
<add> mv.visitVarInsn(ALOAD, 1);
<add> }
<add>
<add> /**
<add> * Record the descriptor for the most recently evaluated expression element.
<add> * @param descriptor type descriptor for most recently evaluated element
<add> */
<add> public void pushDescriptor(String descriptor) {
<add> Assert.notNull(descriptor);
<add> compilationScopes.peek().add(descriptor);
<add> }
<add>
<add> /**
<add> * Enter a new compilation scope, usually due to nested expression evaluation. For
<add> * example when the arguments for a method invocation expression are being evaluated,
<add> * each argument will be evaluated in a new scope.
<add> */
<add> public void enterCompilationScope() {
<add> compilationScopes.push(new ArrayList<String>());
<add> }
<add>
<add> /**
<add> * Exit a compilation scope, usually after a nested expression has been evaluated. For
<add> * example after an argument for a method invocation has been evaluated this method
<add> * returns us to the previous (outer) scope.
<add> */
<add> public void exitCompilationScope() {
<add> compilationScopes.pop();
<add> }
<add>
<add> /**
<add> * @return the descriptor for the item currently on top of the stack (in the current
<add> * scope)
<add> */
<add> public String lastDescriptor() {
<add> if (compilationScopes.peek().size()==0) {
<add> return null;
<add> }
<add> return compilationScopes.peek().get(compilationScopes.peek().size()-1);
<add> }
<add>
<add> /**
<add> * If the codeflow shows the last expression evaluated to java.lang.Boolean then
<add> * insert the necessary instructions to unbox that to a boolean primitive.
<add> * @param mv the visitor into which new instructions should be inserted
<add> */
<add> public void unboxBooleanIfNecessary(MethodVisitor mv) {
<add> if (lastDescriptor().equals("Ljava/lang/Boolean")) {
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false);
<add> }
<add> }
<add>
<add> /**
<add> * Insert any necessary cast and value call to convert from a boxed type to a
<add> * primitive value
<add> * @param mv the method visitor into which instructions should be inserted
<add> * @param ch the primitive type desired as output
<add> * @param isObject indicates whether the type on the stack is being thought of as
<add> * Object (and so requires a cast)
<add> */
<add> public static void insertUnboxInsns(MethodVisitor mv, char ch, boolean isObject) {
<add> switch (ch) {
<add> case 'I':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false);
<add> break;
<add> case 'Z':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false);
<add> break;
<add> case 'B':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Byte");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B", false);
<add> break;
<add> case 'C':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Character");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C", false);
<add> break;
<add> case 'D':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Double");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D", false);
<add> break;
<add> case 'S':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Short");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S", false);
<add> break;
<add> case 'F':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Float");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F", false);
<add> break;
<add> case 'J':
<add> if (isObject) {
<add> mv.visitTypeInsn(CHECKCAST, "java/lang/Long");
<add> }
<add> mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J", false);
<add> break;
<add> default:
<add> throw new IllegalArgumentException("Unboxing should not be attempted for descriptor '" + ch + "'");
<add> }
<add> }
<add>
<add> /**
<add> * Create the JVM signature descriptor for a method. This consists of the descriptors
<add> * for the constructor parameters surrounded with parentheses, followed by the
<add> * descriptor for the return type. Note the descriptors here are JVM descriptors,
<add> * unlike the other descriptor forms the compiler is using which do not include the
<add> * trailing semicolon.
<add> * @param method the method
<add> * @return a String signature descriptor (e.g. "(ILjava/lang/String;)V")
<add> */
<add> public static String createSignatureDescriptor(Method method) {
<add> Class<?>[] params = method.getParameterTypes();
<add> StringBuilder s = new StringBuilder();
<add> s.append("(");
<add> for (int i = 0, max = params.length; i < max; i++) {
<add> s.append(toJVMDescriptor(params[i]));
<add> }
<add> s.append(")");
<add> s.append(toJVMDescriptor(method.getReturnType()));
<add> return s.toString();
<add> }
<add>
<add> /**
<add> * Create the JVM signature descriptor for a constructor. This consists of the
<add> * descriptors for the constructor parameters surrounded with parentheses. Note the
<add> * descriptors here are JVM descriptors, unlike the other descriptor forms the
<add> * compiler is using which do not include the trailing semicolon.
<add> * @param ctor the constructor
<add> * @return a String signature descriptor (e.g. "(ILjava/lang/String;)")
<add> */
<add> public static String createSignatureDescriptor(Constructor<?> ctor) {
<add> Class<?>[] params = ctor.getParameterTypes();
<add> StringBuilder s = new StringBuilder();
<add> s.append("(");
<add> for (int i = 0, max = params.length; i < max; i++) {
<add> s.append(toJVMDescriptor(params[i]));
<add> }
<add> s.append(")V");
<add> return s.toString();
<add> }
<add>
<add> /**
<add> * Determine the JVM descriptor for a specified class. Unlike the other descriptors
<add> * used in the compilation process, this is the one the JVM wants, so this one
<add> * includes any necessary trailing semicolon (e.g. Ljava/lang/String; rather than
<add> * Ljava/lang/String)
<add> *
<add> * @param clazz a class
<add> * @return the JVM descriptor for the class
<add> */
<add> public static String toJVMDescriptor(Class<?> clazz) {
<add> StringBuilder s= new StringBuilder();
<add> if (clazz.isArray()) {
<add> while (clazz.isArray()) {
<add> s.append("[");
<add> clazz = clazz.getComponentType();
<add> }
<add> }
<add> if (clazz.isPrimitive()) {
<add> if (clazz == Void.TYPE) {
<add> s.append('V');
<add> }
<add> else if (clazz == Integer.TYPE) {
<add> s.append('I');
<add> }
<add> else if (clazz == Boolean.TYPE) {
<add> s.append('Z');
<add> }
<add> else if (clazz == Character.TYPE) {
<add> s.append('C');
<add> }
<add> else if (clazz == Long.TYPE) {
<add> s.append('J');
<add> }
<add> else if (clazz == Double.TYPE) {
<add> s.append('D');
<add> }
<add> else if (clazz == Float.TYPE) {
<add> s.append('F');
<add> }
<add> else if (clazz == Byte.TYPE) {
<add> s.append('B');
<add> }
<add> else if (clazz == Short.TYPE) {
<add> s.append('S');
<add> }
<add> } else {
<add> s.append("L");
<add> s.append(clazz.getName().replace('.', '/'));
<add> s.append(";");
<add> }
<add> return s.toString();
<add> }
<add>
<add> /**
<add> * Determine the descriptor for an object instance (or null).
<add> * @param value an object (possibly null)
<add> * @return the type descriptor for the object (descriptor is "Ljava/lang/Object" for
<add> * null value)
<add> */
<add> public static String toDescriptorFromObject(Object value) {
<add> if (value == null) {
<add> return "Ljava/lang/Object";
<add> } else {
<add> return toDescriptor(value.getClass());
<add> }
<add> }
<add>
<add> /**
<add> * @param descriptor type descriptor
<add> * @return true if the descriptor is for a boolean primitive or boolean reference type
<add> */
<add> public static boolean isBooleanCompatible(String descriptor) {
<add> return descriptor != null
<add> && (descriptor.equals("Z") || descriptor.equals("Ljava/lang/Boolean"));
<add> }
<add>
<add> /**
<add> * @param descriptor type descriptor
<add> * @return true if the descriptor is for a primitive type
<add> */
<add> public static boolean isPrimitive(String descriptor) {
<add> return descriptor!=null && descriptor.length()==1;
<add> }
<add>
<add> /**
<add> * @param descriptor the descriptor for a possible primitive array
<add> * @return true if the descriptor is for a primitive array (e.g. "[[I")
<add> */
<add> public static boolean isPrimitiveArray(String descriptor) {
<add> boolean primitive = true;
<add> for (int i = 0, max = descriptor.length(); i < max; i++) {
<add> char ch = descriptor.charAt(i);
<add> if (ch == '[') {
<add> continue;
<add> }
<add> primitive = (ch != 'L');
<add> break;
<add> }
<add> return primitive;
<add> }
<add>
<add> /**
<add> * Determine if boxing/unboxing can get from one type to the other. Assumes at least
<add> * one of the types is in boxed form (i.e. single char descriptor).
<add> *
<add> * @return true if it is possible to get (via boxing) from one descriptor to the other
<add> */
<add> public static boolean areBoxingCompatible(String desc1, String desc2) {
<add> if (desc1.equals(desc2)) {
<add> return true;
<add> }
<add> if (desc1.length()==1) {
<add> if (desc1.equals("D")) {
<add> return desc2.equals("Ljava/lang/Double");
<add> }
<add> else if (desc1.equals("F")) {
<add> return desc2.equals("Ljava/lang/Float");
<add> }
<add> else if (desc1.equals("J")) {
<add> return desc2.equals("Ljava/lang/Long");
<add> }
<add> else if (desc1.equals("I")) {
<add> return desc2.equals("Ljava/lang/Integer");
<add> }
<add> else if (desc1.equals("Z")) {
<add> return desc2.equals("Ljava/lang/Boolean");
<add> }
<add> }
<add> else if (desc2.length()==1) {
<add> if (desc2.equals("D")) {
<add> return desc1.equals("Ljava/lang/Double");
<add> }
<add> else if (desc2.equals("F")) {
<add> return desc1.equals("Ljava/lang/Float");
<add> }
<add> else if (desc2.equals("J")) {
<add> return desc1.equals("Ljava/lang/Long");
<add> }
<add> else if (desc2.equals("I")) {
<add> return desc1.equals("Ljava/lang/Integer");
<add> }
<add> else if (desc2.equals("Z")) {
<add> return desc1.equals("Ljava/lang/Boolean");
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * Determine if the supplied descriptor is for a supported number type or boolean. The
<add> * compilation process only (currently) supports certain number types. These are
<add> * double, float, long and int.
<add> * @param descriptor the descriptor for a type
<add> * @return true if the descriptor is for a supported numeric type or boolean
<add> */
<add> public static boolean isPrimitiveOrUnboxableSupportedNumberOrBoolean(String descriptor) {
<add> if (descriptor==null) {
<add> return false;
<add> }
<add> if (descriptor.length()==1) {
<add> return "DFJZI".indexOf(descriptor.charAt(0))!=-1;
<add> }
<add> if (descriptor.startsWith("Ljava/lang/")) {
<add> if (descriptor.equals("Ljava/lang/Double") || descriptor.equals("Ljava/lang/Integer") ||
<add> descriptor.equals("Ljava/lang/Float") || descriptor.equals("Ljava/lang/Long") ||
<add> descriptor.equals("Ljava/lang/Boolean")) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * Determine if the supplied descriptor is for a supported number. The compilation
<add> * process only (currently) supports certain number types. These are double, float,
<add> * long and int.
<add> * @param descriptor the descriptor for a type
<add> * @return true if the descriptor is for a supported numeric type
<add> */
<add> public static boolean isPrimitiveOrUnboxableSupportedNumber(String descriptor) {
<add> if (descriptor==null) {
<add> return false;
<add> }
<add> if (descriptor.length()==1) {
<add> return "DFJI".indexOf(descriptor.charAt(0))!=-1;
<add> }
<add> if (descriptor.startsWith("Ljava/lang/")) {
<add> if (descriptor.equals("Ljava/lang/Double") || descriptor.equals("Ljava/lang/Integer") ||
<add> descriptor.equals("Ljava/lang/Float") || descriptor.equals("Ljava/lang/Long")) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * @param descriptor a descriptor for a type that should have a primitive
<add> * representation
<add> * @return the single character descriptor for a primitive input descriptor
<add> */
<add> public static char toPrimitiveTargetDesc(String descriptor) {
<add> if (descriptor.length()==1) {
<add> return descriptor.charAt(0);
<add> }
<add> if (descriptor.equals("Ljava/lang/Double")) {
<add> return 'D';
<add> }
<add> else if (descriptor.equals("Ljava/lang/Integer")) {
<add> return 'I';
<add> }
<add> else if (descriptor.equals("Ljava/lang/Float")) {
<add> return 'F';
<add> }
<add> else if (descriptor.equals("Ljava/lang/Long")) {
<add> return 'J';
<add> }
<add> else if (descriptor.equals("Ljava/lang/Boolean")) {
<add> return 'Z';
<add> }
<add> else {
<add> throw new IllegalStateException("No primitive for '"+descriptor+"'");
<add> }
<add> }
<add>
<add> /**
<add> * Insert the appropriate CHECKCAST instruction for the supplied descriptor.
<add> * @param mv the target visitor into which the instruction should be inserted
<add> * @param descriptor the descriptor of the type to cast to
<add> */
<add> public static void insertCheckCast(MethodVisitor mv, String descriptor) {
<add> if (descriptor.length()!=1) {
<add> if (descriptor.charAt(0)=='[') {
<add> if (CodeFlow.isPrimitiveArray(descriptor)) {
<add> mv.visitTypeInsn(CHECKCAST, descriptor);
<add> }
<add> else {
<add> mv.visitTypeInsn(CHECKCAST, descriptor+";");
<add> }
<add> }
<add> else {
<add> // This is chopping off the 'L' to leave us with "java/lang/String"
<add> mv.visitTypeInsn(CHECKCAST, descriptor.substring(1));
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Determine the appropriate boxing instruction for a specific type (if it needs
<add> * boxing) and insert the instruction into the supplied visitor.
<add> * @param mv the target visitor for the new instructions
<add> * @param descriptor the descriptor of a type that may or may not need boxing
<add> */
<add> public static void insertBoxIfNecessary(MethodVisitor mv, String descriptor) {
<add> if (descriptor.length() == 1) {
<add> insertBoxIfNecessary(mv, descriptor.charAt(0));
<add> }
<add> }
<add>
<add> /**
<add> * Determine the appropriate boxing instruction for a specific type (if it needs
<add> * boxing) and insert the instruction into the supplied visitor.
<add> * @param mv the target visitor for the new instructions
<add> * @param ch the descriptor of the type that might need boxing
<add> */
<add> public static void insertBoxIfNecessary(MethodVisitor mv, char ch) {
<add> switch (ch) {
<add> case 'I':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
<add> break;
<add> case 'F':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
<add> break;
<add> case 'S':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false);
<add> break;
<add> case 'Z':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
<add> break;
<add> case 'J':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false);
<add> break;
<add> case 'D':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
<add> break;
<add> case 'C':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", false);
<add> break;
<add> case 'B':
<add> mv.visitMethodInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false);
<add> break;
<add> case 'L':
<add> case 'V':
<add> case '[':
<add> // no box needed
<add> break;
<add> default:
<add> throw new IllegalArgumentException("Boxing should not be attempted for descriptor '" + ch + "'");
<add> }
<add> }
<add>
<add> /**
<add> * Deduce the descriptor for a type. Descriptors are like JVM type names but missing
<add> * the trailing ';' so for Object the descriptor is "Ljava/lang/Object" for int it is
<add> * "I".
<add> * @param type the type (may be primitive) for which to determine the descriptor
<add> * @return the descriptor
<add> */
<add> public static String toDescriptor(Class<?> type) {
<add> String name = type.getName();
<add> if (type.isPrimitive()) {
<add> switch (name.length()) {
<add> case 3:
<add> return "I";
<add> case 4:
<add> if (name.equals("long")) {
<add> return "J";
<add> }
<add> else if (name.equals("char")) {
<add> return "C";
<add> }
<add> else if (name.equals("byte")) {
<add> return "B";
<add> }
<add> else if (name.equals("void")) {
<add> return "V";
<add> }
<add> break;
<add> case 5:
<add> if (name.equals("float")) {
<add> return "F";
<add> }
<add> else if (name.equals("short")) {
<add> return "S";
<add> }
<add> break;
<add> case 6:
<add> if (name.equals("double")) {
<add> return "D";
<add> }
<add> break;
<add> case 7:
<add> if (name.equals("boolean")) {
<add> return "Z";
<add> }
<add> break;
<add> }
<add> }
<add> else {
<add> if (name.charAt(0) != '[') {
<add> return new StringBuilder("L").append(type.getName().replace('.', '/')).toString();
<add> }
<add> else {
<add> if (name.endsWith(";")) {
<add> return name.substring(0, name.length() - 1).replace('.', '/');
<add> }
<add> else {
<add> return name; // array has primitive component type
<add> }
<add> }
<add> }
<add> return null;
<add> }
<add>
<add> /**
<add> * Create an array of descriptors representing the parameter types for the supplied
<add> * method. Returns a zero sized array if there are no parameters.
<add> * @param method a Method
<add> * @return a String array of descriptors, one entry for each method parameter
<add> */
<add> public static String[] toParamDescriptors(Method method) {
<add> return toDescriptors(method.getParameterTypes());
<add> }
<add>
<add> /**
<add> * Create an array of descriptors representing the parameter types for the supplied
<add> * constructor. Returns a zero sized array if there are no parameters.
<add> * @param ctor a Constructor
<add> * @return a String array of descriptors, one entry for each constructor parameter
<add> */
<add> public static String[] toParamDescriptors(Constructor<?> ctor) {
<add> return toDescriptors(ctor.getParameterTypes());
<add> }
<add>
<add> private static String[] toDescriptors(Class<?>[] types) {
<add> int typesCount = types.length;
<add> String[] descriptors = new String[typesCount];
<add> for (int p = 0; p < typesCount; p++) {
<add> descriptors[p] = CodeFlow.toDescriptor(types[p]);
<add> }
<add> return descriptors;
<add> }
<add>
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.expression.spel.standard;
<add>
<add>import java.io.File;
<add>import java.io.FileOutputStream;
<add>import java.io.IOException;
<add>import java.net.URL;
<add>import java.net.URLClassLoader;
<add>import java.util.Collections;
<add>import java.util.Map;
<add>import java.util.WeakHashMap;
<add>
<add>import org.springframework.asm.ClassWriter;
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.asm.Opcodes;
<add>import org.springframework.expression.Expression;
<add>import org.springframework.expression.spel.CompiledExpression;
<add>import org.springframework.expression.spel.SpelParserConfiguration;
<add>import org.springframework.expression.spel.ast.SpelNodeImpl;
<add>import org.springframework.util.ClassUtils;
<add>
<add>/**
<add> * A SpelCompiler will take a regular parsed expression and create (and load) a class
<add> * containing byte code that does the same thing as that expression. The compiled form of
<add> * an expression will evaluate far faster than the interpreted form.
<add> * <p>
<add> * The SpelCompiler is not currently handling all expression types but covers many of the
<add> * common cases. The framework is extensible to cover more cases in the future. For
<add> * absolute maximum speed there is *no checking* in the compiled code. The compiled
<add> * version of the expression uses information learned during interpreted runs of the
<add> * expression when it generates the byte code. For example if it knows that a particular
<add> * property dereference always seems to return a Map then it will generate byte code that
<add> * expects the result of the property dereference to be a Map. This ensures maximal
<add> * performance but should the dereference result in something other than a map, the
<add> * compiled expression will fail - like a ClassCastException would occur if passing data
<add> * of an unexpected type in a regular Java program.
<add> * <p>
<add> * Due to the lack of checking there are likely some expressions that should never be
<add> * compiled, for example if an expression is continuously dealing with different types of
<add> * data. Due to these cases the compiler is something that must be selectively turned on
<add> * for an associated SpelExpressionParser (through the {@link SpelParserConfiguration}
<add> * object), it is not on by default.
<add> * <p>
<add> * Individual expressions can be compiled by calling
<add> * <tt>SpelCompiler.compile(expression)</tt>.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>public class SpelCompiler implements Opcodes {
<add>
<add> // Default number of times to interpret an expression before compiling it
<add> private static int DEFAULT_INTERPRETED_COUNT_THRESHOLD = 100;
<add>
<add> // Once an expression is evaluated the threshold number of times, it will be a candidate for compilation
<add> public static int interpretedCountThreshold = DEFAULT_INTERPRETED_COUNT_THRESHOLD;
<add>
<add> // Useful for debugging
<add> public static final boolean verbose = false;
<add>
<add> // A compiler is created for each classloader, it manages a child class loader of that
<add> // classloader and the child is used to load the compiled expressions.
<add> private static Map<ClassLoader,SpelCompiler> compilers = Collections.synchronizedMap(new WeakHashMap<ClassLoader,SpelCompiler>());
<add>
<add> // The child classloader used to load the compiled expression classes
<add> private ChildClassLoader ccl;
<add>
<add> // counter suffix for generated classes within this SpelCompiler instance
<add> private int suffixId;
<add>
<add> /**
<add> * Factory method for compiler instances. The returned SpelCompiler will
<add> * attach a class loader as the child of the default class loader and this
<add> * child will be used to load compiled expressions.
<add> *
<add> * @return a SpelCompiler instance
<add> */
<add> public static SpelCompiler getCompiler() {
<add> ClassLoader classloader = ClassUtils.getDefaultClassLoader();
<add> synchronized (compilers) {
<add> SpelCompiler compiler = compilers.get(classloader);
<add> if (compiler == null) {
<add> compiler = new SpelCompiler(classloader);
<add> compilers.put(classloader,compiler);
<add> }
<add> return compiler;
<add> }
<add> }
<add>
<add> private SpelCompiler(ClassLoader classloader) {
<add> this.ccl = new ChildClassLoader(classloader);
<add> this.suffixId = 1;
<add> }
<add>
<add> /**
<add> * Attempt compilation of the supplied expression. A check is
<add> * made to see if it is compilable before compilation proceeds. The
<add> * check involves visiting all the nodes in the expression Ast and
<add> * ensuring enough state is known about them that bytecode can
<add> * be generated for them.
<add> * @param expression the expression to compile
<add> * @return an instance of the class implementing the compiled expression, or null
<add> * if compilation is not possible
<add> */
<add> public CompiledExpression compile(SpelNodeImpl expression) {
<add> if (expression.isCompilable()) {
<add> if (verbose) {
<add> System.out.println("SpEL: compiling " + expression.toStringAST());
<add> }
<add> Class<? extends CompiledExpression> clazz = createExpressionClass(expression);
<add> try {
<add> CompiledExpression instance = clazz.newInstance();
<add> return instance;
<add> }
<add> catch (InstantiationException ie) {
<add> ie.printStackTrace();
<add> }
<add> catch (IllegalAccessException iae) {
<add> iae.printStackTrace();
<add> }
<add> }
<add> else {
<add> if (verbose) {
<add> System.out.println("SpEL: unable to compile " + expression.toStringAST());
<add> }
<add> }
<add> return null;
<add> }
<add>
<add> private synchronized int getNextSuffix() {
<add> return suffixId++;
<add> }
<add>
<add> /**
<add> * Generate the class that encapsulates the compiled expression and define it. The
<add> * generated class will be a subtype of CompiledExpression.
<add> * @param expressionToCompile the expression to be compiled
<add> */
<add> @SuppressWarnings("unchecked")
<add> private Class<? extends CompiledExpression> createExpressionClass(SpelNodeImpl expressionToCompile) {
<add>
<add> // Create class outline 'spel/ExNNN extends org.springframework.expression.spel.CompiledExpression'
<add> String clazzName = "spel/Ex" + getNextSuffix();
<add> ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
<add> cw.visit(V1_5, ACC_PUBLIC, clazzName, null,
<add> "org/springframework/expression/spel/CompiledExpression", null);
<add>
<add> // Create default constructor
<add> MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
<add> mv.visitCode();
<add> mv.visitVarInsn(ALOAD, 0);
<add> mv.visitMethodInsn(INVOKESPECIAL, "org/springframework/expression/spel/CompiledExpression", "<init>", "()V",false);
<add> mv.visitInsn(RETURN);
<add> mv.visitMaxs(1, 1);
<add> mv.visitEnd();
<add>
<add> // Create getValue() method
<add> mv = cw.visitMethod(ACC_PUBLIC, "getValue", "(Ljava/lang/Object;Lorg/springframework/expression/EvaluationContext;)Ljava/lang/Object;", null,
<add> new String[]{"org/springframework/expression/EvaluationException"});
<add> mv.visitCode();
<add>
<add> CodeFlow codeflow = new CodeFlow();
<add>
<add> // Ask the expression Ast to generate the body of the method
<add> expressionToCompile.generateCode(mv,codeflow);
<add>
<add> CodeFlow.insertBoxIfNecessary(mv,codeflow.lastDescriptor());
<add> if (codeflow.lastDescriptor() == "V") {
<add> mv.visitInsn(ACONST_NULL);
<add> }
<add> mv.visitInsn(ARETURN);
<add>
<add> mv.visitMaxs(0,0); // not supplied due to COMPUTE_MAXS
<add> mv.visitEnd();
<add> cw.visitEnd();
<add> byte[] data = cw.toByteArray();
<add> // TODO need to make this conditionally occur based on a debug flag
<add> // dump(expressionToCompile.toStringAST(), clazzName, data);
<add> Class<? extends CompiledExpression> clazz = (Class<? extends CompiledExpression>) ccl.defineClass(clazzName.replaceAll("/","."),data);
<add> return clazz;
<add> }
<add>
<add> /**
<add> * For debugging purposes, dump the specified byte code into a file on the disk. Not
<add> * yet hooked in, needs conditionally calling based on a sys prop.
<add> *
<add> * @param expressionText the text of the expression compiled
<add> * @param name the name of the class being used for the compiled expression
<add> * @param bytecode the bytecode for the generated class
<add> */
<add> @SuppressWarnings("unused")
<add> private static void dump(String expressionText, String name, byte[] bytecode) {
<add> name = name.replace('.', '/');
<add> String dir = "";
<add> if (name.indexOf('/') != -1) {
<add> dir = name.substring(0, name.lastIndexOf('/'));
<add> }
<add> String dumplocation = null;
<add> try {
<add> File tempfile = null;
<add> tempfile = File.createTempFile("tmp", null);
<add> tempfile.delete();
<add> File f = new File(tempfile, dir);
<add> f.mkdirs();
<add> dumplocation = tempfile + File.separator + name + ".class";
<add> System.out.println("Expression '" + expressionText + "' compiled code dumped to "
<add> + dumplocation);
<add> f = new File(dumplocation);
<add> FileOutputStream fos = new FileOutputStream(f);
<add> fos.write(bytecode);
<add> fos.flush();
<add> fos.close();
<add> }
<add> catch (IOException ioe) {
<add> throw new IllegalStateException("Unexpected problem dumping class "
<add> + name + " into " + dumplocation, ioe);
<add> }
<add> }
<add>
<add>
<add> /**
<add> * A ChildClassLoader will load the generated compiled expression classes
<add> */
<add> public static class ChildClassLoader extends URLClassLoader {
<add>
<add> private static URL[] NO_URLS = new URL[0];
<add>
<add> public ChildClassLoader(ClassLoader classloader) {
<add> super(NO_URLS, classloader);
<add> }
<add>
<add> public Class<?> defineClass(String name, byte[] bytes) {
<add> return super.defineClass(name, bytes, 0, bytes.length);
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Request that an attempt is made to compile the specified expression. It may fail if
<add> * components of the expression are not suitable for compilation or the data types
<add> * involved are not suitable for compilation. Used for testing.
<add> * @return true if the expression was successfully compiled
<add> */
<add> public static boolean compile(Expression expression) {
<add> if (expression instanceof SpelExpression) {
<add> SpelExpression spelExpression = (SpelExpression)expression;
<add> return spelExpression.compileExpression();
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * Request to revert to the interpreter for expression evaluation. Any compiled form
<add> * is discarded but can be recreated by later recompiling again.
<add> * @param expression the expression
<add> */
<add> public static void revertToInterpreted(Expression expression) {
<add> if (expression instanceof SpelExpression) {
<add> SpelExpression spelExpression = (SpelExpression)expression;
<add> spelExpression.revertToInterpreted();
<add> }
<add> }
<add>}
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelExpression.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.expression.Expression;
<ide> import org.springframework.expression.TypedValue;
<ide> import org.springframework.expression.common.ExpressionUtils;
<add>import org.springframework.expression.spel.CompiledExpression;
<ide> import org.springframework.expression.spel.ExpressionState;
<add>import org.springframework.expression.spel.SpelCompilerMode;
<add>import org.springframework.expression.spel.SpelEvaluationException;
<add>import org.springframework.expression.spel.SpelMessage;
<ide> import org.springframework.expression.spel.SpelNode;
<ide> import org.springframework.expression.spel.SpelParserConfiguration;
<ide> import org.springframework.expression.spel.ast.SpelNodeImpl;
<ide> public class SpelExpression implements Expression {
<ide>
<ide> private final String expression;
<ide>
<del> private final SpelNodeImpl ast;
<add> // Holds the compiled form of the expression (if it has been compiled)
<add> private CompiledExpression compiledAst;
<add>
<add> private SpelNodeImpl ast;
<ide>
<ide> private final SpelParserConfiguration configuration;
<ide>
<ide> // the default context is used if no override is supplied by the user
<ide> private EvaluationContext defaultContext;
<ide>
<add> // Count of many times as the expression been interpreted - can trigger compilation
<add> // when certain limit reached
<add> private int interpretedCount = 0;
<add>
<add> // The number of times compilation was attempted and failed - enables us to eventually
<add> // give up trying to compile it when it just doesn't seem to be possible.
<add> private int failedAttempts = 0;
<add>
<ide>
<ide> /**
<ide> * Construct an expression, only used by the parser.
<ide> public SpelExpression(String expression, SpelNodeImpl ast, SpelParserConfigurati
<ide>
<ide> @Override
<ide> public Object getValue() throws EvaluationException {
<add> Object result = null;
<add> if (compiledAst != null) {
<add> try {
<add> return this.compiledAst.getValue(null,null);
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<ide> ExpressionState expressionState = new ExpressionState(getEvaluationContext(), this.configuration);
<del> return this.ast.getValue(expressionState);
<add> result = this.ast.getValue(expressionState);
<add> checkCompile(expressionState);
<add> return result;
<ide> }
<ide>
<ide> @Override
<ide> public Object getValue(Object rootObject) throws EvaluationException {
<add> Object result = null;
<add> if (compiledAst!=null) {
<add> try {
<add> return this.compiledAst.getValue(rootObject,null);
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<ide> ExpressionState expressionState = new ExpressionState(getEvaluationContext(), toTypedValue(rootObject), this.configuration);
<del> return this.ast.getValue(expressionState);
<add> result = this.ast.getValue(expressionState);
<add> checkCompile(expressionState);
<add> return result;
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public <T> T getValue(Class<T> expectedResultType) throws EvaluationException {
<add> if (compiledAst!=null) {
<add> try {
<add> Object result = this.compiledAst.getValue(null,null);
<add> if (expectedResultType == null) {
<add> return (T)result;
<add> } else {
<add> return ExpressionUtils.convertTypedValue(getEvaluationContext(), new TypedValue(result), expectedResultType);
<add> }
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<ide> ExpressionState expressionState = new ExpressionState(getEvaluationContext(), this.configuration);
<ide> TypedValue typedResultValue = this.ast.getTypedValue(expressionState);
<add> checkCompile(expressionState);
<ide> return ExpressionUtils.convertTypedValue(expressionState.getEvaluationContext(), typedResultValue, expectedResultType);
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public <T> T getValue(Object rootObject, Class<T> expectedResultType) throws EvaluationException {
<add> if (compiledAst!=null) {
<add> try {
<add> Object result = this.compiledAst.getValue(rootObject,null);
<add> if (expectedResultType == null) {
<add> return (T)result;
<add> } else {
<add> return ExpressionUtils.convertTypedValue(getEvaluationContext(), new TypedValue(result), expectedResultType);
<add> }
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<ide> ExpressionState expressionState = new ExpressionState(getEvaluationContext(), toTypedValue(rootObject), this.configuration);
<ide> TypedValue typedResultValue = this.ast.getTypedValue(expressionState);
<add> checkCompile(expressionState);
<ide> return ExpressionUtils.convertTypedValue(expressionState.getEvaluationContext(), typedResultValue, expectedResultType);
<ide> }
<ide>
<ide> @Override
<ide> public Object getValue(EvaluationContext context) throws EvaluationException {
<ide> Assert.notNull(context, "The EvaluationContext is required");
<del> return this.ast.getValue(new ExpressionState(context, this.configuration));
<add> if (compiledAst!= null) {
<add> try {
<add> Object result = this.compiledAst.getValue(null,context);
<add> return result;
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<add> ExpressionState expressionState = new ExpressionState(context, this.configuration);
<add> Object result = this.ast.getValue(expressionState);
<add> checkCompile(expressionState);
<add> return result;
<ide> }
<ide>
<ide> @Override
<ide> public Object getValue(EvaluationContext context, Object rootObject) throws EvaluationException {
<ide> Assert.notNull(context, "The EvaluationContext is required");
<del> return this.ast.getValue(new ExpressionState(context, toTypedValue(rootObject), this.configuration));
<add> if (compiledAst!=null) {
<add> try {
<add> return this.compiledAst.getValue(rootObject,context);
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<add> ExpressionState expressionState = new ExpressionState(context, toTypedValue(rootObject), this.configuration);
<add> Object result = this.ast.getValue(expressionState);
<add> checkCompile(expressionState);
<add> return result;
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public <T> T getValue(EvaluationContext context, Class<T> expectedResultType) throws EvaluationException {
<del> TypedValue typedResultValue = this.ast.getTypedValue(new ExpressionState(context, this.configuration));
<add> if (compiledAst!=null) {
<add> try {
<add> Object result = this.compiledAst.getValue(null,context);
<add> if (expectedResultType!=null) {
<add> return (T) result;
<add> } else {
<add> return ExpressionUtils.convertTypedValue(context, new TypedValue(result), expectedResultType);
<add> }
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<add> ExpressionState expressionState = new ExpressionState(context, this.configuration);
<add> TypedValue typedResultValue = this.ast.getTypedValue(expressionState);
<add> checkCompile(expressionState);
<ide> return ExpressionUtils.convertTypedValue(context, typedResultValue, expectedResultType);
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public <T> T getValue(EvaluationContext context, Object rootObject, Class<T> expectedResultType) throws EvaluationException {
<del> TypedValue typedResultValue = this.ast.getTypedValue(new ExpressionState(context, toTypedValue(rootObject), this.configuration));
<add> if (compiledAst!=null) {
<add> try {
<add> Object result = this.compiledAst.getValue(rootObject,context);
<add> if (expectedResultType!=null) {
<add> return (T) result;
<add> } else {
<add> return ExpressionUtils.convertTypedValue(context, new TypedValue(result), expectedResultType);
<add> }
<add> } catch (Throwable t) {
<add> // If running in mixed mode, revert to interpreted
<add> if (this.configuration.getCompilerMode() == SpelCompilerMode.mixed) {
<add> interpretedCount = 0;
<add> compiledAst = null;
<add> }
<add> else {
<add> // Running in SpelCompilerMode.immediate mode - propagate exception to caller
<add> throw new SpelEvaluationException(t,SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
<add> }
<add> }
<add> }
<add> ExpressionState expressionState = new ExpressionState(context, toTypedValue(rootObject), this.configuration);
<add> TypedValue typedResultValue = this.ast.getTypedValue(expressionState);
<add> checkCompile(expressionState);
<ide> return ExpressionUtils.convertTypedValue(context, typedResultValue, expectedResultType);
<ide> }
<ide>
<ide> public void setValue(EvaluationContext context, Object rootObject, Object value)
<ide>
<ide> // impl only
<ide>
<add> /**
<add> * Compile the expression if it has been evaluated more than the threshold number of times to trigger compilation.
<add> * @param expressionState the expression state used to determine compilation mode
<add> */
<add> private void checkCompile(ExpressionState expressionState) {
<add> interpretedCount++;
<add> SpelCompilerMode compilerMode = expressionState.getConfiguration().getCompilerMode();
<add> if (compilerMode != SpelCompilerMode.off) {
<add> if (compilerMode == SpelCompilerMode.immediate) {
<add> if (interpretedCount > 1) {
<add> compileExpression();
<add> }
<add> }
<add> else {
<add> // compilerMode = SpelCompilerMode.mixed
<add> if (interpretedCount > SpelCompiler.interpretedCountThreshold) {
<add> compileExpression();
<add> }
<add> }
<add> }
<add> }
<add>
<add>
<add> /**
<add> * Perform expression compilation. This will only succeed once exit descriptors for all nodes have
<add> * been determined. If the compilation fails and has failed more than 100 times the expression is
<add> * no longer considered suitable for compilation.
<add> */
<add> public boolean compileExpression() {
<add> if (failedAttempts > 100) {
<add> // Don't try again
<add> return false;
<add> }
<add> if (this.compiledAst == null) {
<add> synchronized (expression) {
<add> // Possibly compiled by another thread before this thread got into the
<add> // sync block
<add> if (this.compiledAst != null) {
<add> return true;
<add> }
<add> this.compiledAst = SpelCompiler.getCompiler().compile(this.ast);
<add> if (this.compiledAst == null) {
<add> failedAttempts++;
<add> }
<add> }
<add> }
<add> return (this.compiledAst != null);
<add> }
<add>
<add> /**
<add> * Cause an expression to revert to being interpreted if it has been using a compiled
<add> * form. It also resets the compilation attempt failure count (an expression is normally no
<add> * longer considered compilable if it cannot be compiled after 100 attempts).
<add> */
<add> public void revertToInterpreted() {
<add> this.compiledAst = null;
<add> this.interpretedCount = 0;
<add> this.failedAttempts = 0;
<add> }
<add>
<ide> /**
<ide> * @return return the Abstract Syntax Tree for the expression
<ide> */
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectionHelper.java
<ide> else if (typeConverter.canConvert(suppliedArg, TypeDescriptor.valueOf(varargsPar
<ide> * @param arguments the actual arguments that need conversion
<ide> * @param methodOrCtor the target Method or Constructor
<ide> * @param varargsPosition the known position of the varargs argument, if any
<add> * @return true if some kind of conversion occurred on an argument
<ide> * @throws EvaluationException if a problem occurs during conversion
<ide> */
<del> static void convertArguments(TypeConverter converter, Object[] arguments, Object methodOrCtor,
<add> static boolean convertArguments(TypeConverter converter, Object[] arguments, Object methodOrCtor,
<ide> Integer varargsPosition) throws EvaluationException {
<del>
<add> boolean conversionOccurred = false;
<ide> if (varargsPosition == null) {
<ide> for (int i = 0; i < arguments.length; i++) {
<ide> TypeDescriptor targetType = new TypeDescriptor(MethodParameter.forMethodOrConstructor(methodOrCtor, i));
<ide> Object argument = arguments[i];
<ide> arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
<add> conversionOccurred |= (argument != arguments[i]);
<ide> }
<ide> }
<ide> else {
<ide> for (int i = 0; i < varargsPosition; i++) {
<ide> TypeDescriptor targetType = new TypeDescriptor(MethodParameter.forMethodOrConstructor(methodOrCtor, i));
<ide> Object argument = arguments[i];
<ide> arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
<add> conversionOccurred |= (argument != arguments[i]);
<ide> }
<ide> MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, varargsPosition);
<ide> if (varargsPosition == arguments.length - 1) {
<ide> TypeDescriptor targetType = new TypeDescriptor(methodParam);
<ide> Object argument = arguments[varargsPosition];
<ide> arguments[varargsPosition] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
<add> conversionOccurred |= (argument != arguments[varargsPosition]);
<ide> }
<ide> else {
<ide> TypeDescriptor targetType = new TypeDescriptor(methodParam).getElementTypeDescriptor();
<ide> for (int i = varargsPosition; i < arguments.length; i++) {
<ide> Object argument = arguments[i];
<ide> arguments[i] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
<add> conversionOccurred |= (argument != arguments[i]);
<ide> }
<ide> }
<ide> }
<add> return conversionOccurred;
<ide> }
<ide>
<ide> /**
<ide> static void convertArguments(TypeConverter converter, Object[] arguments, Object
<ide> * @param converter the converter to use for type conversions
<ide> * @param arguments the arguments to convert to the requested parameter types
<ide> * @param method the target Method
<add> * @return true if some kind of conversion occurred on the argument
<ide> * @throws SpelEvaluationException if there is a problem with conversion
<ide> */
<del> public static void convertAllArguments(TypeConverter converter, Object[] arguments, Method method)
<del> throws SpelEvaluationException {
<del>
<add> public static boolean convertAllArguments(TypeConverter converter, Object[] arguments, Method method) throws SpelEvaluationException {
<ide> Integer varargsPosition = null;
<add> boolean conversionOccurred = false;
<ide> if (method.isVarArgs()) {
<ide> Class<?>[] paramTypes = method.getParameterTypes();
<ide> varargsPosition = paramTypes.length - 1;
<add> conversionOccurred = true;
<ide> }
<ide> for (int argPos = 0; argPos < arguments.length; argPos++) {
<ide> TypeDescriptor targetType;
<ide> public static void convertAllArguments(TypeConverter converter, Object[] argumen
<ide> SpelMessage.TYPE_CONVERSION_ERROR, argument.getClass().getName(), targetType);
<ide> }
<ide> arguments[argPos] = converter.convertValue(argument, TypeDescriptor.forObject(argument), targetType);
<add> conversionOccurred |= (argument != arguments[argPos]);
<ide> }
<ide> }
<ide> catch (EvaluationException ex) {
<ide> public static void convertAllArguments(TypeConverter converter, Object[] argumen
<ide> }
<ide> }
<ide> }
<add> return conversionOccurred;
<ide> }
<ide>
<ide> /**
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveConstructorExecutor.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 3.0
<ide> */
<del>class ReflectiveConstructorExecutor implements ConstructorExecutor {
<add>public class ReflectiveConstructorExecutor implements ConstructorExecutor {
<ide>
<ide> private final Constructor<?> ctor;
<ide>
<ide> public TypedValue execute(EvaluationContext context, Object... arguments) throws
<ide> }
<ide> }
<ide>
<add> public Constructor<?> getConstructor() {
<add> return this.ctor;
<add> }
<add>
<ide> }
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodExecutor.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Juergen Hoeller
<ide> * @since 3.0
<ide> */
<del>class ReflectiveMethodExecutor implements MethodExecutor {
<add>public class ReflectiveMethodExecutor implements MethodExecutor {
<ide>
<ide> private final Method method;
<ide>
<ide> private final Integer varargsPosition;
<ide>
<add> private boolean argumentConversionOccurred = false;
<ide>
<ide> public ReflectiveMethodExecutor(Method method) {
<ide> this.method = method;
<ide> public ReflectiveMethodExecutor(Method method) {
<ide> }
<ide> }
<ide>
<add> public Method getMethod() {
<add> return this.method;
<add> }
<add>
<add> public boolean didArgumentConversionOccur() {
<add> return this.argumentConversionOccurred;
<add> }
<add>
<ide>
<ide> @Override
<ide> public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
<ide> try {
<ide> if (arguments != null) {
<del> ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.method, this.varargsPosition);
<add> this.argumentConversionOccurred = ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.method, this.varargsPosition);
<ide> }
<ide> if (this.method.isVarArgs()) {
<ide> arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.method.getParameterTypes(), arguments);
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java
<ide> import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide>
<add>import org.springframework.asm.MethodVisitor;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.convert.Property;
<ide> import org.springframework.core.convert.TypeDescriptor;
<ide> import org.springframework.core.style.ToStringCreator;
<ide> import org.springframework.expression.AccessException;
<add>import org.springframework.expression.CompilablePropertyAccessor;
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.EvaluationException;
<ide> import org.springframework.expression.PropertyAccessor;
<ide> import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.ast.PropertyOrFieldReference;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<ide> import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> public class ReflectivePropertyAccessor implements PropertyAccessor {
<ide>
<ide> private final Map<CacheKey, TypeDescriptor> typeDescriptorCache = new ConcurrentHashMap<CacheKey, TypeDescriptor>(64);
<ide>
<add> private InvokerPair lastReadInvokerPair;
<ide>
<ide> /**
<ide> * Returns {@code null} which means this is a general purpose accessor.
<ide> public boolean canRead(EvaluationContext context, Object target, String name) th
<ide> }
<ide> return false;
<ide> }
<add>
<add> public Member getLastReadInvokerPair() {
<add> return lastReadInvokerPair.member;
<add> }
<ide>
<ide> @Override
<ide> public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
<ide> public TypedValue read(EvaluationContext context, Object target, String name) th
<ide>
<ide> CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
<ide> InvokerPair invoker = this.readerCache.get(cacheKey);
<add> lastReadInvokerPair = invoker;
<ide>
<ide> if (invoker == null || invoker.member instanceof Method) {
<ide> Method method = (Method) (invoker != null ? invoker.member : null);
<ide> public TypedValue read(EvaluationContext context, Object target, String name) th
<ide> Property property = new Property(type, method, null);
<ide> TypeDescriptor typeDescriptor = new TypeDescriptor(property);
<ide> invoker = new InvokerPair(method, typeDescriptor);
<add> lastReadInvokerPair = invoker;
<ide> this.readerCache.put(cacheKey, invoker);
<ide> }
<ide> }
<ide> public TypedValue read(EvaluationContext context, Object target, String name) th
<ide> field = findField(name, type, target);
<ide> if (field != null) {
<ide> invoker = new InvokerPair(field, new TypeDescriptor(field));
<add> lastReadInvokerPair = invoker;
<ide> this.readerCache.put(cacheKey, invoker);
<ide> }
<ide> }
<ide> public String toString() {
<ide> * accessor exists because looking up the appropriate reflective object by class/name
<ide> * on each read is not cheap.
<ide> */
<del> private static class OptimalPropertyAccessor implements PropertyAccessor {
<add> public static class OptimalPropertyAccessor implements CompilablePropertyAccessor {
<ide>
<del> private final Member member;
<add> public final Member member;
<ide>
<ide> private final TypeDescriptor typeDescriptor;
<ide>
<ide> public TypedValue read(EvaluationContext context, Object target, String name) th
<ide> }
<ide> throw new AccessException("Neither getter nor field found for property '" + name + "'");
<ide> }
<add>
<add> @Override
<add> public Class<?> getPropertyType() {
<add> if (member instanceof Field) {
<add> return ((Field)member).getType();
<add> }
<add> else {
<add> return ((Method)member).getReturnType();
<add> }
<add> }
<ide>
<ide> @Override
<ide> public boolean canWrite(EvaluationContext context, Object target, String name) {
<ide> public boolean canWrite(EvaluationContext context, Object target, String name) {
<ide> public void write(EvaluationContext context, Object target, String name, Object newValue) {
<ide> throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
<ide> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> // If non public must continue to use reflection
<add> if (!Modifier.isPublic(member.getModifiers()) || !Modifier.isPublic(member.getDeclaringClass().getModifiers())) {
<add> return false;
<add> }
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(PropertyOrFieldReference propertyReference, MethodVisitor mv,CodeFlow codeflow) {
<add> boolean isStatic = Modifier.isStatic(member.getModifiers());
<add>
<add> String descriptor = codeflow.lastDescriptor();
<add> String memberDeclaringClassSlashedDescriptor = member.getDeclaringClass().getName().replace('.','/');
<add> if (!isStatic) {
<add> if (descriptor == null) {
<add> codeflow.loadTarget(mv);
<add> }
<add> if (descriptor == null || !memberDeclaringClassSlashedDescriptor.equals(descriptor.substring(1))) {
<add> mv.visitTypeInsn(CHECKCAST, memberDeclaringClassSlashedDescriptor);
<add> }
<add> }
<add> if (member instanceof Field) {
<add> mv.visitFieldInsn(isStatic?GETSTATIC:GETFIELD,memberDeclaringClassSlashedDescriptor,member.getName(),CodeFlow.toJVMDescriptor(((Field) member).getType()));
<add> } else {
<add> mv.visitMethodInsn(isStatic?INVOKESTATIC:INVOKEVIRTUAL, memberDeclaringClassSlashedDescriptor, member.getName(),CodeFlow.createSignatureDescriptor((Method)member),false);
<add> }
<add> }
<add>
<ide> }
<ide>
<ide> }
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel;
<add>
<add>import java.io.IOException;
<add>import java.lang.reflect.Method;
<add>import java.util.ArrayList;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.StringTokenizer;
<add>
<add>import org.junit.Test;
<add>import org.springframework.asm.MethodVisitor;
<add>import org.springframework.expression.AccessException;
<add>import org.springframework.expression.CompilablePropertyAccessor;
<add>import org.springframework.expression.EvaluationContext;
<add>import org.springframework.expression.Expression;
<add>import org.springframework.expression.TypedValue;
<add>import org.springframework.expression.spel.ast.CompoundExpression;
<add>import org.springframework.expression.spel.ast.OpLT;
<add>import org.springframework.expression.spel.ast.PropertyOrFieldReference;
<add>import org.springframework.expression.spel.ast.SpelNodeImpl;
<add>import org.springframework.expression.spel.ast.Ternary;
<add>import org.springframework.expression.spel.standard.CodeFlow;
<add>import org.springframework.expression.spel.standard.SpelCompiler;
<add>import org.springframework.expression.spel.standard.SpelExpression;
<add>import org.springframework.expression.spel.support.StandardEvaluationContext;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Checks the behaviour of the SpelCompiler. This should cover compilation all compiled node types.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>public class SpelCompilationCoverageTests extends AbstractExpressionTests {
<add>
<add> private Expression expression;
<add> private SpelNodeImpl ast;
<add>
<add> /*
<add> * Further TODOs for compilation:
<add> *
<add> * - OpMinus with a single literal operand could be treated as a negative literal. Will save a
<add> * pointless loading of 0 and then a subtract instruction in code gen.
<add> * - allow other accessors/resolvers to participate in compilation and create their own code
<add> * - A TypeReference followed by (what ends up as) a static method invocation can really skip
<add> * code gen for the TypeReference since once that is used to locate the method it is not
<add> * used again.
<add> * - The opEq implementation is quite basic. It will compare numbers of the same type (allowing
<add> * them to be their boxed or unboxed variants) or compare object references. It does not
<add> * compile expressions where numbers are of different types or when objects implement
<add> * Comparable.
<add> *
<add> * Compiled nodes:
<add> *
<add> * TypeReference
<add> * OperatorInstanceOf
<add> * StringLiteral
<add> * NullLiteral
<add> * RealLiteral
<add> * IntLiteral
<add> * LongLiteral
<add> * BooleanLiteral
<add> * FloatLiteral
<add> * OpOr
<add> * OpAnd
<add> * OperatorNot
<add> * Ternary
<add> * Elvis
<add> * VariableReference
<add> * OpLt
<add> * OpLe
<add> * OpGt
<add> * OpGe
<add> * OpEq
<add> * OpNe
<add> * OpPlus
<add> * OpMinus
<add> * OpMultiply
<add> * OpDivide
<add> * MethodReference
<add> * PropertyOrFieldReference
<add> * Indexer
<add> * CompoundExpression
<add> * ConstructorReference
<add> * FunctionReference
<add> *
<add> * Not yet compiled (some may never need to be):
<add> * Assign
<add> * BeanReference
<add> * Identifier
<add> * InlineList
<add> * OpDec
<add> * OpBetween
<add> * OpMatches
<add> * OpPower
<add> * OpInc
<add> * OpModulus
<add> * Projection
<add> * QualifiedId
<add> * Selection
<add> */
<add>
<add> @Test
<add> public void typeReference() throws Exception {
<add> expression = parse("T(String)");
<add> assertEquals(String.class,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(String.class,expression.getValue());
<add>
<add> expression = parse("T(java.io.IOException)");
<add> assertEquals(IOException.class,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(IOException.class,expression.getValue());
<add>
<add> expression = parse("T(java.io.IOException[])");
<add> assertEquals(IOException[].class,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(IOException[].class,expression.getValue());
<add>
<add> expression = parse("T(int[][])");
<add> assertEquals(int[][].class,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(int[][].class,expression.getValue());
<add>
<add> expression = parse("T(int)");
<add> assertEquals(Integer.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Integer.TYPE,expression.getValue());
<add>
<add> expression = parse("T(byte)");
<add> assertEquals(Byte.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Byte.TYPE,expression.getValue());
<add>
<add> expression = parse("T(char)");
<add> assertEquals(Character.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Character.TYPE,expression.getValue());
<add>
<add> expression = parse("T(short)");
<add> assertEquals(Short.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Short.TYPE,expression.getValue());
<add>
<add> expression = parse("T(long)");
<add> assertEquals(Long.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Long.TYPE,expression.getValue());
<add>
<add> expression = parse("T(float)");
<add> assertEquals(Float.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Float.TYPE,expression.getValue());
<add>
<add> expression = parse("T(double)");
<add> assertEquals(Double.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Double.TYPE,expression.getValue());
<add>
<add> expression = parse("T(boolean)");
<add> assertEquals(Boolean.TYPE,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(Boolean.TYPE,expression.getValue());
<add>
<add> expression = parse("T(Missing)");
<add> assertGetValueFail(expression);
<add> assertCantCompile(expression);
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void operatorInstanceOf() throws Exception {
<add> expression = parse("'xyz' instanceof T(String)");
<add> assertEquals(true,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue());
<add>
<add> expression = parse("'xyz' instanceof T(Integer)");
<add> assertEquals(false,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(false,expression.getValue());
<add>
<add> List<String> list = new ArrayList<String>();
<add> expression = parse("#root instanceof T(java.util.List)");
<add> assertEquals(true,expression.getValue(list));
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue(list));
<add>
<add> List<String>[] arrayOfLists = new List[]{new ArrayList<String>()};
<add> expression = parse("#root instanceof T(java.util.List[])");
<add> assertEquals(true,expression.getValue(arrayOfLists));
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue(arrayOfLists));
<add>
<add> int[] intArray = new int[]{1,2,3};
<add> expression = parse("#root instanceof T(int[])");
<add> assertEquals(true,expression.getValue(intArray));
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue(intArray));
<add>
<add> String root = null;
<add> expression = parse("#root instanceof T(Integer)");
<add> assertEquals(false,expression.getValue(root));
<add> assertCanCompile(expression);
<add> assertEquals(false,expression.getValue(root));
<add>
<add> // root still null
<add> expression = parse("#root instanceof T(java.lang.Object)");
<add> assertEquals(false,expression.getValue(root));
<add> assertCanCompile(expression);
<add> assertEquals(false,expression.getValue(root));
<add>
<add> root = "howdy!";
<add> expression = parse("#root instanceof T(java.lang.Object)");
<add> assertEquals(true,expression.getValue(root));
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue(root));
<add> }
<add>
<add> @Test
<add> public void stringLiteral() throws Exception {
<add> expression = parser.parseExpression("'abcde'");
<add> assertEquals("abcde",expression.getValue(new TestClass1(),String.class));
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(new TestClass1(),String.class);
<add> assertEquals("abcde",resultC);
<add> assertEquals("abcde",expression.getValue(String.class));
<add> assertEquals("abcde",expression.getValue());
<add> assertEquals("abcde",expression.getValue(new StandardEvaluationContext()));
<add> expression = parser.parseExpression("\"abcde\"");
<add> assertCanCompile(expression);
<add> assertEquals("abcde",expression.getValue(String.class));
<add> }
<add>
<add> @Test
<add> public void nullLiteral() throws Exception {
<add> expression = parser.parseExpression("null");
<add> Object resultI = expression.getValue(new TestClass1(),Object.class);
<add> assertCanCompile(expression);
<add> Object resultC = expression.getValue(new TestClass1(),Object.class);
<add> assertEquals(null,resultI);
<add> assertEquals(null,resultC);
<add> }
<add>
<add> @Test
<add> public void realLiteral() throws Exception {
<add> expression = parser.parseExpression("3.4d");
<add> double resultI = expression.getValue(new TestClass1(),Double.TYPE);
<add> assertCanCompile(expression);
<add> double resultC = expression.getValue(new TestClass1(),Double.TYPE);
<add> assertEquals(3.4d,resultI,0.1d);
<add> assertEquals(3.4d,resultC,0.1d);
<add>
<add> assertEquals(3.4d,expression.getValue());
<add> }
<add>
<add> @Test
<add> public void intLiteral() throws Exception {
<add> expression = parser.parseExpression("42");
<add> int resultI = expression.getValue(new TestClass1(),Integer.TYPE);
<add> assertCanCompile(expression);
<add> int resultC = expression.getValue(new TestClass1(),Integer.TYPE);
<add> assertEquals(42,resultI);
<add> assertEquals(42,resultC);
<add>
<add> expression = parser.parseExpression("T(Integer).valueOf(42)");
<add> expression.getValue(Integer.class);
<add> assertCanCompile(expression);
<add> assertEquals(new Integer(42),expression.getValue(null,Integer.class));
<add>
<add> // Code gen is different for -1 .. 6 because there are bytecode instructions specifically for those
<add> // values
<add>
<add> // Not an int literal but an opminus with one operand:
<add>// expression = parser.parseExpression("-1");
<add>// assertCanCompile(expression);
<add>// assertEquals(-1,expression.getValue());
<add> expression = parser.parseExpression("0");
<add> assertCanCompile(expression);
<add> assertEquals(0,expression.getValue());
<add> expression = parser.parseExpression("2");
<add> assertCanCompile(expression);
<add> assertEquals(2,expression.getValue());
<add> expression = parser.parseExpression("7");
<add> assertCanCompile(expression);
<add> assertEquals(7,expression.getValue());
<add> }
<add>
<add> @Test
<add> public void longLiteral() throws Exception {
<add> expression = parser.parseExpression("99L");
<add> long resultI = expression.getValue(new TestClass1(),Long.TYPE);
<add> assertCanCompile(expression);
<add> long resultC = expression.getValue(new TestClass1(),Long.TYPE);
<add> assertEquals(99L,resultI);
<add> assertEquals(99L,resultC);
<add> }
<add>
<add> @Test
<add> public void booleanLiteral() throws Exception {
<add> expression = parser.parseExpression("true");
<add> boolean resultI = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(true,resultI);
<add> assertTrue(SpelCompiler.compile(expression));
<add> boolean resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(true,resultC);
<add>
<add> expression = parser.parseExpression("false");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(false,resultI);
<add> assertTrue(SpelCompiler.compile(expression));
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(false,resultC);
<add> }
<add>
<add> @Test
<add> public void floatLiteral() throws Exception {
<add> expression = parser.parseExpression("3.4f");
<add> float resultI = expression.getValue(new TestClass1(),Float.TYPE);
<add> assertCanCompile(expression);
<add> float resultC = expression.getValue(new TestClass1(),Float.TYPE);
<add> assertEquals(3.4f,resultI,0.1f);
<add> assertEquals(3.4f,resultC,0.1f);
<add>
<add> assertEquals(3.4f,expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opOr() throws Exception {
<add> Expression expression = parser.parseExpression("false or false");
<add> boolean resultI = expression.getValue(1,Boolean.TYPE);
<add> SpelCompiler.compile(expression);
<add> boolean resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(false,resultI);
<add> assertEquals(false,resultC);
<add>
<add> expression = parser.parseExpression("false or true");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> assertCanCompile(expression);
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(true,resultI);
<add> assertEquals(true,resultC);
<add>
<add> expression = parser.parseExpression("true or false");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> assertCanCompile(expression);
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(true,resultI);
<add> assertEquals(true,resultC);
<add>
<add> expression = parser.parseExpression("true or true");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> assertCanCompile(expression);
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(true,resultI);
<add> assertEquals(true,resultC);
<add>
<add> TestClass4 tc = new TestClass4();
<add> expression = parser.parseExpression("getfalse() or gettrue()");
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCanCompile(expression);
<add> resultC = expression.getValue(tc,Boolean.TYPE);
<add> assertEquals(true,resultI);
<add> assertEquals(true,resultC);
<add>
<add> // Can't compile this as we aren't going down the getfalse() branch in our evaluation
<add> expression = parser.parseExpression("gettrue() or getfalse()");
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCantCompile(expression);
<add>
<add> expression = parser.parseExpression("getA() or getB()");
<add> tc.a = true;
<add> tc.b = true;
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCantCompile(expression); // Haven't yet been into second branch
<add> tc.a = false;
<add> tc.b = true;
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCanCompile(expression); // Now been down both
<add> assertTrue(resultI);
<add>
<add> boolean b = false;
<add> expression = parse("#root or #root");
<add> Object resultI2 = expression.getValue(b);
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)resultI2);
<add> assertFalse((Boolean)expression.getValue(b));
<add> }
<add>
<add> @Test
<add> public void opAnd() throws Exception {
<add> Expression expression = parser.parseExpression("false and false");
<add> boolean resultI = expression.getValue(1,Boolean.TYPE);
<add> SpelCompiler.compile(expression);
<add> boolean resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(false,resultI);
<add> assertEquals(false,resultC);
<add>
<add> expression = parser.parseExpression("false and true");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> SpelCompiler.compile(expression);
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(false,resultI);
<add> assertEquals(false,resultC);
<add>
<add> expression = parser.parseExpression("true and false");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> SpelCompiler.compile(expression);
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(false,resultI);
<add> assertEquals(false,resultC);
<add>
<add> expression = parser.parseExpression("true and true");
<add> resultI = expression.getValue(1,Boolean.TYPE);
<add> SpelCompiler.compile(expression);
<add> resultC = expression.getValue(1,Boolean.TYPE);
<add> assertEquals(true,resultI);
<add> assertEquals(true,resultC);
<add>
<add> TestClass4 tc = new TestClass4();
<add>
<add> // Can't compile this as we aren't going down the gettrue() branch in our evaluation
<add> expression = parser.parseExpression("getfalse() and gettrue()");
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCantCompile(expression);
<add>
<add> expression = parser.parseExpression("getA() and getB()");
<add> tc.a = false;
<add> tc.b = false;
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCantCompile(expression); // Haven't yet been into second branch
<add> tc.a = true;
<add> tc.b = false;
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertCanCompile(expression); // Now been down both
<add> assertFalse(resultI);
<add> tc.a = true;
<add> tc.b = true;
<add> resultI = expression.getValue(tc,Boolean.TYPE);
<add> assertTrue(resultI);
<add>
<add> boolean b = true;
<add> expression = parse("#root and #root");
<add> Object resultI2 = expression.getValue(b);
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)resultI2);
<add> assertTrue((Boolean)expression.getValue(b));
<add> }
<add>
<add> @Test
<add> public void operatorNot() throws Exception {
<add> expression = parse("!true");
<add> assertEquals(false,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(false,expression.getValue());
<add>
<add> expression = parse("!false");
<add> assertEquals(true,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue());
<add>
<add> boolean b = true;
<add> expression = parse("!#root");
<add> assertEquals(false,expression.getValue(b));
<add> assertCanCompile(expression);
<add> assertEquals(false,expression.getValue(b));
<add>
<add> b = false;
<add> expression = parse("!#root");
<add> assertEquals(true,expression.getValue(b));
<add> assertCanCompile(expression);
<add> assertEquals(true,expression.getValue(b));
<add> }
<add>
<add> @Test
<add> public void ternary() throws Exception {
<add> Expression expression = parser.parseExpression("true?'a':'b'");
<add> String resultI = expression.getValue(String.class);
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(String.class);
<add> assertEquals("a",resultI);
<add> assertEquals("a",resultC);
<add>
<add> expression = parser.parseExpression("false?'a':'b'");
<add> resultI = expression.getValue(String.class);
<add> assertCanCompile(expression);
<add> resultC = expression.getValue(String.class);
<add> assertEquals("b",resultI);
<add> assertEquals("b",resultC);
<add>
<add> expression = parser.parseExpression("false?1:'b'");
<add> // All literals so we can do this straight away
<add> assertCanCompile(expression);
<add> assertEquals("b",expression.getValue());
<add>
<add> boolean root = true;
<add> expression = parser.parseExpression("(#root and true)?T(Integer).valueOf(1):T(Long).valueOf(3L)");
<add> assertEquals(1,expression.getValue(root));
<add> assertCantCompile(expression); // Have not gone down false branch
<add> root = false;
<add> assertEquals(3L,expression.getValue(root));
<add> assertCanCompile(expression);
<add> assertEquals(3L,expression.getValue(root));
<add> root = true;
<add> assertEquals(1,expression.getValue(root));
<add> }
<add>
<add> @Test
<add> public void elvis() throws Exception {
<add> Expression expression = parser.parseExpression("'a'?:'b'");
<add> String resultI = expression.getValue(String.class);
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(String.class);
<add> assertEquals("a",resultI);
<add> assertEquals("a",resultC);
<add>
<add> expression = parser.parseExpression("null?:'a'");
<add> resultI = expression.getValue(String.class);
<add> assertCanCompile(expression);
<add> resultC = expression.getValue(String.class);
<add> assertEquals("a",resultI);
<add> assertEquals("a",resultC);
<add>
<add> String s = "abc";
<add> expression = parser.parseExpression("#root?:'b'");
<add> assertCantCompile(expression);
<add> resultI = expression.getValue(s,String.class);
<add> assertEquals("abc",resultI);
<add> assertCanCompile(expression);
<add> }
<add>
<add> @Test
<add> public void variableReference_root() throws Exception {
<add> String s = "hello";
<add> Expression expression = parser.parseExpression("#root");
<add> String resultI = expression.getValue(s,String.class);
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(s,String.class);
<add> assertEquals(s,resultI);
<add> assertEquals(s,resultC);
<add>
<add> expression = parser.parseExpression("#root");
<add> int i = (Integer)expression.getValue(42);
<add> assertEquals(42,i);
<add> assertCanCompile(expression);
<add> i = (Integer)expression.getValue(42);
<add> assertEquals(42,i);
<add> }
<add>
<add> public static String concat(String a, String b) {
<add> return a+b;
<add> }
<add>
<add> @Test
<add> public void functionReference() throws Exception {
<add> EvaluationContext ctx = new StandardEvaluationContext();
<add> Method m = this.getClass().getDeclaredMethod("concat",String.class,String.class);
<add> ctx.setVariable("concat",m);
<add>
<add> expression = parser.parseExpression("#concat('a','b')");
<add> assertEquals("ab",expression.getValue(ctx));
<add> assertCanCompile(expression);
<add> assertEquals("ab",expression.getValue(ctx));
<add>
<add> expression = parser.parseExpression("#concat(#concat('a','b'),'c').charAt(1)");
<add> assertEquals('b',expression.getValue(ctx));
<add> assertCanCompile(expression);
<add> assertEquals('b',expression.getValue(ctx));
<add>
<add> expression = parser.parseExpression("#concat(#a,#b)");
<add> ctx.setVariable("a", "foo");
<add> ctx.setVariable("b", "bar");
<add> assertEquals("foobar",expression.getValue(ctx));
<add> assertCanCompile(expression);
<add> assertEquals("foobar",expression.getValue(ctx));
<add> ctx.setVariable("b", "boo");
<add> assertEquals("fooboo",expression.getValue(ctx));
<add> }
<add>
<add> @Test
<add> public void variableReference_userDefined() throws Exception {
<add> EvaluationContext ctx = new StandardEvaluationContext();
<add> ctx.setVariable("target", "abc");
<add> expression = parser.parseExpression("#target");
<add> assertEquals("abc",expression.getValue(ctx));
<add> assertCanCompile(expression);
<add> assertEquals("abc",expression.getValue(ctx));
<add> ctx.setVariable("target", "123");
<add> assertEquals("123",expression.getValue(ctx));
<add> ctx.setVariable("target", 42);
<add> try {
<add> assertEquals(42,expression.getValue(ctx));
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertTrue(see.getCause() instanceof ClassCastException);
<add> }
<add>
<add> ctx.setVariable("target", "abc");
<add> expression = parser.parseExpression("#target.charAt(0)");
<add> assertEquals('a',expression.getValue(ctx));
<add> assertCanCompile(expression);
<add> assertEquals('a',expression.getValue(ctx));
<add> ctx.setVariable("target", "1");
<add> assertEquals('1',expression.getValue(ctx));
<add> ctx.setVariable("target", 42);
<add> try {
<add> assertEquals('4',expression.getValue(ctx));
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertTrue(see.getCause() instanceof ClassCastException);
<add> }
<add> }
<add>
<add> @Test
<add> public void opLt() throws Exception {
<add> expression = parse("3.0d < 4.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("3446.0d < 1123.0d");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("3 < 1");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("2 < 4");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3.0f < 1.0f");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("1.0f < 5.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("30L < 30L");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("15L < 20L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> // Differing types of number, not yet supported
<add> expression = parse("1 < 3.0d");
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Integer).valueOf(3) < 4");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(3) < T(Integer).valueOf(3)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("5 < T(Integer).valueOf(3)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opLe() throws Exception {
<add> expression = parse("3.0d <= 4.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("3446.0d <= 1123.0d");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3446.0d <= 3446.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3 <= 1");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("2 <= 4");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("3 <= 3");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3.0f <= 1.0f");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("1.0f <= 5.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("2.0f <= 2.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("30L <= 30L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("15L <= 20L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> // Differing types of number, not yet supported
<add> expression = parse("1 <= 3.0d");
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Integer).valueOf(3) <= 4");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(3) <= T(Integer).valueOf(3)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5 <= T(Integer).valueOf(3)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> }
<add>
<add>
<add> @Test
<add> public void opGt() throws Exception {
<add> expression = parse("3.0d > 4.0d");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3446.0d > 1123.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3 > 1");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("2 > 4");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("3.0f > 1.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("1.0f > 5.0f");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("30L > 30L");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("15L > 20L");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> // Differing types of number, not yet supported
<add> expression = parse("1 > 3.0d");
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Integer).valueOf(3) > 4");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(3) > T(Integer).valueOf(3)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("5 > T(Integer).valueOf(3)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opGe() throws Exception {
<add> expression = parse("3.0d >= 4.0d");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3446.0d >= 1123.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("3446.0d >= 3446.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3 >= 1");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("2 >= 4");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3 >= 3");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3.0f >= 1.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("1.0f >= 5.0f");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3.0f >= 3.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("40L >= 30L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("15L >= 20L");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("30L >= 30L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> // Differing types of number, not yet supported
<add> expression = parse("1 >= 3.0d");
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Integer).valueOf(3) >= 4");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(3) >= T(Integer).valueOf(3)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5 >= T(Integer).valueOf(3)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opEq() throws Exception {
<add>
<add> TestClass7 tc7 = new TestClass7();
<add> expression = parse("property == 'UK'");
<add> assertTrue((Boolean)expression.getValue(tc7));
<add> TestClass7.property = null;
<add> assertFalse((Boolean)expression.getValue(tc7));
<add> assertCanCompile(expression);
<add> TestClass7.reset();
<add> assertTrue((Boolean)expression.getValue(tc7));
<add> TestClass7.property = "UK";
<add> assertTrue((Boolean)expression.getValue(tc7));
<add> TestClass7.reset();
<add> TestClass7.property = null;
<add> assertFalse((Boolean)expression.getValue(tc7));
<add> expression = parse("property == null");
<add> assertTrue((Boolean)expression.getValue(tc7));
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue(tc7));
<add>
<add>
<add> expression = parse("3.0d == 4.0d");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3446.0d == 3446.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3 == 1");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("3 == 3");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("3.0f == 1.0f");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("2.0f == 2.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("30L == 30L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("15L == 20L");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> // number types are not the same
<add> expression = parse("1 == 3.0d");
<add> assertCantCompile(expression);
<add>
<add> Double d = 3.0d;
<add> expression = parse("#root==3.0d");
<add> assertTrue((Boolean)expression.getValue(d));
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue(d));
<add>
<add> Integer i = 3;
<add> expression = parse("#root==3");
<add> assertTrue((Boolean)expression.getValue(i));
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue(i));
<add>
<add> Float f = 3.0f;
<add> expression = parse("#root==3.0f");
<add> assertTrue((Boolean)expression.getValue(f));
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue(f));
<add>
<add> long l = 300l;
<add> expression = parse("#root==300l");
<add> assertTrue((Boolean)expression.getValue(l));
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue(l));
<add>
<add> boolean b = true;
<add> expression = parse("#root==true");
<add> assertTrue((Boolean)expression.getValue(b));
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue(b));
<add>
<add> expression = parse("T(Integer).valueOf(3) == 4");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(3) == T(Integer).valueOf(3)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5 == T(Integer).valueOf(3)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(3.0f) == 4.0f");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(3.0f) == T(Float).valueOf(3.0f)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5.0f == T(Float).valueOf(3.0f)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(3L) == 4L");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(3L) == T(Long).valueOf(3L)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5L == T(Long).valueOf(3L)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Double).valueOf(3.0d) == 4.0d");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Double).valueOf(3.0d) == T(Double).valueOf(3.0d)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5.0d == T(Double).valueOf(3.0d)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("false == true");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Boolean).valueOf('true') == T(Boolean).valueOf('true')");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Boolean).valueOf('true') == true");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("false == T(Boolean).valueOf('false')");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opNe() throws Exception {
<add> expression = parse("3.0d != 4.0d");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("3446.0d != 3446.0d");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("3 != 1");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("3 != 3");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("3.0f != 1.0f");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> expression = parse("2.0f != 2.0f");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("30L != 30L");
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add> expression = parse("15L != 20L");
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> // not compatible number types
<add> expression = parse("1 != 3.0d");
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Integer).valueOf(3) != 4");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(3) != T(Integer).valueOf(3)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("5 != T(Integer).valueOf(3)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(3.0f) != 4.0f");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(3.0f) != T(Float).valueOf(3.0f)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("5.0f != T(Float).valueOf(3.0f)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(3L) != 4L");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(3L) != T(Long).valueOf(3L)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("5L != T(Long).valueOf(3L)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Double).valueOf(3.0d) == 4.0d");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Double).valueOf(3.0d) == T(Double).valueOf(3.0d)");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("5.0d == T(Double).valueOf(3.0d)");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("false == true");
<add> assertFalse((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertFalse((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Boolean).valueOf('true') == T(Boolean).valueOf('true')");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("T(Boolean).valueOf('true') == true");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add>
<add> expression = parse("false == T(Boolean).valueOf('false')");
<add> assertTrue((Boolean)expression.getValue());
<add> assertCanCompile(expression);
<add> assertTrue((Boolean)expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opPlus() throws Exception {
<add> expression = parse("2+2");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(4,expression.getValue());
<add>
<add> expression = parse("2L+2L");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(4L,expression.getValue());
<add>
<add> expression = parse("2.0f+2.0f");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(4.0f,expression.getValue());
<add>
<add> expression = parse("3.0d+4.0d");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(7.0d,expression.getValue());
<add>
<add> expression = parse("+1");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(1,expression.getValue());
<add>
<add> expression = parse("+1L");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(1L,expression.getValue());
<add>
<add> expression = parse("+1.5f");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(1.5f,expression.getValue());
<add>
<add> expression = parse("+2.5d");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(2.5d,expression.getValue());
<add>
<add> expression = parse("+T(Double).valueOf(2.5d)");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(2.5d,expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(2)+6");
<add> assertEquals(8,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(8,expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(1)+T(Integer).valueOf(3)");
<add> assertEquals(4,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(4,expression.getValue());
<add>
<add> expression = parse("1+T(Integer).valueOf(3)");
<add> assertEquals(4,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(4,expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(2.0f)+6");
<add> assertEquals(8.0f,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Float).valueOf(2.0f)+T(Float).valueOf(3.0f)");
<add> assertEquals(5.0f,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(5.0f,expression.getValue());
<add>
<add> expression = parse("3L+T(Long).valueOf(4L)");
<add> assertEquals(7L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(7L,expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(2L)+6");
<add> assertEquals(8L,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Long).valueOf(2L)+T(Long).valueOf(3L)");
<add> assertEquals(5L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(5L,expression.getValue());
<add>
<add> expression = parse("1L+T(Long).valueOf(2L)");
<add> assertEquals(3L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(3L,expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opMinus() throws Exception {
<add> expression = parse("2-2");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(0,expression.getValue());
<add>
<add> expression = parse("4L-2L");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(2L,expression.getValue());
<add>
<add> expression = parse("4.0f-2.0f");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(2.0f,expression.getValue());
<add>
<add> expression = parse("3.0d-4.0d");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(-1.0d,expression.getValue());
<add>
<add> expression = parse("-1");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(-1,expression.getValue());
<add>
<add> expression = parse("-1L");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(-1L,expression.getValue());
<add>
<add> expression = parse("-1.5f");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(-1.5f,expression.getValue());
<add>
<add> expression = parse("-2.5d");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(-2.5d,expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(2)-6");
<add> assertEquals(-4,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(-4,expression.getValue());
<add>
<add> expression = parse("T(Integer).valueOf(1)-T(Integer).valueOf(3)");
<add> assertEquals(-2,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(-2,expression.getValue());
<add>
<add> expression = parse("4-T(Integer).valueOf(3)");
<add> assertEquals(1,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(1,expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(2.0f)-6");
<add> assertEquals(-4.0f,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Float).valueOf(8.0f)-T(Float).valueOf(3.0f)");
<add> assertEquals(5.0f,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(5.0f,expression.getValue());
<add>
<add> expression = parse("11L-T(Long).valueOf(4L)");
<add> assertEquals(7L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(7L,expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(9L)-6");
<add> assertEquals(3L,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Long).valueOf(4L)-T(Long).valueOf(3L)");
<add> assertEquals(1L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(1L,expression.getValue());
<add>
<add> expression = parse("8L-T(Long).valueOf(2L)");
<add> assertEquals(6L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(6L,expression.getValue());
<add> }
<add>
<add>
<add> @Test
<add> public void opMultiply() throws Exception {
<add> expression = parse("2*2");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(4,expression.getValue());
<add>
<add> expression = parse("2L*2L");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(4L,expression.getValue());
<add>
<add> expression = parse("2.0f*2.0f");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(4.0f,expression.getValue());
<add>
<add> expression = parse("3.0d*4.0d");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(12.0d,expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(2.0f)*6");
<add> assertEquals(12.0f,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Float).valueOf(8.0f)*T(Float).valueOf(3.0f)");
<add> assertEquals(24.0f,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(24.0f,expression.getValue());
<add>
<add> expression = parse("11L*T(Long).valueOf(4L)");
<add> assertEquals(44L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(44L,expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(9L)*6");
<add> assertEquals(54L,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Long).valueOf(4L)*T(Long).valueOf(3L)");
<add> assertEquals(12L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(12L,expression.getValue());
<add>
<add> expression = parse("8L*T(Long).valueOf(2L)");
<add> assertEquals(16L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(16L,expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(8.0f)*-T(Float).valueOf(3.0f)");
<add> assertEquals(-24.0f,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(-24.0f,expression.getValue());
<add> }
<add>
<add> @Test
<add> public void opDivide() throws Exception {
<add> expression = parse("2/2");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(1,expression.getValue());
<add>
<add> expression = parse("2L/2L");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(1L,expression.getValue());
<add>
<add> expression = parse("2.0f/2.0f");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(1.0f,expression.getValue());
<add>
<add> expression = parse("3.0d/4.0d");
<add> expression.getValue();
<add> assertCanCompile(expression);
<add> assertEquals(0.75d,expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(6.0f)/2");
<add> assertEquals(3.0f,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Float).valueOf(8.0f)/T(Float).valueOf(2.0f)");
<add> assertEquals(4.0f,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(4.0f,expression.getValue());
<add>
<add> expression = parse("12L/T(Long).valueOf(4L)");
<add> assertEquals(3L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(3L,expression.getValue());
<add>
<add> expression = parse("T(Long).valueOf(44L)/11");
<add> assertEquals(4L,expression.getValue());
<add> assertCantCompile(expression);
<add>
<add> expression = parse("T(Long).valueOf(4L)/T(Long).valueOf(2L)");
<add> assertEquals(2L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(2L,expression.getValue());
<add>
<add> expression = parse("8L/T(Long).valueOf(2L)");
<add> assertEquals(4L,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(4L,expression.getValue());
<add>
<add> expression = parse("T(Float).valueOf(8.0f)/-T(Float).valueOf(4.0f)");
<add> assertEquals(-2.0f,expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals(-2.0f,expression.getValue());
<add> }
<add>
<add>
<add> @Test
<add> public void constructorReference() throws Exception {
<add> // simple ctor
<add> expression = parser.parseExpression("new String('123')");
<add> assertEquals("123",expression.getValue());
<add> assertCanCompile(expression);
<add> assertEquals("123",expression.getValue());
<add>
<add> String testclass8 = "org.springframework.expression.spel.SpelCompilationCoverageTests$TestClass8";
<add> // multi arg ctor that includes primitives
<add> expression = parser.parseExpression("new "+testclass8+"(42,'123',4.0d,true)");
<add> assertEquals(testclass8,expression.getValue().getClass().getName());
<add> assertCanCompile(expression);
<add> Object o = expression.getValue();
<add> assertEquals(testclass8,o.getClass().getName());
<add> TestClass8 tc8 = (TestClass8)o;
<add> assertEquals(42,tc8.i);
<add> assertEquals("123",tc8.s);
<add> assertEquals(4.0d,tc8.d,0.5d);
<add> assertEquals(true,tc8.z);
<add>
<add> // no-arg ctor
<add> expression = parser.parseExpression("new "+testclass8+"()");
<add> assertEquals(testclass8,expression.getValue().getClass().getName());
<add> assertCanCompile(expression);
<add> o = expression.getValue();
<add> assertEquals(testclass8,o.getClass().getName());
<add>
<add> // pass primitive to reference type ctor
<add> expression = parser.parseExpression("new "+testclass8+"(42)");
<add> assertEquals(testclass8,expression.getValue().getClass().getName());
<add> assertCanCompile(expression);
<add> o = expression.getValue();
<add> assertEquals(testclass8,o.getClass().getName());
<add> tc8 = (TestClass8)o;
<add> assertEquals(42,tc8.i);
<add>
<add> // private class, can't compile it
<add> String testclass9 = "org.springframework.expression.spel.SpelCompilationCoverageTests$TestClass9";
<add> expression = parser.parseExpression("new "+testclass9+"(42)");
<add> assertEquals(testclass9,expression.getValue().getClass().getName());
<add> assertCantCompile(expression);
<add> }
<add>
<add> @Test
<add> public void methodReference() throws Exception {
<add> TestClass5 tc = new TestClass5();
<add>
<add> // non-static method, no args, void return
<add> expression = parser.parseExpression("one()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> expression.getValue(tc);
<add> assertEquals(1,tc.i);
<add> tc.reset();
<add>
<add> // static method, no args, void return
<add> expression = parser.parseExpression("two()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> expression.getValue(tc);
<add> assertEquals(1,TestClass5._i);
<add> tc.reset();
<add>
<add> // non-static method, reference type return
<add> expression = parser.parseExpression("three()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> assertEquals("hello",expression.getValue(tc));
<add> tc.reset();
<add>
<add> // non-static method, primitive type return
<add> expression = parser.parseExpression("four()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> assertEquals(3277700L,expression.getValue(tc));
<add> tc.reset();
<add>
<add> // static method, reference type return
<add> expression = parser.parseExpression("five()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> assertEquals("hello",expression.getValue(tc));
<add> tc.reset();
<add>
<add> // static method, primitive type return
<add> expression = parser.parseExpression("six()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> assertEquals(3277700L,expression.getValue(tc));
<add> tc.reset();
<add>
<add> // non-static method, one parameter of reference type
<add> expression = parser.parseExpression("seven(\"foo\")");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> expression.getValue(tc);
<add> assertEquals("foo",tc.s);
<add> tc.reset();
<add>
<add> // static method, one parameter of reference type
<add> expression = parser.parseExpression("eight(\"bar\")");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> expression.getValue(tc);
<add> assertEquals("bar",TestClass5._s);
<add> tc.reset();
<add>
<add> // non-static method, one parameter of primitive type
<add> expression = parser.parseExpression("nine(231)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> expression.getValue(tc);
<add> assertEquals(231,tc.i);
<add> tc.reset();
<add>
<add> // static method, one parameter of primitive type
<add> expression = parser.parseExpression("ten(111)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> expression.getValue(tc);
<add> assertEquals(111,TestClass5._i);
<add> tc.reset();
<add>
<add> // non-static method, varargs with reference type
<add> expression = parser.parseExpression("eleven(\"a\",\"b\",\"c\")");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCantCompile(expression); // Varargs is not yet supported
<add>
<add> expression = parser.parseExpression("eleven()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCantCompile(expression); // Varargs is not yet supported
<add>
<add> // static method, varargs with primitive type
<add> expression = parser.parseExpression("twelve(1,2,3)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCantCompile(expression); // Varargs is not yet supported
<add>
<add> expression = parser.parseExpression("twelve()");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertCantCompile(expression); // Varargs is not yet supported
<add>
<add> // method that gets type converted parameters
<add>
<add> // Converting from an int to a string
<add> expression = parser.parseExpression("seven(123)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertEquals("123",tc.s);
<add> assertCantCompile(expression); // Uncompilable as argument conversion is occurring
<add>
<add> Expression expression = parser.parseExpression("'abcd'.substring(index1,index2)");
<add> String resultI = expression.getValue(new TestClass1(),String.class);
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(new TestClass1(),String.class);
<add> assertEquals("bc",resultI);
<add> assertEquals("bc",resultC);
<add>
<add> // Converting from an int to a Number
<add> expression = parser.parseExpression("takeNumber(123)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertEquals("123",tc.s);
<add> tc.reset();
<add> assertCanCompile(expression); // The generated code should include boxing of the int to a Number
<add> expression.getValue(tc);
<add> assertEquals("123",tc.s);
<add>
<add> // Passing a subtype
<add> expression = parser.parseExpression("takeNumber(T(Integer).valueOf(42))");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertEquals("42",tc.s);
<add> tc.reset();
<add> assertCanCompile(expression); // The generated code should include boxing of the int to a Number
<add> expression.getValue(tc);
<add> assertEquals("42",tc.s);
<add>
<add> // Passing a subtype
<add> expression = parser.parseExpression("takeString(T(Integer).valueOf(42))");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertEquals("42",tc.s);
<add> tc.reset();
<add> assertCantCompile(expression); // method takes a string and we are passing an Integer
<add> }
<add>
<add>
<add> @Test
<add> public void errorHandling() throws Exception {
<add> TestClass5 tc = new TestClass5();
<add>
<add> // changing target
<add>
<add> // from primitive array to reference type array
<add> int[] is = new int[]{1,2,3};
<add> String[] strings = new String[]{"a","b","c"};
<add> expression = parser.parseExpression("[1]");
<add> assertEquals(2,expression.getValue(is));
<add> assertCanCompile(expression);
<add> assertEquals(2,expression.getValue(is));
<add>
<add> try {
<add> assertEquals(2,expression.getValue(strings));
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertTrue(see.getCause() instanceof ClassCastException);
<add> }
<add> SpelCompiler.revertToInterpreted(expression);
<add> assertEquals("b",expression.getValue(strings));
<add> assertCanCompile(expression);
<add> assertEquals("b",expression.getValue(strings));
<add>
<add>
<add> tc.field = "foo";
<add> expression = parser.parseExpression("seven(field)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertEquals("foo",tc.s);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> tc.field="bar";
<add> expression.getValue(tc);
<add>
<add> // method with changing parameter types (change reference type)
<add> tc.obj = "foo";
<add> expression = parser.parseExpression("seven(obj)");
<add> assertCantCompile(expression);
<add> expression.getValue(tc);
<add> assertEquals("foo",tc.s);
<add> assertCanCompile(expression);
<add> tc.reset();
<add> tc.obj=new Integer(42);
<add> try {
<add> expression.getValue(tc);
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> assertTrue(see.getCause() instanceof ClassCastException);
<add> }
<add>
<add>
<add> // method with changing target
<add> expression = parser.parseExpression("#root.charAt(0)");
<add> assertEquals('a',expression.getValue("abc"));
<add> assertCanCompile(expression);
<add> try {
<add> expression.getValue(new Integer(42));
<add> fail();
<add> } catch (SpelEvaluationException see) {
<add> // java.lang.Integer cannot be cast to java.lang.String
<add> assertTrue(see.getCause() instanceof ClassCastException);
<add> }
<add> }
<add>
<add> @Test
<add> public void methodReference_staticMethod() throws Exception {
<add> Expression expression = parser.parseExpression("T(Integer).valueOf(42)");
<add> int resultI = expression.getValue(new TestClass1(),Integer.TYPE);
<add> assertCanCompile(expression);
<add> int resultC = expression.getValue(new TestClass1(),Integer.TYPE);
<add> assertEquals(42,resultI);
<add> assertEquals(42,resultC);
<add> }
<add>
<add> @Test
<add> public void methodReference_literalArguments_int() throws Exception {
<add> Expression expression = parser.parseExpression("'abcd'.substring(1,3)");
<add> String resultI = expression.getValue(new TestClass1(),String.class);
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(new TestClass1(),String.class);
<add> assertEquals("bc",resultI);
<add> assertEquals("bc",resultC);
<add> }
<add>
<add> @Test
<add> public void methodReference_simpleInstanceMethodNoArg() throws Exception {
<add> Expression expression = parser.parseExpression("toString()");
<add> String resultI = expression.getValue(42,String.class);
<add> assertCanCompile(expression);
<add> String resultC = expression.getValue(42,String.class);
<add> assertEquals("42",resultI);
<add> assertEquals("42",resultC);
<add> }
<add>
<add> @Test
<add> public void methodReference_simpleInstanceMethodNoArgReturnPrimitive() throws Exception {
<add> expression = parser.parseExpression("intValue()");
<add> int resultI = expression.getValue(new Integer(42),Integer.TYPE);
<add> assertEquals(42,resultI);
<add> assertCanCompile(expression);
<add> int resultC = expression.getValue(new Integer(42),Integer.TYPE);
<add> assertEquals(42,resultC);
<add> }
<add>
<add> @Test
<add> public void methodReference_simpleInstanceMethodOneArgReturnPrimitive1() throws Exception {
<add> Expression expression = parser.parseExpression("indexOf('b')");
<add> int resultI = expression.getValue("abc",Integer.TYPE);
<add> assertCanCompile(expression);
<add> int resultC = expression.getValue("abc",Integer.TYPE);
<add> assertEquals(1,resultI);
<add> assertEquals(1,resultC);
<add> }
<add>
<add> @Test
<add> public void methodReference_simpleInstanceMethodOneArgReturnPrimitive2() throws Exception {
<add> expression = parser.parseExpression("charAt(2)");
<add> char resultI = expression.getValue("abc",Character.TYPE);
<add> assertEquals('c',resultI);
<add> assertCanCompile(expression);
<add> char resultC = expression.getValue("abc",Character.TYPE);
<add> assertEquals('c',resultC);
<add> }
<add>
<add>
<add> @Test
<add> public void compoundExpression() throws Exception {
<add> Payload payload = new Payload();
<add> expression = parser.parseExpression("DR[0]");
<add> assertEquals("instanceof Two",expression.getValue(payload).toString());
<add> assertCanCompile(expression);
<add> assertEquals("instanceof Two",expression.getValue(payload).toString());
<add> ast = getAst();
<add> assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Two",ast.getExitDescriptor());
<add>
<add> expression = parser.parseExpression("holder.three");
<add> assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three",expression.getValue(payload).getClass().getName());
<add> assertCanCompile(expression);
<add> assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three",expression.getValue(payload).getClass().getName());
<add> ast = getAst();
<add> assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three",ast.getExitDescriptor());
<add>
<add> expression = parser.parseExpression("DR[0]");
<add> assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Two",expression.getValue(payload).getClass().getName());
<add> assertCanCompile(expression);
<add> assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Two",expression.getValue(payload).getClass().getName());
<add> assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Two",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("DR[0].three");
<add> assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three",expression.getValue(payload).getClass().getName());
<add> assertCanCompile(expression);
<add> assertEquals("org.springframework.expression.spel.SpelCompilationCoverageTests$Three",expression.getValue(payload).getClass().getName());
<add> ast = getAst();
<add> assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three",ast.getExitDescriptor());
<add>
<add> expression = parser.parseExpression("DR[0].three.four");
<add> assertEquals(0.04d,expression.getValue(payload));
<add> assertCanCompile(expression);
<add> assertEquals(0.04d,expression.getValue(payload));
<add> assertEquals("D",getAst().getExitDescriptor());
<add> }
<add>
<add>
<add> @Test
<add> public void mixingItUp_indexerOpEqTernary() throws Exception {
<add> Map<String, String> m = new HashMap<String,String>();
<add> m.put("andy","778");
<add>
<add> expression = parse("['andy']==null?1:2");
<add> System.out.println(expression.getValue(m));
<add> assertCanCompile(expression);
<add> assertEquals(2,expression.getValue(m));
<add> m.remove("andy");
<add> assertEquals(1,expression.getValue(m));
<add> }
<add>
<add> @Test
<add> public void propertyReference() throws Exception {
<add> TestClass6 tc = new TestClass6();
<add>
<add> // non static field
<add> expression = parser.parseExpression("orange");
<add> assertCantCompile(expression);
<add> assertEquals("value1",expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals("value1",expression.getValue(tc));
<add>
<add> // static field
<add> expression = parser.parseExpression("apple");
<add> assertCantCompile(expression);
<add> assertEquals("value2",expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals("value2",expression.getValue(tc));
<add>
<add> // non static getter
<add> expression = parser.parseExpression("banana");
<add> assertCantCompile(expression);
<add> assertEquals("value3",expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals("value3",expression.getValue(tc));
<add>
<add> // static getter
<add> expression = parser.parseExpression("plum");
<add> assertCantCompile(expression);
<add> assertEquals("value4",expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals("value4",expression.getValue(tc));
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void indexer() throws Exception {
<add> String[] sss = new String[]{"a","b","c"};
<add> Number[] ns = new Number[]{2,8,9};
<add> int[] is = new int[]{8,9,10};
<add> double[] ds = new double[]{3.0d,4.0d,5.0d};
<add> long[] ls = new long[]{2L,3L,4L};
<add> short[] ss = new short[]{(short)33,(short)44,(short)55};
<add> float[] fs = new float[]{6.0f,7.0f,8.0f};
<add> byte[] bs = new byte[]{(byte)2,(byte)3,(byte)4};
<add> char[] cs = new char[]{'a','b','c'};
<add>
<add> // Access String (reference type) array
<add> expression = parser.parseExpression("[0]");
<add> assertEquals("a",expression.getValue(sss));
<add> assertCanCompile(expression);
<add> assertEquals("a",expression.getValue(sss));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[1]");
<add> assertEquals(8,expression.getValue(ns));
<add> assertCanCompile(expression);
<add> assertEquals(8,expression.getValue(ns));
<add> assertEquals("Ljava/lang/Number",getAst().getExitDescriptor());
<add>
<add> // Access int array
<add> expression = parser.parseExpression("[2]");
<add> assertEquals(10,expression.getValue(is));
<add> assertCanCompile(expression);
<add> assertEquals(10,expression.getValue(is));
<add> assertEquals("I",getAst().getExitDescriptor());
<add>
<add> // Access double array
<add> expression = parser.parseExpression("[1]");
<add> assertEquals(4.0d,expression.getValue(ds));
<add> assertCanCompile(expression);
<add> assertEquals(4.0d,expression.getValue(ds));
<add> assertEquals("D",getAst().getExitDescriptor());
<add>
<add> // Access long array
<add> expression = parser.parseExpression("[0]");
<add> assertEquals(2L,expression.getValue(ls));
<add> assertCanCompile(expression);
<add> assertEquals(2L,expression.getValue(ls));
<add> assertEquals("J",getAst().getExitDescriptor());
<add>
<add> // Access short array
<add> expression = parser.parseExpression("[2]");
<add> assertEquals((short)55,expression.getValue(ss));
<add> assertCanCompile(expression);
<add> assertEquals((short)55,expression.getValue(ss));
<add> assertEquals("S",getAst().getExitDescriptor());
<add>
<add> // Access float array
<add> expression = parser.parseExpression("[0]");
<add> assertEquals(6.0f,expression.getValue(fs));
<add> assertCanCompile(expression);
<add> assertEquals(6.0f,expression.getValue(fs));
<add> assertEquals("F",getAst().getExitDescriptor());
<add>
<add> // Access byte array
<add> expression = parser.parseExpression("[2]");
<add> assertEquals((byte)4,expression.getValue(bs));
<add> assertCanCompile(expression);
<add> assertEquals((byte)4,expression.getValue(bs));
<add> assertEquals("B",getAst().getExitDescriptor());
<add>
<add> // Access char array
<add> expression = parser.parseExpression("[1]");
<add> assertEquals('b',expression.getValue(cs));
<add> assertCanCompile(expression);
<add> assertEquals('b',expression.getValue(cs));
<add> assertEquals("C",getAst().getExitDescriptor());
<add>
<add> // Collections
<add> List<String> strings = new ArrayList<String>();
<add> strings.add("aaa");
<add> strings.add("bbb");
<add> strings.add("ccc");
<add> expression = parser.parseExpression("[1]");
<add> assertEquals("bbb",expression.getValue(strings));
<add> assertCanCompile(expression);
<add> assertEquals("bbb",expression.getValue(strings));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> List<Integer> ints = new ArrayList<Integer>();
<add> ints.add(123);
<add> ints.add(456);
<add> ints.add(789);
<add> expression = parser.parseExpression("[2]");
<add> assertEquals(789,expression.getValue(ints));
<add> assertCanCompile(expression);
<add> assertEquals(789,expression.getValue(ints));
<add> assertEquals("Ljava/lang/Integer",getAst().getExitDescriptor());
<add>
<add> // Maps
<add> Map<String,Integer> map1 = new HashMap<String,Integer>();
<add> map1.put("aaa", 111);
<add> map1.put("bbb", 222);
<add> map1.put("ccc", 333);
<add> expression = parser.parseExpression("['aaa']");
<add> assertEquals(111,expression.getValue(map1));
<add> assertCanCompile(expression);
<add> assertEquals(111,expression.getValue(map1));
<add> assertEquals("Ljava/lang/Integer",getAst().getExitDescriptor());
<add>
<add> // Object
<add> TestClass6 tc = new TestClass6();
<add> expression = parser.parseExpression("['orange']");
<add> assertEquals("value1",expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals("value1",expression.getValue(tc));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("['peach']");
<add> assertEquals(34L,expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals(34L,expression.getValue(tc));
<add> assertEquals("J",getAst().getExitDescriptor());
<add>
<add> // getter
<add> expression = parser.parseExpression("['banana']");
<add> assertEquals("value3",expression.getValue(tc));
<add> assertCanCompile(expression);
<add> assertEquals("value3",expression.getValue(tc));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> // list of arrays
<add>
<add> List<String[]> listOfStringArrays = new ArrayList<String[]>();
<add> listOfStringArrays.add(new String[]{"a","b","c"});
<add> listOfStringArrays.add(new String[]{"d","e","f"});
<add> expression = parser.parseExpression("[1]");
<add> assertEquals("d e f",stringify(expression.getValue(listOfStringArrays)));
<add> assertCanCompile(expression);
<add> assertEquals("d e f",stringify(expression.getValue(listOfStringArrays)));
<add> assertEquals("[Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
<add> listOfIntegerArrays.add(new Integer[]{1,2,3});
<add> listOfIntegerArrays.add(new Integer[]{4,5,6});
<add> expression = parser.parseExpression("[0]");
<add> assertEquals("1 2 3",stringify(expression.getValue(listOfIntegerArrays)));
<add> assertCanCompile(expression);
<add> assertEquals("1 2 3",stringify(expression.getValue(listOfIntegerArrays)));
<add> assertEquals("[Ljava/lang/Integer",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[0][1]");
<add> assertEquals(2,expression.getValue(listOfIntegerArrays));
<add> assertCanCompile(expression);
<add> assertEquals(2,expression.getValue(listOfIntegerArrays));
<add> assertEquals("Ljava/lang/Integer",getAst().getExitDescriptor());
<add>
<add> // array of lists
<add> List<String>[] stringArrayOfLists = new ArrayList[2];
<add> stringArrayOfLists[0] = new ArrayList<String>();
<add> stringArrayOfLists[0].add("a");
<add> stringArrayOfLists[0].add("b");
<add> stringArrayOfLists[0].add("c");
<add> stringArrayOfLists[1] = new ArrayList<String>();
<add> stringArrayOfLists[1].add("d");
<add> stringArrayOfLists[1].add("e");
<add> stringArrayOfLists[1].add("f");
<add> expression = parser.parseExpression("[1]");
<add> assertEquals("d e f",stringify(expression.getValue(stringArrayOfLists)));
<add> assertCanCompile(expression);
<add> assertEquals("d e f",stringify(expression.getValue(stringArrayOfLists)));
<add> assertEquals("Ljava/util/ArrayList",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[1][2]");
<add> assertEquals("f",stringify(expression.getValue(stringArrayOfLists)));
<add> assertCanCompile(expression);
<add> assertEquals("f",stringify(expression.getValue(stringArrayOfLists)));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> // array of arrays
<add> String[][] referenceTypeArrayOfArrays = new String[][]{new String[]{"a","b","c"},new String[]{"d","e","f"}};
<add> expression = parser.parseExpression("[1]");
<add> assertEquals("d e f",stringify(expression.getValue(referenceTypeArrayOfArrays)));
<add> assertCanCompile(expression);
<add> assertEquals("[Ljava/lang/String",getAst().getExitDescriptor());
<add> assertEquals("d e f",stringify(expression.getValue(referenceTypeArrayOfArrays)));
<add> assertEquals("[Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[1][2]");
<add> assertEquals("f",stringify(expression.getValue(referenceTypeArrayOfArrays)));
<add> assertCanCompile(expression);
<add> assertEquals("f",stringify(expression.getValue(referenceTypeArrayOfArrays)));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> int[][] primitiveTypeArrayOfArrays = new int[][]{new int[]{1,2,3},new int[]{4,5,6}};
<add> expression = parser.parseExpression("[1]");
<add> assertEquals("4 5 6",stringify(expression.getValue(primitiveTypeArrayOfArrays)));
<add> assertCanCompile(expression);
<add> assertEquals("4 5 6",stringify(expression.getValue(primitiveTypeArrayOfArrays)));
<add> assertEquals("[I",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[1][2]");
<add> assertEquals("6",stringify(expression.getValue(primitiveTypeArrayOfArrays)));
<add> assertCanCompile(expression);
<add> assertEquals("6",stringify(expression.getValue(primitiveTypeArrayOfArrays)));
<add> assertEquals("I",getAst().getExitDescriptor());
<add>
<add> // list of lists of reference types
<add> List<List<String>> listOfListOfStrings = new ArrayList<List<String>>();
<add> List<String> list = new ArrayList<String>();
<add> list.add("a");
<add> list.add("b");
<add> list.add("c");
<add> listOfListOfStrings.add(list);
<add> list = new ArrayList<String>();
<add> list.add("d");
<add> list.add("e");
<add> list.add("f");
<add> listOfListOfStrings.add(list);
<add>
<add> expression = parser.parseExpression("[1]");
<add> assertEquals("d e f",stringify(expression.getValue(listOfListOfStrings)));
<add> assertCanCompile(expression);
<add> assertEquals("Ljava/util/ArrayList",getAst().getExitDescriptor());
<add> assertEquals("d e f",stringify(expression.getValue(listOfListOfStrings)));
<add> assertEquals("Ljava/util/ArrayList",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[1][2]");
<add> assertEquals("f",stringify(expression.getValue(listOfListOfStrings)));
<add> assertCanCompile(expression);
<add> assertEquals("f",stringify(expression.getValue(listOfListOfStrings)));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> // Map of lists
<add> Map<String,List<String>> mapToLists = new HashMap<String,List<String>>();
<add> list = new ArrayList<String>();
<add> list.add("a");
<add> list.add("b");
<add> list.add("c");
<add> mapToLists.put("foo", list);
<add> expression = parser.parseExpression("['foo']");
<add> assertEquals("a b c",stringify(expression.getValue(mapToLists)));
<add> assertCanCompile(expression);
<add> assertEquals("Ljava/util/ArrayList",getAst().getExitDescriptor());
<add> assertEquals("a b c",stringify(expression.getValue(mapToLists)));
<add> assertEquals("Ljava/util/ArrayList",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("['foo'][2]");
<add> assertEquals("c",stringify(expression.getValue(mapToLists)));
<add> assertCanCompile(expression);
<add> assertEquals("c",stringify(expression.getValue(mapToLists)));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add>
<add> // Map to array
<add> Map<String,int[]> mapToIntArray = new HashMap<String,int[]>();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext();
<add> ctx.addPropertyAccessor(new CompilableMapAccessor());
<add> mapToIntArray.put("foo",new int[]{1,2,3});
<add> expression = parser.parseExpression("['foo']");
<add> assertEquals("1 2 3",stringify(expression.getValue(mapToIntArray)));
<add> assertCanCompile(expression);
<add> assertEquals("[I",getAst().getExitDescriptor());
<add> assertEquals("1 2 3",stringify(expression.getValue(mapToIntArray)));
<add> assertEquals("[I",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("['foo'][1]");
<add> assertEquals(2,expression.getValue(mapToIntArray));
<add> assertCanCompile(expression);
<add> assertEquals(2,expression.getValue(mapToIntArray));
<add>
<add> expression = parser.parseExpression("foo");
<add> assertEquals("1 2 3",stringify(expression.getValue(ctx,mapToIntArray)));
<add> assertCanCompile(expression);
<add> assertEquals("1 2 3",stringify(expression.getValue(ctx,mapToIntArray)));
<add> assertEquals("Ljava/lang/Object",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("foo[1]");
<add> assertEquals(2,expression.getValue(ctx,mapToIntArray));
<add> assertCanCompile(expression);
<add> assertEquals(2,expression.getValue(ctx,mapToIntArray));
<add>
<add> expression = parser.parseExpression("['foo'][2]");
<add> assertEquals("3",stringify(expression.getValue(ctx,mapToIntArray)));
<add> assertCanCompile(expression);
<add> assertEquals("3",stringify(expression.getValue(ctx,mapToIntArray)));
<add> assertEquals("I",getAst().getExitDescriptor());
<add>
<add> // Map array
<add> Map<String,String>[] mapArray = new Map[1];
<add> mapArray[0] = new HashMap<String,String>();
<add> mapArray[0].put("key", "value1");
<add> expression = parser.parseExpression("[0]");
<add> assertEquals("{key=value1}",stringify(expression.getValue(mapArray)));
<add> assertCanCompile(expression);
<add> assertEquals("Ljava/util/Map",getAst().getExitDescriptor());
<add> assertEquals("{key=value1}",stringify(expression.getValue(mapArray)));
<add> assertEquals("Ljava/util/Map",getAst().getExitDescriptor());
<add>
<add> expression = parser.parseExpression("[0]['key']");
<add> assertEquals("value1",stringify(expression.getValue(mapArray)));
<add> assertCanCompile(expression);
<add> assertEquals("value1",stringify(expression.getValue(mapArray)));
<add> assertEquals("Ljava/lang/String",getAst().getExitDescriptor());
<add> }
<add>
<add> @Test
<add> public void mixingItUp_propertyAccessIndexerOpLtTernaryRootNull() throws Exception {
<add> Payload payload = new Payload();
<add>
<add> expression = parser.parseExpression("DR[0].three");
<add> Object v = expression.getValue(payload);
<add> assertEquals("Lorg/springframework/expression/spel/SpelCompilationCoverageTests$Three",getAst().getExitDescriptor());
<add>
<add> Expression expression = parser.parseExpression("DR[0].three.four lt 0.1d?#root:null");
<add> v = expression.getValue(payload);
<add>
<add> SpelExpression sExpr = (SpelExpression)expression;
<add> Ternary ternary = (Ternary)sExpr.getAST();
<add> OpLT oplt = (OpLT)ternary.getChild(0);
<add> CompoundExpression cExpr = (CompoundExpression)oplt.getLeftOperand();
<add> String cExprExitDescriptor = cExpr.getExitDescriptor();
<add> assertEquals("D",cExprExitDescriptor);
<add> assertEquals("Z",oplt.getExitDescriptor());
<add>
<add> assertCanCompile(expression);
<add> Object vc = expression.getValue(payload);
<add> assertEquals(payload,v);
<add> assertEquals(payload,vc);
<add> payload.DR[0].three.four = 0.13d;
<add> vc = expression.getValue(payload);
<add> assertNull(vc);
<add> }
<add>
<add> static class MyAccessor implements CompilablePropertyAccessor {
<add>
<add> private Method method;
<add>
<add> public Class<?>[] getSpecificTargetClasses() {
<add> return new Class[]{Payload2.class};
<add> }
<add>
<add> public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
<add> // target is a Payload2 instance
<add> return true;
<add> }
<add>
<add> public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
<add> Payload2 payload2 = (Payload2)target;
<add> return new TypedValue(payload2.getField(name));
<add> }
<add>
<add> public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
<add> return false;
<add> }
<add>
<add> public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
<add> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(PropertyOrFieldReference propertyReference, MethodVisitor mv,CodeFlow codeflow) {
<add> if (method == null) {
<add> try {
<add> method = Payload2.class.getDeclaredMethod("getField", String.class);
<add> } catch (Exception e) {}
<add> }
<add> String descriptor = codeflow.lastDescriptor();
<add> String memberDeclaringClassSlashedDescriptor = method.getDeclaringClass().getName().replace('.','/');
<add> if (descriptor == null) {
<add> codeflow.loadTarget(mv);
<add> }
<add> if (descriptor == null || !memberDeclaringClassSlashedDescriptor.equals(descriptor.substring(1))) {
<add> mv.visitTypeInsn(CHECKCAST, memberDeclaringClassSlashedDescriptor);
<add> }
<add> mv.visitLdcInsn(propertyReference.getName());
<add> mv.visitMethodInsn(INVOKEVIRTUAL, memberDeclaringClassSlashedDescriptor, method.getName(),CodeFlow.createSignatureDescriptor(method),false);
<add> }
<add>
<add> @Override
<add> public Class<?> getPropertyType() {
<add> return Object.class;
<add> }
<add>
<add> }
<add>
<add> @Test
<add> public void variantGetter() throws Exception {
<add> Payload2Holder holder = new Payload2Holder();
<add> StandardEvaluationContext ctx = new StandardEvaluationContext();
<add> ctx.addPropertyAccessor(new MyAccessor());
<add> expression = parser.parseExpression("payload2.var1");
<add> Object v = expression.getValue(ctx,holder);
<add> assertEquals("abc",v);
<add>
<add>// // time it interpreted
<add>// long stime = System.currentTimeMillis();
<add>// for (int i=0;i<100000;i++) {
<add>// v = expression.getValue(ctx,holder);
<add>// }
<add>// System.out.println((System.currentTimeMillis()-stime));
<add>//
<add> assertCanCompile(expression);
<add> v = expression.getValue(ctx,holder);
<add> assertEquals("abc",v);
<add>//
<add>// // time it compiled
<add>// stime = System.currentTimeMillis();
<add>// for (int i=0;i<100000;i++) {
<add>// v = expression.getValue(ctx,holder);
<add>// }
<add>// System.out.println((System.currentTimeMillis()-stime));
<add>
<add> }
<add>
<add> static class CompilableMapAccessor implements CompilablePropertyAccessor {
<add>
<add> @Override
<add> public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
<add> Map<?,?> map = (Map<?,?>) target;
<add> return map.containsKey(name);
<add> }
<add>
<add> @Override
<add> public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
<add> Map<?,?> map = (Map<?,?>) target;
<add> Object value = map.get(name);
<add> if (value == null && !map.containsKey(name)) {
<add> throw new MapAccessException(name);
<add> }
<add> return new TypedValue(value);
<add> }
<add>
<add> @Override
<add> public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
<add> return true;
<add> }
<add>
<add> @Override
<add> @SuppressWarnings("unchecked")
<add> public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
<add> Map<String,Object> map = (Map<String,Object>) target;
<add> map.put(name, newValue);
<add> }
<add>
<add> @Override
<add> public Class<?>[] getSpecificTargetClasses() {
<add> return new Class[] {Map.class};
<add> }
<add>
<add>
<add> /**
<add> * Exception thrown from {@code read} in order to reset a cached
<add> * PropertyAccessor, allowing other accessors to have a try.
<add> */
<add> @SuppressWarnings("serial")
<add> private static class MapAccessException extends AccessException {
<add>
<add> private final String key;
<add>
<add> public MapAccessException(String key) {
<add> super(null);
<add> this.key = key;
<add> }
<add>
<add> @Override
<add> public String getMessage() {
<add> return "Map does not contain a value for key '" + this.key + "'";
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isCompilable() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void generateCode(PropertyOrFieldReference propertyReference,
<add> MethodVisitor mv, CodeFlow codeflow) {
<add> String descriptor = codeflow.lastDescriptor();
<add> if (descriptor == null) {
<add> codeflow.loadTarget(mv);
<add> }
<add> mv.visitLdcInsn(propertyReference.getName());
<add> mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get","(Ljava/lang/Object;)Ljava/lang/Object;",true);
<add>
<add>// if (method == null) {
<add>// try {
<add>// method = Payload2.class.getDeclaredMethod("getField", String.class);
<add>// } catch (Exception e) {}
<add>// }
<add>// String descriptor = codeflow.lastDescriptor();
<add>// String memberDeclaringClassSlashedDescriptor = method.getDeclaringClass().getName().replace('.','/');
<add>// if (descriptor == null) {
<add>// codeflow.loadTarget(mv);
<add>// }
<add>// if (descriptor == null || !memberDeclaringClassSlashedDescriptor.equals(descriptor.substring(1))) {
<add>// mv.visitTypeInsn(CHECKCAST, memberDeclaringClassSlashedDescriptor);
<add>// }
<add>// mv.visitLdcInsn(propertyReference.getName());
<add>// mv.visitMethodInsn(INVOKEVIRTUAL, memberDeclaringClassSlashedDescriptor, method.getName(),CodeFlow.createDescriptor(method));
<add>// 6: invokeinterface #6, 2; //InterfaceMethod java/util/Map.get:(Ljava/lang/Object;)Ljava/lang/Object;
<add> }
<add>
<add> @Override
<add> public Class<?> getPropertyType() {
<add> return Object.class;
<add> }
<add>
<add> }
<add>
<add>
<add> // helpers
<add>
<add> private SpelNodeImpl getAst() {
<add> SpelExpression spelExpression = (SpelExpression)expression;
<add> SpelNode ast = spelExpression.getAST();
<add> return (SpelNodeImpl)ast;
<add> }
<add>
<add> private String stringify(Object object) {
<add> StringBuilder s = new StringBuilder();
<add> if (object instanceof List) {
<add> List<?> ls = (List<?>)object;
<add> for (Object l: ls) {
<add> s.append(l);
<add> s.append(" ");
<add> }
<add> }
<add> else if (object instanceof Object[]) {
<add> Object[] os = (Object[])object;
<add> for (Object o: os) {
<add> s.append(o);
<add> s.append(" ");
<add> }
<add> }
<add> else if (object instanceof int[]) {
<add> int[] is = (int[])object;
<add> for (int i: is) {
<add> s.append(i);
<add> s.append(" ");
<add> }
<add> }
<add> else {
<add> s.append(object.toString());
<add> }
<add> return s.toString().trim();
<add> }
<add>
<add> private void assertCanCompile(Expression expression) {
<add> assertTrue(SpelCompiler.compile(expression));
<add> }
<add>
<add> private void assertCantCompile(Expression expression) {
<add> assertFalse(SpelCompiler.compile(expression));
<add> }
<add>
<add> private Expression parse(String expression) {
<add> return parser.parseExpression(expression);
<add> }
<add>
<add> private void assertGetValueFail(Expression expression) {
<add> try {
<add> Object o = expression.getValue();
<add> fail("Calling getValue on the expression should have failed but returned "+o);
<add> } catch (Exception ex) {
<add> // success!
<add> }
<add> }
<add>
<add> // test classes
<add>
<add> public static class Payload {
<add> Two[] DR = new Two[]{new Two()};
<add> public Two holder = new Two();
<add>
<add> public Two[] getDR() {
<add> return DR;
<add> }
<add> }
<add>
<add> public static class Payload2 {
<add> String var1 = "abc";
<add> String var2 = "def";
<add> public Object getField(String name) {
<add> if (name.equals("var1")) {
<add> return var1;
<add> } else if (name.equals("var2")) {
<add> return var2;
<add> }
<add> return null;
<add> }
<add> }
<add>
<add> public static class Payload2Holder {
<add> public Payload2 payload2 = new Payload2();
<add> }
<add>
<add> public static class Two {
<add> Three three = new Three();
<add> public Three getThree() {
<add> return three;
<add> }
<add> public String toString() {
<add> return "instanceof Two";
<add> }
<add> }
<add>
<add> public static class Three {
<add> double four = 0.04d;
<add> public double getFour() {
<add> return four;
<add> }
<add> }
<add>
<add> public static class TestClass1 {
<add> public int index1 = 1;
<add> public int index2 = 3;
<add> public String word = "abcd";
<add> }
<add>
<add> public static class TestClass4 {
<add> public boolean a,b;
<add> public boolean gettrue() { return true; }
<add> public boolean getfalse() { return false; }
<add> public boolean getA() { return a; }
<add> public boolean getB() { return b; }
<add> }
<add>
<add> public static class TestClass5 {
<add> public int i = 0;
<add> public String s = null;
<add> public static int _i = 0;
<add> public static String _s = null;
<add>
<add> public Object obj = null;
<add>
<add> public String field = null;
<add>
<add> public void reset() {
<add> i = 0;
<add> _i=0;
<add> s = null;
<add> _s = null;
<add> field = null;
<add> }
<add>
<add> public void one() { i = 1; }
<add>
<add> public static void two() { _i = 1; }
<add>
<add> public String three() { return "hello"; }
<add> public long four() { return 3277700L; }
<add>
<add> public static String five() { return "hello"; }
<add> public static long six() { return 3277700L; }
<add>
<add> public void seven(String toset) { s = toset; }
<add>// public void seven(Number n) { s = n.toString(); }
<add>
<add> public void takeNumber(Number n) { s = n.toString(); }
<add> public void takeString(String s) { this.s = s; }
<add> public static void eight(String toset) { _s = toset; }
<add>
<add> public void nine(int toset) { i = toset; }
<add> public static void ten(int toset) { _i = toset; }
<add>
<add> public void eleven(String... vargs) {
<add> if (vargs==null) {
<add> s = "";
<add> }
<add> else {
<add> s = "";
<add> for (String varg: vargs) {
<add> s+=varg;
<add> }
<add> }
<add> }
<add>
<add> public void twelve(int... vargs) {
<add> if (vargs==null) {
<add> i = 0;
<add> }
<add> else {
<add> i = 0;
<add> for (int varg: vargs) {
<add> i+=varg;
<add> }
<add> }
<add> }
<add> }
<add>
<add> public static class TestClass6 {
<add> public String orange = "value1";
<add> public static String apple = "value2";
<add>
<add> public long peach = 34L;
<add>
<add> public String getBanana() {
<add> return "value3";
<add> }
<add>
<add> public static String getPlum() {
<add> return "value4";
<add> }
<add> }
<add>
<add> public static class TestClass7 {
<add> public static String property;
<add> static {
<add> String s = "UK 123";
<add> StringTokenizer st = new StringTokenizer(s);
<add> property = st.nextToken();
<add> }
<add>
<add> public static void reset() {
<add> String s = "UK 123";
<add> StringTokenizer st = new StringTokenizer(s);
<add> property = st.nextToken();
<add> }
<add>
<add> }
<add>
<add> public static class TestClass8 {
<add> public int i;
<add> public String s;
<add> public double d;
<add> public boolean z;
<add>
<add> public TestClass8(int i, String s, double d, boolean z) {
<add> this.i = i;
<add> this.s = s;
<add> this.d = d;
<add> this.z = z;
<add> }
<add>
<add> public TestClass8() {
<add>
<add> }
<add>
<add> public TestClass8(Integer i) {
<add> this.i = i;
<add> }
<add>
<add> @SuppressWarnings("unused")
<add> private TestClass8(String a, String b) {
<add> this.s = a+b;
<add> }
<add> }
<add>
<add> @SuppressWarnings("unused")
<add> private static class TestClass9 {
<add> public TestClass9(int i) {}
<add> }
<add>
<add>}
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationPerformanceTests.java
<add>/*
<add> * Copyright 2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.expression.spel;
<add>
<add>import org.junit.Ignore;
<add>import org.junit.Test;
<add>import org.springframework.expression.Expression;
<add>import org.springframework.expression.spel.standard.SpelCompiler;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Checks the speed of compiled SpEL expressions.
<add> * By default these tests are marked Ignore since they can fail on a busy machine because they
<add> * compare relative performance of interpreted vs compiled.
<add> *
<add> * @author Andy Clement
<add> * @since 4.1
<add> */
<add>@Ignore
<add>public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
<add>
<add> int count = 50000; // Number of evaluations that are timed in one run
<add> int iterations = 10; // Number of times to repeat 'count' evaluations (for averaging)
<add> private final static boolean noisyTests = true;
<add>
<add> Expression expression;
<add>
<add> public static class Payload {
<add> Two[] DR = new Two[]{new Two()};
<add>
<add> public Two[] getDR() {
<add> return DR;
<add> }
<add> }
<add>
<add> public static class Two {
<add> Three DRFixedSection = new Three();
<add> public Three getDRFixedSection() {
<add> return DRFixedSection;
<add> }
<add> }
<add>
<add> public static class Three {
<add> double duration = 0.4d;
<add> public double getDuration() {
<add> return duration;
<add> }
<add> }
<add>
<add> @Test
<add> public void complexExpressionPerformance() throws Exception {
<add> Payload payload = new Payload();
<add> Expression expression = parser.parseExpression("DR[0].DRFixedSection.duration lt 0.1");
<add> boolean b = false;
<add> long iTotal = 0,cTotal = 0;
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> b = expression.getValue(payload,Boolean.TYPE);
<add> }
<add>
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> long stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> b = expression.getValue(payload,Boolean.TYPE);
<add> }
<add> long etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> iTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> compile(expression);
<add> boolean bc = false;
<add> expression.getValue(payload,Boolean.TYPE);
<add> log("timing compiled: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> long stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> bc = expression.getValue(payload,Boolean.TYPE);
<add> }
<add> long etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> cTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> reportPerformance("complex expression",iTotal, cTotal);
<add>
<add> // Verify the result
<add> assertFalse(b);
<add>
<add> // Verify the same result for compiled vs interpreted
<add> assertEquals(b,bc);
<add>
<add> // Verify if the input changes, the result changes
<add> payload.DR[0].DRFixedSection.duration = 0.04d;
<add> bc = expression.getValue(payload,Boolean.TYPE);
<add> assertTrue(bc);
<add> }
<add>
<add> public static class HW {
<add> public String hello() {
<add> return "foobar";
<add> }
<add> }
<add>
<add> @Test
<add> public void compilingMethodReference() throws Exception {
<add> long interpretedTotal = 0, compiledTotal = 0;
<add> long stime,etime;
<add> String interpretedResult = null,compiledResult = null;
<add>
<add> HW testdata = new HW();
<add> Expression expression = parser.parseExpression("hello()");
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add>
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> interpretedTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> compile(expression);
<add>
<add> log("timing compiled: ");
<add> expression.getValue(testdata,String.class);
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> compiledResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> compiledTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> assertEquals(interpretedResult,compiledResult);
<add> reportPerformance("method reference", interpretedTotal, compiledTotal);
<add> if (compiledTotal>=interpretedTotal) {
<add> fail("Compiled version is slower than interpreted!");
<add> }
<add> }
<add>
<add>
<add>
<add>
<add> public static class TestClass2 {
<add> public String name = "Santa";
<add> private String name2 = "foobar";
<add> public String getName2() {
<add> return name2;
<add> }
<add> public Foo foo = new Foo();
<add> public static class Foo {
<add> public Bar bar = new Bar();
<add> Bar b = new Bar();
<add> public Bar getBaz() {
<add> return b;
<add> }
<add> public Bar bay() {
<add> return b;
<add> }
<add> }
<add> public static class Bar {
<add> public String boo = "oranges";
<add> }
<add> }
<add>
<add> @Test
<add> public void compilingPropertyReferenceField() throws Exception {
<add> long interpretedTotal = 0, compiledTotal = 0, stime, etime;
<add> String interpretedResult = null, compiledResult = null;
<add>
<add> TestClass2 testdata = new TestClass2();
<add> Expression expression = parser.parseExpression("name");
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> expression.getValue(testdata,String.class);
<add> }
<add>
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> interpretedTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> compile(expression);
<add>
<add> log("timing compiled: ");
<add> expression.getValue(testdata,String.class);
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> compiledResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> compiledTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> assertEquals(interpretedResult,compiledResult);
<add> reportPerformance("property reference (field)",interpretedTotal, compiledTotal);
<add> }
<add>
<add> @Test
<add> public void compilingPropertyReferenceNestedField() throws Exception {
<add> long interpretedTotal = 0, compiledTotal = 0, stime, etime;
<add> String interpretedResult = null, compiledResult = null;
<add>
<add> TestClass2 testdata = new TestClass2();
<add>
<add> Expression expression = parser.parseExpression("foo.bar.boo");
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> expression.getValue(testdata,String.class);
<add> }
<add>
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> interpretedTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> compile(expression);
<add>
<add> log("timing compiled: ");
<add> expression.getValue(testdata,String.class);
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> compiledResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> compiledTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> assertEquals(interpretedResult,compiledResult);
<add> reportPerformance("property reference (nested field)",interpretedTotal, compiledTotal);
<add> }
<add>
<add> @Test
<add> public void compilingPropertyReferenceNestedMixedFieldGetter() throws Exception {
<add> long interpretedTotal = 0, compiledTotal = 0, stime, etime;
<add> String interpretedResult = null, compiledResult = null;
<add>
<add> TestClass2 testdata = new TestClass2();
<add> Expression expression = parser.parseExpression("foo.baz.boo");
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> expression.getValue(testdata,String.class);
<add> }
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> interpretedTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> compile(expression);
<add>
<add> log("timing compiled: ");
<add> expression.getValue(testdata,String.class);
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> compiledResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> compiledTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> assertEquals(interpretedResult,compiledResult);
<add> reportPerformance("nested property reference (mixed field/getter)",interpretedTotal, compiledTotal);
<add> }
<add>
<add> @Test
<add> public void compilingNestedMixedFieldPropertyReferenceMethodReference() throws Exception {
<add> long interpretedTotal = 0, compiledTotal = 0, stime, etime;
<add> String interpretedResult = null, compiledResult = null;
<add>
<add> TestClass2 testdata = new TestClass2();
<add> Expression expression = parser.parseExpression("foo.bay().boo");
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> expression.getValue(testdata,String.class);
<add> }
<add>
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> interpretedTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add> compile(expression);
<add>
<add> log("timing compiled: ");
<add> expression.getValue(testdata,String.class);
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> compiledResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> compiledTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add>
<add> }
<add> logln();
<add>
<add> assertEquals(interpretedResult,compiledResult);
<add> reportPerformance("nested reference (mixed field/method)",interpretedTotal, compiledTotal);
<add> }
<add>
<add> @Test
<add> public void compilingPropertyReferenceGetter() throws Exception {
<add> long interpretedTotal = 0, compiledTotal = 0, stime, etime;
<add> String interpretedResult = null, compiledResult = null;
<add>
<add> TestClass2 testdata = new TestClass2();
<add> Expression expression = parser.parseExpression("name2");
<add>
<add> // warmup
<add> for (int i=0;i<count;i++) {
<add> expression.getValue(testdata,String.class);
<add> }
<add>
<add> log("timing interpreted: ");
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> interpretedResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long interpretedSpeed = (etime - stime);
<add> interpretedTotal+=interpretedSpeed;
<add> log(interpretedSpeed+"ms ");
<add> }
<add> logln();
<add>
<add>
<add> compile(expression);
<add>
<add> log("timing compiled: ");
<add> expression.getValue(testdata,String.class);
<add> for (int iter=0;iter<iterations;iter++) {
<add> stime = System.currentTimeMillis();
<add> for (int i=0;i<count;i++) {
<add> compiledResult = expression.getValue(testdata,String.class);
<add> }
<add> etime = System.currentTimeMillis();
<add> long compiledSpeed = (etime - stime);
<add> compiledTotal+=compiledSpeed;
<add> log(compiledSpeed+"ms ");
<add>
<add> }
<add> logln();
<add>
<add> assertEquals(interpretedResult,compiledResult);
<add>
<add> reportPerformance("property reference (getter)", interpretedTotal, compiledTotal);
<add> if (compiledTotal>=interpretedTotal) {
<add> fail("Compiled version is slower than interpreted!");
<add> }
<add> }
<add>
<add> // ---
<add>
<add> private void reportPerformance(String title, long interpretedTotal, long compiledTotal) {
<add> double averageInterpreted = interpretedTotal/(iterations);
<add> double averageCompiled = compiledTotal/(iterations);
<add> double ratio = (averageCompiled/averageInterpreted)*100.0d;
<add> logln(">>"+title+": average for "+count+": compiled="+averageCompiled+"ms interpreted="+averageInterpreted+"ms: compiled takes "+((int)ratio)+"% of the interpreted time");
<add> if (averageCompiled>averageInterpreted) {
<add> fail("Compiled version took longer than interpreted! CompiledSpeed=~"+averageCompiled+
<add> "ms InterpretedSpeed="+averageInterpreted+"ms");
<add> }
<add> logln();
<add> }
<add>
<add> private void log(String message) {
<add> if (noisyTests) {
<add> System.out.print(message);
<add> }
<add> }
<add>
<add> private void logln(String... message) {
<add> if (noisyTests) {
<add> if (message!=null && message.length>0) {
<add> System.out.println(message[0]);
<add> } else {
<add> System.out.println();
<add> }
<add> }
<add> }
<add>
<add> private void compile(Expression expression) {
<add> assertTrue(SpelCompiler.compile(expression));
<add> }
<add>} | 47 |
Javascript | Javascript | add testid prop to button component | 5fdd6b33fa79189c124c122381bdbc35a855ae33 | <ide><path>Libraries/Components/Button.js
<ide> class Button extends React.Component {
<ide> color?: ?string,
<ide> accessibilityLabel?: ?string,
<ide> disabled?: ?boolean,
<add> testID?: ?string,
<ide> };
<ide>
<ide> static propTypes = {
<ide> class Button extends React.Component {
<ide> * Handler to be called when the user taps the button
<ide> */
<ide> onPress: React.PropTypes.func.isRequired,
<add> /**
<add> * Used to locate this view in end-to-end tests.
<add> */
<add> testID: React.PropTypes.string,
<ide> };
<ide>
<ide> render() {
<ide> class Button extends React.Component {
<ide> onPress,
<ide> title,
<ide> disabled,
<add> testID,
<ide> } = this.props;
<ide> const buttonStyles = [styles.button];
<ide> const textStyles = [styles.text];
<ide> class Button extends React.Component {
<ide> accessibilityComponentType="button"
<ide> accessibilityLabel={accessibilityLabel}
<ide> accessibilityTraits={['button']}
<add> testID={testID}
<ide> disabled={disabled}
<ide> onPress={onPress}>
<ide> <View style={buttonStyles}> | 1 |
Python | Python | remove redundant check if method=='delete' | c30712a5c8e89c7d3e235c72867288a4cb5c8c85 | <ide><path>rest_framework/renderers.py
<ide> def get_form(self, view, method, request):
<ide> fields[k] = forms.CharField()
<ide>
<ide> OnTheFlyForm = type("OnTheFlyForm", (forms.Form,), fields)
<del> if obj and not view.request.method == 'DELETE': # Don't fill in the form when the object is deleted
<add> if obj:
<ide> data = serializer.data
<ide> form_instance = OnTheFlyForm(data)
<ide> return form_instance | 1 |
Mixed | Javascript | simplify test skipping | 2d2986ae72f2f5c63d95a94f05fa996d9f0609f1 | <ide><path>test/abort/test-abort-backtrace.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('Backtraces unimplemented on Windows.');
<add>
<ide> const assert = require('assert');
<ide> const cp = require('child_process');
<ide>
<del>if (common.isWindows) {
<del> common.skip('Backtraces unimplemented on Windows.');
<del> return;
<del>}
<del>
<ide> if (process.argv[2] === 'child') {
<ide> process.abort();
<ide> } else {
<ide><path>test/addons/load-long-path/test.js
<ide> 'use strict';
<ide> const common = require('../../common');
<add>if (common.isWOW64)
<add> common.skip('doesn\'t work on WOW64');
<add>
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide> const assert = require('assert');
<ide>
<del>if (common.isWOW64) {
<del> common.skip('doesn\'t work on WOW64');
<del> return;
<del>}
<del>
<ide> common.refreshTmpDir();
<ide>
<ide> // make a path that is more than 260 chars long.
<ide><path>test/addons/openssl-binding/test.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> process.exit(0);
<del>}
<add>
<ide> const assert = require('assert');
<ide> const binding = require(`./build/${common.buildType}/binding`);
<ide> const bytes = new Uint8Array(1024);
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<add>const skipMessage = 'intensive toString tests due to memory confinements';
<add>if (!common.enoughTestMem)
<add> common.skip(skipMessage);
<add>
<ide> const binding = require(`./build/${common.buildType}/binding`);
<ide> const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength;
<ide>
<del>const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<del> common.skip(skipMessage);
<del> return;
<del>}
<del>
<ide> let buf;
<ide> try {
<ide> buf = Buffer.allocUnsafe(kStringMaxLength);
<ide> } catch (e) {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> const maxString = buf.toString('latin1');
<ide> assert.strictEqual(maxString.length, kStringMaxLength);
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> assert.throws(function() {
<ide> buf.toString('ascii');
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> assert.throws(function() {
<ide> buf.toString('base64');
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> assert.throws(function() {
<ide> buf.toString('latin1');
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> assert.throws(function() {
<ide> buf.toString('hex');
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> assert.throws(function() {
<ide> buf.toString();
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> const maxString = buf.toString('utf16le');
<ide> assert.strictEqual(maxString.length, (kStringMaxLength + 2) / 2);
<ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<del>const binding = require(`./build/${common.buildType}/binding`);
<del>const assert = require('assert');
<del>
<ide> const skipMessage = 'intensive toString tests due to memory confinements';
<del>if (!common.enoughTestMem) {
<add>if (!common.enoughTestMem)
<ide> common.skip(skipMessage);
<del> return;
<del>}
<add>
<add>const binding = require(`./build/${common.buildType}/binding`);
<add>const assert = require('assert');
<ide>
<ide> // v8 fails silently if string length > v8::String::kMaxLength
<ide> // v8::String::kMaxLength defined in v8.h
<ide> try {
<ide> // If the exception is not due to memory confinement then rethrow it.
<ide> if (e.message !== 'Array buffer allocation failed') throw (e);
<ide> common.skip(skipMessage);
<del> return;
<ide> }
<ide>
<ide> // Ensure we have enough memory available for future allocations to succeed.
<del>if (!binding.ensureAllocation(2 * kStringMaxLength)) {
<add>if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<del> return;
<del>}
<ide>
<ide> assert.throws(function() {
<ide> buf.toString('utf16le');
<ide><path>test/addons/symlinked-module/test.js
<ide> try {
<ide> } catch (err) {
<ide> if (err.code !== 'EPERM') throw err;
<ide> common.skip('module identity test (no privs for symlinks)');
<del> return;
<ide> }
<ide>
<ide> const sub = require('./submodule');
<ide><path>test/async-hooks/test-connection.ssl.js
<ide> 'use strict';
<ide>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const initHooks = require('./init-hooks');
<ide> const tick = require('./tick');
<del>const common = require('../common');
<ide> const assert = require('assert');
<ide> const { checkInvocations } = require('./hook-checks');
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>
<ide> const tls = require('tls');
<ide> const Connection = process.binding('crypto').Connection;
<ide> const hooks = initHooks();
<ide><path>test/async-hooks/test-crypto-pbkdf2.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tick = require('./tick');
<ide> const initHooks = require('./init-hooks');
<ide><path>test/async-hooks/test-crypto-randomBytes.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tick = require('./tick');
<ide> const initHooks = require('./init-hooks');
<ide><path>test/async-hooks/test-graph.connection.js
<ide> 'use strict';
<ide>
<del>const initHooks = require('./init-hooks');
<ide> const common = require('../common');
<del>const verifyGraph = require('./verify-graph');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const initHooks = require('./init-hooks');
<add>const verifyGraph = require('./verify-graph');
<ide>
<ide> const tls = require('tls');
<ide> const Connection = process.binding('crypto').Connection;
<ide><path>test/async-hooks/test-graph.shutdown.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const initHooks = require('./init-hooks');
<del>const verifyGraph = require('./verify-graph');
<del>
<del>if (!common.hasIPv6) {
<add>if (!common.hasIPv6)
<ide> common.skip('IPv6 support required');
<del> return;
<del>}
<ide>
<add>const initHooks = require('./init-hooks');
<add>const verifyGraph = require('./verify-graph');
<ide> const net = require('net');
<ide>
<ide> const hooks = initHooks();
<ide><path>test/async-hooks/test-graph.tcp.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const initHooks = require('./init-hooks');
<del>const verifyGraph = require('./verify-graph');
<del>
<del>if (!common.hasIPv6) {
<add>if (!common.hasIPv6)
<ide> common.skip('IPv6 support required');
<del> return;
<del>}
<ide>
<add>const initHooks = require('./init-hooks');
<add>const verifyGraph = require('./verify-graph');
<ide> const net = require('net');
<ide>
<ide> const hooks = initHooks();
<ide><path>test/async-hooks/test-graph.tls-write.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const initHooks = require('./init-hooks');
<del>const verifyGraph = require('./verify-graph');
<del>const fs = require('fs');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.hasIPv6) {
<add>if (!common.hasIPv6)
<ide> common.skip('IPv6 support required');
<del> return;
<del>}
<ide>
<add>const initHooks = require('./init-hooks');
<add>const verifyGraph = require('./verify-graph');
<add>const fs = require('fs');
<ide> const tls = require('tls');
<add>
<ide> const hooks = initHooks();
<ide> hooks.enable();
<ide>
<ide><path>test/async-hooks/test-tcpwrap.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasIPv6)
<add> common.skip('IPv6 support required');
<add>
<ide> const assert = require('assert');
<ide> const tick = require('./tick');
<ide> const initHooks = require('./init-hooks');
<ide> const { checkInvocations } = require('./hook-checks');
<del>
<del>if (!common.hasIPv6) {
<del> common.skip('IPv6 support required');
<del> return;
<del>}
<del>
<ide> const net = require('net');
<ide>
<ide> let tcp1, tcp2, tcp3;
<ide><path>test/async-hooks/test-tlswrap.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const tick = require('./tick');
<ide> const initHooks = require('./init-hooks');
<ide> const fs = require('fs');
<ide> const { checkInvocations } = require('./hook-checks');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>
<ide> const tls = require('tls');
<add>
<ide> const hooks = initHooks();
<ide> hooks.enable();
<ide>
<ide><path>test/async-hooks/test-ttywrap.writestream.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>
<add>const tty_fd = common.getTTYfd();
<add>if (tty_fd < 0)
<add> common.skip('no valid TTY fd available');
<add>
<ide> const assert = require('assert');
<ide> const tick = require('./tick');
<ide> const initHooks = require('./init-hooks');
<ide> const { checkInvocations } = require('./hook-checks');
<del>const tty_fd = common.getTTYfd();
<ide>
<del>if (tty_fd < 0)
<del> return common.skip('no valid TTY fd available');
<ide> const ttyStream = (() => {
<ide> try {
<ide> return new (require('tty').WriteStream)(tty_fd);
<ide> const ttyStream = (() => {
<ide> }
<ide> })();
<ide> if (ttyStream === null)
<del> return common.skip('no valid TTY fd available');
<add> common.skip('no valid TTY fd available');
<ide>
<ide> const hooks = initHooks();
<ide> hooks.enable();
<ide><path>test/async-hooks/test-writewrap.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const initHooks = require('./init-hooks');
<ide> const fs = require('fs');
<ide> const { checkInvocations } = require('./hook-checks');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>
<ide> const tls = require('tls');
<add>
<ide> const hooks = initHooks();
<ide> hooks.enable();
<ide>
<ide><path>test/common/README.md
<ide> Path to the test sock.
<ide>
<ide> Port tests are running on.
<ide>
<add>### printSkipMessage(msg)
<add>* `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<add>
<add>Logs '1..0 # Skipped: ' + `msg`
<add>
<ide> ### refreshTmpDir
<ide> * return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<ide>
<ide> Path to the 'root' directory. either `/` or `c:\\` (windows)
<ide> ### skip(msg)
<ide> * `msg` [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<ide>
<del>Logs '1..0 # Skipped: ' + `msg`
<add>Logs '1..0 # Skipped: ' + `msg` and exits with exit code `0`.
<ide>
<ide> ### spawnPwd(options)
<ide> * `options` [<Object>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
<ide><path>test/common/index.js
<ide> exports.mustNotCall = function(msg) {
<ide> };
<ide> };
<ide>
<del>exports.skip = function(msg) {
<add>exports.printSkipMessage = function(msg) {
<ide> console.log(`1..0 # Skipped: ${msg}`);
<ide> };
<ide>
<add>exports.skip = function(msg) {
<add> exports.printSkipMessage(msg);
<add> process.exit(0);
<add>};
<add>
<ide> // A stream to push an array into a REPL
<ide> function ArrayStream() {
<ide> this.run = function(data) {
<ide> exports.expectsError = function expectsError({code, type, message}) {
<ide> exports.skipIfInspectorDisabled = function skipIfInspectorDisabled() {
<ide> if (process.config.variables.v8_enable_inspector === 0) {
<ide> exports.skip('V8 inspector is disabled');
<del> process.exit(0);
<ide> }
<ide> };
<ide>
<ide><path>test/doctool/test-doctool-html.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const fs = require('fs');
<del>const path = require('path');
<del>
<ide> // The doctool currently uses js-yaml from the tool/eslint/ tree.
<ide> try {
<ide> require('../../tools/eslint/node_modules/js-yaml');
<ide> } catch (e) {
<del> return common.skip('missing js-yaml (eslint not present)');
<add> common.skip('missing js-yaml (eslint not present)');
<ide> }
<ide>
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<ide> const processIncludes = require('../../tools/doc/preprocess.js');
<ide> const html = require('../../tools/doc/html.js');
<ide>
<ide><path>test/doctool/test-doctool-json.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const fs = require('fs');
<del>const path = require('path');
<del>
<ide> // The doctool currently uses js-yaml from the tool/eslint/ tree.
<ide> try {
<ide> require('../../tools/eslint/node_modules/js-yaml');
<ide> } catch (e) {
<del> return common.skip('missing js-yaml (eslint not present)');
<add> common.skip('missing js-yaml (eslint not present)');
<ide> }
<ide>
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<ide> const json = require('../../tools/doc/json.js');
<ide>
<ide> // Outputs valid json with the expected fields when given simple markdown
<ide><path>test/fixtures/tls-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const fs = require('fs');
<del>const join = require('path').join;
<ide> // Check if Node was compiled --without-ssl and if so exit early
<ide> // as the require of tls will otherwise throw an Error.
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> process.exit(0);
<del>}
<add>
<add>const fs = require('fs');
<add>const join = require('path').join;
<ide> const tls = require('tls');
<ide> const util = require('util');
<ide>
<ide><path>test/inspector/test-inspector-ip-detection.js
<ide> const os = require('os');
<ide>
<ide> const ip = pickIPv4Address();
<ide>
<del>if (!ip) {
<add>if (!ip)
<ide> common.skip('No IP address found');
<del> return;
<del>}
<ide>
<ide> function checkListResponse(instance, err, response) {
<ide> assert.ifError(err);
<ide> function checkListResponse(instance, err, response) {
<ide> function checkError(instance, error) {
<ide> // Some OSes will not allow us to connect
<ide> if (error.code === 'EHOSTUNREACH') {
<del> common.skip('Unable to connect to self');
<add> common.printSkipMessage('Unable to connect to self');
<ide> } else {
<ide> throw error;
<ide> }
<ide><path>test/internet/test-dgram-broadcast-multi-process.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.inFreeBSDJail)
<add> common.skip('in a FreeBSD jail');
<add>
<ide> const assert = require('assert');
<ide> const dgram = require('dgram');
<ide> const util = require('util');
<ide> const messages = [
<ide> Buffer.from('Fourth message to send')
<ide> ];
<ide>
<del>if (common.inFreeBSDJail) {
<del> common.skip('in a FreeBSD jail');
<del> return;
<del>}
<del>
<ide> let bindAddress = null;
<ide>
<ide> // Take the first non-internal interface as the address for binding.
<ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>// Skip test in FreeBSD jails.
<add>if (common.inFreeBSDJail)
<add> common.skip('In a FreeBSD jail');
<add>
<ide> const assert = require('assert');
<ide> const dgram = require('dgram');
<ide> const fork = require('child_process').fork;
<ide> const listeners = 3;
<ide> let listening, sendSocket, done, timer, dead;
<ide>
<ide>
<del>// Skip test in FreeBSD jails.
<del>if (common.inFreeBSDJail) {
<del> common.skip('In a FreeBSD jail');
<del> return;
<del>}
<del>
<ide> function launchChildProcess() {
<ide> const worker = fork(__filename, ['child']);
<ide> workers[worker.pid] = worker;
<ide><path>test/internet/test-dns-ipv6.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasIPv6)
<add> common.skip('this test, no IPv6 support');
<add>
<ide> const assert = require('assert');
<ide> const dns = require('dns');
<ide> const net = require('net');
<ide> const isIPv6 = net.isIPv6;
<ide> let running = false;
<ide> const queue = [];
<ide>
<del>if (!common.hasIPv6) {
<del> common.skip('this test, no IPv6 support');
<del> return;
<del>}
<del>
<ide> function TEST(f) {
<ide> function next() {
<ide> const f = queue.shift();
<ide><path>test/internet/test-http-https-default-ports.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const https = require('https');
<ide>
<ide> const http = require('http');
<ide><path>test/internet/test-tls-add-ca-cert.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> // Test interaction of compiled-in CAs with user-provided CAs.
<ide>
<ide><path>test/internet/test-tls-connnect-melissadata.js
<ide> // certification between Starfield Class 2 and ValiCert Class 2
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const tls = require('tls');
<ide> const socket = tls.connect(443, 'address.melissadata.net', function() {
<ide><path>test/internet/test-tls-reuse-host-from-socket.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> const net = require('net');
<ide><path>test/known_issues/test-cwd-enoent-file.js
<ide> if (common.isSunOS || common.isWindows || common.isAix) {
<ide> // The current working directory cannot be removed on these platforms.
<ide> // Change this to common.skip() when this is no longer a known issue test.
<ide> assert.fail('cannot rmdir current working directory');
<del> return;
<ide> }
<ide>
<ide> const cp = require('child_process');
<ide><path>test/parallel/test-async-wrap-GH13045.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> // Refs: https://github.com/nodejs/node/issues/13045
<ide> // An HTTP Agent reuses a TLSSocket, and makes a failed call to `asyncReset`.
<ide><path>test/parallel/test-async-wrap-uncaughtexception.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const async_hooks = require('async_hooks');
<ide> const call_log = [0, 0, 0, 0]; // [before, callback, exception, after];
<ide><path>test/parallel/test-benchmark-crypto.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (common.hasFipsCrypto) {
<add>if (common.hasFipsCrypto)
<ide> common.skip('some benchmarks are FIPS-incompatible');
<del> return;
<del>}
<ide>
<ide> // Minimal test for crypto benchmarks. This makes sure the benchmarks aren't
<ide> // horribly broken but nothing more than that.
<ide><path>test/parallel/test-buffer-alloc.js
<ide> if (common.hasCrypto) {
<ide> crypto.createHash('sha1').update(b2).digest('hex')
<ide> );
<ide> } else {
<del> common.skip('missing crypto');
<add> common.printSkipMessage('missing crypto');
<ide> }
<ide>
<ide> const ps = Buffer.poolSize;
<ide><path>test/parallel/test-child-process-fork-dgram.js
<ide> */
<ide>
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('Sending dgram sockets to child processes is not supported');
<add>
<ide> const dgram = require('dgram');
<ide> const fork = require('child_process').fork;
<ide> const assert = require('assert');
<ide>
<del>if (common.isWindows) {
<del> common.skip('Sending dgram sockets to child processes is not supported');
<del> return;
<del>}
<del>
<ide> if (process.argv[2] === 'child') {
<ide> let childServer;
<ide>
<ide><path>test/parallel/test-cli-node-options.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> if (process.config.variables.node_without_node_options)
<del> return common.skip('missing NODE_OPTIONS support');
<add> common.skip('missing NODE_OPTIONS support');
<ide>
<ide> // Test options specified by env variable.
<ide>
<ide><path>test/parallel/test-cluster-bind-privileged-port.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const cluster = require('cluster');
<del>const net = require('net');
<del>
<del>if (common.isWindows) {
<add>if (common.isWindows)
<ide> common.skip('not reliable on Windows.');
<del> return;
<del>}
<ide>
<del>if (process.getuid() === 0) {
<add>if (process.getuid() === 0)
<ide> common.skip('Test is not supposed to be run as root.');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<add>const cluster = require('cluster');
<add>const net = require('net');
<ide>
<ide> if (cluster.isMaster) {
<ide> cluster.fork().on('exit', common.mustCall((exitCode) => {
<ide><path>test/parallel/test-cluster-dgram-1.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('dgram clustering is currently not supported on Windows.');
<add>
<ide> const NUM_WORKERS = 4;
<ide> const PACKETS_PER_WORKER = 10;
<ide>
<ide> const assert = require('assert');
<ide> const cluster = require('cluster');
<ide> const dgram = require('dgram');
<ide>
<del>
<del>if (common.isWindows) {
<del> common.skip('dgram clustering is currently not supported on Windows.');
<del> return;
<del>}
<del>
<ide> if (cluster.isMaster)
<ide> master();
<ide> else
<ide><path>test/parallel/test-cluster-dgram-2.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('dgram clustering is currently not supported on Windows.');
<add>
<ide> const NUM_WORKERS = 4;
<ide> const PACKETS_PER_WORKER = 10;
<ide>
<ide> const cluster = require('cluster');
<ide> const dgram = require('dgram');
<ide> const assert = require('assert');
<ide>
<del>
<del>if (common.isWindows) {
<del> common.skip('dgram clustering is currently not supported on Windows.');
<del> return;
<del>}
<del>
<ide> if (cluster.isMaster)
<ide> master();
<ide> else
<ide><path>test/parallel/test-cluster-dgram-reuse.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('dgram clustering is currently not supported on windows.');
<add>
<ide> const assert = require('assert');
<ide> const cluster = require('cluster');
<ide> const dgram = require('dgram');
<ide>
<del>if (common.isWindows) {
<del> common.skip('dgram clustering is currently not supported on windows.');
<del> return;
<del>}
<del>
<ide> if (cluster.isMaster) {
<ide> cluster.fork().on('exit', common.mustCall((code) => {
<ide> assert.strictEqual(code, 0);
<ide><path>test/parallel/test-cluster-disconnect-race.js
<ide> // Ref: https://github.com/nodejs/node/issues/4205
<ide>
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('This test does not apply to Windows.');
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const cluster = require('cluster');
<ide>
<del>if (common.isWindows) {
<del> common.skip('This test does not apply to Windows.');
<del> return;
<del>}
<del>
<ide> cluster.schedulingPolicy = cluster.SCHED_NONE;
<ide>
<ide> if (cluster.isMaster) {
<ide><path>test/parallel/test-cluster-disconnect-unshared-udp.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (common.isWindows) {
<add>if (common.isWindows)
<ide> common.skip('on windows, because clustered dgram is ENOTSUP');
<del> return;
<del>}
<ide>
<ide> const cluster = require('cluster');
<ide> const dgram = require('dgram');
<ide><path>test/parallel/test-cluster-http-pipe.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const cluster = require('cluster');
<del>const http = require('http');
<del>
<ide> if (common.isWindows) {
<ide> common.skip(
<ide> 'It is not possible to send pipe handles over the IPC pipe on Windows');
<del> return;
<ide> }
<ide>
<add>const assert = require('assert');
<add>const cluster = require('cluster');
<add>const http = require('http');
<add>
<ide> if (cluster.isMaster) {
<ide> common.refreshTmpDir();
<ide> const worker = cluster.fork();
<ide><path>test/parallel/test-cluster-shared-handle-bind-privileged-port.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const cluster = require('cluster');
<del>const net = require('net');
<del>
<del>if (common.isWindows) {
<add>if (common.isWindows)
<ide> common.skip('not reliable on Windows');
<del> return;
<del>}
<ide>
<del>if (process.getuid() === 0) {
<add>if (process.getuid() === 0)
<ide> common.skip('as this test should not be run as `root`');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<add>const cluster = require('cluster');
<add>const net = require('net');
<ide>
<ide> if (cluster.isMaster) {
<ide> // Master opens and binds the socket and shares it with the worker.
<ide><path>test/parallel/test-crypto-authenticated.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> crypto.DEFAULT_ENCODING = 'buffer';
<ide> for (const i in TEST_CASES) {
<ide> const test = TEST_CASES[i];
<ide>
<ide> if (!ciphers.includes(test.algo)) {
<del> common.skip(`unsupported ${test.algo} test`);
<add> common.printSkipMessage(`unsupported ${test.algo} test`);
<ide> continue;
<ide> }
<ide>
<ide> if (common.hasFipsCrypto && test.iv.length < 24) {
<del> common.skip('IV len < 12 bytes unsupported in FIPS mode');
<add> common.printSkipMessage('IV len < 12 bytes unsupported in FIPS mode');
<ide> continue;
<ide> }
<ide>
<ide><path>test/parallel/test-crypto-binary-default.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-crypto-certificate.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> crypto.DEFAULT_ENCODING = 'buffer';
<ide><path>test/parallel/test-crypto-cipher-decipher.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>if (common.hasFipsCrypto) {
<add>
<add>if (common.hasFipsCrypto)
<ide> common.skip('not supported in FIPS mode');
<del> return;
<del>}
<add>
<ide> const crypto = require('crypto');
<ide> const assert = require('assert');
<ide>
<ide><path>test/parallel/test-crypto-cipheriv-decipheriv.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> function testCipher1(key, iv) {
<ide><path>test/parallel/test-crypto-deprecated.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-crypto-dh-odd-key.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> function test() {
<ide><path>test/parallel/test-crypto-dh.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<add>
<ide> const DH_NOT_SUITABLE_GENERATOR = crypto.constants.DH_NOT_SUITABLE_GENERATOR;
<ide>
<ide> // Test Diffie-Hellman with two parties sharing a secret,
<ide><path>test/parallel/test-crypto-domain.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const domain = require('domain');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const crypto = require('crypto');
<ide>
<ide> function test(fn) {
<ide><path>test/parallel/test-crypto-domains.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const domain = require('domain');
<ide> const assert = require('assert');
<add>const crypto = require('crypto');
<add>
<ide> const d = domain.create();
<ide> const expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes'];
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>const crypto = require('crypto');
<del>
<ide> d.on('error', common.mustCall(function(e) {
<ide> assert.strictEqual(e.message, expect.shift());
<ide> }, 3));
<ide><path>test/parallel/test-crypto-ecb.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>if (common.hasFipsCrypto) {
<add>
<add>if (common.hasFipsCrypto)
<ide> common.skip('BF-ECB is not FIPS 140-2 compatible');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> crypto.DEFAULT_ENCODING = 'buffer';
<ide><path>test/parallel/test-crypto-engine.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-crypto-fips.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const spawnSync = require('child_process').spawnSync;
<ide> const path = require('path');
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>
<ide> const FIPS_ENABLED = 1;
<ide> const FIPS_DISABLED = 0;
<ide> const FIPS_ERROR_STRING = 'Error: Cannot set FIPS mode';
<ide><path>test/parallel/test-crypto-from-binary.js
<ide>
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> const EXTERN_APEX = 0xFBEE9;
<ide><path>test/parallel/test-crypto-hash-stream-pipe.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-crypto-hash.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const crypto = require('crypto');
<ide>
<ide> // Test hashing
<ide><path>test/parallel/test-crypto-hmac.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> // Test for binding layer robustness
<ide><path>test/parallel/test-crypto-lazy-transform-writable.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide> const Stream = require('stream');
<ide><path>test/parallel/test-crypto-padding-aes256.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> crypto.DEFAULT_ENCODING = 'buffer';
<ide><path>test/parallel/test-crypto-padding.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide> crypto.DEFAULT_ENCODING = 'buffer';
<ide><path>test/parallel/test-crypto-pbkdf2.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-crypto-random.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide>
<ide><path>test/parallel/test-crypto-rsa-dsa.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>const constants = require('crypto').constants;
<ide> const crypto = require('crypto');
<ide>
<add>const constants = crypto.constants;
<ide> const fixtDir = common.fixturesDir;
<ide>
<ide> // Test certificates
<ide><path>test/parallel/test-crypto-sign-verify.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide> const exec = require('child_process').exec;
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const crypto = require('crypto');
<ide>
<ide> // Test certificates
<ide> const modSize = 1024;
<ide>
<ide> // RSA-PSS Sign test by verifying with 'openssl dgst -verify'
<ide> {
<del> if (!common.opensslCli) {
<add> if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del> }
<ide>
<ide> const pubfile = path.join(common.fixturesDir, 'keys/rsa_public_2048.pem');
<ide> const privfile = path.join(common.fixturesDir, 'keys/rsa_private_2048.pem');
<ide><path>test/parallel/test-crypto-stream.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const stream = require('stream');
<ide> const util = require('util');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const crypto = require('crypto');
<ide>
<ide> // Small stream to buffer converter
<ide><path>test/parallel/test-crypto-verify-failure.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const crypto = require('crypto');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-crypto.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-cwd-enoent-preload.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>// Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX.
<add>if (common.isSunOS || common.isWindows || common.isAix)
<add> common.skip('cannot rmdir current working directory');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>// Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX.
<del>if (common.isSunOS || common.isWindows || common.isAix) {
<del> common.skip('cannot rmdir current working directory');
<del> return;
<del>}
<del>
<ide> const dirname = `${common.tmpDir}/cwd-does-not-exist-${process.pid}`;
<ide> const abspathFile = require('path').join(common.fixturesDir, 'a.js');
<ide> common.refreshTmpDir();
<ide><path>test/parallel/test-cwd-enoent-repl.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>// Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX.
<add>if (common.isSunOS || common.isWindows || common.isAix)
<add> common.skip('cannot rmdir current working directory');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>// Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX.
<del>if (common.isSunOS || common.isWindows || common.isAix) {
<del> common.skip('cannot rmdir current working directory');
<del> return;
<del>}
<del>
<ide> const dirname = `${common.tmpDir}/cwd-does-not-exist-${process.pid}`;
<ide> common.refreshTmpDir();
<ide> fs.mkdirSync(dirname);
<ide><path>test/parallel/test-cwd-enoent.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>// Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX.
<add>if (common.isSunOS || common.isWindows || common.isAix)
<add> common.skip('cannot rmdir current working directory');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>// Fails with EINVAL on SmartOS, EBUSY on Windows, EBUSY on AIX.
<del>if (common.isSunOS || common.isWindows || common.isAix) {
<del> common.skip('cannot rmdir current working directory');
<del> return;
<del>}
<del>
<ide> const dirname = `${common.tmpDir}/cwd-does-not-exist-${process.pid}`;
<ide> common.refreshTmpDir();
<ide> fs.mkdirSync(dirname);
<ide><path>test/parallel/test-debug-usage.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>
<ide> const child = spawn(process.execPath, ['debug']);
<ide> child.stderr.setEncoding('utf8');
<ide>
<ide><path>test/parallel/test-dgram-bind-default-address.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const dgram = require('dgram');
<del>
<ide> // skip test in FreeBSD jails since 0.0.0.0 will resolve to default interface
<del>if (common.inFreeBSDJail) {
<add>if (common.inFreeBSDJail)
<ide> common.skip('In a FreeBSD jail');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<add>const dgram = require('dgram');
<ide>
<ide> dgram.createSocket('udp4').bind(0, common.mustCall(function() {
<ide> assert.strictEqual(typeof this.address().port, 'number');
<ide> dgram.createSocket('udp4').bind(0, common.mustCall(function() {
<ide> }));
<ide>
<ide> if (!common.hasIPv6) {
<del> common.skip('udp6 part of test, because no IPv6 support');
<add> common.printSkipMessage('udp6 part of test, because no IPv6 support');
<ide> return;
<ide> }
<ide>
<ide><path>test/parallel/test-dgram-cluster-close-during-bind.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('dgram clustering is currently not supported on windows.');
<add>
<ide> const assert = require('assert');
<ide> const cluster = require('cluster');
<ide> const dgram = require('dgram');
<ide>
<del>if (common.isWindows) {
<del> common.skip('dgram clustering is currently not supported on windows.');
<del> return;
<del>}
<del>
<ide> if (cluster.isMaster) {
<ide> cluster.fork();
<ide> } else {
<ide><path>test/parallel/test-dgram-send-empty-array.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (common.isOSX) {
<add>if (common.isOSX)
<ide> common.skip('because of 17894467 Apple bug');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const dgram = require('dgram');
<ide><path>test/parallel/test-dgram-send-empty-buffer.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (common.isOSX) {
<add>if (common.isOSX)
<ide> common.skip('because of 17894467 Apple bug');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const dgram = require('dgram');
<ide>
<ide> const client = dgram.createSocket('udp4');
<ide><path>test/parallel/test-dgram-send-empty-packet.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (common.isOSX) {
<add>if (common.isOSX)
<ide> common.skip('because of 17894467 Apple bug');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const dgram = require('dgram');
<ide>
<ide> const client = dgram.createSocket('udp4');
<ide><path>test/parallel/test-dgram-udp6-send-default-host.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasIPv6)
<add> common.skip('no IPv6 support');
<add>
<ide> const assert = require('assert');
<ide> const dgram = require('dgram');
<ide>
<del>if (!common.hasIPv6) {
<del> common.skip('no IPv6 support');
<del> return;
<del>}
<del>
<ide> const client = dgram.createSocket('udp6');
<ide>
<ide> const toSend = [Buffer.alloc(256, 'x'),
<ide><path>test/parallel/test-dh-padding.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('node compiled without OpenSSL.');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-domain-crypto.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('node compiled without OpenSSL.');
<del> return;
<del>}
<ide>
<ide> const crypto = require('crypto');
<ide>
<ide><path>test/parallel/test-dsa-fips-invalid-key.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasFipsCrypto) {
<add>if (!common.hasFipsCrypto)
<ide> common.skip('node compiled without FIPS OpenSSL.');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const crypto = require('crypto');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-fs-long-path.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.isWindows)
<add> common.skip('this test is Windows-specific.');
<add>
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide> const assert = require('assert');
<ide>
<del>if (!common.isWindows) {
<del> common.skip('this test is Windows-specific.');
<del> return;
<del>}
<del>
<ide> // make a path that will be at least 260 chars long.
<ide> const fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1);
<ide> const fileName = path.join(common.tmpDir, 'x'.repeat(fileNameLen));
<ide><path>test/parallel/test-fs-read-file-sync-hostname.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.isLinux)
<add> common.skip('Test is linux specific.');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide>
<del>if (!common.isLinux) {
<del> common.skip('Test is linux specific.');
<del> return;
<del>}
<del>
<ide> // Test to make sure reading a file under the /proc directory works. See:
<ide> // https://groups.google.com/forum/#!topic/nodejs-dev/rxZ_RoH1Gn0
<ide> const hostname = fs.readFileSync('/proc/sys/kernel/hostname');
<ide><path>test/parallel/test-fs-readdir-ucs2.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.isLinux)
<add> common.skip('Test is linux specific.');
<add>
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide> const assert = require('assert');
<ide>
<del>if (!common.isLinux) {
<del> common.skip('Test is linux specific.');
<del> return;
<del>}
<del>
<ide> common.refreshTmpDir();
<ide> const filename = '\uD83D\uDC04';
<ide> const root = Buffer.from(`${common.tmpDir}${path.sep}`);
<ide><path>test/parallel/test-fs-readfile-error.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const exec = require('child_process').exec;
<del>const path = require('path');
<del>
<ide> // `fs.readFile('/')` does not fail on FreeBSD, because you can open and read
<ide> // the directory there.
<del>if (common.isFreeBSD) {
<add>if (common.isFreeBSD)
<ide> common.skip('platform not supported.');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<add>const exec = require('child_process').exec;
<add>const path = require('path');
<ide>
<ide> function test(env, cb) {
<ide> const filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js');
<ide><path>test/parallel/test-fs-readfile-pipe-large.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const path = require('path');
<ide>
<ide> // simulate `cat readfile.js | node readfile.js`
<ide>
<del>if (common.isWindows || common.isAix) {
<add>if (common.isWindows || common.isAix)
<ide> common.skip(`No /dev/stdin on ${process.platform}.`);
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<add>const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> if (process.argv[2] === 'child') {
<ide><path>test/parallel/test-fs-readfile-pipe.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<ide>
<ide> // simulate `cat readfile.js | node readfile.js`
<ide>
<del>if (common.isWindows || common.isAix) {
<add>if (common.isWindows || common.isAix)
<ide> common.skip(`No /dev/stdin on ${process.platform}.`);
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const fs = require('fs');
<ide>
<ide> const dataExpected = fs.readFileSync(__filename, 'utf8');
<ide><path>test/parallel/test-fs-readfilesync-pipe-large.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const path = require('path');
<ide>
<ide> // simulate `cat readfile.js | node readfile.js`
<ide>
<del>if (common.isWindows || common.isAix) {
<add>if (common.isWindows || common.isAix)
<ide> common.skip(`No /dev/stdin on ${process.platform}.`);
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<add>const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> if (process.argv[2] === 'child') {
<ide><path>test/parallel/test-fs-realpath-on-substed-drive.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.isWindows)
<add> common.skip('Test for Windows only');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const spawnSync = require('child_process').spawnSync;
<ide>
<del>if (!common.isWindows) {
<del> common.skip('Test for Windows only');
<del> return;
<del>}
<ide> let result;
<ide>
<ide> // create a subst drive
<ide> for (i = 0; i < driveLetters.length; ++i) {
<ide> if (result.status === 0)
<ide> break;
<ide> }
<del>if (i === driveLetters.length) {
<add>if (i === driveLetters.length)
<ide> common.skip('Cannot create subst drive');
<del> return;
<del>}
<ide>
<ide> // schedule cleanup (and check if all callbacks where called)
<ide> process.on('exit', function() {
<ide><path>test/parallel/test-fs-realpath-pipe.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (common.isWindows || common.isAix) {
<add>if (common.isWindows || common.isAix)
<ide> common.skip(`No /dev/stdin on ${process.platform}.`);
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide>
<ide><path>test/parallel/test-fs-realpath.js
<ide> function test_simple_error_callback(cb) {
<ide> function test_simple_relative_symlink(callback) {
<ide> console.log('test_simple_relative_symlink');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide> const entry = `${tmpDir}/symlink`;
<ide> function test_simple_absolute_symlink(callback) {
<ide> function test_deep_relative_file_symlink(callback) {
<ide> console.log('test_deep_relative_file_symlink');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide>
<ide> function test_deep_relative_file_symlink(callback) {
<ide> function test_deep_relative_dir_symlink(callback) {
<ide> console.log('test_deep_relative_dir_symlink');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide> const expected = path.join(common.fixturesDir, 'cycles', 'folder');
<ide> function test_deep_relative_dir_symlink(callback) {
<ide> function test_cyclic_link_protection(callback) {
<ide> console.log('test_cyclic_link_protection');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide> const entry = path.join(tmpDir, '/cycles/realpath-3a');
<ide> function test_cyclic_link_protection(callback) {
<ide> function test_cyclic_link_overprotection(callback) {
<ide> console.log('test_cyclic_link_overprotection');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide> const cycles = `${tmpDir}/cycles`;
<ide> function test_cyclic_link_overprotection(callback) {
<ide> function test_relative_input_cwd(callback) {
<ide> console.log('test_relative_input_cwd');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide>
<ide> function test_deep_symlink_mix(callback) {
<ide> if (common.isWindows) {
<ide> // This one is a mix of files and directories, and it's quite tricky
<ide> // to get the file/dir links sorted out correctly.
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide>
<ide> assertEqualPath(
<ide> function test_up_multiple(cb) {
<ide> console.error('test_up_multiple');
<ide> if (skipSymlinks) {
<del> common.skip('symlink test (no privs)');
<add> common.printSkipMessage('symlink test (no privs)');
<ide> return runNextTest();
<ide> }
<ide> function cleanup() {
<ide><path>test/parallel/test-fs-symlink.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.canCreateSymLink())
<add> common.skip('insufficient privileges');
<add>
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> let linkTime;
<ide> let fileTime;
<ide>
<del>if (!common.canCreateSymLink()) {
<del> common.skip('insufficient privileges');
<del> return;
<del>}
<del>
<ide> common.refreshTmpDir();
<ide>
<ide> // test creating and reading symbolic link
<ide><path>test/parallel/test-fs-watch-encoding.js
<ide> // On SmartOS, the watch events fire but the filename is null.
<ide>
<ide> const common = require('../common');
<del>const fs = require('fs');
<del>const path = require('path');
<ide>
<ide> // fs-watch on folders have limited capability in AIX.
<ide> // The testcase makes use of folder watching, and causes
<ide> // hang. This behavior is documented. Skip this for AIX.
<ide>
<del>if (common.isAix) {
<add>if (common.isAix)
<ide> common.skip('folder watch capability is limited in AIX.');
<del> return;
<del>}
<add>
<add>const fs = require('fs');
<add>const path = require('path');
<ide>
<ide> common.refreshTmpDir();
<ide>
<ide><path>test/parallel/test-fs-watch-recursive.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!(common.isOSX || common.isWindows)) {
<add>if (!(common.isOSX || common.isWindows))
<ide> common.skip('recursive option is darwin/windows specific');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http-chunk-problem.js
<ide> 'use strict';
<ide> // http://groups.google.com/group/nodejs/browse_thread/thread/f66cd3c960406919
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide>
<ide> if (process.argv[2] === 'request') {
<ide> const http = require('http');
<ide><path>test/parallel/test-http-default-port.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const http = require('http');
<ide> const https = require('https');
<ide><path>test/parallel/test-http-dns-error.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide> function test(mod) {
<ide> if (common.hasCrypto) {
<ide> test(https);
<ide> } else {
<del> common.skip('missing crypto');
<add> common.printSkipMessage('missing crypto');
<ide> }
<ide>
<ide> test(http);
<ide><path>test/parallel/test-http-full-response.js
<ide> function runAb(opts, callback) {
<ide> exec(command, function(err, stdout, stderr) {
<ide> if (err) {
<ide> if (/ab|apr/i.test(stderr)) {
<del> common.skip(`problem spawning \`ab\`.\n${stderr}`);
<add> common.printSkipMessage(`problem spawning \`ab\`.\n${stderr}`);
<ide> process.reallyExit(0);
<ide> }
<ide> process.exit();
<ide><path>test/parallel/test-http-invalid-urls.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide><path>test/parallel/test-http-localaddress.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasMultiLocalhost())
<add> common.skip('platform-specific test.');
<add>
<ide> const http = require('http');
<ide> const assert = require('assert');
<ide>
<del>if (!common.hasMultiLocalhost()) {
<del> common.skip('platform-specific test.');
<del> return;
<del>}
<del>
<ide> const server = http.createServer(function(req, res) {
<ide> console.log(`Connect from: ${req.connection.remoteAddress}`);
<ide> assert.strictEqual('127.0.0.2', req.connection.remoteAddress);
<ide><path>test/parallel/test-http-url.parse-https.request.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const url = require('url');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-https-agent-constructor.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide>
<ide><path>test/parallel/test-https-agent-create-connection.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-agent-disable-session-reuse.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>
<del>const TOTAL_REQS = 2;
<ide>
<add>const assert = require('assert');
<ide> const https = require('https');
<del>
<ide> const fs = require('fs');
<ide>
<add>const TOTAL_REQS = 2;
<add>
<ide> const options = {
<ide> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<ide> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<ide><path>test/parallel/test-https-agent-getname.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-agent-secure-protocol.js
<ide> 'use strict';
<del>const assert = require('assert');
<ide> const common = require('../common');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const https = require('https');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-https-agent-servername.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const https = require('https');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-https-agent-session-eviction.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-agent-session-reuse.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const https = require('https');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-https-agent-sni.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-agent-sockets-leak.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const fs = require('fs');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-agent.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-argument-of-creating.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-byteswritten.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-client-checkServerIdentity.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-https-client-get-url.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> // disable strict server certificate validation by the client
<ide> process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
<ide>
<ide> const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<del>
<ide> const fs = require('fs');
<ide> const url = require('url');
<add>
<ide> const URL = url.URL;
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-client-reject.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-https-client-resume.js
<ide> // Cache session and close connection. Use session on second connection.
<ide> // ASSERT resumption.
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-https-close.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const fs = require('fs');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const fs = require('fs');
<ide> const https = require('https');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-connect-address-family.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.hasIPv6) {
<add>if (!common.hasIPv6)
<ide> common.skip('no IPv6 support');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide> function runTest() {
<ide>
<ide> dns.lookup('localhost', {family: 6, all: true}, (err, addresses) => {
<ide> if (err) {
<del> if (err.code === 'ENOTFOUND') {
<add> if (err.code === 'ENOTFOUND')
<ide> common.skip('localhost does not resolve to ::1');
<del> return;
<del> }
<add>
<ide> throw err;
<ide> }
<ide>
<ide><path>test/parallel/test-https-connecting-to-http.js
<ide> // This tests the situation where you try to connect a https client
<ide> // to an http server. You should get an error and exit.
<ide> const common = require('../common');
<del>const http = require('http');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const http = require('http');
<add>const https = require('https');
<ide> const server = http.createServer(common.mustNotCall());
<ide>
<ide> server.listen(0, common.mustCall(function() {
<ide><path>test/parallel/test-https-drain.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-https-eof-for-eom.js
<ide> // correctly.
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const https = require('https');
<ide> const tls = require('tls');
<del>
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-foafssl.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const join = require('path').join;
<del>
<ide> const fs = require('fs');
<ide> const spawn = require('child_process').spawn;
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-host-headers.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<add>
<ide> const options = {
<ide> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<ide> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<ide><path>test/parallel/test-https-localaddress-bind-error.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-localaddress.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const fs = require('fs');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<del>if (!common.hasMultiLocalhost()) {
<add>if (!common.hasMultiLocalhost())
<ide> common.skip('platform-specific test.');
<del> return;
<del>}
<add>
<add>const fs = require('fs');
<add>const assert = require('assert');
<add>const https = require('https');
<ide>
<ide> const options = {
<ide> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<ide><path>test/parallel/test-https-pfx.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<ide>
<ide> const pfx = fs.readFileSync(`${common.fixturesDir}/test_cert.pfx`);
<ide><path>test/parallel/test-https-req-split.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> // disable strict server certificate validation by the client
<ide> process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<ide>
<ide> const tls = require('tls');
<ide><path>test/parallel/test-https-resume-after-renew.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const fs = require('fs');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-server-keep-alive-timeout.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-https-simple.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-socket-options.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const https = require('https');
<ide> const fs = require('fs');
<del>
<ide> const http = require('http');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-https-strict.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> // disable strict server certificate validation by the client
<ide> process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
<ide>
<ide> const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide> const https = require('https');
<del>
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-https-timeout-server-2.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-https-timeout-server.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide>
<ide><path>test/parallel/test-https-timeout.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const https = require('https');
<ide>
<ide> const fs = require('fs');
<ide><path>test/parallel/test-https-truncate.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-https-unix-socket-self-signed.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> common.refreshTmpDir();
<ide>
<ide><path>test/parallel/test-icu-data-dir.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!(common.hasIntl && common.hasSmallICU)) {
<add>if (!(common.hasIntl && common.hasSmallICU))
<ide> common.skip('missing Intl');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const { spawnSync } = require('child_process');
<ide>
<ide><path>test/parallel/test-icu-punycode.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasIntl) {
<add>if (!common.hasIntl)
<ide> common.skip('missing Intl');
<del> return;
<del>}
<ide>
<ide> const icu = process.binding('icu');
<ide> const assert = require('assert');
<ide><path>test/parallel/test-icu-stringwidth.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasIntl) {
<add>if (!common.hasIntl)
<ide> common.skip('missing Intl');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const readline = require('internal/readline');
<ide><path>test/parallel/test-icu-transcode.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasIntl) {
<add>if (!common.hasIntl)
<ide> common.skip('missing Intl');
<del> return;
<del>}
<ide>
<ide> const buffer = require('buffer');
<ide> const assert = require('assert');
<ide><path>test/parallel/test-inspector-open.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>common.skipIfInspectorDisabled();
<ide>
<ide> // Test inspector open()/close()/url() API. It uses ephemeral ports so can be
<ide> // run safely in parallel.
<ide> const fork = require('child_process').fork;
<ide> const net = require('net');
<ide> const url = require('url');
<ide>
<del>common.skipIfInspectorDisabled();
<del>
<ide> if (process.env.BE_CHILD)
<ide> return beChild();
<ide>
<ide><path>test/parallel/test-intl-v8BreakIterator.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasIntl || Intl.v8BreakIterator === undefined) {
<del> return common.skip('missing Intl');
<del>}
<add>if (!common.hasIntl || Intl.v8BreakIterator === undefined)
<add> common.skip('missing Intl');
<ide>
<ide> const assert = require('assert');
<ide> const warning = 'Intl.v8BreakIterator is deprecated and will be removed soon.';
<ide><path>test/parallel/test-intl.js
<ide> if (!common.hasIntl) {
<ide> `"Intl" object is NOT present but v8_enable_i18n_support is ${enablei18n}`;
<ide> assert.strictEqual(enablei18n, 0, erMsg);
<ide> common.skip('Intl tests because Intl object not present.');
<del>
<ide> } else {
<ide> const erMsg =
<ide> `"Intl" object is present but v8_enable_i18n_support is ${
<ide> if (!common.hasIntl) {
<ide>
<ide> // If list is specified and doesn't contain 'en' then return.
<ide> if (process.config.variables.icu_locales && !haveLocale('en')) {
<del> common.skip(
<add> common.printSkipMessage(
<ide> 'detailed Intl tests because English is not listed as supported.');
<ide> // Smoke test. Does it format anything, or fail?
<ide> console.log(`Date(0) formatted to: ${dtf.format(date0)}`);
<ide><path>test/parallel/test-listen-fd-cluster.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('This test is disabled on windows.');
<add>
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide> const net = require('net');
<ide> const cluster = require('cluster');
<ide>
<ide> console.error('Cluster listen fd test', process.argv[2] || 'runner');
<ide>
<del>if (common.isWindows) {
<del> common.skip('This test is disabled on windows.');
<del> return;
<del>}
<del>
<ide> // Process relationship is:
<ide> //
<ide> // parent: the test main script
<ide><path>test/parallel/test-listen-fd-detached-inherit.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('This test is disabled on windows.');
<add>
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide> const net = require('net');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>if (common.isWindows) {
<del> common.skip('This test is disabled on windows.');
<del> return;
<del>}
<del>
<ide> switch (process.argv[2]) {
<ide> case 'child': return child();
<ide> case 'parent': return parent();
<ide><path>test/parallel/test-listen-fd-detached.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('This test is disabled on windows.');
<add>
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide> const net = require('net');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>if (common.isWindows) {
<del> common.skip('This test is disabled on windows.');
<del> return;
<del>}
<del>
<ide> switch (process.argv[2]) {
<ide> case 'child': return child();
<ide> case 'parent': return parent();
<ide><path>test/parallel/test-listen-fd-server.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('This test is disabled on windows.');
<add>
<ide> const assert = require('assert');
<ide> const http = require('http');
<ide> const net = require('net');
<ide>
<del>if (common.isWindows) {
<del> common.skip('This test is disabled on windows.');
<del> return;
<del>}
<del>
<ide> switch (process.argv[2]) {
<ide> case 'child': return child();
<ide> }
<ide><path>test/parallel/test-module-circular-symlinks.js
<ide> try {
<ide> } catch (err) {
<ide> if (err.code !== 'EPERM') throw err;
<ide> common.skip('insufficient privileges for symlinks');
<del> return;
<ide> }
<ide>
<ide> fs.writeFileSync(path.join(tmpDir, 'index.js'),
<ide><path>test/parallel/test-module-symlinked-peer-modules.js
<ide> try {
<ide> } catch (err) {
<ide> if (err.code !== 'EPERM') throw err;
<ide> common.skip('insufficient privileges for symlinks');
<del> return;
<ide> }
<ide>
<ide> fs.writeFileSync(path.join(moduleA, 'package.json'),
<ide><path>test/parallel/test-net-access-byteswritten.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-net-connect-options-fd.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('Does not support wrapping sockets with fd on Windows');
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const path = require('path');
<ide> const Pipe = process.binding('pipe_wrap').Pipe;
<ide>
<del>if (common.isWindows) {
<del> common.skip('Does not support wrapping sockets with fd on Windows');
<del> return;
<del>}
<del>
<ide> common.refreshTmpDir();
<ide>
<ide> function testClients(getSocketOpt, getConnectOpt, getConnectCb) {
<ide><path>test/parallel/test-net-connect-options-ipv6.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasIPv6)
<add> common.skip('no IPv6 support');
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide>
<del>if (!common.hasIPv6) {
<del> common.skip('no IPv6 support');
<del> return;
<del>}
<del>
<ide> const hosts = common.localIPv6Hosts;
<ide> let hostIdx = 0;
<ide> let host = hosts[hostIdx];
<ide> function tryConnect() {
<ide> if (host)
<ide> tryConnect();
<ide> else {
<del> common.skip('no IPv6 localhost support');
<ide> server.close();
<add> common.skip('no IPv6 localhost support');
<ide> }
<ide> return;
<ide> }
<ide><path>test/parallel/test-net-socket-local-address.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const net = require('net');
<del>
<ide> // skip test in FreeBSD jails
<del>if (common.inFreeBSDJail) {
<add>if (common.inFreeBSDJail)
<ide> common.skip('In a FreeBSD jail');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<add>const net = require('net');
<ide>
<ide> let conns = 0;
<ide> const clientLocalPorts = [];
<ide><path>test/parallel/test-npm-install.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const path = require('path');
<ide> const spawn = require('child_process').spawn;
<ide><path>test/parallel/test-openssl-ca-options.js
<ide> // This test checks the usage of --use-bundled-ca and --use-openssl-ca arguments
<ide> // to verify that both are not used at the same time.
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const os = require('os');
<ide> const childProcess = require('child_process');
<ide><path>test/parallel/test-pipe-writev.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('Unix-specific test');
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide>
<del>if (common.isWindows) {
<del> common.skip('Unix-specific test');
<del> return;
<del>}
<del>
<ide> common.refreshTmpDir();
<ide>
<ide> const server = net.createServer((connection) => {
<ide><path>test/parallel/test-preload.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>// Refs: https://github.com/nodejs/node/pull/2253
<add>if (common.isSunOS)
<add> common.skip('unreliable on SunOS');
<add>
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide> const childProcess = require('child_process');
<ide>
<del>// Refs: https://github.com/nodejs/node/pull/2253
<del>if (common.isSunOS) {
<del> common.skip('unreliable on SunOS');
<del> return;
<del>}
<del>
<ide> const nodeBinary = process.argv[0];
<ide>
<ide> const preloadOption = (preloads) => {
<ide><path>test/parallel/test-process-execpath.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('symlinks are weird on windows');
<add>
<ide> const assert = require('assert');
<ide> const child_process = require('child_process');
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> assert.strictEqual(process.execPath, fs.realpathSync(process.execPath));
<ide>
<del>if (common.isWindows) {
<del> common.skip('symlinks are weird on windows');
<del> return;
<del>}
<del>
<ide> if (process.argv[2] === 'child') {
<ide> // The console.log() output is part of the test here.
<ide> console.log(process.execPath);
<ide><path>test/parallel/test-process-getgroups.js
<ide> const common = require('../common');
<ide>
<ide> // Check `id -G` and `process.getgroups()` return same groups.
<ide>
<del>if (common.isOSX) {
<add>if (common.isOSX)
<ide> common.skip('Output of `id -G` is unreliable on Darwin.');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const exec = require('child_process').exec;
<ide>
<ide><path>test/parallel/test-process-remove-all-signal-listeners.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (common.isWindows)
<add> common.skip('Win32 does not support signals.');
<add>
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>if (common.isWindows) {
<del> common.skip('Win32 doesn\'t have signals, just a kind of ' +
<del> 'emulation, insufficient for this test to apply.');
<del> return;
<del>}
<del>
<ide> if (process.argv[2] !== '--do-test') {
<ide> // We are the master, fork a child so we can verify it exits with correct
<ide> // status.
<ide><path>test/parallel/test-regress-GH-1531.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const https = require('https');
<ide>
<ide> const fs = require('fs');
<ide><path>test/parallel/test-regress-GH-3542.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>// This test is only relevant on Windows.
<add>if (!common.isWindows)
<add> common.skip('Windows specific test.');
<add>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<del>// This test is only relevant on Windows.
<del>if (!common.isWindows) {
<del> common.skip('Windows specific test.');
<del> return;
<del>}
<del>
<ide> function test(p) {
<ide> const result = fs.realpathSync(p);
<ide> assert.strictEqual(result.toLowerCase(), path.resolve(p).toLowerCase());
<ide><path>test/parallel/test-regress-GH-9819.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<ide> const assert = require('assert');
<ide> const execFile = require('child_process').execFile;
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<del>
<ide> const setup = 'const enc = { toString: () => { throw new Error("xyz"); } };';
<ide>
<ide> const scripts = [
<ide><path>test/parallel/test-repl-history-perm.js
<ide> if (common.isWindows) {
<ide> common.skip('Win32 uses ACLs for file permissions, ' +
<ide> 'modes are always 0666 and says nothing about group/other ' +
<ide> 'read access.');
<del> return;
<ide> }
<ide>
<ide> const assert = require('assert');
<ide><path>test/parallel/test-repl-sigint-nested-eval.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>const spawn = require('child_process').spawn;
<del>
<ide> if (common.isWindows) {
<ide> // No way to send CTRL_C_EVENT to processes from JS right now.
<ide> common.skip('platform not supported');
<del> return;
<ide> }
<ide>
<add>const assert = require('assert');
<add>const spawn = require('child_process').spawn;
<add>
<ide> process.env.REPL_TEST_PPID = process.pid;
<ide> const child = spawn(process.execPath, [ '-i' ], {
<ide> stdio: [null, null, 2]
<ide><path>test/parallel/test-repl-sigint.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>const spawn = require('child_process').spawn;
<del>
<ide> if (common.isWindows) {
<ide> // No way to send CTRL_C_EVENT to processes from JS right now.
<ide> common.skip('platform not supported');
<del> return;
<ide> }
<ide>
<add>const assert = require('assert');
<add>const spawn = require('child_process').spawn;
<add>
<ide> process.env.REPL_TEST_PPID = process.pid;
<ide> const child = spawn(process.execPath, [ '-i' ], {
<ide> stdio: [null, null, 2]
<ide><path>test/parallel/test-require-long-path.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.isWindows)
<add> common.skip('this test is Windows-specific.');
<add>
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<del>if (!common.isWindows) {
<del> common.skip('this test is Windows-specific.');
<del> return;
<del>}
<del>
<ide> // make a path that is more than 260 chars long.
<ide> const dirNameLen = Math.max(260 - common.tmpDir.length, 1);
<ide> const dirName = path.join(common.tmpDir, 'x'.repeat(dirNameLen));
<ide><path>test/parallel/test-require-symlink.js
<ide> if (common.isWindows) {
<ide> // On Windows, creating symlinks requires admin privileges.
<ide> // We'll only try to run symlink test if we have enough privileges.
<ide> exec('whoami /priv', function(err, o) {
<del> if (err || !o.includes('SeCreateSymbolicLinkPrivilege')) {
<add> if (err || !o.includes('SeCreateSymbolicLinkPrivilege'))
<ide> common.skip('insufficient privileges');
<del> return;
<del> }
<ide>
<ide> test();
<ide> });
<ide><path>test/parallel/test-setproctitle.js
<ide> const common = require('../common');
<ide>
<ide> // FIXME add sunos support
<del>if (common.isSunOS) {
<del> return common.skip(`Unsupported platform [${process.platform}]`);
<del>}
<add>if (common.isSunOS)
<add> common.skip(`Unsupported platform [${process.platform}]`);
<ide>
<ide> const assert = require('assert');
<ide> const exec = require('child_process').exec;
<ide> process.title = title;
<ide> assert.strictEqual(process.title, title);
<ide>
<ide> // Test setting the title but do not try to run `ps` on Windows.
<del>if (common.isWindows) {
<del> return common.skip('Windows does not have "ps" utility');
<del>}
<add>if (common.isWindows)
<add> common.skip('Windows does not have "ps" utility');
<ide>
<ide> // To pass this test on alpine, since Busybox `ps` does not
<ide> // support `-p` switch, use `ps -o` and `grep` instead.
<ide><path>test/parallel/test-signal-handler.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (common.isWindows) {
<add>if (common.isWindows)
<ide> common.skip('SIGUSR1 and SIGHUP signals are not supported');
<del> return;
<del>}
<ide>
<ide> console.log(`process.pid: ${process.pid}`);
<ide>
<ide><path>test/parallel/test-spawn-cmd-named-pipe.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<ide> // This test is intended for Windows only
<del>if (!common.isWindows) {
<add>if (!common.isWindows)
<ide> common.skip('this test is Windows-specific.');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide>
<ide> if (!process.argv[2]) {
<ide> // parent
<ide><path>test/parallel/test-tls-0-dns-altname.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide>
<ide> // Check getPeerCertificate can properly handle '\0' for fix CVE-2009-2408.
<ide>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<add>const assert = require('assert');
<ide> const tls = require('tls');
<del>
<ide> const fs = require('fs');
<ide>
<ide> const server = tls.createServer({
<ide><path>test/parallel/test-tls-alert-handling.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.opensslCli) {
<del> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>if (!common.opensslCli)
<add> common.skip('node compiled without OpenSSL CLI.');
<ide>
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-alert.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<del>
<del>if (!common.hasCrypto) {
<del> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const { spawn } = require('child_process');
<ide><path>test/parallel/test-tls-alpn-server-client.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> if (!process.features.tls_alpn || !process.features.tls_npn) {
<ide> common.skip(
<ide> 'Skipping because node compiled without NPN or ALPN feature of OpenSSL.');
<del> return;
<ide> }
<ide>
<ide> const assert = require('assert');
<ide><path>test/parallel/test-tls-async-cb-after-socket-end.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const path = require('path');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-basic-validations.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-cert-regression.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide>
<ide><path>test/parallel/test-tls-check-server-identity.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const util = require('util');
<ide><path>test/parallel/test-tls-cipher-list.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const spawn = require('child_process').spawn;
<ide><path>test/parallel/test-tls-client-abort.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-tls-client-abort2.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide> const conn = tls.connect(0, common.mustNotCall());
<ide><path>test/parallel/test-tls-client-default-ciphers.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide> function Done() {}
<ide><path>test/parallel/test-tls-client-destroy-soon.js
<ide> // ASSERT resumption.
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-tls-client-getephemeralkeyinfo.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> process.exit();
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<add>
<ide> const key = fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`);
<ide> const cert = fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`);
<ide>
<ide><path>test/parallel/test-tls-client-mindhsize.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> process.exit();
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<add>
<ide> const key = fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`);
<ide> const cert = fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`);
<ide>
<ide><path>test/parallel/test-tls-client-reject.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-tls-client-resume.js
<ide> // ASSERT resumption.
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-tls-client-verify.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-close-error.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const server = tls.createServer({
<ide><path>test/parallel/test-tls-close-notify.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const server = tls.createServer({
<ide><path>test/parallel/test-tls-cnnic-whitelist.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-connect-address-family.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.hasIPv6) {
<add>if (!common.hasIPv6)
<ide> common.skip('no IPv6 support');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> function runTest() {
<ide>
<ide> dns.lookup('localhost', {family: 6, all: true}, (err, addresses) => {
<ide> if (err) {
<del> if (err.code === 'ENOTFOUND') {
<add> if (err.code === 'ENOTFOUND')
<ide> common.skip('localhost does not resolve to ::1');
<del> return;
<del> }
<add>
<ide> throw err;
<ide> }
<ide>
<ide><path>test/parallel/test-tls-connect-given-socket.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const net = require('net');
<ide> const fs = require('fs');
<ide> const path = require('path');
<add>
<ide> const options = {
<ide> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')),
<ide> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))
<ide><path>test/parallel/test-tls-connect-no-host.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> const assert = require('assert');
<ide><path>test/parallel/test-tls-connect-pipe.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-connect-simple.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-connect-stream-writes.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-connect.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-tls-delayed-attach-error.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-delayed-attach.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide>
<ide><path>test/parallel/test-tls-destroy-whilst-write.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide> const stream = require('stream');
<ide>
<ide><path>test/parallel/test-tls-dhe.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('missing openssl-cli');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<del>
<ide> const spawn = require('child_process').spawn;
<ide> const fs = require('fs');
<add>
<ide> const key = fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`);
<ide> const cert = fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`);
<ide> let nsuccess = 0;
<ide><path>test/parallel/test-tls-ecdh-disable.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('missing openssl-cli');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<del>
<ide> const exec = require('child_process').exec;
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-tls-ecdh.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('missing openssl-cli');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-econnreset.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide> const cacert =
<ide><path>test/parallel/test-tls-empty-sni-context.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide>
<del>if (!process.features.tls_sni) {
<add>if (!process.features.tls_sni)
<ide> common.skip('node compiled without OpenSSL or with old OpenSSL version.');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<del> return common.skip('missing crypto');
<del>}
<del>
<ide> const tls = require('tls');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-tls-env-bad-extra-ca.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-env-extra-ca.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-external-accessor.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>// Ensure accessing ._external doesn't hit an assert in the accessor method.
<add>const assert = require('assert');
<ide> const tls = require('tls');
<add>
<add>// Ensure accessing ._external doesn't hit an assert in the accessor method.
<ide> {
<ide> const pctx = tls.createSecureContext().context;
<ide> const cctx = Object.create(pctx);
<ide><path>test/parallel/test-tls-fast-writing.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const dir = common.fixturesDir;
<ide><path>test/parallel/test-tls-friendly-error-message.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const key = fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`);
<ide><path>test/parallel/test-tls-getcipher.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-tls-getprotocol.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-tls-handshake-error.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const server = tls.createServer({
<ide><path>test/parallel/test-tls-handshake-nohang.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> // neither should hang
<ide><path>test/parallel/test-tls-hello-parser-failure.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-honorcipherorder.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<add>
<ide> let nconns = 0;
<ide>
<ide> // We explicitly set TLS version to 1.2 so as to be safe when the
<ide><path>test/parallel/test-tls-inception.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-interleave.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide>
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-invoke-queued.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-js-stream.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const stream = require('stream');
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-junk-closes-server.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-junk-server.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const https = require('https');
<ide><path>test/parallel/test-tls-key-mismatch.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-legacy-deprecated.js
<ide> // Flags: --no-warnings
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-tls-legacy-onselect.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide> const net = require('net');
<ide>
<ide><path>test/parallel/test-tls-lookup.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-tls-max-send-fragment.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const buf = Buffer.allocUnsafe(10000);
<ide><path>test/parallel/test-tls-multi-key.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-tls-no-cert-required.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>const assert = require('assert');
<ide> const common = require('../common');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide> // Omitting the cert or pfx option to tls.createServer() should not throw.
<ide><path>test/parallel/test-tls-no-rsa-key.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-tls-no-sslv23.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide> assert.throws(function() {
<ide><path>test/parallel/test-tls-no-sslv3.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>if (common.opensslCli === false)
<add> common.skip('node compiled without OpenSSL CLI.');
<add>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const spawn = require('child_process').spawn;
<ide>
<del>if (common.opensslCli === false) {
<del> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<del>
<ide> const cert = fs.readFileSync(`${common.fixturesDir}/test_cert.pem`);
<ide> const key = fs.readFileSync(`${common.fixturesDir}/test_key.pem`);
<ide> const server = tls.createServer({ cert: cert, key: key }, common.mustNotCall());
<ide> server.on('tlsClientError', (err) => errors.push(err));
<ide>
<ide> process.on('exit', function() {
<ide> if (/unknown option -ssl3/.test(stderr)) {
<del> common.skip('`openssl s_client -ssl3` not supported.');
<add> common.printSkipMessage('`openssl s_client -ssl3` not supported.');
<ide> } else {
<ide> assert.strictEqual(errors.length, 1);
<ide> assert(/:wrong version number/.test(errors[0].message));
<ide><path>test/parallel/test-tls-npn-server-client.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!process.features.tls_npn) {
<del> common.skip('Skipping because node compiled without NPN feature of OpenSSL.');
<del> return;
<del>}
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>if (!process.features.tls_npn)
<add> common.skip('Skipping because node compiled without NPN feature of OpenSSL.');
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-ocsp-callback.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!process.features.tls_ocsp) {
<add>if (!process.features.tls_ocsp)
<ide> common.skip('node compiled without OpenSSL or with old OpenSSL version.');
<del> return;
<del>}
<del>if (!common.opensslCli) {
<add>
<add>if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> const assert = require('assert');
<ide><path>test/parallel/test-tls-on-empty-socket.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-tls-over-http-tunnel.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const https = require('https');
<ide>
<add>const assert = require('assert');
<add>const https = require('https');
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide> const http = require('http');
<ide><path>test/parallel/test-tls-parse-cert-string.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-passphrase.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-tls-pause.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-tls-peer-certificate-encoding.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const util = require('util');
<ide> const join = require('path').join;
<ide><path>test/parallel/test-tls-peer-certificate-multi-keys.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const util = require('util');
<ide> const join = require('path').join;
<ide><path>test/parallel/test-tls-pfx-gh-5100-regr.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('node compiled without crypto.');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-regr-gh-5108.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-request-timeout.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-tls-retain-handle-no-abort.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide> const util = require('util');
<ide><path>test/parallel/test-tls-securepair-fiftharg.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-securepair-leak.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const { createSecureContext } = require('tls');
<ide> const { createSecurePair } = require('_tls_legacy');
<ide>
<ide><path>test/parallel/test-tls-securepair-server.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('missing openssl-cli');
<del> return;
<del>}
<ide>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<del>
<ide> const join = require('path').join;
<ide> const net = require('net');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-server-connection-server.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-server-failed-handshake-emits-clienterror.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide> const net = require('net');
<ide> const assert = require('assert');
<ide><path>test/parallel/test-tls-server-verify.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.opensslCli) {
<del> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>if (!common.opensslCli)
<add> common.skip('node compiled without OpenSSL CLI.');
<ide>
<ide> // This is a rather complex test which sets up various TLS servers with node
<ide> // and connects to them using the 'openssl s_client' command line utility
<ide><path>test/parallel/test-tls-session-cache.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> doTest({ tickets: false }, function() {
<ide> doTest({ tickets: true }, function() {
<ide><path>test/parallel/test-tls-set-ciphers.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.opensslCli) {
<add>if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<del> return;
<del>}
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const exec = require('child_process').exec;
<ide><path>test/parallel/test-tls-set-encoding.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<del>
<ide> const options = {
<ide> key: fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`),
<ide> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`)
<ide><path>test/parallel/test-tls-sni-option.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!process.features.tls_sni) {
<del> common.skip('node compiled without OpenSSL or with old OpenSSL version.');
<del> return;
<del>}
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>if (!process.features.tls_sni)
<add> common.skip('node compiled without OpenSSL or with old OpenSSL version.');
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-sni-server-client.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!process.features.tls_sni) {
<del> common.skip('node compiled without OpenSSL or with old OpenSSL version.');
<del> return;
<del>}
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<add>if (!process.features.tls_sni)
<add> common.skip('node compiled without OpenSSL or with old OpenSSL version.');
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-socket-close.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const assert = require('assert');
<ide>
<add>const assert = require('assert');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-socket-destroy.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-socket-failed-handshake-emits-error.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide> const net = require('net');
<ide> const assert = require('assert');
<ide><path>test/parallel/test-tls-startcom-wosign-whitelist.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-starttls-server.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-tls-ticket-cluster.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const cluster = require('cluster');
<ide> const fs = require('fs');
<ide> const join = require('path').join;
<ide><path>test/parallel/test-tls-ticket.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide> const net = require('net');
<ide> const crypto = require('crypto');
<ide><path>test/parallel/test-tls-timeout-server-2.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const assert = require('assert');
<add>const tls = require('tls');
<ide> const fs = require('fs');
<ide>
<ide> const options = {
<ide><path>test/parallel/test-tls-timeout-server.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<del>const tls = require('tls');
<ide>
<add>const tls = require('tls');
<ide> const net = require('net');
<ide> const fs = require('fs');
<ide>
<ide><path>test/parallel/test-tls-two-cas-one-string.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const fs = require('fs');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-wrap-econnreset-localaddress.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-wrap-econnreset-pipe.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-wrap-econnreset-socket.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-wrap-econnreset.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const tls = require('tls');
<ide><path>test/parallel/test-tls-wrap-event-emmiter.js
<ide> */
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide>
<ide> const TlsSocket = require('tls').TLSSocket;
<ide><path>test/parallel/test-tls-wrap-no-abort.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const util = require('util');
<ide> const TLSWrap = process.binding('tls_wrap').TLSWrap;
<ide><path>test/parallel/test-tls-wrap-timeout.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide>
<ide><path>test/parallel/test-tls-writewrap-leak.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide><path>test/parallel/test-tls-zero-clear-in.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasCrypto) {
<add>if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<del> return;
<del>}
<add>
<ide> const tls = require('tls');
<ide>
<ide> const fs = require('fs');
<ide><path>test/parallel/test-url-domain-ascii-unicode.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasIntl) {
<add>if (!common.hasIntl)
<ide> common.skip('missing Intl');
<del> return;
<del>}
<add>
<ide> const strictEqual = require('assert').strictEqual;
<ide> const url = require('url');
<ide>
<ide><path>test/parallel/test-url-format-whatwg.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>if (!common.hasIntl) {
<add>if (!common.hasIntl)
<ide> common.skip('missing Intl');
<del> return;
<del>}
<add>
<ide> const assert = require('assert');
<ide> const url = require('url');
<ide> const URL = url.URL;
<ide><path>test/parallel/test-util-sigint-watchdog.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const assert = require('assert');
<del>const binding = process.binding('util');
<del>
<ide> if (common.isWindows) {
<ide> // No way to send CTRL_C_EVENT to processes from JS right now.
<ide> common.skip('platform not supported');
<del> return;
<ide> }
<ide>
<add>const assert = require('assert');
<add>const binding = process.binding('util');
<add>
<ide> [(next) => {
<ide> // Test with no signal observed.
<ide> binding.startSigintWatchdog();
<ide><path>test/parallel/test-vm-sigint-existing-handler.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (common.isWindows) {
<add> // No way to send CTRL_C_EVENT to processes from JS right now.
<add> common.skip('platform not supported');
<add>}
<add>
<ide> const assert = require('assert');
<ide> const vm = require('vm');
<del>
<ide> const spawn = require('child_process').spawn;
<ide>
<ide> const methods = [
<ide> 'runInThisContext',
<ide> 'runInContext'
<ide> ];
<ide>
<del>if (common.isWindows) {
<del> // No way to send CTRL_C_EVENT to processes from JS right now.
<del> common.skip('platform not supported');
<del> return;
<del>}
<del>
<ide> if (process.argv[2] === 'child') {
<ide> const method = process.argv[3];
<ide> assert.ok(method);
<ide><path>test/parallel/test-vm-sigint.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>
<del>const assert = require('assert');
<del>const vm = require('vm');
<del>
<del>const spawn = require('child_process').spawn;
<del>
<ide> if (common.isWindows) {
<ide> // No way to send CTRL_C_EVENT to processes from JS right now.
<ide> common.skip('platform not supported');
<del> return;
<ide> }
<ide>
<add>const assert = require('assert');
<add>const vm = require('vm');
<add>const spawn = require('child_process').spawn;
<add>
<ide> if (process.argv[2] === 'child') {
<ide> const method = process.argv[3];
<ide> const listeners = +process.argv[4];
<ide><path>test/parallel/test-warn-sigprof.js
<ide> const common = require('../common');
<ide>
<ide> common.skipIfInspectorDisabled();
<ide>
<del>if (common.isWindows) {
<add>if (common.isWindows)
<ide> common.skip('test does not apply to Windows');
<del> return;
<del>}
<ide>
<ide> common.expectWarning('Warning',
<ide> 'process.on(SIGPROF) is reserved while debugging');
<ide><path>test/parallel/test-whatwg-url-constructor.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const path = require('path');
<del>const { URL, URLSearchParams } = require('url');
<del>const { test, assert_equals, assert_true, assert_throws } =
<del> require('../common/wpt');
<del>
<ide> if (!common.hasIntl) {
<ide> // A handful of the tests fail when ICU is not included.
<ide> common.skip('missing Intl');
<del> return;
<ide> }
<ide>
<add>const path = require('path');
<add>const { URL, URLSearchParams } = require('url');
<add>const { test, assert_equals, assert_true, assert_throws } =
<add> require('../common/wpt');
<add>
<ide> const request = {
<ide> response: require(path.join(common.fixturesDir, 'url-tests'))
<ide> };
<ide><path>test/parallel/test-whatwg-url-domainto.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (!common.hasIntl) {
<add>if (!common.hasIntl)
<ide> common.skip('missing Intl');
<del> return;
<del>}
<ide>
<ide> const assert = require('assert');
<ide> const { domainToASCII, domainToUnicode } = require('url');
<ide><path>test/parallel/test-whatwg-url-historical.js
<ide> 'use strict';
<ide> const common = require('../common');
<del>const URL = require('url').URL;
<del>const { test, assert_equals, assert_throws } = require('../common/wpt');
<del>
<ide> if (!common.hasIntl) {
<ide> // A handful of the tests fail when ICU is not included.
<ide> common.skip('missing Intl');
<del> return;
<ide> }
<ide>
<add>const URL = require('url').URL;
<add>const { test, assert_equals, assert_throws } = require('../common/wpt');
<add>
<ide> /* eslint-disable */
<ide> /* WPT Refs:
<ide> https://github.com/w3c/web-platform-tests/blob/8791bed/url/historical.html
<ide><path>test/parallel/test-whatwg-url-inspect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<del>const util = require('util');
<del>const URL = require('url').URL;
<del>const assert = require('assert');
<del>
<ide> if (!common.hasIntl) {
<ide> // A handful of the tests fail when ICU is not included.
<ide> common.skip('missing Intl');
<del> return;
<ide> }
<ide>
<add>const util = require('util');
<add>const URL = require('url').URL;
<add>const assert = require('assert');
<add>
<ide> // Tests below are not from WPT.
<ide> const url = new URL('https://username:password@host.name:8080/path/name/?que=ry#hash');
<ide> | 300 |
PHP | PHP | check datatype for localizedtime cakephp | 7e4d7d13217190a5771ed8da6eec6a466407d2d8 | <ide><path>src/Validation/Validation.php
<ide> public static function localizedTime($check, string $type = 'datetime', $format
<ide> if ($check instanceof DateTimeInterface) {
<ide> return true;
<ide> }
<del> if (is_object($check)) {
<add> if (!is_string($check)) {
<ide> return false;
<ide> }
<ide> static $methods = [ | 1 |
Text | Text | fix a typo in docs | bc139c29b77d0abcc73217b12bde3d2582a79b87 | <ide><path>docs/advanced-features/custom-server.md
<ide> description: Start a Next.js app programmatically using a custom server.
<ide> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/custom-server-express">Express integration</a></li>
<ide> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/custom-server-hapi">Hapi integration</a></li>
<ide> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/custom-server-koa">Koa integration</a></li>
<del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/ssr-caching">SSR Catching</a></li>
<add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/ssr-caching">SSR Caching</a></li>
<ide> </ul>
<ide> </details>
<ide> | 1 |
Ruby | Ruby | improve various examples and api description texts | 6547e6897cb07f73f05c13eef3bd6d211ec6dafd | <ide><path>activerecord/lib/active_record/base.rb
<ide> def update(id, attributes)
<ide> # is executed on the database which means that no callbacks are fired off running this. This is an efficient method
<ide> # of deleting records that don't need cleaning up after or other actions to be taken.
<ide> #
<del> # Objects are _not_ instantiated with this method.
<add> # Objects are _not_ instantiated with this method, and so +:dependent+ rules
<add> # defined on associations are not honered.
<ide> #
<ide> # ==== Parameters
<ide> #
<ide> def update_all(updates, conditions = nil, options = {})
<ide> #
<ide> # ==== Example
<ide> #
<del> # Person.destroy_all "last_login < '2004-04-04'"
<add> # Person.destroy_all("last_login < '2004-04-04'")
<ide> #
<ide> # This loads and destroys each person one by one, including its dependent associations and before_ and
<ide> # after_destroy callbacks.
<add> #
<add> # +conditions+ can be anything that +find+ also accepts:
<add> #
<add> # Person.destroy_all(:last_login => 6.hours.ago)
<ide> def destroy_all(conditions = nil)
<ide> find(:all, :conditions => conditions).each { |object| object.destroy }
<ide> end
<ide>
<ide> # Deletes the records matching +conditions+ without instantiating the records first, and hence not
<ide> # calling the +destroy+ method nor invoking callbacks. This is a single SQL DELETE statement that
<del> # goes straight to the database, much more efficient than +destroy_all+. Careful with relations
<del> # though, in particular <tt>:dependent</tt> is not taken into account.
<add> # goes straight to the database, much more efficient than +destroy_all+. Be careful with relations
<add> # though, in particular <tt>:dependent</tt> rules defined on associations are not honored.
<ide> #
<ide> # ==== Parameters
<ide> #
<ide> # * +conditions+ - Conditions are specified the same way as with +find+ method.
<ide> #
<ide> # ==== Example
<ide> #
<del> # Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
<add> # Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
<add> # Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
<ide> #
<del> # This deletes the affected posts all at once with a single DELETE statement. If you need to destroy dependent
<add> # Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent
<ide> # associations or call your <tt>before_*</tt> or +after_destroy+ callbacks, use the +destroy_all+ method instead.
<ide> def delete_all(conditions = nil)
<ide> sql = "DELETE FROM #{quoted_table_name} "
<ide> def define_attr_method(name, value=nil, &block)
<ide> # end
<ide> # end
<ide> # end
<add> #
<add> # *Note*: the +:find+ scope also has effect on update and deletion methods,
<add> # like +update_all+ and +delete_all+.
<ide> def with_scope(method_scoping = {}, action = :merge, &block)
<ide> method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)
<ide> | 1 |
Text | Text | add "math planet" | 70841e6497ec3019ba428128ed5c25429ff8a3d8 | <ide><path>guide/english/mathematics/algebra/index.md
<ide> Linear algebra: the study of vector spaces and linear mappings.
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<ide> [Wikipedia article](https://en.wikipedia.org/wiki/Algebra)
<ide> [Learn algebra on Khan Academy](https://www.khanacademy.org/math/algebra-home)
<add>[Learn Algebra on Math Planet](https://www.mathplanet.com/education/pre-algebra/introducing-algebra)
<ide>
<ide> #### Resources:
<ide> - [Definition](https://www.merriam-webster.com/dictionary/algebra) | 1 |
Javascript | Javascript | fix invalid octal number | 35c0d2304fc43e2a2371ab7f16a0adf3981efa1c | <ide><path>test/moment/create.js
<ide> exports.create = {
<ide> },
<ide>
<ide> "parsing iso" : function (test) {
<del> var offset = moment([2011, 9, 08]).zone(),
<add> var offset = moment([2011, 9, 8]).zone(),
<ide> pad = function (input) {
<ide> if (input < 10) {
<ide> return '0' + input; | 1 |
Text | Text | update the security policy | 6f0d2fa502c75f73d1d54e6d9abe49b6c9edfd31 | <ide><path>docs/security.md
<del># Security Policy
<add># freeCodeCamp.org's Security Policy
<ide>
<ide> This document outlines our security policy for the codebases, platforms that we operate, and how to report vulnerabilities.
<ide>
<ide> ## Reporting a Vulnerability
<ide>
<del>If you think you have found a vulnerability, _please report responsibly_. Don't create GitHub issues for security issues. Instead, please send an email to `security@freecodecamp.org` and we'll look into it immediately.
<add>> [!NOTE]
<add>> If you think you have found a vulnerability, **please report responsibly**. Do not create GitHub issues for security issues. Instead follow this guide.
<ide>
<del>Ensure that you are using the **latest**, **stable** and **updated** version of the Operating System and Web Browser available to you on your machine.
<add>### Guidelines
<ide>
<del>We appreciate any responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users.
<add>We appreciate a responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users. In the interest of saving everyone time, we encourage you to report vulnerabilities with these in mind:
<ide>
<del>Once you report a vulnerability, we will look into it and make sure that it is not a false positive. We will get back to you if we need to clarify any details. You can submit separate reports for each issue you find.
<add>1. Ensure that you are using the **latest**, **stable** and **updated** versions of the Operating System and Web Browser(s) available to you on your machine.
<add>2. We consider using tools & online utilities to report issues with SPF & DKIM configs, or SSL Server tests, etc. in the category of ["beg bounties"](https://www.troyhunt.com/beg-bounties/) and are unable to respond to these reports.
<add>3. While we do not offer any bounties or swags at the moment, we'll be happy to list your name in our [Hall of Fame](security-hall-of-fame.md) list, provided the reports are not low-effort.
<ide>
<del>While we do not offer any bounties or swags at the moment, we'll be happy to list your name in our [Hall of Fame](security-hall-of-fame.md) list, provided the reports are not low-effort.
<add>### Reporting
<ide>
<del>We consider using tools & online utilities to report issues with SPF & DKIM configs, or SSL Server tests, etc. in the category of ["beg bounties"](https://www.troyhunt.com/beg-bounties/) and are unable to respond to these reports.
<add>After confirming the above guidelines, please feel free to either send an email to `possible-security-issue [at] freecodecamp.org`. You can also send us an PGP encrypted message at `flowcrypt.com/me/freecodecamp` if you prefer.
<add>
<add>Once you report a vulnerability, we will look into it and make sure that it is not a false positive. If we need to clarify any details, we will get back to you. You can submit separate reports for each issue you find. Please note that we will not be able to respond to any issues that we think are outside the guidelines.
<ide>
<ide> ## Platforms & Codebases
<ide>
<ide> Here is a list of the platforms and codebases we are accepting reports for:
<ide> | production | Yes | `freecodecamp.org/news` |
<ide> | localized | Yes | `freecodecamp.org/<language>/news` |
<ide>
<del>### Mobile app
<add>### Mobile App
<ide>
<ide> | Version | Supported | Website active |
<ide> | ---------- | --------- | ---------------------------------------------------------------- |
<ide> | production | Yes | `https://play.google.com/store/apps/details?id=org.freecodecamp` |
<ide>
<add>### Other Platforms
<add>
<ide> Apart from the above, we are also accepting reports for repositories hosted on GitHub, under the freeCodeCamp organization.
<ide>
<add>### Other Self-hosted Applications
<add>
<ide> We self-host some of our platforms using open-source software like Ghost & Discourse. If you are reporting a vulnerability please ensure that it is not a bug in the upstream software. | 1 |
Go | Go | use containerd/sys to detect usernamespaces | f7d5d70e44e3717f308c43b35aca5968ee8df4f1 | <ide><path>pkg/archive/archive_linux_test.go
<ide> import (
<ide> "syscall"
<ide> "testing"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/pkg/reexec"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/moby/sys/mount"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "github.com/pkg/errors"
<ide> "golang.org/x/sys/unix"
<ide> "gotest.tools/v3/assert"
<ide> import (
<ide> // └── f1 # whiteout, 0644
<ide> func setupOverlayTestDir(t *testing.T, src string) {
<ide> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<del> skip.If(t, rsystem.RunningInUserNS(), "skipping test that requires initial userns (trusted.overlay.opaque xattr cannot be set in userns, even with Ubuntu kernel)")
<add> skip.If(t, sys.RunningInUserNS(), "skipping test that requires initial userns (trusted.overlay.opaque xattr cannot be set in userns, even with Ubuntu kernel)")
<ide> // Create opaque directory containing single file and permission 0700
<ide> err := os.Mkdir(filepath.Join(src, "d1"), 0700)
<ide> assert.NilError(t, err)
<ide> func isOpaque(dir string) error {
<ide>
<ide> func TestReexecUserNSOverlayWhiteoutConverter(t *testing.T) {
<ide> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<del> skip.If(t, rsystem.RunningInUserNS(), "skipping test that requires initial userns")
<add> skip.If(t, sys.RunningInUserNS(), "skipping test that requires initial userns")
<ide> if err := supportsUserNSOverlay(); err != nil {
<ide> t.Skipf("skipping test that requires kernel support for overlay-in-userns: %v", err)
<ide> }
<ide><path>pkg/archive/archive_test.go
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/ioutils"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "gotest.tools/v3/assert"
<ide> is "gotest.tools/v3/assert/cmp"
<ide> "gotest.tools/v3/skip"
<ide> func TestReplaceFileTarWrapper(t *testing.T) {
<ide> // version of this package that was built with <=go17 are still readable.
<ide> func TestPrefixHeaderReadable(t *testing.T) {
<ide> skip.If(t, runtime.GOOS != "windows" && os.Getuid() != 0, "skipping test that requires root")
<del> skip.If(t, rsystem.RunningInUserNS(), "skipping test that requires more than 010000000 UIDs, which is unlikely to be satisfied when running in userns")
<add> skip.If(t, sys.RunningInUserNS(), "skipping test that requires more than 010000000 UIDs, which is unlikely to be satisfied when running in userns")
<ide> // https://gist.github.com/stevvooe/e2a790ad4e97425896206c0816e1a882#file-out-go
<ide> var testFile = []byte("\x1f\x8b\x08\x08\x44\x21\x68\x59\x00\x03\x74\x2e\x74\x61\x72\x00\x4b\xcb\xcf\x67\xa0\x35\x30\x80\x00\x86\x06\x10\x47\x01\xc1\x37\x40\x00\x54\xb6\xb1\xa1\xa9\x99\x09\x48\x25\x1d\x40\x69\x71\x49\x62\x91\x02\xe5\x76\xa1\x79\x84\x21\x91\xd6\x80\x72\xaf\x8f\x82\x51\x30\x0a\x46\x36\x00\x00\xf0\x1c\x1e\x95\x00\x06\x00\x00")
<ide>
<ide><path>pkg/archive/archive_unix.go
<ide> import (
<ide> "strings"
<ide> "syscall"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/system"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "golang.org/x/sys/unix"
<ide> )
<ide>
<ide> func getFileUIDGID(stat interface{}) (idtools.Identity, error) {
<ide> // handleTarTypeBlockCharFifo is an OS-specific helper function used by
<ide> // createTarFile to handle the following types of header: Block; Char; Fifo
<ide> func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {
<del> if rsystem.RunningInUserNS() {
<add> if sys.RunningInUserNS() {
<ide> // cannot create a device if running in user namespace
<ide> return nil
<ide> }
<ide><path>pkg/archive/archive_unix_test.go
<ide> import (
<ide> "syscall"
<ide> "testing"
<ide>
<add> "github.com/containerd/containerd/sys"
<ide> "github.com/docker/docker/pkg/system"
<del> rsystem "github.com/opencontainers/runc/libcontainer/system"
<ide> "golang.org/x/sys/unix"
<ide> "gotest.tools/v3/assert"
<ide> is "gotest.tools/v3/assert/cmp"
<ide> func getInode(path string) (uint64, error) {
<ide>
<ide> func TestTarWithBlockCharFifo(t *testing.T) {
<ide> skip.If(t, os.Getuid() != 0, "skipping test that requires root")
<del> skip.If(t, rsystem.RunningInUserNS(), "skipping test that requires initial userns")
<add> skip.If(t, sys.RunningInUserNS(), "skipping test that requires initial userns")
<ide> origin, err := ioutil.TempDir("", "docker-test-tar-hardlink")
<ide> assert.NilError(t, err)
<ide> | 4 |
Ruby | Ruby | remove unecessary config_accessors | e6bfcc21a8b1a139dacc8d6c957bc4ab3e55c3b6 | <ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> module Rendering
<ide> include AbstractController::ViewPaths
<ide>
<ide> included do
<del> config_accessor :protected_instance_variables, :instance_reader => false
<add> class_attribute :protected_instance_variables
<ide> self.protected_instance_variables = []
<ide> end
<ide>
<ide> def view_context_class
<ide>
<ide> attr_internal_writer :view_context_class
<ide>
<del> # Explicitly define protected_instance_variables so it can be
<del> # inherited and overwritten by other modules if needed.
<del> def protected_instance_variables
<del> config.protected_instance_variables
<del> end
<del>
<ide> def view_context_class
<ide> @_view_context_class ||= self.class.view_context_class
<ide> end
<ide><path>actionpack/lib/action_controller/caching/pages.rb
<ide> module Pages
<ide> # For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>Rails.root + "/public"</tt>). Changing
<ide> # this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your
<ide> # web server to look in the new location for cached files.
<del> config_accessor :page_cache_directory
<add> class_attribute :page_cache_directory
<ide> self.page_cache_directory ||= ''
<ide>
<ide> # Most Rails requests do not have an extension, such as <tt>/weblog/new</tt>. In these cases, the page caching mechanism will add one in
<ide> # order to make it easy for the cached files to be picked up properly by the web server. By default, this cache extension is <tt>.html</tt>.
<ide> # If you want something else, like <tt>.php</tt> or <tt>.shtml</tt>, just set Base.page_cache_extension. In cases where a request already has an
<ide> # extension, such as <tt>.xml</tt> or <tt>.rss</tt>, page caching will not add an extension. This allows it to work well with RESTful apps.
<del> config_accessor :page_cache_extension
<add> class_attribute :page_cache_extension
<ide> self.page_cache_extension ||= '.html'
<ide>
<ide> # The compression used for gzip. If false (default), the page is not compressed.
<ide> # If can be a symbol showing the ZLib compression method, for example, :best_compression
<ide> # or :best_speed or an integer configuring the compression level.
<del> config_accessor :page_cache_compression
<add> class_attribute :page_cache_compression
<ide> self.page_cache_compression ||= false
<ide> end
<ide>
<ide><path>actionpack/lib/action_controller/metal/helpers.rb
<ide> module Helpers
<ide> include AbstractController::Helpers
<ide>
<ide> included do
<del> config_accessor :helpers_path, :include_all_helpers
<add> class_attribute :helpers_path, :include_all_helpers
<ide> self.helpers_path ||= []
<ide> self.include_all_helpers = true
<ide> end | 3 |
Python | Python | fix dummy creation script | 032d63b97657d802362a707f57641ad702d5a0df | <ide><path>utils/check_dummies.py
<ide> _re_backend = re.compile(r"is\_([a-z_]*)_available()")
<ide> # Matches from xxx import bla
<ide> _re_single_line_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
<del>_re_test_backend = re.compile(r"^\s+if\s+is\_[a-z]*\_available\(\)")
<add>_re_test_backend = re.compile(r"^\s+if\s+not\s+is\_[a-z]*\_available\(\)")
<ide>
<ide>
<ide> DUMMY_CONSTANT = """
<ide> def read_init():
<ide> # If the line is an if is_backend_available, we grab all objects associated.
<ide> backend = find_backend(lines[line_index])
<ide> if backend is not None:
<add> while not lines[line_index].startswith(" else:"):
<add> line_index += 1
<ide> line_index += 1
<ide>
<ide> objects = [] | 1 |
PHP | PHP | allow newlines in confirm messages | 6790a901a553b54cc60c5cf8689b72f416a1f95a | <ide><path>src/View/Helper.php
<ide> public function __get($name)
<ide> */
<ide> protected function _confirm($message, $okCode, $cancelCode = '', $options = [])
<ide> {
<del> $message = json_encode($message);
<add> $message = str_replace('\n', "\n", json_encode($message));
<ide> $confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
<ide> // We cannot change the key here in 3.x, but the behavior is inverted in this case
<ide> $escape = isset($options['escape']) && $options['escape'] === false;
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testPostLink()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Form->postLink('Delete', '/posts/delete/1', ['confirm' => 'Confirm?']);
<del> $expected = [
<del> 'form' => [
<del> 'method' => 'post', 'action' => '/posts/delete/1',
<del> 'name' => 'preg:/post_\w+/', 'style' => 'display:none;'
<del> ],
<del> 'input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST'],
<del> '/form',
<del> 'a' => ['href' => '#', 'onclick' => 'preg:/if \(confirm\("Confirm\?"\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/'],
<del> 'Delete',
<del> '/a'
<del> ];
<del> $this->assertHtml($expected, $result);
<del>
<ide> $result = $this->Form->postLink(
<ide> 'Delete',
<ide> '/posts/delete/1',
<del> ['escape' => false, 'confirm' => '\'Confirm\' this "deletion"?']
<add> ['target' => '_blank', 'class' => 'btn btn-danger']
<ide> );
<ide> $expected = [
<ide> 'form' => [
<del> 'method' => 'post', 'action' => '/posts/delete/1',
<add> 'method' => 'post', 'target' => '_blank', 'action' => '/posts/delete/1',
<ide> 'name' => 'preg:/post_\w+/', 'style' => 'display:none;'
<ide> ],
<ide> 'input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST'],
<ide> '/form',
<del> 'a' => ['href' => '#', 'onclick' => 'preg:/if \(confirm\("'Confirm' this \\\\"deletion\\\\"\?"\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/'],
<add> 'a' => ['class' => 'btn btn-danger', 'href' => '#', 'onclick' => 'preg:/document\.post_\w+\.submit\(\); event\.returnValue = false; return false;/'],
<ide> 'Delete',
<ide> '/a'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<add> }
<ide>
<del> $result = $this->Form->postLink('Delete', '/posts/delete/1', ['target' => '_blank']);
<add> /**
<add> * Test the confirm option for postLink()
<add> *
<add> * @return void
<add> */
<add> public function testPostLinkWithConfirm()
<add> {
<add> $result = $this->Form->postLink('Delete', '/posts/delete/1', ['confirm' => 'Confirm?']);
<ide> $expected = [
<ide> 'form' => [
<del> 'method' => 'post', 'target' => '_blank', 'action' => '/posts/delete/1',
<add> 'method' => 'post', 'action' => '/posts/delete/1',
<ide> 'name' => 'preg:/post_\w+/', 'style' => 'display:none;'
<ide> ],
<ide> 'input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST'],
<ide> '/form',
<del> 'a' => ['href' => '#', 'onclick' => 'preg:/document\.post_\w+\.submit\(\); event\.returnValue = false; return false;/'],
<add> 'a' => ['href' => '#', 'onclick' => 'preg:/if \(confirm\("Confirm\?"\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/'],
<ide> 'Delete',
<ide> '/a'
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->postLink(
<del> '',
<del> ['controller' => 'items', 'action' => 'delete', 10],
<del> ['class' => 'btn btn-danger', 'escape' => false, 'confirm' => 'Confirm thing']
<add> 'Delete',
<add> '/posts/delete/1',
<add> ['escape' => false, 'confirm' => "'Confirm'\nthis \"deletion\"?"]
<ide> );
<ide> $expected = [
<ide> 'form' => [
<del> 'method' => 'post', 'action' => '/items/delete/10',
<add> 'method' => 'post', 'action' => '/posts/delete/1',
<ide> 'name' => 'preg:/post_\w+/', 'style' => 'display:none;'
<ide> ],
<ide> 'input' => ['type' => 'hidden', 'name' => '_method', 'value' => 'POST'],
<ide> '/form',
<del> 'a' => ['class' => 'btn btn-danger', 'href' => '#', 'onclick' => 'preg:/if \(confirm\(\"\;Confirm thing\"\;\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/'],
<add> 'a' => ['href' => '#', 'onclick' => "preg:/if \(confirm\("'Confirm'\\nthis \\\\"deletion\\\\"\?"\)\) \{ document\.post_\w+\.submit\(\); \} event\.returnValue = false; return false;/"],
<add> 'Delete',
<ide> '/a'
<ide> ];
<ide> $this->assertHtml($expected, $result); | 2 |
Go | Go | use go-generate to build volume/driver/proxy.go | 88e4dff9a966485413d4acc1ecd99de6a6574e10 | <ide><path>volume/drivers/api.go
<add>//go:generate pluginrpc-gen -i $GOFILE -o proxy.go -type VolumeDriver -name VolumeDriver
<add>
<ide> package volumedrivers
<ide>
<ide> import "github.com/docker/docker/volume"
<ide>
<del>type client interface {
<del> Call(string, interface{}, interface{}) error
<del>}
<del>
<ide> func NewVolumeDriver(name string, c client) volume.Driver {
<ide> proxy := &volumeDriverProxy{c}
<ide> return &volumeDriverAdapter{name, proxy}
<ide> }
<ide>
<ide> type VolumeDriver interface {
<add> // Create a volume with the given name
<ide> Create(name string) (err error)
<add> // Remove the volume with the given name
<ide> Remove(name string) (err error)
<add> // Get the mountpoint of the given volume
<ide> Path(name string) (mountpoint string, err error)
<add> // Mount the given volume and return the mountpoint
<ide> Mount(name string) (mountpoint string, err error)
<add> // Unmount the given volume
<ide> Unmount(name string) (err error)
<ide> }
<ide><path>volume/drivers/proxy.go
<add>// generated code - DO NOT EDIT
<add>
<ide> package volumedrivers
<ide>
<del>import "fmt"
<add>import "errors"
<ide>
<del>// currently created by hand. generation tool would generate this like:
<del>// $ rpc-gen volume/drivers/api.go VolumeDriver > volume/drivers/proxy.go
<add>type client interface {
<add> Call(string, interface{}, interface{}) error
<add>}
<ide>
<del>type volumeDriverRequest struct {
<del> Name string
<add>type volumeDriverProxy struct {
<add> client
<ide> }
<ide>
<del>type volumeDriverResponse struct {
<del> Mountpoint string `json:",omitempty"`
<del> Err string `json:",omitempty"`
<add>type volumeDriverProxyCreateRequest struct {
<add> Name string
<ide> }
<ide>
<del>type volumeDriverProxy struct {
<del> c client
<add>type volumeDriverProxyCreateResponse struct {
<add> Err string
<ide> }
<ide>
<del>func (pp *volumeDriverProxy) Create(name string) error {
<del> args := volumeDriverRequest{name}
<del> var ret volumeDriverResponse
<del> err := pp.c.Call("VolumeDriver.Create", args, &ret)
<del> if err != nil {
<del> return pp.fmtError(name, err.Error())
<add>func (pp *volumeDriverProxy) Create(name string) (err error) {
<add> var (
<add> req volumeDriverProxyCreateRequest
<add> ret volumeDriverProxyCreateResponse
<add> )
<add>
<add> req.Name = name
<add> if err = pp.Call("VolumeDriver.Create", req, &ret); err != nil {
<add> return
<ide> }
<del> return pp.fmtError(name, ret.Err)
<del>}
<ide>
<del>func (pp *volumeDriverProxy) Remove(name string) error {
<del> args := volumeDriverRequest{name}
<del> var ret volumeDriverResponse
<del> err := pp.c.Call("VolumeDriver.Remove", args, &ret)
<del> if err != nil {
<del> return pp.fmtError(name, err.Error())
<add> if ret.Err != "" {
<add> err = errors.New(ret.Err)
<ide> }
<del> return pp.fmtError(name, ret.Err)
<add>
<add> return
<add>}
<add>
<add>type volumeDriverProxyRemoveRequest struct {
<add> Name string
<ide> }
<ide>
<del>func (pp *volumeDriverProxy) Path(name string) (string, error) {
<del> args := volumeDriverRequest{name}
<del> var ret volumeDriverResponse
<del> if err := pp.c.Call("VolumeDriver.Path", args, &ret); err != nil {
<del> return "", pp.fmtError(name, err.Error())
<add>type volumeDriverProxyRemoveResponse struct {
<add> Err string
<add>}
<add>
<add>func (pp *volumeDriverProxy) Remove(name string) (err error) {
<add> var (
<add> req volumeDriverProxyRemoveRequest
<add> ret volumeDriverProxyRemoveResponse
<add> )
<add>
<add> req.Name = name
<add> if err = pp.Call("VolumeDriver.Remove", req, &ret); err != nil {
<add> return
<ide> }
<del> return ret.Mountpoint, pp.fmtError(name, ret.Err)
<add>
<add> if ret.Err != "" {
<add> err = errors.New(ret.Err)
<add> }
<add>
<add> return
<ide> }
<ide>
<del>func (pp *volumeDriverProxy) Mount(name string) (string, error) {
<del> args := volumeDriverRequest{name}
<del> var ret volumeDriverResponse
<del> if err := pp.c.Call("VolumeDriver.Mount", args, &ret); err != nil {
<del> return "", pp.fmtError(name, err.Error())
<add>type volumeDriverProxyPathRequest struct {
<add> Name string
<add>}
<add>
<add>type volumeDriverProxyPathResponse struct {
<add> Mountpoint string
<add> Err string
<add>}
<add>
<add>func (pp *volumeDriverProxy) Path(name string) (mountpoint string, err error) {
<add> var (
<add> req volumeDriverProxyPathRequest
<add> ret volumeDriverProxyPathResponse
<add> )
<add>
<add> req.Name = name
<add> if err = pp.Call("VolumeDriver.Path", req, &ret); err != nil {
<add> return
<ide> }
<del> return ret.Mountpoint, pp.fmtError(name, ret.Err)
<add>
<add> mountpoint = ret.Mountpoint
<add>
<add> if ret.Err != "" {
<add> err = errors.New(ret.Err)
<add> }
<add>
<add> return
<add>}
<add>
<add>type volumeDriverProxyMountRequest struct {
<add> Name string
<add>}
<add>
<add>type volumeDriverProxyMountResponse struct {
<add> Mountpoint string
<add> Err string
<ide> }
<ide>
<del>func (pp *volumeDriverProxy) Unmount(name string) error {
<del> args := volumeDriverRequest{name}
<del> var ret volumeDriverResponse
<del> err := pp.c.Call("VolumeDriver.Unmount", args, &ret)
<del> if err != nil {
<del> return pp.fmtError(name, err.Error())
<add>func (pp *volumeDriverProxy) Mount(name string) (mountpoint string, err error) {
<add> var (
<add> req volumeDriverProxyMountRequest
<add> ret volumeDriverProxyMountResponse
<add> )
<add>
<add> req.Name = name
<add> if err = pp.Call("VolumeDriver.Mount", req, &ret); err != nil {
<add> return
<ide> }
<del> return pp.fmtError(name, ret.Err)
<add>
<add> mountpoint = ret.Mountpoint
<add>
<add> if ret.Err != "" {
<add> err = errors.New(ret.Err)
<add> }
<add>
<add> return
<add>}
<add>
<add>type volumeDriverProxyUnmountRequest struct {
<add> Name string
<ide> }
<ide>
<del>func (pp *volumeDriverProxy) fmtError(name string, err string) error {
<del> if len(err) == 0 {
<del> return nil
<add>type volumeDriverProxyUnmountResponse struct {
<add> Err string
<add>}
<add>
<add>func (pp *volumeDriverProxy) Unmount(name string) (err error) {
<add> var (
<add> req volumeDriverProxyUnmountRequest
<add> ret volumeDriverProxyUnmountResponse
<add> )
<add>
<add> req.Name = name
<add> if err = pp.Call("VolumeDriver.Unmount", req, &ret); err != nil {
<add> return
<ide> }
<del> return fmt.Errorf("External volume driver request failed for %s: %v", name, err)
<add>
<add> if ret.Err != "" {
<add> err = errors.New(ret.Err)
<add> }
<add>
<add> return
<ide> } | 2 |
Javascript | Javascript | make reloads faster for simple file changes | 5df9c673517fe14c64762ad979c2c50adca5b41e | <ide><path>packager/react-packager/src/Bundler/Bundle.js
<ide> class Bundle extends BundleBase {
<ide> this._addRequireCall(super.getMainModuleId());
<ide> }
<ide>
<del> super.finalize();
<add> super.finalize(options);
<ide> }
<ide>
<ide> _addRequireCall(moduleId) {
<ide><path>packager/react-packager/src/Bundler/BundleBase.js
<ide> class BundleBase {
<ide> }
<ide>
<ide> finalize(options) {
<del> Object.freeze(this._modules);
<del> Object.freeze(this._assets);
<add> if (!options.allowUpdates) {
<add> Object.freeze(this._modules);
<add> Object.freeze(this._assets);
<add> }
<ide>
<ide> this._finalized = true;
<ide> }
<ide> class BundleBase {
<ide> return this._source;
<ide> }
<ide>
<add> invalidateSource() {
<add> this._source = null;
<add> }
<add>
<ide> assertFinalized(message) {
<ide> if (!this._finalized) {
<ide> throw new Error(message || 'Bundle needs to be finalized before getting any source');
<ide><path>packager/react-packager/src/Bundler/__tests__/Bundler-test.js
<ide> describe('Bundler', function() {
<ide> dependencies: modules,
<ide> transformOptions,
<ide> getModuleId: () => 123,
<add> getResolvedDependencyPairs: () => [],
<ide> })
<ide> );
<ide>
<ide> describe('Bundler', function() {
<ide> });
<ide> });
<ide>
<del> pit('create a bundle', function() {
<add> it('create a bundle', function() {
<ide> assetServer.getAssetData.mockImpl(() => {
<ide> return {
<ide> scales: [1,2,3],
<ide> describe('Bundler', function() {
<ide> expect(ithAddedModule(3)).toEqual('/root/img/new_image.png');
<ide> expect(ithAddedModule(4)).toEqual('/root/file.json');
<ide>
<del> expect(bundle.finalize.mock.calls[0]).toEqual([
<del> {runMainModule: true, runBeforeMainModule: []}
<del> ]);
<add> expect(bundle.finalize.mock.calls[0]).toEqual([{
<add> runMainModule: true,
<add> runBeforeMainModule: [],
<add> allowUpdates: false,
<add> }]);
<ide>
<ide> expect(bundle.addAsset.mock.calls[0]).toEqual([{
<ide> __packager_asset: true,
<ide><path>packager/react-packager/src/Bundler/index.js
<ide> const validateOpts = declareOpts({
<ide> type: 'boolean',
<ide> default: false,
<ide> },
<add> allowBundleUpdates: {
<add> type: 'boolean',
<add> default: false,
<add> },
<ide> });
<ide>
<ide> const assetPropertyBlacklist = new Set([
<ide> class Bundler {
<ide> bundle.finalize({
<ide> runMainModule,
<ide> runBeforeMainModule: runBeforeMainModuleIds,
<add> allowUpdates: this._opts.allowBundleUpdates,
<ide> });
<ide> return bundle;
<ide> });
<ide> class Bundler {
<ide> entryFilePath,
<ide> transformOptions: response.transformOptions,
<ide> getModuleId: response.getModuleId,
<add> dependencyPairs: response.getResolvedDependencyPairs(module),
<ide> }).then(transformed => {
<ide> modulesByName[transformed.name] = module;
<ide> onModuleTransformed({
<ide> class Bundler {
<ide> );
<ide> }
<ide>
<del> _toModuleTransport({module, bundle, entryFilePath, transformOptions, getModuleId}) {
<add> _toModuleTransport({
<add> module,
<add> bundle,
<add> entryFilePath,
<add> transformOptions,
<add> getModuleId,
<add> dependencyPairs,
<add> }) {
<ide> let moduleTransport;
<ide> const moduleId = getModuleId(module);
<ide>
<ide> class Bundler {
<ide> id: moduleId,
<ide> code,
<ide> map,
<del> meta: {dependencies, dependencyOffsets, preloaded},
<add> meta: {dependencies, dependencyOffsets, preloaded, dependencyPairs},
<ide> sourceCode: source,
<ide> sourcePath: module.path
<ide> });
<ide><path>packager/react-packager/src/Server/index.js
<ide> const mime = require('mime-types');
<ide> const path = require('path');
<ide> const url = require('url');
<ide>
<del>function debounce(fn, delay) {
<del> var timeout;
<del> return () => {
<add>const debug = require('debug')('ReactNativePackager:Server');
<add>
<add>function debounceAndBatch(fn, delay) {
<add> let timeout, args = [];
<add> return (value) => {
<add> args.push(value);
<ide> clearTimeout(timeout);
<del> timeout = setTimeout(fn, delay);
<add> timeout = setTimeout(() => {
<add> const a = args;
<add> args = [];
<add> fn(a);
<add> }, delay);
<ide> };
<ide> }
<ide>
<ide> const bundleOpts = declareOpts({
<ide> isolateModuleIDs: {
<ide> type: 'boolean',
<ide> default: false
<del> }
<add> },
<add> resolutionResponse: {
<add> type: 'object',
<add> },
<ide> });
<ide>
<ide> const dependencyOpts = declareOpts({
<ide> const dependencyOpts = declareOpts({
<ide> type: 'boolean',
<ide> default: false,
<ide> },
<add> minify: {
<add> type: 'boolean',
<add> default: undefined,
<add> },
<ide> });
<ide>
<add>const bundleDeps = new WeakMap();
<add>
<ide> class Server {
<ide> constructor(options) {
<ide> const opts = validateOpts(options);
<ide> class Server {
<ide> const bundlerOpts = Object.create(opts);
<ide> bundlerOpts.fileWatcher = this._fileWatcher;
<ide> bundlerOpts.assetServer = this._assetServer;
<add> bundlerOpts.allowBundleUpdates = !options.nonPersistent;
<ide> this._bundler = new Bundler(bundlerOpts);
<ide>
<ide> this._fileWatcher.on('all', this._onFileChange.bind(this));
<ide>
<del> this._debouncedFileChangeHandler = debounce(filePath => {
<del> this._clearBundles();
<add> this._debouncedFileChangeHandler = debounceAndBatch(filePaths => {
<add> // only clear bundles for non-JS changes
<add> if (filePaths.every(RegExp.prototype.test, /\.js(?:on)?$/i)) {
<add> for (const key in this._bundles) {
<add> this._bundles[key].then(bundle => {
<add> const deps = bundleDeps.get(bundle);
<add> filePaths.forEach(filePath => {
<add> if (deps.files.has(filePath)) {
<add> deps.outdated.add(filePath);
<add> }
<add> });
<add> });
<add> }
<add> } else {
<add> this._clearBundles();
<add> }
<ide> this._informChangeWatchers();
<ide> }, 50);
<ide> }
<ide> class Server {
<ide> }
<ide>
<ide> const opts = bundleOpts(options);
<del> return this._bundler.bundle(opts);
<add> const building = this._bundler.bundle(opts);
<add> building.then(bundle => {
<add> const modules = bundle.getModules();
<add> const nonVirtual = modules.filter(m => !m.virtual);
<add> bundleDeps.set(bundle, {
<add> files: new Map(
<add> nonVirtual
<add> .map(({sourcePath, meta = {dependencies: []}}) =>
<add> [sourcePath, meta.dependencies])
<add> ),
<add> idToIndex: new Map(modules.map(({id}, i) => [id, i])),
<add> dependencyPairs: new Map(
<add> nonVirtual
<add> .filter(({meta}) => meta && meta.dependencyPairs)
<add> .map(m => [m.sourcePath, m.meta.dependencyPairs])
<add> ),
<add> outdated: new Set(),
<add> });
<add> });
<add> return building;
<ide> });
<ide> }
<ide>
<ide> class Server {
<ide> ).done(() => Activity.endEvent(assetEvent));
<ide> }
<ide>
<add> _useCachedOrUpdateOrCreateBundle(options) {
<add> const optionsJson = JSON.stringify(options);
<add> const bundleFromScratch = () => {
<add> const building = this.buildBundle(options);
<add> this._bundles[optionsJson] = building;
<add> return building;
<add> };
<add>
<add> if (optionsJson in this._bundles) {
<add> return this._bundles[optionsJson].then(bundle => {
<add> const deps = bundleDeps.get(bundle);
<add> const {dependencyPairs, files, idToIndex, outdated} = deps;
<add> if (outdated.size) {
<add> debug('Attempt to update existing bundle');
<add> const changedModules =
<add> Array.from(outdated, this.getModuleForPath, this);
<add> deps.outdated = new Set();
<add>
<add> const opts = bundleOpts(options);
<add> const {platform, dev, minify, hot} = opts;
<add>
<add> // Need to create a resolution response to pass to the bundler
<add> // to process requires after transform. By providing a
<add> // specific response we can compute a non recursive one which
<add> // is the least we need and improve performance.
<add> const bundlePromise = this._bundles[optionsJson] =
<add> this.getDependencies({
<add> platform, dev, hot, minify,
<add> entryFile: options.entryFile,
<add> recursive: false,
<add> }).then(response => {
<add> debug('Update bundle: rebuild shallow bundle');
<add>
<add> changedModules.forEach(m => {
<add> response.setResolvedDependencyPairs(
<add> m,
<add> dependencyPairs.get(m.path),
<add> {ignoreFinalized: true},
<add> );
<add> });
<add>
<add> return this.buildBundle({
<add> ...options,
<add> resolutionResponse: response.copy({
<add> dependencies: changedModules,
<add> })
<add> }).then(updateBundle => {
<add> const oldModules = bundle.getModules();
<add> const newModules = updateBundle.getModules();
<add> for (let i = 0, n = newModules.length; i < n; i++) {
<add> const moduleTransport = newModules[i];
<add> const {meta, sourcePath} = moduleTransport;
<add> if (outdated.has(sourcePath)) {
<add> if (!contentsEqual(meta.dependencies, new Set(files.get(sourcePath)))) {
<add> // bail out if any dependencies changed
<add> return Promise.reject(Error(
<add> `Dependencies of ${sourcePath} changed from [${
<add> files.get(sourcePath).join(', ')
<add> }] to [${meta.dependencies.join(', ')}]`
<add> ));
<add> }
<add>
<add> oldModules[idToIndex.get(moduleTransport.id)] = moduleTransport;
<add> }
<add> }
<add>
<add> bundle.invalidateSource();
<add> debug('Successfully updated existing bundle');
<add> return bundle;
<add> });
<add> }).catch(e => {
<add> debug('Failed to update existing bundle, rebuilding...', e.stack || e.message);
<add> return bundleFromScratch();
<add> });
<add> return bundlePromise;
<add> } else {
<add> debug('Using cached bundle');
<add> return bundle;
<add> }
<add> });
<add> }
<add>
<add> return bundleFromScratch();
<add> }
<add>
<ide> processRequest(req, res, next) {
<ide> const urlObj = url.parse(req.url, true);
<ide> const pathname = urlObj.pathname;
<ide> class Server {
<ide>
<ide> const startReqEventId = Activity.startEvent('request:' + req.url);
<ide> const options = this._getOptionsFromUrl(req.url);
<del> const optionsJson = JSON.stringify(options);
<del> const building = this._bundles[optionsJson] || this.buildBundle(options);
<del>
<del> this._bundles[optionsJson] = building;
<add> debug('Getting bundle for request');
<add> const building = this._useCachedOrUpdateOrCreateBundle(options);
<ide> building.then(
<ide> p => {
<ide> if (requestType === 'bundle') {
<add> debug('Generating source code');
<ide> const bundleSource = p.getSource({
<ide> inlineSourceMap: options.inlineSourceMap,
<ide> minify: options.minify,
<ide> dev: options.dev,
<ide> });
<add> debug('Writing response headers');
<ide> res.setHeader('Content-Type', 'application/javascript');
<ide> res.setHeader('ETag', p.getEtag());
<ide> if (req.headers['if-none-match'] === res.getHeader('ETag')){
<add> debug('Responding with 304');
<ide> res.statusCode = 304;
<ide> res.end();
<ide> } else {
<add> debug('Writing request body');
<ide> res.end(bundleSource);
<ide> }
<add> debug('Finished response');
<ide> Activity.endEvent(startReqEventId);
<ide> } else if (requestType === 'map') {
<ide> let sourceMap = p.getSourceMap({
<ide> class Server {
<ide> Activity.endEvent(startReqEventId);
<ide> }
<ide> },
<del> this._handleError.bind(this, res, optionsJson)
<add> error => this._handleError(res, JSON.stringify(options), error)
<ide> ).done();
<ide> }
<ide>
<ide> class Server {
<ide>
<ide> _sourceMapForURL(reqUrl) {
<ide> const options = this._getOptionsFromUrl(reqUrl);
<del> const optionsJson = JSON.stringify(options);
<del> const building = this._bundles[optionsJson] || this.buildBundle(options);
<del> this._bundles[optionsJson] = building;
<add> const building = this._useCachedOrUpdateOrCreateBundle(options);
<ide> return building.then(p => {
<ide> const sourceMap = p.getSourceMap({
<ide> minify: options.minify,
<ide> class Server {
<ide> }
<ide> }
<ide>
<add>function contentsEqual(array, set) {
<add> return array.length === set.size && array.every(set.has, set);
<add>}
<add>
<ide> module.exports = Server;
<ide><path>packager/react-packager/src/node-haste/DependencyGraph/ResolutionResponse.js
<ide> */
<ide> 'use strict';
<ide>
<add>const NO_OPTIONS = {};
<add>
<ide> class ResolutionResponse {
<ide> constructor({transformOptions}) {
<ide> this.transformOptions = transformOptions;
<ide> class ResolutionResponse {
<ide> this.numPrependedDependencies += 1;
<ide> }
<ide>
<del> setResolvedDependencyPairs(module, pairs) {
<del> this._assertNotFinalized();
<add> setResolvedDependencyPairs(module, pairs, options = NO_OPTIONS) {
<add> if (!options.ignoreFinalized) {
<add> this._assertNotFinalized();
<add> }
<ide> const hash = module.hash();
<ide> if (this._mappings[hash] == null) {
<ide> this._mappings[hash] = pairs; | 6 |
Javascript | Javascript | update collada exporter to export lightmap uvs | b886901e6ce83ff42b2286879c58c586e5f2f835 | <ide><path>examples/jsm/exporters/ColladaExporter.js
<ide> ColladaExporter.prototype = {
<ide> triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="0" />`;
<ide>
<ide> }
<add>
<add> // serialize lightmap uvs
<add> if ( 'uv2' in bufferGeometry.attributes ) {
<add> var uvName = `${ meshid }-texcoord2`;
<add> gnode += getAttribute( bufferGeometry.attributes.uv2, uvName, [ 'S', 'T' ], 'float' );
<add> triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="1" />`;
<add> }
<ide>
<ide> // serialize colors
<ide> if ( 'color' in bufferGeometry.attributes ) {
<ide> ColladaExporter.prototype = {
<ide> triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
<ide>
<ide> }
<del>
<add>
<ide> var indexArray = null;
<ide> if ( bufferGeometry.index ) {
<ide> | 1 |
Text | Text | add link to systemd article, fix typo | b9e6be25d1afbf04a3455ff55394bd9037238b2c | <ide><path>docs/installation/debian.md
<ide> To verify that everything has worked as expected:
<ide> This command downloads and runs the `hello-world` image in a container. When the
<ide> container runs, it prints an informational message. Then, it exits.
<ide>
<add>If you need to add an HTTP Proxy, set a different directory or partition for the
<add>Docker runtime files, or make other customizations, read our Systemd article to
<add>learn how to [customize your Systemd Docker daemon options](/articles/systemd/).
<add>
<ide> > **Note**:
<ide> > If you want to enable memory and swap accounting see
<del>> [this](/installation/ubuntulinux/#memory-and-swap-accounting).
<add>> [this](/installation/ubuntulinux/#adjust-memory-and-swap-accounting).
<ide>
<ide> ### Uninstallation
<ide> | 1 |
Javascript | Javascript | add deprecation to `name_key` | 914f3cc37763cad7d48a22fef65d979743d5a26e | <ide><path>packages/ember/index.js
<ide> Ember.canInvoke = utils.canInvoke;
<ide> Ember.tryInvoke = utils.tryInvoke;
<ide> Ember.wrap = utils.wrap;
<ide> Ember.uuid = utils.uuid;
<del>Ember.NAME_KEY = utils.NAME_KEY;
<add>
<add>Object.defineProperty(Ember, 'NAME_KEY', {
<add> enumerable: false,
<add> get() {
<add> deprecate('Using `Ember.NAME_KEY` is deprecated, override `.toString` instead', false, {
<add> id: 'ember-name-key-usage',
<add> until: '3.9.0',
<add> });
<add>
<add> return utils.NAME_KEY;
<add> },
<add>});
<add>
<ide> Ember._Cache = utils.Cache;
<ide>
<ide> // ****@ember/-internals/container****
<ide><path>packages/ember/tests/reexports_test.js
<ide> moduleFor(
<ide> }, /EXTEND_PROTOTYPES is deprecated/);
<ide> }
<ide>
<add> ['@test Ember.NAME_KEY is deprecated']() {
<add> expectDeprecation(() => {
<add> Ember.NAME_KEY;
<add> }, 'Using `Ember.NAME_KEY` is deprecated, override `.toString` instead');
<add> }
<add>
<ide> '@test Ember.FEATURES is exported'(assert) {
<ide> for (let feature in FEATURES) {
<ide> assert.equal(
<ide> let allExports = [
<ide> ['canInvoke', '@ember/-internals/utils'],
<ide> ['tryInvoke', '@ember/-internals/utils'],
<ide> ['wrap', '@ember/-internals/utils'],
<del> ['NAME_KEY', '@ember/-internals/utils'],
<ide>
<ide> // @ember/-internals/container
<ide> ['Registry', '@ember/-internals/container', 'Registry'], | 2 |
Java | Java | fix race condition on startsurface | 74a756846fdab1ef7d183c4df3069a23fcd0d49e | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public void showDevOptionsDialog() {
<ide> }
<ide>
<ide> private void clearReactRoot(ReactRoot reactRoot) {
<add> if (ReactFeatureFlags.enableStartSurfaceRaceConditionFix) {
<add> reactRoot.getState().compareAndSet(ReactRoot.STATE_STARTED, ReactRoot.STATE_STOPPED);
<add> }
<ide> reactRoot.getRootViewGroup().removeAllViews();
<ide> reactRoot.getRootViewGroup().setId(View.NO_ID);
<ide> }
<ide> private void clearReactRoot(ReactRoot reactRoot) {
<ide> @ThreadConfined(UI)
<ide> public void attachRootView(ReactRoot reactRoot) {
<ide> UiThreadUtil.assertOnUiThread();
<del> mAttachedReactRoots.add(reactRoot);
<ide>
<del> // Reset reactRoot content as it's going to be populated by the application content from JS.
<del> clearReactRoot(reactRoot);
<add> // Calling clearReactRoot is necessary to initialize the Id on reactRoot
<add> // This is necessary independently if the RN Bridge has been initialized or not.
<add> // Ideally reactRoot should be initialized with id == NO_ID
<add> if (ReactFeatureFlags.enableStartSurfaceRaceConditionFix) {
<add> if (mAttachedReactRoots.add(reactRoot)) {
<add> clearReactRoot(reactRoot);
<add> }
<add> } else {
<add> mAttachedReactRoots.add(reactRoot);
<add> clearReactRoot(reactRoot);
<add> }
<ide>
<ide> // If react context is being created in the background, JS application will be started
<ide> // automatically when creation completes, as reactRoot reactRoot is part of the attached
<ide> // reactRoot reactRoot list.
<ide> ReactContext currentContext = getCurrentReactContext();
<ide> if (mCreateReactContextThread == null && currentContext != null) {
<del> attachRootViewToInstance(reactRoot);
<add> if (!ReactFeatureFlags.enableStartSurfaceRaceConditionFix
<add> || reactRoot.getState().compareAndSet(ReactRoot.STATE_STOPPED, ReactRoot.STATE_STARTED)) {
<add> attachRootViewToInstance(reactRoot);
<add> }
<ide> }
<ide> }
<ide>
<ide> private void setupReactContext(final ReactApplicationContext reactContext) {
<ide>
<ide> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_START);
<ide> for (ReactRoot reactRoot : mAttachedReactRoots) {
<del> attachRootViewToInstance(reactRoot);
<add> if (!ReactFeatureFlags.enableStartSurfaceRaceConditionFix
<add> || reactRoot
<add> .getState()
<add> .compareAndSet(ReactRoot.STATE_STOPPED, ReactRoot.STATE_STARTED)) {
<add> attachRootViewToInstance(reactRoot);
<add> }
<ide> }
<ide> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_END);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> import com.facebook.react.uimanager.common.UIManagerType;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.systrace.Systrace;
<add>import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> /**
<ide> * Default root view for catalyst apps. Provides the ability to listen for size changes so that a UI
<ide> public interface ReactRootViewEventListener {
<ide> private int mLastOffsetX = Integer.MIN_VALUE;
<ide> private int mLastOffsetY = Integer.MIN_VALUE;
<ide> private @UIManagerType int mUIManagerType = DEFAULT;
<add> private final AtomicInteger mState = new AtomicInteger(STATE_STOPPED);
<ide>
<ide> public ReactRootView(Context context) {
<ide> super(context);
<ide> public String getSurfaceID() {
<ide> return appProperties != null ? appProperties.getString("surfaceID") : null;
<ide> }
<ide>
<add> public AtomicInteger getState() {
<add> return mState;
<add> }
<add>
<ide> public static Point getViewportOffset(View v) {
<ide> int[] locationInWindow = new int[2];
<ide> v.getLocationInWindow(locationInWindow);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
<ide> public class ReactFeatureFlags {
<ide>
<ide> /** Disable UI update operations in non-Fabric renderer after catalyst instance was destroyed */
<ide> public static boolean disableNonFabricViewOperationsOnCatalystDestroy = false;
<add>
<add> /**
<add> * Fixes race-condition in the initialization of RN surface. TODO T78832286: remove this flag once
<add> * we verify the fix is correct in production
<add> */
<add> public static boolean enableStartSurfaceRaceConditionFix = false;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactRoot.java
<ide> import android.view.ViewGroup;
<ide> import androidx.annotation.Nullable;
<ide> import com.facebook.react.uimanager.common.UIManagerType;
<add>import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> /** Interface for the root native view of a React native application */
<ide> public interface ReactRoot {
<ide>
<add> /** This constant represents that ReactRoot hasn't started yet or it has been destroyed. */
<add> int STATE_STOPPED = 0;
<add> /** This constant represents that ReactRoot has started. */
<add> int STATE_STARTED = 1;
<add>
<ide> /** Return cached launch properties for app */
<ide> @Nullable
<ide> Bundle getAppProperties();
<ide> public interface ReactRoot {
<ide> @Deprecated
<ide> @Nullable
<ide> String getSurfaceID();
<add>
<add> /**
<add> * This API is likely to change once the fix of T78832286 is confirmed TODO: T78832286 revisit
<add> * this API
<add> *
<add> * @return an {@link AtomicInteger} that represents the state of the ReactRoot object. WARNING:
<add> */
<add> AtomicInteger getState();
<ide> } | 4 |
PHP | PHP | add additional tests to verify listener identity | e79c9f76ba84c49f23d99e00ce61706607abaab2 | <ide><path>Cake/Test/TestCase/ORM/BehaviorRegistryTest.php
<ide> public function testLoadBindEvents() {
<ide> $this->Behaviors->load('Sluggable');
<ide> $result = $this->EventManager->listeners('Model.beforeFind');
<ide> $this->assertCount(1, $result);
<add> $this->assertInstanceOf('TestApp\Model\Behavior\SluggableBehavior', $result[0]['callable'][0]);
<add> $this->assertEquals('beforeFind', $result[0]['callable'][1], 'Method name should match.');
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | add direction in security_group_rule creation | 33e694f37876693ec2bcb772684900f1ef3d38a1 | <ide><path>libcloud/compute/drivers/openstack.py
<ide> def ex_create_security_group_rule(self, security_group, ip_protocol,
<ide> return self._to_security_group_rule(self.network_connection.request(
<ide> '/v2.0/security-group-rules', method='POST',
<ide> data={'security_group_rule': {
<add> 'direction': 'ingress',
<ide> 'protocol': ip_protocol,
<ide> 'port_range_min': from_port,
<ide> 'port_range_max': to_port, | 1 |
Text | Text | add v3.13.4 to changelog | 93b2e873acd01347b5f792e233d6417a2670003d | <ide><path>CHANGELOG.md
<ide> - [#18381](https://github.com/emberjs/ember.js/pull/18381) Drop Node 6 and 11 support.
<ide> - [#18410](https://github.com/emberjs/ember.js/pull/18410) Use ember-cli-htmlbars for inline precompilation if possible.
<ide>
<add>### v3.13.4 (October 29,2019)
<add>
<add>- [#18476](https://github.com/emberjs/ember.js/pull/18476) [BUGFIX] Ensure model can be observed by sync observers.
<add>- [#18477](https://github.com/emberjs/ember.js/pull/18477) [BUGFIX] Allows @each to work with arrays that contain falsy values.
<add>- [#18500](https://github.com/emberjs/ember.js/pull/18500) [BUGFIX] Remove requirement for disabling jquery-integration in Octane.
<add>
<ide> ### v3.13.3 (October 8, 2019)
<ide>
<ide> - [#18462](https://github.com/emberjs/ember.js/pull/18462) [BUGFIX] Prevents observer re-entry. | 1 |
Javascript | Javascript | fix two overflow cases in sourcemap vlq decoding | 0214b90308404b18efd60ce07cb89014073ee161 | <ide><path>lib/internal/source_map/source_map.js
<ide> function decodeVLQ(stringCharIterator) {
<ide>
<ide> // Fix the sign.
<ide> const negative = result & 1;
<del> result >>= 1;
<del> return negative ? -result : result;
<add> // Use unsigned right shift, so that the 32nd bit is properly shifted to the
<add> // 31st, and the 32nd becomes unset.
<add> result >>>= 1;
<add> if (!negative) {
<add> return result;
<add> }
<add>
<add> // We need to OR here to ensure the 32nd bit (the sign bit in an Int32) is
<add> // always set for negative numbers. If `result` were 1, (meaning `negate` is
<add> // true and all other bits were zeros), `result` would now be 0. But -0
<add> // doesn't flip the 32nd bit as intended. All other numbers will successfully
<add> // set the 32nd bit without issue, so doing this is a noop for them.
<add> return -result | (1 << 31);
<ide> }
<ide>
<ide> /**
<ide><path>test/parallel/test-source-map-api.js
<ide> const { readFileSync } = require('fs');
<ide> assert.strictEqual(payload.sources[0], sourceMap.payload.sources[0]);
<ide> assert.notStrictEqual(payload.sources, sourceMap.payload.sources);
<ide> }
<add>
<add>// Test various known decodings to ensure decodeVLQ works correctly.
<add>{
<add> function makeMinimalMap(column) {
<add> return {
<add> sources: ['test.js'],
<add> // Mapping from the 0th line, 0th column of the output file to the 0th
<add> // source file, 0th line, ${column}th column.
<add> mappings: `AAA${column}`,
<add> };
<add> }
<add> const knownDecodings = {
<add> 'A': 0,
<add> 'B': -2147483648,
<add> 'C': 1,
<add> 'D': -1,
<add> 'E': 2,
<add> 'F': -2,
<add>
<add> // 2^31 - 1, maximum values
<add> '+/////D': 2147483647,
<add> '8/////D': 2147483646,
<add> '6/////D': 2147483645,
<add> '4/////D': 2147483644,
<add> '2/////D': 2147483643,
<add> '0/////D': 2147483642,
<add>
<add> // -2^31 + 1, minimum values
<add> '//////D': -2147483647,
<add> '9/////D': -2147483646,
<add> '7/////D': -2147483645,
<add> '5/////D': -2147483644,
<add> '3/////D': -2147483643,
<add> '1/////D': -2147483642,
<add> };
<add>
<add> for (const column in knownDecodings) {
<add> const sourceMap = new SourceMap(makeMinimalMap(column));
<add> const { originalColumn } = sourceMap.findEntry(0, 0);
<add> assert.strictEqual(originalColumn, knownDecodings[column]);
<add> }
<add>} | 2 |
Javascript | Javascript | compile only content | c2989f6cc6ea8be34101b9ab9bc25d14a2468e20 | <ide><path>src/widgets.js
<ide> var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile'
<ide> var srcExp = attr.src,
<ide> scopeExp = attr.scope || '',
<ide> autoScrollExp = attr.autoscroll;
<del> if (!element[0]['ng:compiled']) {
<del> element[0]['ng:compiled'] = true;
<del> return function(scope, element, attr){
<del> var changeCounter = 0,
<del> childScope;
<del>
<del> function incrementChange() { changeCounter++;}
<del> scope.$watch(srcExp, incrementChange);
<del> scope.$watch(function() {
<del> var includeScope = scope.$eval(scopeExp);
<del> if (includeScope) return includeScope.$id;
<del> }, incrementChange);
<del> scope.$watch(function() {return changeCounter;}, function(newChangeCounter) {
<del> var src = scope.$eval(srcExp),
<del> useScope = scope.$eval(scopeExp);
<del>
<del> function clearContent() {
<del> // if this callback is still desired
<del> if (newChangeCounter === changeCounter) {
<del> if (childScope) childScope.$destroy();
<del> childScope = null;
<del> element.html('');
<del> }
<add>
<add> return function(scope, element, attr) {
<add> var changeCounter = 0,
<add> childScope;
<add>
<add> function incrementChange() { changeCounter++;}
<add> scope.$watch(srcExp, incrementChange);
<add> scope.$watch(function() {
<add> var includeScope = scope.$eval(scopeExp);
<add> if (includeScope) return includeScope.$id;
<add> }, incrementChange);
<add> scope.$watch(function() {return changeCounter;}, function(newChangeCounter) {
<add> var src = scope.$eval(srcExp),
<add> useScope = scope.$eval(scopeExp);
<add>
<add> function clearContent() {
<add> // if this callback is still desired
<add> if (newChangeCounter === changeCounter) {
<add> if (childScope) childScope.$destroy();
<add> childScope = null;
<add> element.html('');
<ide> }
<add> }
<ide>
<del> if (src) {
<del> $http.get(src, {cache: $templateCache}).success(function(response) {
<del> // if this callback is still desired
<del> if (newChangeCounter === changeCounter) {
<del> element.html(response);
<del> if (childScope) childScope.$destroy();
<del> childScope = useScope ? useScope : scope.$new();
<del> $compile(element)(childScope);
<del> if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
<del> $anchorScroll();
<del> }
<del> scope.$emit('$contentLoaded');
<add> if (src) {
<add> $http.get(src, {cache: $templateCache}).success(function(response) {
<add> // if this callback is still desired
<add> if (newChangeCounter === changeCounter) {
<add> element.html(response);
<add> if (childScope) childScope.$destroy();
<add> childScope = useScope ? useScope : scope.$new();
<add> $compile(element.contents())(childScope);
<add> if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
<add> $anchorScroll();
<ide> }
<del> }).error(clearContent);
<del> } else {
<del> clearContent();
<del> }
<del> });
<del> };
<del> }
<add> scope.$emit('$contentLoaded');
<add> }
<add> }).error(clearContent);
<add> } else {
<add> clearContent();
<add> }
<add> });
<add> };
<ide> }
<ide> }
<ide> }];
<ide><path>test/widgetsSpec.js
<ide> describe('widget', function() {
<ide> }));
<ide>
<ide>
<add> it('should compile only the content', inject(function($compile, $rootScope, $templateCache) {
<add> // regression
<add>
<add> var onload = jasmine.createSpy('$contentLoaded');
<add> $rootScope.$on('$contentLoaded', onload);
<add> $templateCache.put('tpl.html', [200, 'partial {{tpl}}', {}]);
<add>
<add> element = $compile('<div><div ng:repeat="i in [1]">' +
<add> '<ng:include src="tpl"></ng:include></div></div>')($rootScope);
<add> expect(onload).not.toHaveBeenCalled();
<add>
<add> $rootScope.$apply(function() {
<add> $rootScope.tpl = 'tpl.html';
<add> });
<add> expect(onload).toHaveBeenCalledOnce();
<add> }));
<add>
<add>
<ide> describe('autoscoll', function() {
<ide> var autoScrollSpy;
<ide> | 2 |
PHP | PHP | remove extra space | 4e8fe094179116471e64c336d8516d4dd483e6ea | <ide><path>src/Illuminate/Cache/RedisTaggedCache.php
<ide> public function forever($key, $value)
<ide> {
<ide> $this->pushForeverKeys($namespace = $this->tags->getNamespace(), $key);
<ide>
<del> parent::forever( $key, $value);
<add> parent::forever($key, $value);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | fix anchor links in reference-react documentation | 81cf21c6d1bffe1f0b09d4c2a52c0fb19f40b59f | <ide><path>docs/docs/reference-react.md
<ide> redirect_from:
<ide>
<ide> React components let you split the UI into independent, reusable pieces, and think about each piece in isolation. React components can be defined by subclassing `React.Component` or `React.PureComponent`.
<ide>
<del> - [`React.Component`](#react.component)
<del> - [`React.PureComponent`](#react.purecomponent)
<add> - [`React.Component`](#reactcomponent)
<add> - [`React.PureComponent`](#reactpurecomponent)
<ide>
<ide> If you don't use ES6 classes, you may use the `create-react-class` module instead. See [Using React without ES6](/docs/react-without-es6.html) for more information.
<ide>
<ide> See [Using React without JSX](/docs/react-without-jsx.html) for more information
<ide>
<ide> - [`cloneElement()`](#cloneelement)
<ide> - [`isValidElement()`](#isvalidelement)
<del>- [`React.Children`](#react.children)
<add>- [`React.Children`](#reactchildren)
<ide>
<ide> * * *
<ide>
<ide> See the [React.Component API Reference](/docs/react-component.html) for a list o
<ide>
<ide> ### `React.PureComponent`
<ide>
<del>`React.PureComponent` is exactly like [`React.Component`](#react.component) but implements [`shouldComponentUpdate()`](/docs/react-component.html#shouldcomponentupdate) with a shallow prop and state comparison.
<add>`React.PureComponent` is exactly like [`React.Component`](#reactcomponent) but implements [`shouldComponentUpdate()`](/docs/react-component.html#shouldcomponentupdate) with a shallow prop and state comparison.
<ide>
<ide> If your React component's `render()` function renders the same result given the same props and state, you can use `React.PureComponent` for a performance boost in some cases.
<ide>
<ide> Invokes a function on every immediate child contained within `children` with `th
<ide> React.Children.forEach(children, function[(thisArg)])
<ide> ```
<ide>
<del>Like [`React.Children.map()`](#react.children.map) but does not return an array.
<add>Like [`React.Children.map()`](#reactchildrenmap) but does not return an array.
<ide>
<ide> #### `React.Children.count`
<ide> | 1 |
Ruby | Ruby | add configuration to new appcast check | 0939c8832d9a12b436bc570240ab29e9f26a0298 | <ide><path>Library/Homebrew/cask/audit.rb
<ide> def check_download
<ide> def check_appcast_contains_version
<ide> return unless check_appcast?
<ide> return if cask.appcast.to_s.empty?
<add> return if cask.appcast.configuration == :no_check
<ide>
<ide> appcast_stanza = cask.appcast.to_s
<del> appcast_contents, = curl_output("--max-time", "5", appcast_stanza)
<add> appcast_contents, = curl_output("-L", "--max-time", "5", appcast_stanza)
<ide> version_stanza = cask.version.to_s
<del> adjusted_version_stanza = version_stanza.split(",")[0].split("-")[0].split("_")[0]
<add> if cask.appcast.configuration.to_s.empty?
<add> adjusted_version_stanza = version_stanza.split(",")[0].split("-")[0].split("_")[0]
<add> else
<add> adjusted_version_stanza = cask.appcast.configuration
<add> end
<ide> return if appcast_contents.include? adjusted_version_stanza
<ide>
<ide> add_warning "appcast at URL '#{appcast_stanza}' does not contain"\
<ide><path>Library/Homebrew/cask/dsl/appcast.rb
<ide> module Cask
<ide> class DSL
<ide> class Appcast
<add> ATTRIBUTES = [
<add> :configuration,
<add> ].freeze
<ide> attr_reader :uri, :parameters
<add> attr_reader(*ATTRIBUTES)
<ide>
<ide> def initialize(uri, **parameters)
<ide> @uri = URI(uri)
<ide> @parameters = parameters
<add>
<add> ATTRIBUTES.each do |attribute|
<add> next unless parameters.key?(attribute)
<add>
<add> instance_variable_set("@#{attribute}", parameters[attribute])
<add> end
<ide> end
<ide>
<ide> def to_yaml | 2 |
PHP | PHP | add class_exists() check for view class | f1931e43efa2221bc8f1d4a43f8c99aae67f7835 | <ide><path>lib/Cake/Controller/Component/RequestHandlerComponent.php
<ide> public function renderAs(Controller $controller, $type, $options = array()) {
<ide> $controller->ext = '.ctp';
<ide>
<ide> $viewClass = Inflector::classify($type);
<del> App::uses($viewClass . 'View', 'View');
<del>
<del> if (class_exists($viewClass . 'View')) {
<add> $viewName = $viewClass . 'View';
<add> if (!class_exists($viewName)) {
<add> App::uses($viewName, 'View');
<add> }
<add> if (class_exists($viewName)) {
<ide> $controller->viewClass = $viewClass;
<ide> } elseif (empty($this->_renderType)) {
<ide> $controller->viewPath .= DS . $type; | 1 |
Javascript | Javascript | remove unnecessary checks | 7f909c3b7922a3c7cdca03527dd6dc3687ae4e8b | <ide><path>lib/events.js
<ide> EventEmitter.prototype.removeListener =
<ide> if (!list)
<ide> return this;
<ide>
<del> if (list === listener || (list.listener && list.listener === listener)) {
<add> if (list === listener || list.listener === listener) {
<ide> if (--this._eventsCount === 0)
<ide> this._events = new EventHandlers();
<ide> else {
<ide> EventEmitter.prototype.removeListener =
<ide> position = -1;
<ide>
<ide> for (i = list.length; i-- > 0;) {
<del> if (list[i] === listener ||
<del> (list[i].listener && list[i].listener === listener)) {
<add> if (list[i] === listener || list[i].listener === listener) {
<ide> originalListener = list[i].listener;
<ide> position = i;
<ide> break; | 1 |
PHP | PHP | apply fixes from styleci | 6b849d116167d57be4d0ac9c6e49be85602381db | <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php
<ide> protected function shouldBlockPhpUpload($value, $parameters)
<ide> }
<ide>
<ide> $phpExtensions = [
<del> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar'
<add> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar',
<ide> ];
<ide>
<ide> return ($value instanceof UploadedFile) | 1 |
Javascript | Javascript | exclude specific spec folders | 83bc6b8379de88649de20a50be6ba2a3527d7b73 | <ide><path>script/lib/include-path-in-packaged-app.js
<ide> const EXCLUDE_REGEXPS_SOURCES = [
<ide> escapeRegExp(path.sep),
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.d\\.ts$',
<ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.js\\.map$',
<del> '.*' + escapeRegExp(path.sep) + 'test.*\\.html$'
<add> '.*' + escapeRegExp(path.sep) + 'test.*\\.html$',
<add>
<add> // specific spec folders hand-picked
<add> 'node_modules' +
<add> escapeRegExp(path.sep) +
<add> '(oniguruma|dev-live-reload|deprecation-cop|one-dark-ui|incompatible-packages|git-diff|line-ending-selector|link|grammar-selector|json-schema-traverse|exception-reporting|one-light-ui|autoflow|about|go-to-line|sylvester|apparatus)' +
<add> escapeRegExp(path.sep) +
<add> 'spec' +
<add> escapeRegExp(path.sep),
<add>
<add> // babel-core spec
<add> 'node_modules' +
<add> escapeRegExp(path.sep) +
<add> 'babel-core' +
<add> escapeRegExp(path.sep) +
<add> 'lib' +
<add> escapeRegExp(path.sep) +
<add> 'transformation' +
<add> escapeRegExp(path.sep) +
<add> 'transforers' +
<add> escapeRegExp(path.sep) +
<add> 'spec' +
<add> escapeRegExp(path.sep)
<ide> ];
<ide>
<ide> // Ignore spec directories in all bundled packages | 1 |
Go | Go | add some debug to runtime.restore() | fde909ffb8e09ae39310093b7389f61aa4ec29df | <ide><path>graph.go
<ide> func (graph *Graph) restore() error {
<ide> graph.idIndex.Add(id)
<ide> }
<ide> }
<add> utils.Debugf("Restored %d elements", len(dir))
<ide> return nil
<ide> }
<ide>
<ide><path>runtime.go
<ide> func (runtime *Runtime) Register(container *Container) error {
<ide> }
<ide>
<ide> container.waitLock = make(chan struct{})
<del>
<ide> go container.monitor()
<ide> }
<ide> }
<ide> func (runtime *Runtime) Destroy(container *Container) error {
<ide> }
<ide>
<ide> func (runtime *Runtime) restore() error {
<del> wheel := "-\\|/"
<ide> if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
<del> fmt.Printf("Loading containers: ")
<add> fmt.Printf("Loading containers: ")
<ide> }
<ide> dir, err := ioutil.ReadDir(runtime.repository)
<ide> if err != nil {
<ide> func (runtime *Runtime) restore() error {
<ide> containers := make(map[string]*Container)
<ide> currentDriver := runtime.driver.String()
<ide>
<del> for i, v := range dir {
<add> for _, v := range dir {
<ide> id := v.Name()
<ide> container, err := runtime.load(id)
<del> if i%21 == 0 && os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
<del> fmt.Printf("\b%c", wheel[i%4])
<add> if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
<add> fmt.Print(".")
<ide> }
<ide> if err != nil {
<ide> utils.Errorf("Failed to load container %v: %v", id, err)
<ide> func (runtime *Runtime) restore() error {
<ide>
<ide> if entities := runtime.containerGraph.List("/", -1); entities != nil {
<ide> for _, p := range entities.Paths() {
<add> if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
<add> fmt.Print(".")
<add> }
<ide> e := entities[p]
<ide> if container, ok := containers[e.ID()]; ok {
<ide> register(container)
<ide> func (runtime *Runtime) restore() error {
<ide> }
<ide>
<ide> if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
<del> fmt.Printf("\bdone.\n")
<add> fmt.Printf(": done.\n")
<ide> }
<ide>
<ide> return nil
<ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) {
<ide> }
<ide>
<ide> if ad, ok := driver.(*aufs.Driver); ok {
<add> utils.Debugf("Migrating existing containers")
<ide> if err := ad.Migrate(config.Root, setupInitLayer); err != nil {
<ide> return nil, err
<ide> }
<ide> }
<ide>
<add> utils.Debugf("Escaping AppArmor confinement")
<ide> if err := linkLxcStart(config.Root); err != nil {
<ide> return nil, err
<ide> }
<add> utils.Debugf("Creating images graph")
<ide> g, err := NewGraph(path.Join(config.Root, "graph"), driver)
<ide> if err != nil {
<ide> return nil, err
<ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) {
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> utils.Debugf("Creating volumes graph")
<ide> volumes, err := NewGraph(path.Join(config.Root, "volumes"), volumesDriver)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> utils.Debugf("Creating repository list")
<ide> repositories, err := NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g)
<ide> if err != nil {
<ide> return nil, fmt.Errorf("Couldn't create Tag store: %s", err) | 2 |
Ruby | Ruby | remove explicit return | a3bd62e1bae64569d0c2d45f8068f291e3e0e776 | <ide><path>activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
<ide> def insert_record(record, force = true, validate = true)
<ide> relation.insert(attributes)
<ide> end
<ide>
<del> return true
<add> true
<ide> end
<ide>
<ide> def delete_records(records)
<ide> def delete_records(records)
<ide> ).delete
<ide> end
<ide> end
<del>
<add>
<ide> def construct_joins
<ide> "INNER JOIN #{@owner.connection.quote_table_name @reflection.options[:join_table]} ON #{@reflection.quoted_table_name}.#{@reflection.klass.primary_key} = #{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.association_foreign_key}"
<ide> end | 1 |
Text | Text | correct typo in readme.md | 415bd8222605687f06b1ff1e021e83e2718321d5 | <ide><path>README.md
<ide> Once you have earned the Responsive Web Design, Algorithms and Data Structures,
<ide>
<ide> #### Legacy Certifications
<ide>
<del>We also have 4 legacy certifications dating back to our 2015 curriculum, which is still available. All of the required projects for these legacy certifications will remain available on freeCodeCamp.org.
<add>We also have 4 legacy certifications dating back to our 2015 curriculum, which are still available. All of the required projects for these legacy certifications will remain available on freeCodeCamp.org.
<ide>
<ide> - Legacy Front End Development Certification
<ide> - Legacy Data Visualization Certification | 1 |
Javascript | Javascript | fix passport js maybe | a2259c937c5a48e1695f0f7ae3dcc847e87ed78b | <ide><path>config/passport.js
<ide> passport.use(new LinkedInStrategy(secrets.linkedin, function(req, accessToken, r
<ide> }
<ide> }));
<ide>
<del>
<del>// Login Required middleware.
<del>
<del>module.exports = {
<del> isAuthenticated: isAuthenticated,
<del> isAuthorized: isAuthorized
<del>};
<del>
<del>function isAuthenticated(req, res, next) {
<del> if (req.isAuthenticated()) return next();
<del> res.redirect('/login');
<del>}
<del>
<del>// Authorization Required middleware.
<del>function isAuthorized(req, res, next) {
<del> var provider = req.path.split('/').slice(-1)[0];
<del>
<del> if (_.find(req.user.tokens, { kind: provider })) {
<del> next();
<del> } else {
<del> res.redirect('/auth/' + provider);
<del> }
<del>}
<del>
<del>/*
<del>passport.use(new InstagramStrategy(secrets.instagram,function(req, accessToken, refreshToken, profile, done) {
<del> if (req.user) {
<del> User.findOne({ instagram: profile.id }, function(err, existingUser) {
<del> if (existingUser) {
<del> req.flash('errors', { msg: 'There is already an Instagram account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<del> done(err);
<del> } else {
<del> User.findById(req.user.id, function(err, user) {
<del> user.instagram = profile.id;
<del> user.tokens.push({ kind: 'instagram', accessToken: accessToken });
<del> user.profile.name = user.profile.name || profile.displayName;
<del> user.profile.picture = user.profile.picture || profile._json.data.profile_picture;
<del> user.profile.website = user.profile.website || profile._json.data.website;
<del> user.save(function(err) {
<del> req.flash('info', { msg: 'Instagram account has been linked.' });
<del> done(err, user);
<del> });
<del> });
<del> }
<del> });
<del> } else {
<del> User.findOne({ instagram: profile.id }, function(err, existingUser) {
<del> if (existingUser) return done(null, existingUser);
<del>
<del> var user = new User();
<del> user.instagram = profile.id;
<del> user.tokens.push({ kind: 'instagram', accessToken: accessToken });
<del> user.profile.name = profile.displayName;
<del> // Similar to Twitter API, assigns a temporary e-mail address
<del> // to get on with the registration process. It can be changed later
<del> // to a valid e-mail address in Profile Management.
<del> user.email = profile.username + "@instagram.com";
<del> user.profile.website = profile._json.data.website;
<del> user.profile.picture = profile._json.data.profile_picture;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> });
<del> }
<del>}));
<del>
<ide> // Sign in using Email and Password.
<ide> passport.use(new LocalStrategy({ usernameField: 'email' }, function(email, password, done) {
<ide> User.findOne({ email: email }, function(err, user) {
<ide> passport.use(new GoogleStrategy(secrets.google, function(req, accessToken, refre
<ide> }));
<ide>
<ide>
<add>// Login Required middleware.
<add>
<add>module.exports = {
<add> isAuthenticated: isAuthenticated,
<add> isAuthorized: isAuthorized
<add>};
<add>
<add>function isAuthenticated(req, res, next) {
<add> if (req.isAuthenticated()) return next();
<add> res.redirect('/login');
<add>}
<add>
<add>// Authorization Required middleware.
<add>function isAuthorized(req, res, next) {
<add> var provider = req.path.split('/').slice(-1)[0];
<add>
<add> if (_.find(req.user.tokens, { kind: provider })) {
<add> next();
<add> } else {
<add> res.redirect('/auth/' + provider);
<add> }
<add>}
<add>
<add>/*
<add>passport.use(new InstagramStrategy(secrets.instagram,function(req, accessToken, refreshToken, profile, done) {
<add> if (req.user) {
<add> User.findOne({ instagram: profile.id }, function(err, existingUser) {
<add> if (existingUser) {
<add> req.flash('errors', { msg: 'There is already an Instagram account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<add> done(err);
<add> } else {
<add> User.findById(req.user.id, function(err, user) {
<add> user.instagram = profile.id;
<add> user.tokens.push({ kind: 'instagram', accessToken: accessToken });
<add> user.profile.name = user.profile.name || profile.displayName;
<add> user.profile.picture = user.profile.picture || profile._json.data.profile_picture;
<add> user.profile.website = user.profile.website || profile._json.data.website;
<add> user.save(function(err) {
<add> req.flash('info', { msg: 'Instagram account has been linked.' });
<add> done(err, user);
<add> });
<add> });
<add> }
<add> });
<add> } else {
<add> User.findOne({ instagram: profile.id }, function(err, existingUser) {
<add> if (existingUser) return done(null, existingUser);
<add>
<add> var user = new User();
<add> user.instagram = profile.id;
<add> user.tokens.push({ kind: 'instagram', accessToken: accessToken });
<add> user.profile.name = profile.displayName;
<add> // Similar to Twitter API, assigns a temporary e-mail address
<add> // to get on with the registration process. It can be changed later
<add> // to a valid e-mail address in Profile Management.
<add> user.email = profile.username + "@instagram.com";
<add> user.profile.website = profile._json.data.website;
<add> user.profile.picture = profile._json.data.profile_picture;
<add> user.save(function(err) {
<add> done(err, user);
<add> });
<add> });
<add> }
<add>}));
<add>
<add>
<ide> // Tumblr API setup.
<ide>
<ide> passport.use('tumblr', new OAuthStrategy({ | 1 |
Text | Text | add missing newline for bash code example | ed7907a988fe336711603e38c8b79d673e87c902 | <ide><path>docs/sources/installation/ubuntulinux.md
<ide> install Docker using the following:
<ide>
<ide> If `wget` isn't installed, install it after updating your manager:
<ide>
<del> $ sudo apt-get update $ sudo apt-get install wget
<add> $ sudo apt-get update
<add> $ sudo apt-get install wget
<ide>
<ide> 3. Get the latest Docker package.
<ide> | 1 |
Go | Go | move testmergeoncommit to integration-cli | ed6074ea6be17518a3b21e4dd5038f13ca835194 | <ide><path>integration-cli/docker_cli_commit_test.go
<ide> func TestCommitChange(t *testing.T) {
<ide>
<ide> logDone("commit - commit --change")
<ide> }
<add>
<add>// TODO: commit --run is deprecated, remove this once --run is removed
<add>func TestCommitMergeConfigRun(t *testing.T) {
<add> defer deleteAllContainers()
<add> name := "commit-test"
<add> out, _, _ := dockerCmd(t, "run", "-d", "-e=FOO=bar", "busybox", "/bin/sh", "-c", "echo testing > /tmp/foo")
<add> id := strings.TrimSpace(out)
<add>
<add> dockerCmd(t, "commit", `--run={"Cmd": ["cat", "/tmp/foo"]}`, id, "commit-test")
<add> defer deleteImages("commit-test")
<add>
<add> out, _, _ = dockerCmd(t, "run", "--name", name, "commit-test")
<add> if strings.TrimSpace(out) != "testing" {
<add> t.Fatal("run config in commited container was not merged")
<add> }
<add>
<add> type cfg struct {
<add> Env []string
<add> Cmd []string
<add> }
<add> config1 := cfg{}
<add> if err := inspectFieldAndMarshall(id, "Config", &config1); err != nil {
<add> t.Fatal(err)
<add> }
<add> config2 := cfg{}
<add> if err := inspectFieldAndMarshall(name, "Config", &config2); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Env has at least PATH loaded as well here, so let's just grab the FOO one
<add> var env1, env2 string
<add> for _, e := range config1.Env {
<add> if strings.HasPrefix(e, "FOO") {
<add> env1 = e
<add> break
<add> }
<add> }
<add> for _, e := range config2.Env {
<add> if strings.HasPrefix(e, "FOO") {
<add> env2 = e
<add> break
<add> }
<add> }
<add>
<add> if len(config1.Env) != len(config2.Env) || env1 != env2 && env2 != "" {
<add> t.Fatalf("expected envs to match: %v - %v", config1.Env, config2.Env)
<add> }
<add>
<add> logDone("commit - configs are merged with --run")
<add>}
<ide><path>integration/server_test.go
<ide> package docker
<ide>
<del>import (
<del> "bytes"
<del> "testing"
<del>
<del> "github.com/docker/docker/builder"
<del> "github.com/docker/docker/engine"
<del>)
<add>import "testing"
<ide>
<ide> func TestCreateNumberHostname(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> func TestCreateNumberHostname(t *testing.T) {
<ide> createTestContainer(eng, config, t)
<ide> }
<ide>
<del>func TestCommit(t *testing.T) {
<del> eng := NewTestEngine(t)
<del> b := &builder.BuilderJob{Engine: eng}
<del> b.Install()
<del> defer mkDaemonFromEngine(eng, t).Nuke()
<del>
<del> config, _, _, err := parseRun([]string{unitTestImageID, "/bin/cat"})
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> id := createTestContainer(eng, config, t)
<del>
<del> job := eng.Job("commit", id)
<del> job.Setenv("repo", "testrepo")
<del> job.Setenv("tag", "testtag")
<del> job.SetenvJson("config", config)
<del> if err := job.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del>}
<del>
<del>func TestMergeConfigOnCommit(t *testing.T) {
<del> eng := NewTestEngine(t)
<del> b := &builder.BuilderJob{Engine: eng}
<del> b.Install()
<del> runtime := mkDaemonFromEngine(eng, t)
<del> defer runtime.Nuke()
<del>
<del> container1, _, _ := mkContainer(runtime, []string{"-e", "FOO=bar", unitTestImageID, "echo test > /tmp/foo"}, t)
<del> defer runtime.Rm(container1)
<del>
<del> config, _, _, err := parseRun([]string{container1.ID, "cat /tmp/foo"})
<del> if err != nil {
<del> t.Error(err)
<del> }
<del>
<del> job := eng.Job("commit", container1.ID)
<del> job.Setenv("repo", "testrepo")
<del> job.Setenv("tag", "testtag")
<del> job.SetenvJson("config", config)
<del> var outputBuffer = bytes.NewBuffer(nil)
<del> job.Stdout.Add(outputBuffer)
<del> if err := job.Run(); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> container2, _, _ := mkContainer(runtime, []string{engine.Tail(outputBuffer, 1)}, t)
<del> defer runtime.Rm(container2)
<del>
<del> job = eng.Job("container_inspect", container1.Name)
<del> baseContainer, _ := job.Stdout.AddEnv()
<del> if err := job.Run(); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> job = eng.Job("container_inspect", container2.Name)
<del> commitContainer, _ := job.Stdout.AddEnv()
<del> if err := job.Run(); err != nil {
<del> t.Error(err)
<del> }
<del>
<del> baseConfig := baseContainer.GetSubEnv("Config")
<del> commitConfig := commitContainer.GetSubEnv("Config")
<del>
<del> if commitConfig.Get("Env") != baseConfig.Get("Env") {
<del> t.Fatalf("Env config in committed container should be %v, was %v",
<del> baseConfig.Get("Env"), commitConfig.Get("Env"))
<del> }
<del>
<del> if baseConfig.Get("Cmd") != "[\"echo test \\u003e /tmp/foo\"]" {
<del> t.Fatalf("Cmd in base container should be [\"echo test \\u003e /tmp/foo\"], was %s",
<del> baseConfig.Get("Cmd"))
<del> }
<del>
<del> if commitConfig.Get("Cmd") != "[\"cat /tmp/foo\"]" {
<del> t.Fatalf("Cmd in committed container should be [\"cat /tmp/foo\"], was %s",
<del> commitConfig.Get("Cmd"))
<del> }
<del>}
<del>
<ide> func TestImagesFilter(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> defer nuke(mkDaemonFromEngine(eng, t)) | 2 |
Text | Text | fix grammatical errors | a50c6edd30f87269b82080d467e368a341247e98 | <ide><path>guide/spanish/accessibility/index.md
<ide> title: Accessibility
<ide> localeTitle: Accesibilidad
<ide> ---
<del>## Accesibilidad
<add>## La Accesibilidad
<ide>
<ide> **La accesibilidad web significa que las personas con discapacidades pueden usar la web** .
<ide>
<del>Más específicamente, la accesibilidad a la Web significa que las personas con discapacidades pueden percibir, comprender, navegar e interactuar con la Web, y que pueden Contribuye a la web. La accesibilidad web también beneficia a otros, incluidas [las personas mayores](https://www.w3.org/WAI/bcase/soc.html#of) con habilidades cambiantes Debido al envejecimiento.
<add>Más específicamente, la accesibilidad a la Web significa que las personas con discapacidades pueden percibir, comprender, navegar e interactuar con la Web, y que pueden contribuir a la web. La accesibilidad web también beneficia a otros, incluidas [las personas mayores](https://www.w3.org/WAI/bcase/soc.html#of) con habilidades cambiantes debido al envejecimiento.
<ide>
<del>La accesibilidad a la Web abarca todas las discapacidades que afectan el acceso a la Web, incluyendo visual, auditiva, física, del habla, cognitiva y neurológica. discapacidades El documento [Cómo las personas con discapacidades usan la web](http://www.w3.org/WAI/intro/people-use-web/Overview.html) describe cómo diferentes las discapacidades afectan el uso de la Web e incluyen escenarios de personas con discapacidades que utilizan la Web.
<add>La accesibilidad a la Web abarca todas las discapacidades que afectan el acceso a la Web, incluyendo visual, auditiva, física, del habla, cognitiva y neurológica. El documento [Cómo las personas con discapacidades usan la web](http://www.w3.org/WAI/intro/people-use-web/Overview.html) describe cómo las discapacidades diferentes afectan el uso de la Web e incluyen escenarios de personas con discapacidades que utilizan la Web.
<ide>
<del>La accesibilidad web también **beneficia a las** personas _sin_ discapacidad. Por ejemplo, un principio clave de la accesibilidad web es el diseño de sitios web y software. que son flexibles para satisfacer diferentes necesidades de los usuarios, preferencias y situaciones. Esta **flexibilidad** también beneficia a las personas _sin_ discapacidad en ciertos situaciones, como personas que utilizan una conexión lenta a Internet, personas con "discapacidades temporales", como un brazo roto, y personas con capacidades cambiantes Debido al envejecimiento. El documento [Desarrollo de un caso de negocio de accesibilidad web para su organización](https://www.w3.org/WAI/bcase/Overview) describe muchos Diferentes beneficios de la accesibilidad web, incluyendo **beneficios para las organizaciones** .
<add>La accesibilidad web también **beneficia a las** personas _sin_ discapacidad. Por ejemplo, un principio clave de la accesibilidad web es el diseño de sitios web y software que son flexibles para satisfacer diferentes necesidades de los usuarios, preferencias y situaciones. Esta **flexibilidad** también beneficia a las personas _sin_ discapacidad en ciertos situaciones, como personas que utilizan una conexión lenta a Internet, personas con "discapacidades temporales", como un brazo roto, y personas con capacidades cambiantes debido al envejecimiento. El documento [Desarrollo de un caso de negocio de accesibilidad web para su organización](https://www.w3.org/WAI/bcase/Overview) describe muchos beneficios de la accesibilidad web, incluyendo **beneficios para las organizaciones** .
<ide>
<ide> La accesibilidad a la web también debe incluir a las personas que no tienen acceso a Internet ni a las computadoras.
<ide>
<del>Una importante guía para el desarrollo web fue presentada por el [World Wide Web Consortium (W3C)](https://www.w3.org/) , la [Iniciativa de Accesibilidad Web.](https://www.w3.org/WAI/) de donde obtenemos el [WAI-ARIA](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) , el paquete de aplicaciones de Internet enriquecidas accesibles. Donde WAI aborda la semántica de html para enganchar más fácilmente el árbol DOM, ARIA intenta crear aplicaciones web, especialmente aquellas desarrolladas con javascript y AJAX, más accesible.
<add>Una guía importante para el desarrollo web fue presentada por el [World Wide Web Consortium (W3C)](https://www.w3.org/) , la [Iniciativa de Accesibilidad Web.](https://www.w3.org/WAI/) de donde obtenemos el [WAI-ARIA](https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics), el paquete de aplicaciones de Internet enriquecidas accesibles. Donde WAI aborda la semántica de html para enganchar más fácilmente el árbol DOM, ARIA intenta crear aplicaciones web, especialmente aquellas desarrolladas con javascript y AJAX, más accesible.
<ide>
<del>El uso de imágenes y gráficos en sitios web puede disminuir la accesibilidad para las personas con discapacidades visuales. Sin embargo, esto no significa que los diseñadores deben evitar utilizando estos elementos visuales. Cuando se usan correctamente, los elementos visuales pueden transmitir el aspecto apropiado a los usuarios sin discapacidades y deben usarse para hacerlo Para utilizar estos elementos de manera adecuada, los diseñadores web deben usar el texto alternativo para comunicar el mensaje de estos elementos a aquellos que no pueden ver. ellos. El texto alternativo debe ser corto y al punto, generalmente [no más de cinco a 15 palabras](https://www.thoughtco.com/writing-great-alt-text-3466185) . Si un El gráfico se utiliza para transmitir información que excede las limitaciones del texto alternativo, esa información también debe existir como texto web para que se pueda leer por pantalla lectores [Aprenda más sobre el texto alternativo](https://webaim.org/techniques/alttext/) .
<add>El uso de imágenes y gráficos en sitios web puede disminuir la accesibilidad para las personas con discapacidades visuales. Sin embargo, esto no significa que los diseñadores deban evitar utilizando estos elementos visuales. Cuando se usan correctamente, los elementos visuales pueden transmitir el aspecto apropiado a los usuarios. Los diseñadores web pueden usar el texto alternativo para comunicar el mensaje de estos elementos a aquellos que no pueden verlos. El texto alternativo debe ser corto y al punto, generalmente [no más de cinco a 15 palabras](https://www.thoughtco.com/writing-great-alt-text-3466185). Si un gráfico se utiliza para transmitir información que excede las limitaciones del texto alternativo, esa información también debe existir como texto web para que se pueda leer por lector de pantalla con audio [Aprenda más sobre el texto alternativo](https://webaim.org/techniques/alttext/).
<ide>
<del>Al igual que el texto Alt es para personas con discapacidades visuales, las transcripciones del audio son para las personas que no pueden escuchar. Proporcionar un documento escrito o una transcripción de lo que se está hablando accesible a las personas con problemas de audición.
<add>Al igual que el texto Alt es para personas con discapacidades visuales, las transcripciones del audio son para las personas que no pueden oír. Proporcionar un documento escrito o una transcripción de lo que se está hablando accesible a las personas con problemas de audición.
<ide>
<del>Copyright © 2005 [World Wide Web Consortium](http://www.w3.org) , ( [MIT](http://www.csail.mit.edu/) , [ERCIM](http://www.ercim.org) , [Keio](http://www.keio.ac.jp) , [Beihang](http://ev.buaa.edu.cn) ). http://www.w3.org/Consortium/Legal/2015/doc-license
<add>Copyright © 2005 [World Wide Web Consortium](http://www.w3.org), ( [MIT](http://www.csail.mit.edu/), [ERCIM](http://www.ercim.org), [Keio](http://www.keio.ac.jp), [Beihang](http://ev.buaa.edu.cn) ). http://www.w3.org/Consortium/Legal/2015/doc-license
<ide>
<ide> ### Más información:
<ide>
<del>[w3.org introducción a la accesibilidad.](https://www.w3.org/WAI/intro/accessibility.php) [El proyecto A11Y](http://a11yproject.com/)
<ide>\ No newline at end of file
<add>[w3.org introducción a la accesibilidad.](https://www.w3.org/WAI/intro/accessibility.php) [El proyecto A11Y](http://a11yproject.com/) | 1 |
Javascript | Javascript | isolate unusual assert test in its own file | 6e1324e4cfd28ee1ddcc8a6957f6134948b268ce | <ide><path>test/parallel/test-assert-builtins-not-read-from-filesystem.js
<add>// Flags: --expose-internals
<add>
<add>'use strict';
<add>
<add>require('../common');
<add>
<add>const assert = require('assert');
<add>const EventEmitter = require('events');
<add>const { errorCache } = require('internal/assert');
<add>const { writeFileSync, unlinkSync } = require('fs');
<add>
<add>// Do not read filesystem for error messages in builtin modules.
<add>{
<add> const e = new EventEmitter();
<add>
<add> e.on('hello', assert);
<add>
<add> let threw = false;
<add> try {
<add> e.emit('hello', false);
<add> } catch (err) {
<add> const frames = err.stack.split('\n');
<add> const [, filename, line, column] = frames[1].match(/\((.+):(\d+):(\d+)\)/);
<add> // Reset the cache to check again
<add> const size = errorCache.size;
<add> errorCache.delete(`${filename}${line - 1}${column - 1}`);
<add> assert.strictEqual(errorCache.size, size - 1);
<add> const data = `${'\n'.repeat(line - 1)}${' '.repeat(column - 1)}` +
<add> 'ok(failed(badly));';
<add> try {
<add> writeFileSync(filename, data);
<add> assert.throws(
<add> () => e.emit('hello', false),
<add> {
<add> message: 'false == true'
<add> }
<add> );
<add> threw = true;
<add> } finally {
<add> unlinkSync(filename);
<add> }
<add> }
<add> assert(threw);
<add>}
<ide><path>test/parallel/test-assert.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<del>// Flags: --expose-internals
<del>
<ide> 'use strict';
<ide>
<ide> /* eslint-disable node-core/prefer-common-expectserror */
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const EventEmitter = require('events');
<del>const { errorCache } = require('internal/assert');
<del>const { writeFileSync, unlinkSync } = require('fs');
<ide> const { inspect } = require('util');
<ide> const a = assert;
<ide>
<ide> common.expectsError(
<ide> }
<ide> );
<ide>
<del>// Do not try to check Node.js modules.
<del>{
<del> const e = new EventEmitter();
<del>
<del> e.on('hello', assert);
<del>
<del> let threw = false;
<del> try {
<del> e.emit('hello', false);
<del> } catch (err) {
<del> const frames = err.stack.split('\n');
<del> const [, filename, line, column] = frames[1].match(/\((.+):(\d+):(\d+)\)/);
<del> // Reset the cache to check again
<del> const size = errorCache.size;
<del> errorCache.delete(`${filename}${line - 1}${column - 1}`);
<del> assert.strictEqual(errorCache.size, size - 1);
<del> const data = `${'\n'.repeat(line - 1)}${' '.repeat(column - 1)}` +
<del> 'ok(failed(badly));';
<del> try {
<del> writeFileSync(filename, data);
<del> assert.throws(
<del> () => e.emit('hello', false),
<del> {
<del> message: 'false == true'
<del> }
<del> );
<del> threw = true;
<del> } finally {
<del> unlinkSync(filename);
<del> }
<del> }
<del> assert(threw);
<del>}
<del>
<ide> common.expectsError(
<ide> // eslint-disable-next-line no-restricted-syntax
<ide> () => assert.throws(() => {}, 'Error message', 'message'), | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.