diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000000000..c29ea07ce66841 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +lib/punycode.js +test/fixtures +test/**/node_modules +test/parallel/test-fs-non-number-arguments-throw.js diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000000000..e023327fbb7d00 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,96 @@ +env: + node: true + +# enable ECMAScript features +ecmaFeatures: + blockBindings: true + templateStrings: true + octalLiterals: true + binaryLiterals: true + generators: true + forOf: true + +rules: + # Possible Errors + # list: https://github.com/eslint/eslint/tree/master/docs/rules#possible-errors + ## check debugger sentence + no-debugger: 2 + ## check duplicate arguments + no-dupe-args: 2 + ## check duplicate object keys + no-dupe-keys: 2 + ## check duplicate switch-case + no-duplicate-case: 2 + ## disallow assignment of exceptional params + no-ex-assign: 2 + ## disallow use of reserved words as keys like enum, class + no-reserved-keys: 2 + ## disallow unreachable code + no-unreachable: 2 + ## require valid typeof compared string like typeof foo === 'strnig' + valid-typeof: 2 + + # Best Practices + # list: https://github.com/eslint/eslint/tree/master/docs/rules#best-practices + ## require falls through comment on switch-case + no-fallthrough: 2 + + # Stylistic Issues + # list: https://github.com/eslint/eslint/tree/master/docs/rules#stylistic-issues + ## use single quote, we can use double quote when escape chars + quotes: + - 2 + - "single" + - "avoid-escape" + ## 2 space indentation + indent: + - 2 + - 2 + ## add space after comma + ## set to 'warn' because of https://github.com/eslint/eslint/issues/2408 + comma-spacing: 1 + ## put semi-colon + semi: 2 + ## require spaces operator like var sum = 1 + 1; + space-infix-ops: 2 + ## require spaces return, throw, case + space-return-throw-case: 2 + ## no space before function, eg. 'function()' + space-before-function-paren: [2, "never"] + ## require space before blocks, eg 'function() {' + space-before-blocks: [2, "always"] + ## require parens for Constructor + new-parens: 2 + ## max 80 length + max-len: + - 2 + - 80 + - 2 + + # Strict Mode + # list: https://github.com/eslint/eslint/tree/master/docs/rules#strict-mode + ## 'use strict' on top + strict: + - 2 + - "global" + +# Global scoped method and vars +globals: + DTRACE_HTTP_CLIENT_REQUEST: true + LTTNG_HTTP_CLIENT_REQUEST: true + COUNTER_HTTP_CLIENT_REQUEST: true + DTRACE_HTTP_CLIENT_RESPONSE: true + LTTNG_HTTP_CLIENT_RESPONSE: true + COUNTER_HTTP_CLIENT_RESPONSE: true + DTRACE_HTTP_SERVER_REQUEST: true + LTTNG_HTTP_SERVER_REQUEST: true + COUNTER_HTTP_SERVER_REQUEST: true + DTRACE_HTTP_SERVER_RESPONSE: true + LTTNG_HTTP_SERVER_RESPONSE: true + COUNTER_HTTP_SERVER_RESPONSE: true + DTRACE_NET_STREAM_END: true + LTTNG_NET_STREAM_END: true + COUNTER_NET_SERVER_CONNECTION_CLOSE: true + DTRACE_NET_SERVER_CONNECTION: true + LTTNG_NET_SERVER_CONNECTION: true + COUNTER_NET_SERVER_CONNECTION: true diff --git a/.gitignore b/.gitignore index 19fb3840039160..ebb9a7bc56375c 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,7 @@ deps/zlib/zlib.target.mk tools/faketime icu_config.gypi test.tap + +# Xcode workspaces and project folders +*.xcodeproj +*.xcworkspace diff --git a/Makefile b/Makefile index 8fc67d604e91b0..94f130f5fb3287 100644 --- a/Makefile +++ b/Makefile @@ -138,19 +138,7 @@ test-debugger: all $(PYTHON) tools/test.py debugger test-npm: $(NODE_EXE) - rm -rf npm-cache npm-tmp npm-prefix - mkdir npm-cache npm-tmp npm-prefix - cd deps/npm ; npm_config_cache="$(shell pwd)/npm-cache" \ - npm_config_prefix="$(shell pwd)/npm-prefix" \ - npm_config_tmp="$(shell pwd)/npm-tmp" \ - ../../$(NODE_EXE) cli.js install --ignore-scripts - cd deps/npm ; npm_config_cache="$(shell pwd)/npm-cache" \ - npm_config_prefix="$(shell pwd)/npm-prefix" \ - npm_config_tmp="$(shell pwd)/npm-tmp" \ - ../../$(NODE_EXE) cli.js run-script test-all && \ - ../../$(NODE_EXE) cli.js prune --prod && \ - cd ../.. && \ - rm -rf npm-cache npm-tmp npm-prefix + NODE_EXE=$(NODE_EXE) tools/test-npm.sh test-npm-publish: $(NODE_EXE) npm_package_config_publishtest=true ./$(NODE_EXE) deps/npm/test/run.js @@ -386,11 +374,8 @@ bench-idle: sleep 1 ./$(NODE_EXE) benchmark/idle_clients.js & -jslintfix: - PYTHONPATH=tools/closure_linter/:tools/gflags/ $(PYTHON) tools/closure_linter/closure_linter/fixjsstyle.py --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js - jslint: - PYTHONPATH=tools/closure_linter/:tools/gflags/ $(PYTHON) tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js + ./$(NODE_EXE) tools/eslint/bin/eslint.js src lib test --reset --quiet CPPLINT_EXCLUDE ?= CPPLINT_EXCLUDE += src/node_lttng.cc diff --git a/benchmark/misc/next-tick-breadth-args.js b/benchmark/misc/next-tick-breadth-args.js new file mode 100644 index 00000000000000..e617fcfc824f7f --- /dev/null +++ b/benchmark/misc/next-tick-breadth-args.js @@ -0,0 +1,37 @@ +'use strict'; + +var common = require('../common.js'); +var bench = common.createBenchmark(main, { + millions: [2] +}); + +function main(conf) { + var N = +conf.millions * 1e6; + var n = 0; + + function cb1(arg1) { + n++; + if (n === N) + bench.end(n / 1e6); + } + function cb2(arg1, arg2) { + n++; + if (n === N) + bench.end(n / 1e6); + } + function cb3(arg1, arg2, arg3) { + n++; + if (n === N) + bench.end(n / 1e6); + } + + bench.start(); + for (var i = 0; i < N; i++) { + if (i % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (i % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } +} diff --git a/benchmark/misc/next-tick-depth-args.js b/benchmark/misc/next-tick-depth-args.js new file mode 100644 index 00000000000000..066b4837856f60 --- /dev/null +++ b/benchmark/misc/next-tick-depth-args.js @@ -0,0 +1,48 @@ +'use strict'; + +var common = require('../common.js'); +var bench = common.createBenchmark(main, { + millions: [2] +}); + +process.maxTickDepth = Infinity; + +function main(conf) { + var n = +conf.millions * 1e6; + + function cb3(arg1, arg2, arg3) { + if (--n) { + if (n % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (n % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } else + bench.end(+conf.millions); + } + function cb2(arg1, arg2) { + if (--n) { + if (n % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (n % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } else + bench.end(+conf.millions); + } + function cb1(arg1) { + if (--n) { + if (n % 3 === 0) + process.nextTick(cb3, 512, true, null); + else if (n % 2 === 0) + process.nextTick(cb2, false, 5.1); + else + process.nextTick(cb1, 0); + } else + bench.end(+conf.millions); + } + bench.start(); + process.nextTick(cb1, true); +} diff --git a/configure b/configure index 8a19a5313cd67e..4a30973a3720ab 100755 --- a/configure +++ b/configure @@ -31,6 +31,16 @@ valid_arm_float_abi = ('soft', 'softfp', 'hard') valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx') valid_mips_fpu = ('fp32', 'fp64', 'fpxx') valid_mips_float_abi = ('soft', 'hard') +valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu') + +# create option groups +shared_optgroup = optparse.OptionGroup(parser, "Shared libraries", + "Flags that allows you to control whether you want to build against " + "built-in dependencies or its shared representations. If necessary, " + "provide multiple libraries with comma.") +intl_optgroup = optparse.OptionGroup(parser, "Internationalization", + "Flags that lets you enable i18n features in io.js as well as which " + "library you want to build against.") # Options should be in alphabetical order but keep --prefix at the top, # that's arguably the one people will be looking for most. @@ -78,90 +88,92 @@ parser.add_option("--openssl-no-asm", dest="openssl_no_asm", help="Do not build optimized assembly for OpenSSL") -parser.add_option('--shared-http-parser', +shared_optgroup.add_option('--shared-http-parser', action='store_true', dest='shared_http_parser', help='link to a shared http_parser DLL instead of static linking') -parser.add_option('--shared-http-parser-includes', +shared_optgroup.add_option('--shared-http-parser-includes', action='store', dest='shared_http_parser_includes', help='directory containing http_parser header files') -parser.add_option('--shared-http-parser-libname', +shared_optgroup.add_option('--shared-http-parser-libname', action='store', dest='shared_http_parser_libname', default='http_parser', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-http-parser-libpath', +shared_optgroup.add_option('--shared-http-parser-libpath', action='store', dest='shared_http_parser_libpath', help='a directory to search for the shared http_parser DLL') -parser.add_option('--shared-libuv', +shared_optgroup.add_option('--shared-libuv', action='store_true', dest='shared_libuv', help='link to a shared libuv DLL instead of static linking') -parser.add_option('--shared-libuv-includes', +shared_optgroup.add_option('--shared-libuv-includes', action='store', dest='shared_libuv_includes', help='directory containing libuv header files') -parser.add_option('--shared-libuv-libname', +shared_optgroup.add_option('--shared-libuv-libname', action='store', dest='shared_libuv_libname', default='uv', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-libuv-libpath', +shared_optgroup.add_option('--shared-libuv-libpath', action='store', dest='shared_libuv_libpath', help='a directory to search for the shared libuv DLL') -parser.add_option('--shared-openssl', +shared_optgroup.add_option('--shared-openssl', action='store_true', dest='shared_openssl', help='link to a shared OpenSSl DLL instead of static linking') -parser.add_option('--shared-openssl-includes', +shared_optgroup.add_option('--shared-openssl-includes', action='store', dest='shared_openssl_includes', help='directory containing OpenSSL header files') -parser.add_option('--shared-openssl-libname', +shared_optgroup.add_option('--shared-openssl-libname', action='store', dest='shared_openssl_libname', default='crypto,ssl', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-openssl-libpath', +shared_optgroup.add_option('--shared-openssl-libpath', action='store', dest='shared_openssl_libpath', help='a directory to search for the shared OpenSSL DLLs') -parser.add_option('--shared-zlib', +shared_optgroup.add_option('--shared-zlib', action='store_true', dest='shared_zlib', help='link to a shared zlib DLL instead of static linking') -parser.add_option('--shared-zlib-includes', +shared_optgroup.add_option('--shared-zlib-includes', action='store', dest='shared_zlib_includes', help='directory containing zlib header files') -parser.add_option('--shared-zlib-libname', +shared_optgroup.add_option('--shared-zlib-libname', action='store', dest='shared_zlib_libname', default='z', help='alternative lib name to link to [default: %default]') -parser.add_option('--shared-zlib-libpath', +shared_optgroup.add_option('--shared-zlib-libpath', action='store', dest='shared_zlib_libpath', help='a directory to search for the shared zlib DLL') +parser.add_option_group(shared_optgroup) + # TODO document when we've decided on what the tracing API and its options will # look like parser.add_option('--systemtap-includes', @@ -225,33 +237,38 @@ parser.add_option('--with-etw', dest='with_etw', help='build with ETW (default is true on Windows)') -parser.add_option('--download', +intl_optgroup.add_option('--with-intl', action='store', - dest='download_list', - help=nodedownload.help()) + dest='with_intl', + default='none', + choices=valid_intl_modes, + help='Intl mode (valid choices: {0}) [default: %default]'.format( + ', '.join(valid_intl_modes))) -parser.add_option('--with-icu-path', +intl_optgroup.add_option('--with-icu-path', action='store', dest='with_icu_path', help='Path to icu.gyp (ICU i18n, Chromium version only.)') -parser.add_option('--with-icu-locales', +intl_optgroup.add_option('--with-icu-locales', action='store', dest='with_icu_locales', default='root,en', help='Comma-separated list of locales for "small-icu". "root" is assumed. ' '[default: %default]') -parser.add_option('--with-intl', - action='store', - dest='with_intl', - help='Intl mode: none, full-icu, small-icu [default: none]') - -parser.add_option('--with-icu-source', +intl_optgroup.add_option('--with-icu-source', action='store', dest='with_icu_source', help='Intl mode: optional local path to icu/ dir, or path/URL of icu source archive.') +intl_optgroup.add_option('--download', + action='store', + dest='download_list', + help=nodedownload.help()) + +parser.add_option_group(intl_optgroup) + parser.add_option('--with-perfctr', action='store_true', dest='with_perfctr', @@ -277,15 +294,15 @@ parser.add_option('--without-perfctr', dest='without_perfctr', help='build without performance counters') +# Dummy option for backwards compatibility parser.add_option('--with-snapshot', action='store_true', - dest='with_snapshot', + dest='unused_with_snapshot', help=optparse.SUPPRESS_HELP) -# Dummy option for backwards compatibility. parser.add_option('--without-snapshot', action='store_true', - dest='unused_without_snapshot', + dest='without_snapshot', help=optparse.SUPPRESS_HELP) parser.add_option('--without-ssl', @@ -326,17 +343,28 @@ def b(value): def pkg_config(pkg): - cmd = os.popen('pkg-config --libs %s' % pkg, 'r') - libs = cmd.readline().strip() - ret = cmd.close() - if (ret): return None - - cmd = os.popen('pkg-config --cflags %s' % pkg, 'r') - cflags = cmd.readline().strip() - ret = cmd.close() - if (ret): return None - - return (libs, cflags) + pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config') + args = '--silence-errors' + retval = () + for flag in ['--libs-only-l', '--cflags-only-I', '--libs-only-L']: + try: + val = subprocess.check_output([pkg_config, args, flag, pkg]) + # check_output returns bytes + val = val.encode().strip().rstrip('\n') + except subprocess.CalledProcessError: + # most likely missing a .pc-file + val = None + except OSError: + # no pkg-config/pkgconf installed + return (None, None, None) + retval += (val,) + return retval + + +def format_libraries(list): + """Returns string of space separated libraries""" + libraries = list.split(',') + return ' '.join('-l{0}'.format(i) for i in libraries) def try_check_compiler(cc, lang): @@ -562,10 +590,6 @@ def configure_arm(o): o['variables']['arm_fpu'] = 'vfpv3' o['variables']['arm_version'] = '7' - # Print warning when snapshot is enabled and building on armv6 - if is_arch_armv6() and options.with_snapshot: - warn('when building on ARMv6, don\'t use --with-snapshot') - def configure_mips(o): can_use_fpu_instructions = (options.mips_float_abi != 'soft') @@ -587,10 +611,10 @@ def configure_node(o): o['variables']['host_arch'] = host_arch o['variables']['target_arch'] = target_arch - if target_arch != host_arch and options.with_snapshot: - o['variables']['want_separate_host_toolset'] = 1 - else: - o['variables']['want_separate_host_toolset'] = 0 + cross_compiling = target_arch != host_arch + want_snapshots = not options.without_snapshot + o['variables']['want_separate_host_toolset'] = int( + cross_compiling and want_snapshots) if target_arch == 'arm': configure_arm(o) @@ -655,40 +679,30 @@ def configure_node(o): o['variables']['node_target_type'] = 'static_library' -def configure_libz(o): - o['variables']['node_shared_zlib'] = b(options.shared_zlib) - - if options.shared_zlib: - o['libraries'] += ['-l%s' % options.shared_zlib_libname] - if options.shared_zlib_libpath: - o['libraries'] += ['-L%s' % options.shared_zlib_libpath] - if options.shared_zlib_includes: - o['include_dirs'] += [options.shared_zlib_includes] - - -def configure_http_parser(o): - o['variables']['node_shared_http_parser'] = b(options.shared_http_parser) - - if options.shared_http_parser: - o['libraries'] += ['-l%s' % options.shared_http_parser_libname] - if options.shared_http_parser_libpath: - o['libraries'] += ['-L%s' % options.shared_http_parser_libpath] - if options.shared_http_parser_includes: - o['include_dirs'] += [options.shared_http_parser_includes] - - -def configure_libuv(o): - o['variables']['node_shared_libuv'] = b(options.shared_libuv) - - if options.shared_libuv: - o['libraries'] += ['-l%s' % options.shared_libuv_libname] - if options.shared_libuv_libpath: - o['libraries'] += ['-L%s' % options.shared_libuv_libpath] - else: - o['variables']['uv_library'] = 'static_library' - - if options.shared_libuv_includes: - o['include_dirs'] += [options.shared_libuv_includes] +def configure_library(lib, output): + shared_lib = 'shared_' + lib + output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib)) + + if getattr(options, shared_lib): + default_cflags = getattr(options, shared_lib + '_includes') + default_lib = format_libraries(getattr(options, shared_lib + '_libname')) + default_libpath = getattr(options, shared_lib + '_libpath') + if default_libpath: + default_libpath = '-L' + default_libpath + (pkg_libs, pkg_cflags, pkg_libpath) = pkg_config(lib) + cflags = pkg_cflags.split('-I') if pkg_cflags else default_cflags + libs = pkg_libs if pkg_libs else default_lib + libpath = pkg_libpath if pkg_libpath else default_libpath + + # libpath needs to be provided ahead libraries + if libpath: + output['libraries'] += [libpath] + if libs: + # libs passed to the linker cannot contain spaces. + # (libpath on the other hand can) + output['libraries'] += libs.split() + if cflags: + output['include_dirs'] += [cflags] def configure_v8(o): @@ -696,30 +710,16 @@ def configure_v8(o): o['variables']['v8_no_strict_aliasing'] = 1 # Work around compiler bugs. o['variables']['v8_optimized_debug'] = 0 # Compile with -O0 in debug builds. o['variables']['v8_random_seed'] = 0 # Use a random seed for hash tables. - o['variables']['v8_use_snapshot'] = b(options.with_snapshot) + o['variables']['v8_use_snapshot'] = 0 if options.without_snapshot else 1 def configure_openssl(o): o['variables']['node_use_openssl'] = b(not options.without_ssl) o['variables']['node_shared_openssl'] = b(options.shared_openssl) - o['variables']['openssl_no_asm'] = ( - 1 if options.openssl_no_asm else 0) + o['variables']['openssl_no_asm'] = 1 if options.openssl_no_asm else 0 if options.without_ssl: return - - if options.shared_openssl: - (libs, cflags) = pkg_config('openssl') or ('-lssl -lcrypto', '') - - libnames = options.shared_openssl_libname.split(',') - o['libraries'] += ['-l%s' % s for s in libnames] - - if options.shared_openssl_libpath: - o['libraries'] += ['-L%s' % options.shared_openssl_libpath] - - if options.shared_openssl_includes: - o['include_dirs'] += [options.shared_openssl_includes] - else: - o['cflags'] += cflags.split() + configure_library('openssl', o) def configure_fullystatic(o): @@ -812,7 +812,7 @@ def configure_intl(o): with_intl = options.with_intl with_icu_source = options.with_icu_source have_icu_path = bool(options.with_icu_path) - if have_icu_path and with_intl: + if have_icu_path and with_intl != 'none': print 'Error: Cannot specify both --with-icu-path and --with-intl' sys.exit(1) elif have_icu_path: @@ -840,21 +840,19 @@ def configure_intl(o): # ICU from pkg-config. o['variables']['v8_enable_i18n_support'] = 1 pkgicu = pkg_config('icu-i18n') - if not pkgicu: + if pkgicu[0] is None: print 'Error: could not load pkg-config data for "icu-i18n".' print 'See above errors or the README.md.' sys.exit(1) - (libs, cflags) = pkgicu + (libs, cflags, libpath) = pkgicu + # libpath provides linker path which may contain spaces + o['libraries'] += [libpath] + # safe to split, cannot contain spaces o['libraries'] += libs.split() o['cflags'] += cflags.split() # use the "system" .gyp o['variables']['icu_gyp_path'] = 'tools/icu/icu-system.gyp' return - else: - print 'Error: unknown value --with-intl=%s' % with_intl - sys.exit(1) - # Note: non-ICU implementations could use other 'with_intl' - # values. # this is just the 'deps' dir. Used for unpacking. icu_parent_path = os.path.join(root_dir, 'deps') @@ -1008,9 +1006,9 @@ if (options.dest_os): flavor = GetFlavor(flavor_params) configure_node(output) -configure_libz(output) -configure_http_parser(output) -configure_libuv(output) +configure_library('zlib', output) +configure_library('http_parser', output) +configure_library('libuv', output) configure_v8(output) configure_openssl(output) configure_winsdk(output) diff --git a/deps/cares/cares.gyp b/deps/cares/cares.gyp index dfa35a25ef5e56..8fd8662e1bdf6f 100644 --- a/deps/cares/cares.gyp +++ b/deps/cares/cares.gyp @@ -26,7 +26,6 @@ 'direct_dependent_settings': { 'include_dirs': [ 'include' ] }, - 'defines': [ 'HAVE_CONFIG_H' ], 'sources': [ 'common.gypi', 'include/ares.h', @@ -96,7 +95,6 @@ 'src/inet_ntop.c', 'src/ares_inet_net_pton.h', 'src/setup_once.h', - 'src/windows_port.c' ], 'conditions': [ [ 'library=="static_library"', { @@ -107,7 +105,7 @@ [ 'OS=="win"', { 'include_dirs': [ 'config/win32' ], 'sources': [ - 'config/win32/ares_config.h', + 'src/config-win32.h', 'src/windows_port.c', 'src/ares_getenv.c', 'src/ares_iphlpapi.h', @@ -126,6 +124,7 @@ '-Wextra', '-Wno-unused-parameter' ], + 'defines': [ 'HAVE_CONFIG_H' ], }], [ 'OS not in "win android"', { 'cflags': [ diff --git a/deps/cares/config/win32/ares_config.h b/deps/cares/config/win32/ares_config.h deleted file mode 100644 index 6ded638093f8f7..00000000000000 --- a/deps/cares/config/win32/ares_config.h +++ /dev/null @@ -1,369 +0,0 @@ -#ifndef __ARES_CONFIG_WIN32_H -#define __ARES_CONFIG_WIN32_H - -/* when building c-ares library */ -#define CARES_BUILDING_LIBRARY 1 - -/* Copyright (C) 2004 - 2008 by Daniel Stenberg et al - * - * Permission to use, copy, modify, and distribute this software and its - * documentation for any purpose and without fee is hereby granted, provided - * that the above copyright notice appear in all copies and that both that - * copyright notice and this permission notice appear in supporting - * documentation, and that the name of M.I.T. not be used in advertising or - * publicity pertaining to distribution of the software without specific, - * written prior permission. M.I.T. makes no representations about the - * suitability of this software for any purpose. It is provided "as is" - * without express or implied warranty. - */ - -#define ARES_ - -/* ================================================================ */ -/* ares/config-win32.h - Hand crafted config file for Windows */ -/* ================================================================ */ - -/* ---------------------------------------------------------------- */ -/* HEADER FILES */ -/* ---------------------------------------------------------------- */ - -/* Define if you have the header file. */ -#if defined(__MINGW32__) || defined(__POCC__) -#define HAVE_GETOPT_H 1 -#endif - -/* Define if you have the header file. */ -#define HAVE_LIMITS_H 1 - -/* Define if you have the header file. */ -#ifndef __SALFORDC__ -#define HAVE_PROCESS_H 1 -#endif - -/* Define if you have the header file. */ -#define HAVE_SIGNAL_H 1 - -/* Define if you have the header file */ -#if defined(__MINGW32__) -#define HAVE_SYS_TIME_H 1 -#endif - -/* Define if you have the header file. */ -#define HAVE_TIME_H 1 - -/* Define if you have the header file. */ -#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \ - defined(__POCC__) -#define HAVE_UNISTD_H 1 -#endif - -/* Define if you have the windows.h header file. */ -#define HAVE_WINDOWS_H 1 - -/* Define if you have the header file. */ -#define HAVE_WINSOCK_H 1 - -/* Define if you have the header file. */ -#ifndef __SALFORDC__ -#define HAVE_WINSOCK2_H 1 -#endif - -/* Define if you have the header file. */ -#ifndef __SALFORDC__ -#define HAVE_WS2TCPIP_H 1 -#endif - -/* ---------------------------------------------------------------- */ -/* OTHER HEADER INFO */ -/* ---------------------------------------------------------------- */ - -/* Define if sig_atomic_t is an available typedef. */ -#define HAVE_SIG_ATOMIC_T 1 - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and . */ -/* #define TIME_WITH_SYS_TIME 1 */ - -/* ---------------------------------------------------------------- */ -/* FUNCTIONS */ -/* ---------------------------------------------------------------- */ - -/* Define if you have the closesocket function. */ -#define HAVE_CLOSESOCKET 1 - -/* Define if you have the gethostname function. */ -#define HAVE_GETHOSTNAME 1 - -/* Define if you have the ioctlsocket function. */ -#define HAVE_IOCTLSOCKET 1 - -/* Define if you have a working ioctlsocket FIONBIO function. */ -#define HAVE_IOCTLSOCKET_FIONBIO 1 - -/* Define if you have the strcasecmp function. */ -/* #define HAVE_STRCASECMP 1 */ - -/* Define if you have the getenv function. */ -#define HAVE_GETENV 1 - -/* Define if you have the strdup function. */ -#define HAVE_STRDUP 1 - -/* Define if you have the stricmp function. */ -#define HAVE_STRICMP 1 - -/* Define if you have the strncasecmp function. */ -/* #define HAVE_STRNCASECMP 1 */ - -/* Define if you have the strnicmp function. */ -#define HAVE_STRNICMP 1 - -/* Define if you have the recv function. */ -#define HAVE_RECV 1 - -/* Define to the type of arg 1 for recv. */ -#define RECV_TYPE_ARG1 SOCKET - -/* Define to the type of arg 2 for recv. */ -#define RECV_TYPE_ARG2 char * - -/* Define to the type of arg 3 for recv. */ -#define RECV_TYPE_ARG3 int - -/* Define to the type of arg 4 for recv. */ -#define RECV_TYPE_ARG4 int - -/* Define to the function return type for recv. */ -#define RECV_TYPE_RETV int - -/* Define if you have the recvfrom function. */ -#define HAVE_RECVFROM 1 - -/* Define to the type of arg 1 for recvfrom. */ -#define RECVFROM_TYPE_ARG1 SOCKET - -/* Define to the type pointed by arg 2 for recvfrom. */ -#define RECVFROM_TYPE_ARG2 char - -/* Define to the type of arg 3 for recvfrom. */ -#define RECVFROM_TYPE_ARG3 int - -/* Define to the type of arg 4 for recvfrom. */ -#define RECVFROM_TYPE_ARG4 int - -/* Define to the type pointed by arg 5 for recvfrom. */ -#define RECVFROM_TYPE_ARG5 struct sockaddr - -/* Define to the type pointed by arg 6 for recvfrom. */ -#define RECVFROM_TYPE_ARG6 int - -/* Define to the function return type for recvfrom. */ -#define RECVFROM_TYPE_RETV int - -/* Define if you have the send function. */ -#define HAVE_SEND 1 - -/* Define to the type of arg 1 for send. */ -#define SEND_TYPE_ARG1 SOCKET - -/* Define to the type qualifier of arg 2 for send. */ -#define SEND_QUAL_ARG2 const - -/* Define to the type of arg 2 for send. */ -#define SEND_TYPE_ARG2 char * - -/* Define to the type of arg 3 for send. */ -#define SEND_TYPE_ARG3 int - -/* Define to the type of arg 4 for send. */ -#define SEND_TYPE_ARG4 int - -/* Define to the function return type for send. */ -#define SEND_TYPE_RETV int - -/* Specifics for the Watt-32 tcp/ip stack */ -#ifdef WATT32 - #define SOCKET int - #define NS_INADDRSZ 4 - #define HAVE_ARPA_NAMESER_H 1 - #define HAVE_ARPA_INET_H 1 - #define HAVE_NETDB_H 1 - #define HAVE_NETINET_IN_H 1 - #define HAVE_SYS_SOCKET_H 1 - #define HAVE_NETINET_TCP_H 1 - #define HAVE_AF_INET6 1 - #define HAVE_PF_INET6 1 - #define HAVE_STRUCT_IN6_ADDR 1 - #define HAVE_STRUCT_SOCKADDR_IN6 1 - #undef HAVE_WINSOCK_H - #undef HAVE_WINSOCK2_H - #undef HAVE_WS2TCPIP_H -#endif - -/* ---------------------------------------------------------------- */ -/* TYPEDEF REPLACEMENTS */ -/* ---------------------------------------------------------------- */ - -/* Define this if in_addr_t is not an available 'typedefed' type */ -#define in_addr_t unsigned long - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define ssize_t if it is not an available 'typedefed' type */ -#ifndef _SSIZE_T_DEFINED -# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \ - defined(__POCC__) || \ - defined(__MINGW32__) -# elif defined(_WIN64) -# define _SSIZE_T_DEFINED -# define ssize_t __int64 -# else -# define _SSIZE_T_DEFINED -# define ssize_t int -# endif -#endif - -/* ---------------------------------------------------------------- */ -/* TYPE SIZES */ -/* ---------------------------------------------------------------- */ - -/* The size of `int', as computed by sizeof. */ -#define SIZEOF_INT 4 - -/* The size of `short', as computed by sizeof. */ -#define SIZEOF_SHORT 2 - -/* The size of `size_t', as computed by sizeof. */ -#if defined(_WIN64) -# define SIZEOF_SIZE_T 8 -#else -# define SIZEOF_SIZE_T 4 -#endif - -/* ---------------------------------------------------------------- */ -/* STRUCT RELATED */ -/* ---------------------------------------------------------------- */ - -/* Define this if you have struct addrinfo */ -#define HAVE_STRUCT_ADDRINFO 1 - -/* Define this if you have struct sockaddr_storage */ -#ifndef __SALFORDC__ -#define HAVE_STRUCT_SOCKADDR_STORAGE 1 -#endif - -/* Define this if you have struct timeval */ -#define HAVE_STRUCT_TIMEVAL 1 - -/* ---------------------------------------------------------------- */ -/* COMPILER SPECIFIC */ -/* ---------------------------------------------------------------- */ - -/* Define to avoid VS2005 complaining about portable C functions */ -#if defined(_MSC_VER) && (_MSC_VER >= 1400) -#define _CRT_SECURE_NO_DEPRECATE 1 -#define _CRT_NONSTDC_NO_DEPRECATE 1 -#endif - -/* Officially, Microsoft's Windows SDK versions 6.X do not support Windows - 2000 as a supported build target. VS2008 default installations provide an - embedded Windows SDK v6.0A along with the claim that Windows 2000 is a - valid build target for VS2008. Popular belief is that binaries built using - Windows SDK versions 6.X and Windows 2000 as a build target are functional */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -# define VS2008_MINIMUM_TARGET 0x0500 -#endif - -/* When no build target is specified VS2008 default build target is Windows - Vista, which leaves out even Winsows XP. If no build target has been given - for VS2008 we will target the minimum Officially supported build target, - which happens to be Windows XP. */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -# define VS2008_DEFAULT_TARGET 0x0501 -#endif - -/* VS2008 default target settings and minimum build target check */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -# ifndef _WIN32_WINNT -# define _WIN32_WINNT VS2008_DEFAULT_TARGET -# endif -# ifndef WINVER -# define WINVER VS2008_DEFAULT_TARGET -# endif -# if (_WIN32_WINNT < VS2008_MINIMUM_TARGET) || (WINVER < VS2008_MINIMUM_TARGET) -# error VS2008 does not support Windows build targets prior to Windows 2000 -# endif -#endif - -/* When no build target is specified Pelles C 5.00 and later default build - target is Windows Vista. We override default target to be Windows 2000. */ -#if defined(__POCC__) && (__POCC__ >= 500) -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0500 -# endif -# ifndef WINVER -# define WINVER 0x0500 -# endif -#endif - -/* Availability of freeaddrinfo, getaddrinfo and getnameinfo functions is - quite convoluted, compiler dependent and even build target dependent. */ -#if defined(HAVE_WS2TCPIP_H) -# if defined(__POCC__) -# define HAVE_FREEADDRINFO 1 -# define HAVE_GETADDRINFO 1 -# define HAVE_GETNAMEINFO 1 -# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) -# define HAVE_FREEADDRINFO 1 -# define HAVE_GETADDRINFO 1 -# define HAVE_GETNAMEINFO 1 -# elif defined(_MSC_VER) && (_MSC_VER >= 1200) -# define HAVE_FREEADDRINFO 1 -# define HAVE_GETADDRINFO 1 -# define HAVE_GETNAMEINFO 1 -# endif -#endif - -#if defined(__POCC__) -# ifndef _MSC_VER -# error Microsoft extensions /Ze compiler option is required -# endif -# ifndef __POCC__OLDNAMES -# error Compatibility names /Go compiler option is required -# endif -#endif - -/* ---------------------------------------------------------------- */ -/* IPV6 COMPATIBILITY */ -/* ---------------------------------------------------------------- */ - -/* Define this if you have address family AF_INET6 */ -#ifdef HAVE_WINSOCK2_H -#define HAVE_AF_INET6 1 -#endif - -/* Define this if you have protocol family PF_INET6 */ -#ifdef HAVE_WINSOCK2_H -#define HAVE_PF_INET6 1 -#endif - -/* Define this if you have struct in6_addr */ -#ifdef HAVE_WS2TCPIP_H -#define HAVE_STRUCT_IN6_ADDR 1 -#endif - -/* Define this if you have struct sockaddr_in6 */ -#ifdef HAVE_WS2TCPIP_H -#define HAVE_STRUCT_SOCKADDR_IN6 1 -#endif - -/* Define this if you have sockaddr_in6 with scopeid */ -#ifdef HAVE_WS2TCPIP_H -#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 -#endif - - -#endif /* __ARES_CONFIG_WIN32_H */ diff --git a/deps/cares/include/ares.h b/deps/cares/include/ares.h index 3091064b5113b4..f9abe854d5846a 100644 --- a/deps/cares/include/ares.h +++ b/deps/cares/include/ares.h @@ -29,55 +29,8 @@ # define WIN32 #endif -/*************************** libuv patch ***************/ - -/* - * We want to avoid autoconf altogether since there are a finite number of - * operating systems and simply build c-ares. Therefore we do not want the - * configurations provided by ares_build.h since we are always statically - * linking c-ares into libuv. Having a system dependent ares_build.h forces - * all users of ares.h to include the correct ares_build.h. We do not care - * about the linking checks provided by ares_rules.h. This would complicate - * the libuv build process. - */ - - -#if defined(WIN32) -/* Configure process defines this to 1 when it finds out that system */ -/* header file ws2tcpip.h must be included by the external interface. */ -/* #undef CARES_PULL_WS2TCPIP_H */ -# include -# include -# include - -#else /* Not Windows */ - -# include -# include -# include -#endif - -#if 0 -/* The size of `long', as computed by sizeof. */ -#define CARES_SIZEOF_LONG 4 -#endif - -/* Integral data type used for ares_socklen_t. */ -#define CARES_TYPEOF_ARES_SOCKLEN_T socklen_t - -#if 0 -/* The size of `ares_socklen_t', as computed by sizeof. */ -#define CARES_SIZEOF_ARES_SOCKLEN_T 4 -#endif - /* Data type definition of ares_socklen_t. */ -typedef int ares_socklen_t; - -#if 0 /* libuv disabled */ -#include "ares_rules.h" /* c-ares rules enforcement */ -#endif - -/*********************** end libuv patch ***************/ +typedef unsigned ares_socklen_t; #include diff --git a/deps/cares/include/ares_version.h b/deps/cares/include/ares_version.h index cdd49924cc4b80..2c9146d7d954a6 100644 --- a/deps/cares/include/ares_version.h +++ b/deps/cares/include/ares_version.h @@ -7,11 +7,11 @@ #define ARES_VERSION_MAJOR 1 #define ARES_VERSION_MINOR 10 -#define ARES_VERSION_PATCH 0 +#define ARES_VERSION_PATCH 1 #define ARES_VERSION ((ARES_VERSION_MAJOR<<16)|\ (ARES_VERSION_MINOR<<8)|\ (ARES_VERSION_PATCH)) -#define ARES_VERSION_STR "1.10.0-DEV" +#define ARES_VERSION_STR "1.10.1-DEV" #if (ARES_VERSION >= 0x010700) # define CARES_HAVE_ARES_LIBRARY_INIT 1 diff --git a/deps/cares/src/ares__read_line.c b/deps/cares/src/ares__read_line.c index bd9504fc4f0be0..6ebd42fe6efb34 100644 --- a/deps/cares/src/ares__read_line.c +++ b/deps/cares/src/ares__read_line.c @@ -61,7 +61,10 @@ int ares__read_line(FILE *fp, char **buf, size_t *bufsize) /* Allocate more space. */ newbuf = realloc(*buf, *bufsize * 2); if (!newbuf) - return ARES_ENOMEM; + { + free(*buf); + return ARES_ENOMEM; + } *buf = newbuf; *bufsize *= 2; } diff --git a/deps/cares/src/ares_gethostbyname.c b/deps/cares/src/ares_gethostbyname.c index 2b27b2e1048fcc..ba6b0f0f0c5661 100644 --- a/deps/cares/src/ares_gethostbyname.c +++ b/deps/cares/src/ares_gethostbyname.c @@ -188,8 +188,9 @@ static void host_callback(void *arg, int status, int timeouts, else if (hquery->sent_family == AF_INET6) { status = ares_parse_aaaa_reply(abuf, alen, &host, NULL, NULL); - if ((status == ARES_ENODATA || status == ARES_EBADRESP) && - hquery->want_family == AF_UNSPEC) { + if ((status == ARES_ENODATA || status == ARES_EBADRESP || + (status == ARES_SUCCESS && host && host->h_addr_list[0] == NULL)) && + hquery->want_family == AF_UNSPEC) { /* The query returned something but either there were no AAAA records (e.g. just CNAME) or the response was malformed. Try looking up A instead. */ diff --git a/deps/cares/src/ares_getnameinfo.c b/deps/cares/src/ares_getnameinfo.c index 5b9f6386b29e01..b0bc6da868cdda 100644 --- a/deps/cares/src/ares_getnameinfo.c +++ b/deps/cares/src/ares_getnameinfo.c @@ -281,6 +281,8 @@ static char *lookup_service(unsigned short port, int flags, struct servent se; #endif char tmpbuf[4096]; + char *name; + size_t name_len; if (port) { @@ -323,14 +325,20 @@ static char *lookup_service(unsigned short port, int flags, #endif } if (sep && sep->s_name) - /* get service name */ - strcpy(tmpbuf, sep->s_name); + { + /* get service name */ + name = sep->s_name; + } else - /* get port as a string */ - sprintf(tmpbuf, "%u", (unsigned int)ntohs(port)); - if (strlen(tmpbuf) < buflen) + { + /* get port as a string */ + sprintf(tmpbuf, "%u", (unsigned int)ntohs(port)); + name = tmpbuf; + } + name_len = strlen(name); + if (name_len < buflen) /* return it if buffer big enough */ - strcpy(buf, tmpbuf); + memcpy(buf, name, name_len + 1); else /* avoid reusing previous one */ buf[0] = '\0'; diff --git a/deps/cares/src/ares_getsock.c b/deps/cares/src/ares_getsock.c index 07d2854cfd1538..22d344679faa60 100644 --- a/deps/cares/src/ares_getsock.c +++ b/deps/cares/src/ares_getsock.c @@ -30,9 +30,7 @@ int ares_getsock(ares_channel channel, /* Are there any active queries? */ int active_queries = !ares__is_list_empty(&(channel->all_queries)); - for (i = 0; - (i < channel->nservers) && (sockindex < ARES_GETSOCK_MAXNUM); - i++) + for (i = 0; i < channel->nservers; i++) { server = &channel->servers[i]; /* We only need to register interest in UDP sockets if we have @@ -40,7 +38,7 @@ int ares_getsock(ares_channel channel, */ if (active_queries && server->udp_socket != ARES_SOCKET_BAD) { - if(sockindex >= numsocks) + if(sockindex >= numsocks || sockindex >= ARES_GETSOCK_MAXNUM) break; socks[sockindex] = server->udp_socket; bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex); @@ -52,7 +50,7 @@ int ares_getsock(ares_channel channel, */ if (server->tcp_socket != ARES_SOCKET_BAD) { - if(sockindex >= numsocks) + if(sockindex >= numsocks || sockindex >= ARES_GETSOCK_MAXNUM) break; socks[sockindex] = server->tcp_socket; bitmap |= ARES_GETSOCK_READABLE(setbits, sockindex); diff --git a/deps/cares/src/ares_init.c b/deps/cares/src/ares_init.c index 05bf70c3b6d80f..bd3336e5d63e46 100644 --- a/deps/cares/src/ares_init.c +++ b/deps/cares/src/ares_init.c @@ -266,7 +266,10 @@ int ares_dup(ares_channel *dest, ares_channel src) which is most of them */ rc = ares_save_options(src, &opts, &optmask); if(rc) + { + ares_destroy_options(&opts); return rc; + } /* Then create the new channel with those options */ rc = ares_init_options(dest, &opts, optmask); @@ -1158,20 +1161,24 @@ static int init_by_resolv_conf(ares_channel channel) FILE *fp; size_t linesize; int error; + int update_domains; /* Don't read resolv.conf and friends if we don't have to */ if (ARES_CONFIG_CHECK(channel)) return ARES_SUCCESS; + /* Only update search domains if they're not already specified */ + update_domains = (channel->ndomains == -1); + fp = fopen(PATH_RESOLV_CONF, "r"); if (fp) { while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS) { - if ((p = try_config(line, "domain", ';'))) + if ((p = try_config(line, "domain", ';')) && update_domains) status = config_domain(channel, p); else if ((p = try_config(line, "lookup", ';')) && !channel->lookups) status = config_lookup(channel, p, "bind", "file"); - else if ((p = try_config(line, "search", ';'))) + else if ((p = try_config(line, "search", ';')) && update_domains) status = set_search(channel, p); else if ((p = try_config(line, "nameserver", ';')) && channel->nservers == -1) @@ -1410,7 +1417,7 @@ static int init_by_defaults(ares_channel channel) goto error; } - } WHILE_FALSE; + } while (res != 0); dot = strchr(hostname, '.'); if (dot) { diff --git a/deps/cares/src/ares_ipv6.h b/deps/cares/src/ares_ipv6.h index 6f1022a76f5338..1830076a81092a 100644 --- a/deps/cares/src/ares_ipv6.h +++ b/deps/cares/src/ares_ipv6.h @@ -71,7 +71,7 @@ struct addrinfo #endif #endif -/* Defined in ares_net_pton.c for no particular reason. */ +/* Defined in inet_net_pton.c for no particular reason. */ extern const struct ares_in6_addr ares_in6addr_any; /* :: */ diff --git a/deps/cares/src/ares_nowarn.c b/deps/cares/src/ares_nowarn.c index 397e70b01844a1..d4bd272c6d9e8c 100644 --- a/deps/cares/src/ares_nowarn.c +++ b/deps/cares/src/ares_nowarn.c @@ -1,5 +1,5 @@ -/* Copyright (C) 2010-2012 by Daniel Stenberg +/* Copyright (C) 2010-2013 by Daniel Stenberg * * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without @@ -21,6 +21,10 @@ # include #endif +#ifdef HAVE_LIMITS_H +#include +#endif + #if defined(__INTEL_COMPILER) && defined(__unix__) #ifdef HAVE_NETINET_IN_H @@ -36,13 +40,43 @@ #include "ares_nowarn.h" -#define CARES_MASK_USHORT (~(unsigned short) 0) -#define CARES_MASK_UINT (~(unsigned int) 0) -#define CARES_MASK_ULONG (~(unsigned long) 0) +#if (SIZEOF_SHORT == 2) +# define CARES_MASK_SSHORT 0x7FFF +# define CARES_MASK_USHORT 0xFFFF +#elif (SIZEOF_SHORT == 4) +# define CARES_MASK_SSHORT 0x7FFFFFFF +# define CARES_MASK_USHORT 0xFFFFFFFF +#elif (SIZEOF_SHORT == 8) +# define CARES_MASK_SSHORT 0x7FFFFFFFFFFFFFFF +# define CARES_MASK_USHORT 0xFFFFFFFFFFFFFFFF +#else +# error "SIZEOF_SHORT not defined" +#endif -#define CARES_MASK_SSHORT (CARES_MASK_USHORT >> 1) -#define CARES_MASK_SINT (CARES_MASK_UINT >> 1) -#define CARES_MASK_SLONG (CARES_MASK_ULONG >> 1) +#if (SIZEOF_INT == 2) +# define CARES_MASK_SINT 0x7FFF +# define CARES_MASK_UINT 0xFFFF +#elif (SIZEOF_INT == 4) +# define CARES_MASK_SINT 0x7FFFFFFF +# define CARES_MASK_UINT 0xFFFFFFFF +#elif (SIZEOF_INT == 8) +# define CARES_MASK_SINT 0x7FFFFFFFFFFFFFFF +# define CARES_MASK_UINT 0xFFFFFFFFFFFFFFFF +#elif (SIZEOF_INT == 16) +# define CARES_MASK_SINT 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF +# define CARES_MASK_UINT 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF +#else +# error "SIZEOF_INT not defined" +#endif + +#ifndef HAVE_LIMITS_H +/* systems without we guess have 32 bit longs */ +#define CARES_MASK_SLONG 0x7FFFFFFFL +#define CARES_MASK_ULONG 0xFFFFFFFFUL +#else +#define CARES_MASK_ULONG ULONG_MAX +#define CARES_MASK_SLONG LONG_MAX +#endif /* ** unsigned size_t to signed long diff --git a/deps/cares/src/ares_options.c b/deps/cares/src/ares_options.c index 76d82dfb94d0a8..cf88433a1b5ae4 100644 --- a/deps/cares/src/ares_options.c +++ b/deps/cares/src/ares_options.c @@ -158,6 +158,9 @@ int ares_set_servers_csv(ares_channel channel, return ARES_SUCCESS; /* blank all servers */ csv = malloc(i + 2); + if (!csv) + return ARES_ENOMEM; + strcpy(csv, _csv); if (csv[i-1] != ',') { /* make parsing easier by ensuring ending ',' */ csv[i] = ','; diff --git a/deps/cares/src/ares_parse_soa_reply.c b/deps/cares/src/ares_parse_soa_reply.c index da1c6dccaf13ee..9a578a1f19a226 100644 --- a/deps/cares/src/ares_parse_soa_reply.c +++ b/deps/cares/src/ares_parse_soa_reply.c @@ -86,7 +86,10 @@ ares_parse_soa_reply(const unsigned char *abuf, int alen, /* allocate result struct */ soa = ares_malloc_data(ARES_DATATYPE_SOA_REPLY); if (!soa) - return ARES_ENOMEM; + { + status = ARES_ENOMEM; + goto failed_stat; + } /* nsname */ status = ares__expand_name_for_response(aptr, abuf, alen, &soa->nsname, &len); diff --git a/deps/cares/src/ares_private.h b/deps/cares/src/ares_private.h index ab5be5a58aa6c9..8f486a449a8ae2 100644 --- a/deps/cares/src/ares_private.h +++ b/deps/cares/src/ares_private.h @@ -310,12 +310,7 @@ struct ares_channeldata { /* return true if now is exactly check time or later */ int ares__timedout(struct timeval *now, struct timeval *check); -/* add the specific number of milliseconds to the time in the first argument */ -int ares__timeadd(struct timeval *now, - int millisecs); -/* return time offset between now and (future) check, in milliseconds */ -long ares__timeoffset(struct timeval *now, - struct timeval *check); + /* returns ARES_SUCCESS if library has been initialized */ int ares_library_initialized(void); void ares__send_query(ares_channel channel, struct query *query, diff --git a/deps/cares/src/ares_process.c b/deps/cares/src/ares_process.c index bbeca5e737e73f..020a1319e55ea4 100644 --- a/deps/cares/src/ares_process.c +++ b/deps/cares/src/ares_process.c @@ -102,8 +102,7 @@ int ares__timedout(struct timeval *now, } /* add the specific number of milliseconds to the time in the first argument */ -int ares__timeadd(struct timeval *now, - int millisecs) +static void timeadd(struct timeval *now, int millisecs) { now->tv_sec += millisecs/1000; now->tv_usec += (millisecs%1000)*1000; @@ -112,19 +111,8 @@ int ares__timeadd(struct timeval *now, ++(now->tv_sec); now->tv_usec -= 1000000; } - - return 0; -} - -/* return time offset between now and (future) check, in milliseconds */ -long ares__timeoffset(struct timeval *now, - struct timeval *check) -{ - return (check->tv_sec - now->tv_sec)*1000 + - (check->tv_usec - now->tv_usec)/1000; } - /* * generic process function */ @@ -831,8 +819,7 @@ void ares__send_query(ares_channel channel, struct query *query, timeplus = channel->timeout << (query->try_count / channel->nservers); timeplus = (timeplus * (9 + (rand () & 7))) / 16; query->timeout = *now; - ares__timeadd(&query->timeout, - timeplus); + timeadd(&query->timeout, timeplus); /* Keep track of queries bucketed by timeout, so we can process * timeout events quickly. */ diff --git a/deps/cares/src/ares_rules.h b/deps/cares/src/ares_rules.h index f94c5b59165e7a..44f08f807c3cb7 100644 --- a/deps/cares/src/ares_rules.h +++ b/deps/cares/src/ares_rules.h @@ -68,11 +68,6 @@ * Verify that some macros are actually defined. */ -#ifndef CARES_SIZEOF_LONG -# error "CARES_SIZEOF_LONG definition is missing!" - Error Compilation_aborted_CARES_SIZEOF_LONG_is_missing -#endif - #ifndef CARES_TYPEOF_ARES_SOCKLEN_T # error "CARES_TYPEOF_ARES_SOCKLEN_T definition is missing!" Error Compilation_aborted_CARES_TYPEOF_ARES_SOCKLEN_T_is_missing @@ -91,15 +86,6 @@ #define CareschkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1 -/* - * Verify that the size previously defined and expected for long - * is the same as the one reported by sizeof() at compile time. - */ - -typedef char - __cares_rule_01__ - [CareschkszEQ(long, CARES_SIZEOF_LONG)]; - /* * Verify that the size previously defined and expected for * ares_socklen_t is actually the the same as the one reported diff --git a/deps/cares/src/ares_search.c b/deps/cares/src/ares_search.c index ec076405adb7a1..f9558a9a50f463 100644 --- a/deps/cares/src/ares_search.c +++ b/deps/cares/src/ares_search.c @@ -239,7 +239,7 @@ static int single_domain(ares_channel channel, const char *name, char **s) /* If the name contains a trailing dot, then the single query is the name * sans the trailing dot. */ - if (name[len - 1] == '.') + if ((len > 0) && (name[len - 1] == '.')) { *s = strdup(name); return (*s) ? ARES_SUCCESS : ARES_ENOMEM; diff --git a/deps/cares/src/ares_setup.h b/deps/cares/src/ares_setup.h index 18e14557cde56d..dee3e6ba6e4c05 100644 --- a/deps/cares/src/ares_setup.h +++ b/deps/cares/src/ares_setup.h @@ -75,9 +75,9 @@ /* please, do it beyond the point further indicated in this file. */ /* ================================================================ */ -#if 1 /* libuv hack */ -#include /* needed on windows */ -#else +#if 1 +# define SIZEOF_SHORT 2 +#else /* Disabled for the gyp-ified build. */ /* * c-ares external interface definitions are also used internally, * and might also include required system header files to define them. @@ -90,7 +90,7 @@ */ #include -#endif /* libuv hack */ +#endif /* ================================================================= */ /* No system header file shall be included in this file before this */ diff --git a/deps/cares/src/ares_timeout.c b/deps/cares/src/ares_timeout.c index 0b5a435f510f4c..293e4af02161e8 100644 --- a/deps/cares/src/ares_timeout.c +++ b/deps/cares/src/ares_timeout.c @@ -23,6 +23,13 @@ #include "ares.h" #include "ares_private.h" +/* return time offset between now and (future) check, in milliseconds */ +static long timeoffset(struct timeval *now, struct timeval *check) +{ + return (check->tv_sec - now->tv_sec)*1000 + + (check->tv_usec - now->tv_usec)/1000; +} + /* WARNING: Beware that this is linear in the number of outstanding * requests! You are probably far better off just calling ares_process() * once per second, rather than calling ares_timeout() to figure out @@ -53,7 +60,7 @@ struct timeval *ares_timeout(ares_channel channel, struct timeval *maxtv, query = list_node->data; if (query->timeout.tv_sec == 0) continue; - offset = ares__timeoffset(&now, &query->timeout); + offset = timeoffset(&now, &query->timeout); if (offset < 0) offset = 0; if (min_offset == -1 || offset < min_offset) diff --git a/deps/cares/src/config-win32.h b/deps/cares/src/config-win32.h new file mode 100644 index 00000000000000..1245ba2abbef89 --- /dev/null +++ b/deps/cares/src/config-win32.h @@ -0,0 +1,385 @@ +#ifndef HEADER_CARES_CONFIG_WIN32_H +#define HEADER_CARES_CONFIG_WIN32_H + +/* Copyright (C) 2004 - 2011 by Daniel Stenberg et al + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose and without fee is hereby granted, provided + * that the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. M.I.T. makes no representations about the + * suitability of this software for any purpose. It is provided "as is" + * without express or implied warranty. + */ + +/* ================================================================ */ +/* c-ares/config-win32.h - Hand crafted config file for Windows */ +/* ================================================================ */ + +/* ---------------------------------------------------------------- */ +/* HEADER FILES */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the header file. */ +#define HAVE_ASSERT_H 1 + +/* Define if you have the header file. */ +#define HAVE_ERRNO_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) || defined(__POCC__) +#define HAVE_GETOPT_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_PROCESS_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_SIGNAL_H 1 + +/* Define if you have the header file */ +/* #define HAVE_SYS_TIME_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_TIME_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \ + defined(__POCC__) +#define HAVE_UNISTD_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_WINDOWS_H 1 + +/* Define if you have the header file. */ +#define HAVE_WINSOCK_H 1 + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_WINSOCK2_H 1 +#endif + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_WS2TCPIP_H 1 +#endif + +/* ---------------------------------------------------------------- */ +/* OTHER HEADER INFO */ +/* ---------------------------------------------------------------- */ + +/* Define if sig_atomic_t is an available typedef. */ +#define HAVE_SIG_ATOMIC_T 1 + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if you can safely include both and . */ +/* #define TIME_WITH_SYS_TIME 1 */ + +/* ---------------------------------------------------------------- */ +/* FUNCTIONS */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the closesocket function. */ +#define HAVE_CLOSESOCKET 1 + +/* Define if you have the getenv function. */ +#define HAVE_GETENV 1 + +/* Define if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define if you have the ioctlsocket function. */ +#define HAVE_IOCTLSOCKET 1 + +/* Define if you have a working ioctlsocket FIONBIO function. */ +#define HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define if you have the strcasecmp function. */ +/* #define HAVE_STRCASECMP 1 */ + +/* Define if you have the strdup function. */ +#define HAVE_STRDUP 1 + +/* Define if you have the stricmp function. */ +#define HAVE_STRICMP 1 + +/* Define if you have the strncasecmp function. */ +/* #define HAVE_STRNCASECMP 1 */ + +/* Define if you have the strnicmp function. */ +#define HAVE_STRNICMP 1 + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 SOCKET + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the recvfrom function. */ +#define HAVE_RECVFROM 1 + +/* Define to the type of arg 1 for recvfrom. */ +#define RECVFROM_TYPE_ARG1 SOCKET + +/* Define to the type pointed by arg 2 for recvfrom. */ +#define RECVFROM_TYPE_ARG2 char + +/* Define to the type of arg 3 for recvfrom. */ +#define RECVFROM_TYPE_ARG3 int + +/* Define to the type of arg 4 for recvfrom. */ +#define RECVFROM_TYPE_ARG4 int + +/* Define to the type pointed by arg 5 for recvfrom. */ +#define RECVFROM_TYPE_ARG5 struct sockaddr + +/* Define to the type pointed by arg 6 for recvfrom. */ +#define RECVFROM_TYPE_ARG6 int + +/* Define to the function return type for recvfrom. */ +#define RECVFROM_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 SOCKET + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* Specifics for the Watt-32 tcp/ip stack. */ +#ifdef WATT32 + #define SOCKET int + #define NS_INADDRSZ 4 + #define HAVE_ARPA_NAMESER_H 1 + #define HAVE_ARPA_INET_H 1 + #define HAVE_NETDB_H 1 + #define HAVE_NETINET_IN_H 1 + #define HAVE_SYS_SOCKET_H 1 + #define HAVE_NETINET_TCP_H 1 + #define HAVE_AF_INET6 1 + #define HAVE_PF_INET6 1 + #define HAVE_STRUCT_IN6_ADDR 1 + #define HAVE_STRUCT_SOCKADDR_IN6 1 + #undef HAVE_WINSOCK_H + #undef HAVE_WINSOCK2_H + #undef HAVE_WS2TCPIP_H +#endif + +/* ---------------------------------------------------------------- */ +/* TYPEDEF REPLACEMENTS */ +/* ---------------------------------------------------------------- */ + +/* Define if in_addr_t is not an available 'typedefed' type. */ +#define in_addr_t unsigned long + +/* Define to the return type of signal handlers (int or void). */ +#define RETSIGTYPE void + +/* Define if ssize_t is not an available 'typedefed' type. */ +#ifndef _SSIZE_T_DEFINED +# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \ + defined(__POCC__) || \ + defined(__MINGW32__) +# elif defined(_WIN64) +# define _SSIZE_T_DEFINED +# define ssize_t __int64 +# else +# define _SSIZE_T_DEFINED +# define ssize_t int +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* TYPE SIZES */ +/* ---------------------------------------------------------------- */ + +/* Define to the size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define to the size of `short', as computed by sizeof. */ +#define SIZEOF_SHORT 2 + +/* Define to the size of `size_t', as computed by sizeof. */ +#if defined(_WIN64) +# define SIZEOF_SIZE_T 8 +#else +# define SIZEOF_SIZE_T 4 +#endif + +/* ---------------------------------------------------------------- */ +/* STRUCT RELATED */ +/* ---------------------------------------------------------------- */ + +/* Define if you have struct addrinfo. */ +#define HAVE_STRUCT_ADDRINFO 1 + +/* Define if you have struct sockaddr_storage. */ +#if !defined(__SALFORDC__) && !defined(__BORLANDC__) +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 +#endif + +/* Define if you have struct timeval. */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* ---------------------------------------------------------------- */ +/* COMPILER SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Define to avoid VS2005 complaining about portable C functions. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +# define _CRT_SECURE_NO_DEPRECATE 1 +# define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif + +/* Officially, Microsoft's Windows SDK versions 6.X do not support Windows + 2000 as a supported build target. VS2008 default installations provide + an embedded Windows SDK v6.0A along with the claim that Windows 2000 is + a valid build target for VS2008. Popular belief is that binaries built + with VS2008 using Windows SDK versions 6.X and Windows 2000 as a build + target are functional. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +# define VS2008_MIN_TARGET 0x0500 +#endif + +/* When no build target is specified VS2008 default build target is Windows + Vista, which leaves out even Winsows XP. If no build target has been given + for VS2008 we will target the minimum Officially supported build target, + which happens to be Windows XP. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +# define VS2008_DEF_TARGET 0x0501 +#endif + +/* VS2008 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2008_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2008_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET) +# error VS2008 does not support Windows build targets prior to Windows 2000 +# endif +#endif + +/* When no build target is specified Pelles C 5.00 and later default build + target is Windows Vista. We override default target to be Windows 2000. */ +#if defined(__POCC__) && (__POCC__ >= 500) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0500 +# endif +# ifndef WINVER +# define WINVER 0x0500 +# endif +#endif + +/* Availability of freeaddrinfo, getaddrinfo and getnameinfo functions is + quite convoluted, compiler dependent and even build target dependent. */ +#if defined(HAVE_WS2TCPIP_H) +# if defined(__POCC__) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETNAMEINFO 1 +# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETNAMEINFO 1 +# elif defined(_MSC_VER) && (_MSC_VER >= 1200) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETNAMEINFO 1 +# endif +#endif + +#if defined(__POCC__) +# ifndef _MSC_VER +# error Microsoft extensions /Ze compiler option is required +# endif +# ifndef __POCC__OLDNAMES +# error Compatibility names /Go compiler option is required +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* IPV6 COMPATIBILITY */ +/* ---------------------------------------------------------------- */ + +/* Define if you have address family AF_INET6. */ +#ifdef HAVE_WINSOCK2_H +#define HAVE_AF_INET6 1 +#endif + +/* Define if you have protocol family PF_INET6. */ +#ifdef HAVE_WINSOCK2_H +#define HAVE_PF_INET6 1 +#endif + +/* Define if you have struct in6_addr. */ +#ifdef HAVE_WS2TCPIP_H +#define HAVE_STRUCT_IN6_ADDR 1 +#endif + +/* Define if you have struct sockaddr_in6. */ +#ifdef HAVE_WS2TCPIP_H +#define HAVE_STRUCT_SOCKADDR_IN6 1 +#endif + +/* Define if you have sockaddr_in6 with scopeid. */ +#ifdef HAVE_WS2TCPIP_H +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 +#endif + +/* ---------------------------------------------------------------- */ +/* Win CE */ +/* ---------------------------------------------------------------- */ + +/* FIXME: A proper config-win32ce.h should be created to hold these */ + +/* + * System error codes for Windows CE + */ + +#if defined(_WIN32_WCE) && !defined(HAVE_ERRNO_H) +# define ENOENT ERROR_FILE_NOT_FOUND +# define ESRCH ERROR_PATH_NOT_FOUND +# define ENOMEM ERROR_NOT_ENOUGH_MEMORY +# define ENOSPC ERROR_INVALID_PARAMETER +#endif + +#endif /* HEADER_CARES_CONFIG_WIN32_H */ diff --git a/deps/uv/AUTHORS b/deps/uv/AUTHORS index 6929fff222cd91..a0e3dd46f092f4 100644 --- a/deps/uv/AUTHORS +++ b/deps/uv/AUTHORS @@ -181,3 +181,19 @@ Johan Bergström Alex Mo Luis Martinez de Bartolome Michael Penick +Michael +Massimiliano Torromeo +TomCrypto +Brett Vickers +Ole André Vadla Ravnås +Kazuho Oku +Ryan Phillips +Brian Green +Devchandra Meetei Leishangthem +Corey Farrell +Per Nilsson +Alan Rogers +Daryl Haresign +Rui Abreu Ferreira +João Reis +farblue68 diff --git a/deps/uv/ChangeLog b/deps/uv/ChangeLog index 7bbe5027a7aa28..e5c79808d2e1cc 100644 --- a/deps/uv/ChangeLog +++ b/deps/uv/ChangeLog @@ -1,4 +1,108 @@ -2015.02.27, Version 1.4.2 (Stable) +2015.05.07, Version 1.5.0 (Stable), 4e77f74c7b95b639b3397095db1bc5bcc016c203 + +Changes since version 1.4.2: + +* doc: clarify that the thread pool primites are not thread safe (Andrius + Bentkus) + +* aix: always deregister closing fds from epoll (Michael) + +* unix: fix glibc-2.20+ macro incompatibility (Massimiliano Torromeo) + +* doc: add Sphinx plugin for generating links to man pages (Saúl Ibarra + Corretgé) + +* doc: link system and library calls to man pages (Saúl Ibarra Corretgé) + +* doc: document uv_getnameinfo_t.{host|service} (Saúl Ibarra Corretgé) + +* build: update the location of gyp (Stephen von Takach) + +* win: name all anonymous structs and unions (TomCrypto) + +* linux: work around epoll bug in kernels 3.10-3.19 (Ben Noordhuis) + +* darwin: fix size calculation in select() fallback (Ole André Vadla Ravnås) + +* solaris: fix setsockopt for multicast options (Julien Gilli) + +* test: fix race condition in multithreaded test (Ben Noordhuis) + +* doc: fix long lines in tty.rst (Ben Noordhuis) + +* test: use UV_TTY_MODE_* values in tty test (Ben Noordhuis) + +* unix: don't clobber errno in uv_tty_reset_mode() (Ben Noordhuis) + +* unix: reject non-tty fds in uv_tty_init() (Ben Noordhuis) + +* win: fix pipe blocking writes (Alexis Campailla) + +* build: fix cross-compiling for iOS (Steven Kabbes) + +* win: remove unnecessary malloc.h + +* include: use `extern "c++"` for defining C++ code (Kazuho Oku) + +* unix: reap child on execvp() failure (Ryan Phillips) + +* windows: fix handle leak on EMFILE (Brian Green) + +* test: fix tty_file, close handle if initialized (Saúl Ibarra Corretgé) + +* doc: clarify what uv_*_open accepts (Saúl Ibarra Corretgé) + +* doc: clarify that we don't maintain external doc resources (Saúl Ibarra + Corretgé) + +* build: add documentation for ninja support (Devchandra Meetei Leishangthem) + +* doc: document uv_buf_t members (Corey Farrell) + +* linux: fix epoll_pwait() fallback on arm64 (Ben Noordhuis) + +* android: fix compilation warning (Saúl Ibarra Corretgé) + +* unix: don't close the fds we just setup (Sam Roberts) + +* test: spawn child replacing std{out,err} to stderr (Saúl Ibarra Corretgé) + +* unix: fix swapping fds order in uv_spawn (Saúl Ibarra Corretgé) + +* unix: fix potential bug if dup2 fails in uv_spawn (Saúl Ibarra Corretgé) + +* test: remove LOG and LOGF variadic macros (Saúl Ibarra Corretgé) + +* win: fix uv_fs_access on directories (Saúl Ibarra Corretgé) + +* win: fix of double free in uv_uptime (Per Nilsson) + +* unix: open "/dev/null" instead of "/" for emfile_fd (Alan Rogers) + +* docs: add some missing words (Daryl Haresign) + +* unix: clean up uv_fs_open() O_CLOEXEC logic (Ben Noordhuis) + +* build: set SONAME for shared library in uv.gyp (Rui Abreu Ferreira) + +* windows: define snprintf replacement as inline instead of static (Rui Abreu + Ferreira) + +* win: fix unlink of readonly files (João Reis) + +* doc: fix uv_run(UV_RUN_DEFAULT) description (Ben Noordhuis) + +* linux: intercept syscall when running under memory sanitizer (Keno Fischer) + +* aix: fix uv_interface_addresses return value (farblue68) + +* windows: defer reporting TCP write failure until next tick (Saúl Ibarra + Corretgé) + +* test: add test for deferred TCP write failure (Saúl Ibarra Corretgé) + + +2015.02.27, Version 1.4.2 (Stable), 1a7391348a11d5450c0f69c828d5302e2cb842eb Changes since version 1.4.1: diff --git a/deps/uv/Makefile.am b/deps/uv/Makefile.am index 9c511db47a6c8f..b9fb80c6738b52 100644 --- a/deps/uv/Makefile.am +++ b/deps/uv/Makefile.am @@ -226,6 +226,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \ test/test-tcp-write-to-half-open-connection.c \ test/test-tcp-write-after-connect.c \ test/test-tcp-writealot.c \ + test/test-tcp-write-fail.c \ test/test-tcp-try-write.c \ test/test-tcp-write-queue-order.c \ test/test-thread-equal.c \ diff --git a/deps/uv/README.md b/deps/uv/README.md index a267f0d5b527e5..a7da8b898c581d 100644 --- a/deps/uv/README.md +++ b/deps/uv/README.md @@ -72,19 +72,23 @@ NOTE: Windows users need to use make.bat instead of plain 'make'. Documentation can be browsed online [here](http://docs.libuv.org). +The [tests and benchmarks](https://github.com/libuv/libuv/tree/master/test) +also serve as API specification and usage examples. + ### Other resources * [An Introduction to libuv](http://nikhilm.github.com/uvbook/) — An overview of libuv with tutorials. * [LXJS 2012 talk](http://www.youtube.com/watch?v=nGn60vDSxQ4) — High-level introductory talk about libuv. - * [Tests and benchmarks](https://github.com/libuv/libuv/tree/master/test) - — API specification and usage examples. * [libuv-dox](https://github.com/thlorenz/libuv-dox) — Documenting types and methods of libuv, mostly by reading uv.h. * [learnuv](https://github.com/thlorenz/learnuv) — Learn uv for fun and profit, a self guided workshop to libuv. +These resources are not handled by libuv maintainers and might be out of +date. Please verify it before opening new issues. + ## Build Instructions For GCC there are two build methods: via autotools or via [GYP][]. @@ -113,8 +117,6 @@ To have GYP generate build script for another system, checkout GYP into the project tree manually: $ git clone https://chromium.googlesource.com/external/gyp.git build/gyp - OR - $ svn co http://gyp.googlecode.com/svn/trunk build/gyp ### Unix @@ -153,6 +155,15 @@ Run: Note for UNIX users: compile your project with `-D_LARGEFILE_SOURCE` and `-D_FILE_OFFSET_BITS=64`. GYP builds take care of that automatically. +### Using Ninja + +To use ninja for build on ninja supported platforms, run: + + $ ./gyp_uv.py -f ninja + $ ninja -C out/Debug #for debug build OR + $ ninja -C out/Release + + ### Running tests Run: diff --git a/deps/uv/configure.ac b/deps/uv/configure.ac index 9473d5ffcb09d2..71cb4704138c57 100644 --- a/deps/uv/configure.ac +++ b/deps/uv/configure.ac @@ -13,7 +13,7 @@ # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. AC_PREREQ(2.57) -AC_INIT([libuv], [1.4.2], [https://github.com/libuv/libuv/issues]) +AC_INIT([libuv], [1.5.0], [https://github.com/libuv/libuv/issues]) AC_CONFIG_MACRO_DIR([m4]) m4_include([m4/libuv-extra-automake-flags.m4]) m4_include([m4/as_case.m4]) diff --git a/deps/uv/docs/src/conf.py b/deps/uv/docs/src/conf.py index f614fc5b434b24..b9eaa137432dea 100644 --- a/deps/uv/docs/src/conf.py +++ b/deps/uv/docs/src/conf.py @@ -38,7 +38,7 @@ def get_libuv_version(): # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('sphinx-plugins')) # -- General configuration ------------------------------------------------ @@ -48,7 +48,7 @@ def get_libuv_version(): # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = [] +extensions = ['manpage'] # Add any paths that contain templates here, relative to this directory. templates_path = ['templates'] diff --git a/deps/uv/docs/src/design.rst b/deps/uv/docs/src/design.rst index 63141bedf58438..34c3cff68e54ca 100644 --- a/deps/uv/docs/src/design.rst +++ b/deps/uv/docs/src/design.rst @@ -40,7 +40,7 @@ The I/O loop The I/O (or event) loop is the central part of libuv. It establishes the content for all I/O operations, and it's meant to be tied to a single thread. One can run multiple event loops as long as each runs in a different thread. The libuv event loop (or any other API involving -the loop or handles, for that matter) **is not thread-safe** except stated otherwise. +the loop or handles, for that matter) **is not thread-safe** except where stated otherwise. The event loop follows the rather usual single threaded asynchronous I/O approach: all (network) I/O is performed on non-blocking sockets which are polled using the best mechanism available @@ -113,7 +113,7 @@ stages of a loop iteration: .. note:: While the polling mechanism is different, libuv makes the execution model consistent - Unix systems and Windows. + across Unix systems and Windows. File I/O diff --git a/deps/uv/docs/src/dns.rst b/deps/uv/docs/src/dns.rst index 3b15377f91e419..1d881580966315 100644 --- a/deps/uv/docs/src/dns.rst +++ b/deps/uv/docs/src/dns.rst @@ -51,6 +51,18 @@ Public members Loop that started this getnameinfo request and where completion will be reported. Readonly. +.. c:member:: char[NI_MAXHOST] uv_getnameinfo_t.host + + Char array containing the resulting host. It's null terminated. + + .. versionchanged:: 1.3.0 the field is declared as public. + +.. c:member:: char[NI_MAXSERV] uv_getnameinfo_t.service + + Char array containing the resulting service. It's null terminated. + + .. versionchanged:: 1.3.0 the field is declared as public. + .. seealso:: The :c:type:`uv_req_t` members also apply. @@ -59,7 +71,7 @@ API .. c:function:: int uv_getaddrinfo(uv_loop_t* loop, uv_getaddrinfo_t* req, uv_getaddrinfo_cb getaddrinfo_cb, const char* node, const char* service, const struct addrinfo* hints) - Asynchronous ``getaddrinfo(3)``. + Asynchronous :man:`getaddrinfo(3)`. Either node or service may be NULL but not both. @@ -84,7 +96,7 @@ API .. c:function:: int uv_getnameinfo(uv_loop_t* loop, uv_getnameinfo_t* req, uv_getnameinfo_cb getnameinfo_cb, const struct sockaddr* addr, int flags) - Asynchronous ``getnameinfo(3)``. + Asynchronous :man:`getnameinfo(3)`. Returns 0 on success or an error code < 0 on failure. If successful, the callback will get called sometime in the future with the lookup result. diff --git a/deps/uv/docs/src/fs.rst b/deps/uv/docs/src/fs.rst index cd535f756fc1c9..c2a3fc252a1ffe 100644 --- a/deps/uv/docs/src/fs.rst +++ b/deps/uv/docs/src/fs.rst @@ -162,46 +162,46 @@ API .. c:function:: int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) - Equivalent to ``close(2)``. + Equivalent to :man:`close(2)`. .. c:function:: int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb) - Equivalent to ``open(2)``. + Equivalent to :man:`open(2)`. .. c:function:: int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb) - Equivalent to ``preadv(2)``. + Equivalent to :man:`preadv(2)`. .. c:function:: int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``unlink(2)``. + Equivalent to :man:`unlink(2)`. .. c:function:: int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb) - Equivalent to ``pwritev(2)``. + Equivalent to :man:`pwritev(2)`. .. c:function:: int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) - Equivalent to ``mkdir(2)``. + Equivalent to :man:`mkdir(2)`. .. note:: `mode` is currently not implemented on Windows. .. c:function:: int uv_fs_mkdtemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb) - Equivalent to ``mkdtemp(3)``. + Equivalent to :man:`mkdtemp(3)`. .. note:: The result can be found as a null terminated string at `req->path`. .. c:function:: int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``rmdir(2)``. + Equivalent to :man:`rmdir(2)`. .. c:function:: int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, uv_fs_cb cb) .. c:function:: int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent) - Equivalent to ``scandir(3)``, with a slightly different API. Once the callback + Equivalent to :man:`scandir(3)`, with a slightly different API. Once the callback for the request is called, the user can use :c:func:`uv_fs_scandir_next` to get `ent` populated with the next directory entry data. When there are no more entries ``UV_EOF`` will be returned. @@ -210,49 +210,49 @@ API .. c:function:: int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) .. c:function:: int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``(f/l)stat(2)``. + Equivalent to :man:`stat(2)`, :man:`fstat(2)` and :man:`fstat(2)` respectively. .. c:function:: int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb) - Equivalent to ``rename(2)``. + Equivalent to :man:`rename(2)`. .. c:function:: int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) - Equivalent to ``fsync(2)``. + Equivalent to :man:`fsync(2)`. .. c:function:: int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) - Equivalent to ``fdatasync(2)``. + Equivalent to :man:`fdatasync(2)`. .. c:function:: int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file file, int64_t offset, uv_fs_cb cb) - Equivalent to ``ftruncate(2)``. + Equivalent to :man:`ftruncate(2)`. .. c:function:: int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb) - Limited equivalent to ``sendfile(2)``. + Limited equivalent to :man:`sendfile(2)`. .. c:function:: int uv_fs_access(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) - Equivalent to ``access(2)`` on Unix. Windows uses ``GetFileAttributesW()``. + Equivalent to :man:`access(2)` on Unix. Windows uses ``GetFileAttributesW()``. .. c:function:: int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) .. c:function:: int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file file, int mode, uv_fs_cb cb) - Equivalent to ``(f)chmod(2)``. + Equivalent to :man:`chmod(2)` and :man:`fchmod(2)` respectively. .. c:function:: int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb) .. c:function:: int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file file, double atime, double mtime, uv_fs_cb cb) - Equivalent to ``(f)utime(s)(2)``. + Equivalent to :man:`utime(2)` and :man:`futime(2)` respectively. .. c:function:: int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb) - Equivalent to ``link(2)``. + Equivalent to :man:`link(2)`. .. c:function:: int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb) - Equivalent to ``symlink(2)``. + Equivalent to :man:`symlink(2)`. .. note:: On Windows the `flags` parameter can be specified to control how the symlink will @@ -265,12 +265,12 @@ API .. c:function:: int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) - Equivalent to ``readlink(2)``. + Equivalent to :man:`readlink(2)`. .. c:function:: int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) .. c:function:: int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) - Equivalent to ``(f)chown(2)``. + Equivalent to :man:`chown(2)` and :man:`fchown(2)` respectively. .. note:: These functions are not implemented on Windows. diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 203672bd34f00a..2a01d796375e8e 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -92,7 +92,9 @@ API specified mode: - UV_RUN_DEFAULT: Runs the event loop until there are no more active and - referenced handles or requests. Always returns zero. + referenced handles or requests. Returns non-zero if :c:func:`uv_stop` + was called and there are still active handles or requests. Returns + zero in all other cases. - UV_RUN_ONCE: Poll for i/o once. Note that this function blocks if there are no pending callbacks. Returns zero when done (no active handles or requests left), or non-zero if more callbacks are expected (meaning diff --git a/deps/uv/docs/src/misc.rst b/deps/uv/docs/src/misc.rst index 10c349e9b736f3..bb97a260057fc8 100644 --- a/deps/uv/docs/src/misc.rst +++ b/deps/uv/docs/src/misc.rst @@ -15,6 +15,17 @@ Data types Buffer data type. + .. c:member:: char* uv_buf_t.base + + Pointer to the base of the buffer. Readonly. + + .. c:member:: size_t uv_buf_t.len + + Total bytes in the buffer. Readonly. + + .. note:: + On Windows this field is ULONG. + .. c:type:: uv_file Cross platform representation of a file handle. @@ -26,7 +37,7 @@ Data types .. c:type:: uv_os_fd_t Abstract representation of a file descriptor. On Unix systems this is a - `typedef` of `int` and on Windows fa `HANDLE`. + `typedef` of `int` and on Windows a `HANDLE`. .. c:type:: uv_rusage_t @@ -101,7 +112,8 @@ API descriptor. Usually this will be used during initialization to guess the type of the stdio streams. - For ``isatty()`` functionality use this function and test for ``UV_TTY``. + For :man:`isatty(3)` equivalent functionality use this function and test + for ``UV_TTY``. .. c:function:: unsigned int uv_version(void) @@ -195,8 +207,8 @@ API .. c:function:: int uv_inet_ntop(int af, const void* src, char* dst, size_t size) .. c:function:: int uv_inet_pton(int af, const char* src, void* dst) - Cross-platform IPv6-capable implementation of the 'standard' ``inet_ntop()`` - and ``inet_pton()`` functions. On success they return 0. In case of error + Cross-platform IPv6-capable implementation of :man:`inet_ntop(3)` + and :man:`inet_pton(3)`. On success they return 0. In case of error the target `dst` pointer is unmodified. .. c:function:: int uv_exepath(char* buffer, size_t* size) diff --git a/deps/uv/docs/src/pipe.rst b/deps/uv/docs/src/pipe.rst index 8f8402c29bbadd..df896a0583447f 100644 --- a/deps/uv/docs/src/pipe.rst +++ b/deps/uv/docs/src/pipe.rst @@ -40,6 +40,10 @@ API .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode. + .. note:: + The passed file descriptor or HANDLE is not checked for its type, but + it's required that it represents a valid pipe. + .. c:function:: int uv_pipe_bind(uv_pipe_t* handle, const char* name) Bind the pipe to a file path (Unix) or a name (Windows). diff --git a/deps/uv/docs/src/poll.rst b/deps/uv/docs/src/poll.rst index 907cb1a613dfbb..6dc41839ac1e92 100644 --- a/deps/uv/docs/src/poll.rst +++ b/deps/uv/docs/src/poll.rst @@ -5,7 +5,7 @@ =================================== Poll handles are used to watch file descriptors for readability and -writability, similar to the purpose of poll(2). +writability, similar to the purpose of :man:`poll(2)`. The purpose of poll handles is to enable integrating external libraries that rely on the event loop to signal it about the socket status changes, like @@ -29,7 +29,7 @@ closed immediately after a call to :c:func:`uv_poll_stop` or :c:func:`uv_close`. .. note:: On windows only sockets can be polled with poll handles. On Unix any file - descriptor that would be accepted by poll(2) can be used. + descriptor that would be accepted by :man:`poll(2)` can be used. Data types diff --git a/deps/uv/docs/src/sphinx-plugins/manpage.py b/deps/uv/docs/src/sphinx-plugins/manpage.py new file mode 100644 index 00000000000000..1d1dc379f410ee --- /dev/null +++ b/deps/uv/docs/src/sphinx-plugins/manpage.py @@ -0,0 +1,46 @@ +# encoding: utf-8 + +# +# Copyright (c) 2013 Dariusz Dwornikowski. All rights reserved. +# +# Adapted from https://github.com/tdi/sphinxcontrib-manpage +# License: Apache 2 +# + + +import re + +from docutils import nodes, utils +from docutils.parsers.rst.roles import set_classes +from string import Template + + +def make_link_node(rawtext, app, name, manpage_num, options): + ref = app.config.man_url_regex + if not ref: + ref = "http://linux.die.net/man/%s/%s" % (manpage_num, name) + else: + s = Template(ref) + ref = s.substitute(num=manpage_num, topic=name) + set_classes(options) + node = nodes.reference(rawtext, "%s(%s)" % (name, manpage_num), refuri=ref, **options) + return node + + +def man_role(name, rawtext, text, lineno, inliner, options={}, content=[]): + app = inliner.document.settings.env.app + p = re.compile("([a-zA-Z0-9_\.-_]+)\((\d)\)") + m = p.match(text) + + manpage_num = m.group(2) + name = m.group(1) + node = make_link_node(rawtext, app, name, manpage_num, options) + return [node], [] + + +def setup(app): + app.info('Initializing manpage plugin') + app.add_role('man', man_role) + app.add_config_value('man_url_regex', None, 'env') + return + diff --git a/deps/uv/docs/src/stream.rst b/deps/uv/docs/src/stream.rst index 1f6682adc1cfc2..880f0e2ebc75d3 100644 --- a/deps/uv/docs/src/stream.rst +++ b/deps/uv/docs/src/stream.rst @@ -104,7 +104,7 @@ API .. c:function:: int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) Start listening for incoming connections. `backlog` indicates the number of - connections the kernel might queue, same as ``listen(2)``. When a new + connections the kernel might queue, same as :man:`listen(2)`. When a new incoming connection is received the :c:type:`uv_connection_cb` callback is called. diff --git a/deps/uv/docs/src/tcp.rst b/deps/uv/docs/src/tcp.rst index 8baedde86c5c15..2b5d268ddd86e6 100644 --- a/deps/uv/docs/src/tcp.rst +++ b/deps/uv/docs/src/tcp.rst @@ -38,6 +38,10 @@ API .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode. + .. note:: + The passed file descriptor or SOCKET is not checked for its type, but + it's required that it represents a valid stream socket. + .. c:function:: int uv_tcp_nodelay(uv_tcp_t* handle, int enable) Enable / disable Nagle's algorithm. diff --git a/deps/uv/docs/src/threadpool.rst b/deps/uv/docs/src/threadpool.rst index 89f00844ef2c65..18949507e75004 100644 --- a/deps/uv/docs/src/threadpool.rst +++ b/deps/uv/docs/src/threadpool.rst @@ -18,6 +18,10 @@ libuv preallocates and initializes the maximum number of threads allowed by ``UV_THREADPOOL_SIZE``. This causes a relatively minor memory overhead (~1MB for 128 threads) but increases the performance of threading at runtime. +.. note:: + Note that even though a global thread pool which is shared across all events + loops is used, the functions are not thread safe. + Data types ---------- diff --git a/deps/uv/docs/src/tty.rst b/deps/uv/docs/src/tty.rst index 6c20c84bf75e58..18f34ef46d97b5 100644 --- a/deps/uv/docs/src/tty.rst +++ b/deps/uv/docs/src/tty.rst @@ -24,14 +24,14 @@ Data types :: - typedef enum { - /* Initial/normal terminal mode */ - UV_TTY_MODE_NORMAL, - /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */ - UV_TTY_MODE_RAW, - /* Binary-safe I/O mode for IPC (Unix-only) */ - UV_TTY_MODE_IO - } uv_tty_mode_t; + typedef enum { + /* Initial/normal terminal mode */ + UV_TTY_MODE_NORMAL, + /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */ + UV_TTY_MODE_RAW, + /* Binary-safe I/O mode for IPC (Unix-only) */ + UV_TTY_MODE_IO + } uv_tty_mode_t; @@ -58,18 +58,22 @@ API `readable`, specifies if you plan on calling :c:func:`uv_read_start` with this stream. stdin is readable, stdout is not. - On Unix this function will try to open ``/dev/tty`` and use it if the passed file - descriptor refers to a TTY. This lets libuv put the tty in non-blocking mode - without affecting other processes that share the tty. + On Unix this function will try to open ``/dev/tty`` and use it if the passed + file descriptor refers to a TTY. This lets libuv put the tty in non-blocking + mode without affecting other processes that share the tty. .. note:: - If opening ``/dev/tty`` fails, libuv falls back to blocking writes for non-readable - TTY streams. + If opening ``/dev/tty`` fails, libuv falls back to blocking writes for + non-readable TTY streams. + + .. versionchanged:: 1.5.0: trying to initialize a TTY stream with a file + descriptor that refers to a file returns `UV_EINVAL` + on UNIX. .. c:function:: int uv_tty_set_mode(uv_tty_t*, uv_tty_mode_t mode) - .. versionchanged:: 1.2.0: the mode is specified as a :c:type:`uv_tty_mode_t` - value. + .. versionchanged:: 1.2.0: the mode is specified as a + :c:type:`uv_tty_mode_t` value. Set the TTY using the specified terminal mode. diff --git a/deps/uv/docs/src/udp.rst b/deps/uv/docs/src/udp.rst index 9c4aa2102bdcfc..ec7ce56d38f52c 100644 --- a/deps/uv/docs/src/udp.rst +++ b/deps/uv/docs/src/udp.rst @@ -122,6 +122,10 @@ API .. versionchanged:: 1.2.1 the file descriptor is set to non-blocking mode. + .. note:: + The passed file descriptor or SOCKET is not checked for its type, but + it's required that it represents a valid datagram socket. + .. c:function:: int uv_udp_bind(uv_udp_t* handle, const struct sockaddr* addr, unsigned int flags) Bind the UDP handle to an IP address and port. diff --git a/deps/uv/include/uv-version.h b/deps/uv/include/uv-version.h index 836d399d774a32..0b4e6d781c35f6 100644 --- a/deps/uv/include/uv-version.h +++ b/deps/uv/include/uv-version.h @@ -31,8 +31,8 @@ */ #define UV_VERSION_MAJOR 1 -#define UV_VERSION_MINOR 4 -#define UV_VERSION_PATCH 2 +#define UV_VERSION_MINOR 5 +#define UV_VERSION_PATCH 0 #define UV_VERSION_IS_RELEASE 1 #define UV_VERSION_SUFFIX "" diff --git a/deps/uv/include/uv-win.h b/deps/uv/include/uv-win.h index 24b22b31a9562b..fd844202b99a1a 100644 --- a/deps/uv/include/uv-win.h +++ b/deps/uv/include/uv-win.h @@ -43,16 +43,6 @@ typedef struct pollfd { # define LOCALE_INVARIANT 0x007f #endif -#ifndef _malloca -# if defined(_DEBUG) -# define _malloca(size) malloc(size) -# define _freea(ptr) free(ptr) -# else -# define _malloca(size) alloca(size) -# define _freea(ptr) -# endif -#endif - #include #include #include @@ -366,8 +356,8 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); struct { \ OVERLAPPED overlapped; \ size_t queued_bytes; \ - }; \ - }; \ + } io; \ + } u; \ struct uv_req_s* next_req; #define UV_WRITE_PRIVATE_FIELDS \ @@ -419,9 +409,9 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); int activecnt; \ uv_read_t read_req; \ union { \ - struct { uv_stream_connection_fields }; \ - struct { uv_stream_server_fields }; \ - }; + struct { uv_stream_connection_fields } conn; \ + struct { uv_stream_server_fields } serv; \ + } stream; #define uv_tcp_server_fields \ uv_tcp_accept_t* accept_reqs; \ @@ -437,9 +427,9 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); SOCKET socket; \ int delayed_error; \ union { \ - struct { uv_tcp_server_fields }; \ - struct { uv_tcp_connection_fields }; \ - }; + struct { uv_tcp_server_fields } serv; \ + struct { uv_tcp_connection_fields } conn; \ + } tcp; #define UV_UDP_PRIVATE_FIELDS \ SOCKET socket; \ @@ -476,9 +466,9 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); HANDLE handle; \ WCHAR* name; \ union { \ - struct { uv_pipe_server_fields }; \ - struct { uv_pipe_connection_fields }; \ - }; + struct { uv_pipe_server_fields } serv; \ + struct { uv_pipe_connection_fields } conn; \ + } pipe; /* TODO: put the parser states in an union - TTY handles are always */ /* half-duplex so read-state can safely overlap write-state. */ @@ -496,7 +486,7 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); unsigned char last_key_len; \ WCHAR last_utf16_high_surrogate; \ INPUT_RECORD last_input_record; \ - }; \ + } rd; \ struct { \ /* Used for writable TTY handles */ \ /* utf8-to-utf16 conversion state */ \ @@ -510,8 +500,8 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); unsigned short ansi_csi_argv[4]; \ COORD saved_position; \ WORD saved_attributes; \ - }; \ - }; + } wr; \ + } tty; #define UV_POLL_PRIVATE_FIELDS \ SOCKET socket; \ @@ -600,7 +590,7 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); /* TODO: remove me in 0.9. */ \ WCHAR* pathw; \ int fd; \ - }; \ + } file; \ union { \ struct { \ int mode; \ @@ -611,12 +601,12 @@ RB_HEAD(uv_timer_tree_s, uv_timer_s); uv_buf_t* bufs; \ int64_t offset; \ uv_buf_t bufsml[4]; \ - }; \ + } info; \ struct { \ double atime; \ double mtime; \ - }; \ - }; + } time; \ + } fs; #define UV_WORK_PRIVATE_FIELDS \ struct uv__work work_req; diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index 55f75218b58682..75b3a4a5d2f8bf 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -644,13 +644,13 @@ UV_EXTERN int uv_tty_reset_mode(void); UV_EXTERN int uv_tty_get_winsize(uv_tty_t*, int* width, int* height); #ifdef __cplusplus -} /* extern "C" */ +extern "C++" { inline int uv_tty_set_mode(uv_tty_t* handle, int mode) { return uv_tty_set_mode(handle, static_cast(mode)); } -extern "C" { +} #endif UV_EXTERN uv_handle_type uv_guess_handle(uv_file file); @@ -799,6 +799,7 @@ struct uv_getnameinfo_s { UV_REQ_FIELDS /* read-only */ uv_loop_t* loop; + /* host and service are marked as private, but they really aren't. */ UV_GETNAMEINFO_PRIVATE_FIELDS }; diff --git a/deps/uv/src/unix/aix.c b/deps/uv/src/unix/aix.c index ec800c7a323f4b..e21a9cc78b6979 100644 --- a/deps/uv/src/unix/aix.c +++ b/deps/uv/src/unix/aix.c @@ -1111,19 +1111,19 @@ int uv_interface_addresses(uv_interface_address_t** addresses, *count = 0; if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) { - return -ENOSYS; + return -errno; } if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) { - uv__close(sockfd); - return -ENOSYS; + SAVE_ERRNO(uv__close(sockfd)); + return -errno; } ifc.ifc_req = (struct ifreq*)malloc(size); ifc.ifc_len = size; if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) { - uv__close(sockfd); - return -ENOSYS; + SAVE_ERRNO(uv__close(sockfd)); + return -errno; } #define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p)) @@ -1141,8 +1141,8 @@ int uv_interface_addresses(uv_interface_address_t** addresses, memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name)); if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) { - uv__close(sockfd); - return -ENOSYS; + SAVE_ERRNO(uv__close(sockfd)); + return -errno; } if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING)) @@ -1218,16 +1218,23 @@ void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { struct pollfd* events; uintptr_t i; uintptr_t nfds; + struct poll_ctl pc; assert(loop->watchers != NULL); events = (struct pollfd*) loop->watchers[loop->nwatchers]; nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1]; - if (events == NULL) - return; - /* Invalidate events with same file descriptor */ - for (i = 0; i < nfds; i++) - if ((int) events[i].fd == fd) - events[i].fd = -1; + if (events != NULL) + /* Invalidate events with same file descriptor */ + for (i = 0; i < nfds; i++) + if ((int) events[i].fd == fd) + events[i].fd = -1; + + /* Remove the file descriptor from the poll set */ + pc.events = 0; + pc.cmd = PS_DELETE; + pc.fd = fd; + if(loop->backend_fd >= 0) + pollset_ctl(loop->backend_fd, &pc, 1); } diff --git a/deps/uv/src/unix/android-ifaddrs.c b/deps/uv/src/unix/android-ifaddrs.c index 3cda578dd1a94c..a99b0191d54808 100644 --- a/deps/uv/src/unix/android-ifaddrs.c +++ b/deps/uv/src/unix/android-ifaddrs.c @@ -24,6 +24,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "android-ifaddrs.h" +#include "uv-common.h" #include #include diff --git a/deps/uv/src/unix/fs.c b/deps/uv/src/unix/fs.c index e7eee2f9abc4ed..7792801e9b6fd6 100644 --- a/deps/uv/src/unix/fs.c +++ b/deps/uv/src/unix/fs.c @@ -202,6 +202,44 @@ static ssize_t uv__fs_mkdtemp(uv_fs_t* req) { } +static ssize_t uv__fs_open(uv_fs_t* req) { + static int no_cloexec_support; + int r; + + /* Try O_CLOEXEC before entering locks */ + if (no_cloexec_support == 0) { +#ifdef O_CLOEXEC + r = open(req->path, req->flags | O_CLOEXEC, req->mode); + if (r >= 0) + return r; + if (errno != EINVAL) + return r; + no_cloexec_support = 1; +#endif /* O_CLOEXEC */ + } + + if (req->cb != NULL) + uv_rwlock_rdlock(&req->loop->cloexec_lock); + + r = open(req->path, req->flags, req->mode); + + /* In case of failure `uv__cloexec` will leave error in `errno`, + * so it is enough to just set `r` to `-1`. + */ + if (r >= 0 && uv__cloexec(r, 1) != 0) { + r = uv__close(r); + if (r != 0 && r != -EINPROGRESS) + abort(); + r = -1; + } + + if (req->cb != NULL) + uv_rwlock_rdunlock(&req->loop->cloexec_lock); + + return r; +} + + static ssize_t uv__fs_read(uv_fs_t* req) { #if defined(__linux__) static int no_preadv; @@ -661,8 +699,22 @@ static void uv__to_stat(struct stat* src, uv_stat_t* dst) { dst->st_birthtim.tv_nsec = src->st_birthtimespec.tv_nsec; dst->st_flags = src->st_flags; dst->st_gen = src->st_gen; -#elif !defined(_AIX) && \ - (defined(_BSD_SOURCE) || defined(_SVID_SOURCE) || defined(_XOPEN_SOURCE)) +#elif defined(__ANDROID__) + dst->st_atim.tv_sec = src->st_atime; + dst->st_atim.tv_nsec = src->st_atime_nsec; + dst->st_mtim.tv_sec = src->st_mtime; + dst->st_mtim.tv_nsec = src->st_mtime_nsec; + dst->st_ctim.tv_sec = src->st_ctime; + dst->st_ctim.tv_nsec = src->st_ctime_nsec; + dst->st_birthtim.tv_sec = src->st_ctime; + dst->st_birthtim.tv_nsec = src->st_ctime_nsec; + dst->st_flags = 0; + dst->st_gen = 0; +#elif !defined(_AIX) && ( \ + defined(_BSD_SOURCE) || \ + defined(_SVID_SOURCE) || \ + defined(_XOPEN_SOURCE) || \ + defined(_DEFAULT_SOURCE)) dst->st_atim.tv_sec = src->st_atim.tv_sec; dst->st_atim.tv_nsec = src->st_atim.tv_nsec; dst->st_mtim.tv_sec = src->st_mtim.tv_sec; @@ -729,9 +781,6 @@ static void uv__fs_work(struct uv__work* w) { int retry_on_eintr; uv_fs_t* req; ssize_t r; -#ifdef O_CLOEXEC - static int no_cloexec_support; -#endif /* O_CLOEXEC */ req = container_of(w, uv_fs_t, work_req); retry_on_eintr = !(req->fs_type == UV_FS_CLOSE); @@ -760,6 +809,7 @@ static void uv__fs_work(struct uv__work* w) { X(LINK, link(req->path, req->new_path)); X(MKDIR, mkdir(req->path, req->mode)); X(MKDTEMP, uv__fs_mkdtemp(req)); + X(OPEN, uv__fs_open(req)); X(READ, uv__fs_read(req)); X(SCANDIR, uv__fs_scandir(req)); X(READLINK, uv__fs_readlink(req)); @@ -771,41 +821,10 @@ static void uv__fs_work(struct uv__work* w) { X(UNLINK, unlink(req->path)); X(UTIME, uv__fs_utime(req)); X(WRITE, uv__fs_write(req)); - case UV_FS_OPEN: -#ifdef O_CLOEXEC - /* Try O_CLOEXEC before entering locks */ - if (!no_cloexec_support) { - r = open(req->path, req->flags | O_CLOEXEC, req->mode); - if (r >= 0) - break; - if (errno != EINVAL) - break; - no_cloexec_support = 1; - } -#endif /* O_CLOEXEC */ - if (req->cb != NULL) - uv_rwlock_rdlock(&req->loop->cloexec_lock); - r = open(req->path, req->flags, req->mode); - - /* - * In case of failure `uv__cloexec` will leave error in `errno`, - * so it is enough to just set `r` to `-1`. - */ - if (r >= 0 && uv__cloexec(r, 1) != 0) { - r = uv__close(r); - if (r != 0 && r != -EINPROGRESS) - abort(); - r = -1; - } - if (req->cb != NULL) - uv_rwlock_rdunlock(&req->loop->cloexec_lock); - break; default: abort(); } - #undef X - } - while (r == -1 && errno == EINTR && retry_on_eintr); + } while (r == -1 && errno == EINTR && retry_on_eintr); if (r == -1) req->result = -errno; diff --git a/deps/uv/src/unix/internal.h b/deps/uv/src/unix/internal.h index 101dc745499f8d..31db5e29ea68b8 100644 --- a/deps/uv/src/unix/internal.h +++ b/deps/uv/src/unix/internal.h @@ -55,6 +55,9 @@ #define ACCESS_ONCE(type, var) \ (*(volatile type*) &(var)) +#define ROUND_UP(a, b) \ + ((a) % (b) ? ((a) + (b)) - ((a) % (b)) : (a)) + #define UNREACHABLE() \ do { \ assert(0 && "unreachable code"); \ diff --git a/deps/uv/src/unix/linux-core.c b/deps/uv/src/unix/linux-core.c index 33a735dc674f14..d07494dd654bb3 100644 --- a/deps/uv/src/unix/linux-core.c +++ b/deps/uv/src/unix/linux-core.c @@ -130,8 +130,13 @@ void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { * * We pass in a dummy epoll_event, to work around a bug in old kernels. */ - if (loop->backend_fd >= 0) + if (loop->backend_fd >= 0) { + /* Work around a bug in kernels 3.10 to 3.19 where passing a struct that + * has the EPOLLWAKEUP flag set generates spurious audit syslog warnings. + */ + memset(&dummy, 0, sizeof(dummy)); uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, &dummy); + } } diff --git a/deps/uv/src/unix/linux-syscalls.c b/deps/uv/src/unix/linux-syscalls.c index 7bf2c0f87dbea4..566e1f37cfed12 100644 --- a/deps/uv/src/unix/linux-syscalls.c +++ b/deps/uv/src/unix/linux-syscalls.c @@ -26,6 +26,13 @@ #include #include +#if defined(__has_feature) +# if __has_feature(memory_sanitizer) +# define MSAN_ACTIVE 1 +# include +# endif +#endif + #if defined(__i386__) # ifndef __NR_socketcall # define __NR_socketcall 102 @@ -310,7 +317,13 @@ int uv__epoll_wait(int epfd, int nevents, int timeout) { #if defined(__NR_epoll_wait) - return syscall(__NR_epoll_wait, epfd, events, nevents, timeout); + int result; + result = syscall(__NR_epoll_wait, epfd, events, nevents, timeout); +#if MSAN_ACTIVE + if (result > 0) + __msan_unpoison(events, sizeof(events[0]) * result); +#endif + return result; #else return errno = ENOSYS, -1; #endif @@ -323,13 +336,19 @@ int uv__epoll_pwait(int epfd, int timeout, uint64_t sigmask) { #if defined(__NR_epoll_pwait) - return syscall(__NR_epoll_pwait, - epfd, - events, - nevents, - timeout, - &sigmask, - sizeof(sigmask)); + int result; + result = syscall(__NR_epoll_pwait, + epfd, + events, + nevents, + timeout, + &sigmask, + sizeof(sigmask)); +#if MSAN_ACTIVE + if (result > 0) + __msan_unpoison(events, sizeof(events[0]) * result); +#endif + return result; #else return errno = ENOSYS, -1; #endif @@ -374,7 +393,13 @@ int uv__inotify_rm_watch(int fd, int32_t wd) { int uv__pipe2(int pipefd[2], int flags) { #if defined(__NR_pipe2) - return syscall(__NR_pipe2, pipefd, flags); + int result; + result = syscall(__NR_pipe2, pipefd, flags); +#if MSAN_ACTIVE + if (!result) + __msan_unpoison(pipefd, sizeof(int[2])); +#endif + return result; #else return errno = ENOSYS, -1; #endif diff --git a/deps/uv/src/unix/process.c b/deps/uv/src/unix/process.c index be283b480d6a23..380f3db1dce7f4 100644 --- a/deps/uv/src/unix/process.c +++ b/deps/uv/src/unix/process.c @@ -280,6 +280,21 @@ static void uv__process_child_init(const uv_process_options_t* options, if (options->flags & UV_PROCESS_DETACHED) setsid(); + /* First duplicate low numbered fds, since it's not safe to duplicate them, + * they could get replaced. Example: swapping stdout and stderr; without + * this fd 2 (stderr) would be duplicated into fd 1, thus making both + * stdout and stderr go to the same fd, which was not the intention. */ + for (fd = 0; fd < stdio_count; fd++) { + use_fd = pipes[fd][1]; + if (use_fd < 0 || use_fd >= fd) + continue; + pipes[fd][1] = fcntl(use_fd, F_DUPFD, stdio_count); + if (pipes[fd][1] == -1) { + uv__write_int(error_fd, -errno); + _exit(127); + } + } + for (fd = 0; fd < stdio_count; fd++) { close_fd = pipes[fd][0]; use_fd = pipes[fd][1]; @@ -304,7 +319,12 @@ static void uv__process_child_init(const uv_process_options_t* options, if (fd == use_fd) uv__cloexec(use_fd, 0); else - dup2(use_fd, fd); + fd = dup2(use_fd, fd); + + if (fd == -1) { + uv__write_int(error_fd, -errno); + _exit(127); + } if (fd <= 2) uv__nonblock(fd, 0); @@ -316,8 +336,8 @@ static void uv__process_child_init(const uv_process_options_t* options, for (fd = 0; fd < stdio_count; fd++) { use_fd = pipes[fd][1]; - if (use_fd >= 0 && fd != use_fd) - close(use_fd); + if (use_fd >= stdio_count) + uv__close(use_fd); } if (options->cwd != NULL && chdir(options->cwd)) { @@ -367,6 +387,7 @@ int uv_spawn(uv_loop_t* loop, int err; int exec_errorno; int i; + int status; assert(options->file != NULL); assert(!(options->flags & ~(UV_PROCESS_DETACHED | @@ -453,11 +474,17 @@ int uv_spawn(uv_loop_t* loop, if (r == 0) ; /* okay, EOF */ - else if (r == sizeof(exec_errorno)) - ; /* okay, read errorno */ - else if (r == -1 && errno == EPIPE) - ; /* okay, got EPIPE */ - else + else if (r == sizeof(exec_errorno)) { + do + err = waitpid(pid, &status, 0); /* okay, read errorno */ + while (err == -1 && errno == EINTR); + assert(err == pid); + } else if (r == -1 && errno == EPIPE) { + do + err = waitpid(pid, &status, 0); /* okay, got EPIPE */ + while (err == -1 && errno == EINTR); + assert(err == pid); + } else abort(); uv__close(signal_pipe[0]); diff --git a/deps/uv/src/unix/stream.c b/deps/uv/src/unix/stream.c index 518a2fce0f2e46..48827b65d36dee 100644 --- a/deps/uv/src/unix/stream.c +++ b/deps/uv/src/unix/stream.c @@ -88,7 +88,12 @@ void uv__stream_init(uv_loop_t* loop, stream->write_queue_size = 0; if (loop->emfile_fd == -1) { - err = uv__open_cloexec("/", O_RDONLY); + err = uv__open_cloexec("/dev/null", O_RDONLY); + if (err < 0) + /* In the rare case that "/dev/null" isn't mounted open "/" + * instead. + */ + err = uv__open_cloexec("/", O_RDONLY); if (err >= 0) loop->emfile_fd = err; } @@ -301,7 +306,7 @@ int uv__stream_try_select(uv_stream_t* stream, int* fd) { if (fds[1] > max_fd) max_fd = fds[1]; - sread_sz = (max_fd + NBBY) / NBBY; + sread_sz = ROUND_UP(max_fd + 1, sizeof(uint32_t) * NBBY) / NBBY; swrite_sz = sread_sz; s = malloc(sizeof(*s) + sread_sz + swrite_sz); diff --git a/deps/uv/src/unix/tty.c b/deps/uv/src/unix/tty.c index b1782df95b2010..7783548a6e987d 100644 --- a/deps/uv/src/unix/tty.c +++ b/deps/uv/src/unix/tty.c @@ -35,10 +35,19 @@ static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER; int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) { + uv_handle_type type; int flags; int newfd; int r; + /* File descriptors that refer to files cannot be monitored with epoll. + * That restriction also applies to character devices like /dev/random + * (but obviously not /dev/tty.) + */ + type = uv_guess_handle(fd); + if (type == UV_FILE || type == UV_UNKNOWN_HANDLE) + return -EINVAL; + flags = 0; newfd = -1; @@ -54,7 +63,7 @@ int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) { * different struct file, hence changing its properties doesn't affect * other processes. */ - if (isatty(fd)) { + if (type == UV_TTY) { r = uv__open_cloexec("/dev/tty", O_RDWR); if (r < 0) { @@ -237,8 +246,10 @@ uv_handle_type uv_guess_handle(uv_file file) { * critical section when the signal was raised. */ int uv_tty_reset_mode(void) { + int saved_errno; int err; + saved_errno = errno; if (!uv_spinlock_trylock(&termios_spinlock)) return -EBUSY; /* In uv_tty_set_mode(). */ @@ -248,5 +259,7 @@ int uv_tty_reset_mode(void) { err = -errno; uv_spinlock_unlock(&termios_spinlock); + errno = saved_errno; + return err; } diff --git a/deps/uv/src/unix/udp.c b/deps/uv/src/unix/udp.c index 941c0aec6e2f0b..22c2e1388e14ac 100644 --- a/deps/uv/src/unix/udp.c +++ b/deps/uv/src/unix/udp.c @@ -601,40 +601,47 @@ int uv_udp_set_membership(uv_udp_t* handle, } } - -static int uv__setsockopt_maybe_char(uv_udp_t* handle, - int option4, - int option6, - int val) { +static int uv__setsockopt(uv_udp_t* handle, + int option4, + int option6, + const void* val, + size_t size) { int r; -#if defined(__sun) || defined(_AIX) - char arg = val; -#else - int arg = val; -#endif - - if (val < 0 || val > 255) - return -EINVAL; if (handle->flags & UV_HANDLE_IPV6) r = setsockopt(handle->io_watcher.fd, IPPROTO_IPV6, option6, - &arg, - sizeof(arg)); + val, + size); else r = setsockopt(handle->io_watcher.fd, IPPROTO_IP, option4, - &arg, - sizeof(arg)); - + val, + size); if (r) return -errno; return 0; } +static int uv__setsockopt_maybe_char(uv_udp_t* handle, + int option4, + int option6, + int val) { +#if defined(__sun) || defined(_AIX) + char arg = val; +#else + int arg = val; +#endif + + if (val < 0 || val > 255) + return -EINVAL; + + return uv__setsockopt(handle, option4, option6, &arg, sizeof(arg)); +} + int uv_udp_set_broadcast(uv_udp_t* handle, int on) { if (setsockopt(handle->io_watcher.fd, @@ -653,6 +660,20 @@ int uv_udp_set_ttl(uv_udp_t* handle, int ttl) { if (ttl < 1 || ttl > 255) return -EINVAL; +/* + * On Solaris and derivatives such as SmartOS, the length of socket options + * is sizeof(int) for IP_TTL and IPV6_UNICAST_HOPS, + * so hardcode the size of these options on this platform, + * and use the general uv__setsockopt_maybe_char call on other platforms. + */ +#if defined(__sun) + return uv__setsockopt(handle, + IP_TTL, + IPV6_UNICAST_HOPS, + &ttl, + sizeof(ttl)); +#endif /* defined(__sun) */ + return uv__setsockopt_maybe_char(handle, IP_TTL, IPV6_UNICAST_HOPS, @@ -661,6 +682,21 @@ int uv_udp_set_ttl(uv_udp_t* handle, int ttl) { int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl) { +/* + * On Solaris and derivatives such as SmartOS, the length of socket options + * is sizeof(int) for IPV6_MULTICAST_HOPS and sizeof(char) for + * IP_MULTICAST_TTL, so hardcode the size of the option in the IPv6 case, + * and use the general uv__setsockopt_maybe_char call otherwise. + */ +#if defined(__sun) + if (handle->flags & UV_HANDLE_IPV6) + return uv__setsockopt(handle, + IP_MULTICAST_TTL, + IPV6_MULTICAST_HOPS, + &ttl, + sizeof(ttl)); +#endif /* defined(__sun) */ + return uv__setsockopt_maybe_char(handle, IP_MULTICAST_TTL, IPV6_MULTICAST_HOPS, @@ -669,6 +705,21 @@ int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl) { int uv_udp_set_multicast_loop(uv_udp_t* handle, int on) { +/* + * On Solaris and derivatives such as SmartOS, the length of socket options + * is sizeof(int) for IPV6_MULTICAST_LOOP and sizeof(char) for + * IP_MULTICAST_LOOP, so hardcode the size of the option in the IPv6 case, + * and use the general uv__setsockopt_maybe_char call otherwise. + */ +#if defined(__sun) + if (handle->flags & UV_HANDLE_IPV6) + return uv__setsockopt(handle, + IP_MULTICAST_LOOP, + IPV6_MULTICAST_LOOP, + &on, + sizeof(on)); +#endif /* defined(__sun) */ + return uv__setsockopt_maybe_char(handle, IP_MULTICAST_LOOP, IPV6_MULTICAST_LOOP, diff --git a/deps/uv/src/uv-common.c b/deps/uv/src/uv-common.c index 791c09b4e28e77..02341f8b95d9c0 100644 --- a/deps/uv/src/uv-common.c +++ b/deps/uv/src/uv-common.c @@ -379,15 +379,28 @@ int uv_fs_event_getpath(uv_fs_event_t* handle, char* buffer, size_t* size) { return 0; } +/* The windows implementation does not have the same structure layout as + * the unix implementation (nbufs is not directly inside req but is + * contained in a nested union/struct) so this function locates it. +*/ +static unsigned int* uv__get_nbufs(uv_fs_t* req) { +#ifdef _WIN32 + return &req->fs.info.nbufs; +#else + return &req->nbufs; +#endif +} void uv__fs_scandir_cleanup(uv_fs_t* req) { uv__dirent_t** dents; + unsigned int* nbufs = uv__get_nbufs(req); + dents = req->ptr; - if (req->nbufs > 0 && req->nbufs != (unsigned int) req->result) - req->nbufs--; - for (; req->nbufs < (unsigned int) req->result; req->nbufs++) - free(dents[req->nbufs]); + if (*nbufs > 0 && *nbufs != (unsigned int) req->result) + (*nbufs)--; + for (; *nbufs < (unsigned int) req->result; (*nbufs)++) + free(dents[*nbufs]); } @@ -395,20 +408,22 @@ int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent) { uv__dirent_t** dents; uv__dirent_t* dent; + unsigned int* nbufs = uv__get_nbufs(req); + dents = req->ptr; /* Free previous entity */ - if (req->nbufs > 0) - free(dents[req->nbufs - 1]); + if (*nbufs > 0) + free(dents[*nbufs - 1]); /* End was already reached */ - if (req->nbufs == (unsigned int) req->result) { + if (*nbufs == (unsigned int) req->result) { free(dents); req->ptr = NULL; return UV_EOF; } - dent = dents[req->nbufs++]; + dent = dents[(*nbufs)++]; ent->name = dent->d_name; #ifdef HAVE_DIRENT_TYPES @@ -522,6 +537,7 @@ void uv_loop_delete(uv_loop_t* loop) { default_loop = default_loop_ptr; err = uv_loop_close(loop); + (void) err; /* Squelch compiler warnings. */ assert(err == 0); if (loop != default_loop) free(loop); diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c index a101159438341f..115449224f9651 100644 --- a/deps/uv/src/win/core.c +++ b/deps/uv/src/win/core.c @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include diff --git a/deps/uv/src/win/error.c b/deps/uv/src/win/error.c index 5c5514736e8304..a265a272dced19 100644 --- a/deps/uv/src/win/error.c +++ b/deps/uv/src/win/error.c @@ -21,7 +21,6 @@ #include #include -#include #include #include #include diff --git a/deps/uv/src/win/fs-event.c b/deps/uv/src/win/fs-event.c index 7ad99a88b1ebef..640651b6c9634b 100644 --- a/deps/uv/src/win/fs-event.c +++ b/deps/uv/src/win/fs-event.c @@ -20,7 +20,6 @@ */ #include -#include #include #include #include @@ -39,7 +38,8 @@ static void uv_fs_event_queue_readdirchanges(uv_loop_t* loop, assert(handle->dir_handle != INVALID_HANDLE_VALUE); assert(!handle->req_pending); - memset(&(handle->req.overlapped), 0, sizeof(handle->req.overlapped)); + memset(&(handle->req.u.io.overlapped), 0, + sizeof(handle->req.u.io.overlapped)); if (!ReadDirectoryChangesW(handle->dir_handle, handle->buffer, uv_directory_watcher_buffer_size, @@ -53,7 +53,7 @@ static void uv_fs_event_queue_readdirchanges(uv_loop_t* loop, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, NULL, - &handle->req.overlapped, + &handle->req.u.io.overlapped, NULL)) { /* Make this req pending reporting an error. */ SET_REQ_ERROR(&handle->req, GetLastError()); @@ -232,7 +232,8 @@ int uv_fs_event_start(uv_fs_event_t* handle, uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } - memset(&(handle->req.overlapped), 0, sizeof(handle->req.overlapped)); + memset(&(handle->req.u.io.overlapped), 0, + sizeof(handle->req.u.io.overlapped)); if (!ReadDirectoryChangesW(handle->dir_handle, handle->buffer, @@ -247,7 +248,7 @@ int uv_fs_event_start(uv_fs_event_t* handle, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, NULL, - &handle->req.overlapped, + &handle->req.u.io.overlapped, NULL)) { last_error = GetLastError(); goto error; @@ -349,7 +350,7 @@ void uv_process_fs_event_req(uv_loop_t* loop, uv_req_t* req, file_info = (FILE_NOTIFY_INFORMATION*)(handle->buffer + offset); if (REQ_SUCCESS(req)) { - if (req->overlapped.InternalHigh > 0) { + if (req->u.io.overlapped.InternalHigh > 0) { do { file_info = (FILE_NOTIFY_INFORMATION*)((char*)file_info + offset); assert(!filename); diff --git a/deps/uv/src/win/fs.c b/deps/uv/src/win/fs.c index 33bc9da304054f..af7ec74276f995 100644 --- a/deps/uv/src/win/fs.c +++ b/deps/uv/src/win/fs.c @@ -21,7 +21,6 @@ #include #include -#include #include #include #include @@ -161,8 +160,8 @@ INLINE static int fs__capture_path(uv_loop_t* loop, uv_fs_t* req, if (buf_sz == 0) { - req->pathw = NULL; - req->new_pathw = NULL; + req->file.pathw = NULL; + req->fs.info.new_pathw = NULL; req->path = NULL; return 0; } @@ -182,10 +181,10 @@ INLINE static int fs__capture_path(uv_loop_t* loop, uv_fs_t* req, (WCHAR*) pos, pathw_len); assert(r == (DWORD) pathw_len); - req->pathw = (WCHAR*) pos; + req->file.pathw = (WCHAR*) pos; pos += r * sizeof(WCHAR); } else { - req->pathw = NULL; + req->file.pathw = NULL; } if (new_path != NULL) { @@ -196,10 +195,10 @@ INLINE static int fs__capture_path(uv_loop_t* loop, uv_fs_t* req, (WCHAR*) pos, new_pathw_len); assert(r == (DWORD) new_pathw_len); - req->new_pathw = (WCHAR*) pos; + req->fs.info.new_pathw = (WCHAR*) pos; pos += r * sizeof(WCHAR); } else { - req->new_pathw = NULL; + req->fs.info.new_pathw = NULL; } if (!copy_path) { @@ -388,7 +387,7 @@ void fs__open(uv_fs_t* req) { DWORD attributes = 0; HANDLE file; int fd, current_umask; - int flags = req->file_flags; + int flags = req->fs.info.file_flags; /* Obtain the active umask. umask() never fails and returns the previous */ /* umask. */ @@ -450,7 +449,7 @@ void fs__open(uv_fs_t* req) { attributes |= FILE_ATTRIBUTE_NORMAL; if (flags & _O_CREAT) { - if (!((req->mode & ~current_umask) & _S_IWRITE)) { + if (!((req->fs.info.mode & ~current_umask) & _S_IWRITE)) { attributes |= FILE_ATTRIBUTE_READONLY; } } @@ -480,7 +479,7 @@ void fs__open(uv_fs_t* req) { /* Setting this flag makes it possible to open a directory. */ attributes |= FILE_FLAG_BACKUP_SEMANTICS; - file = CreateFileW(req->pathw, + file = CreateFileW(req->file.pathw, access, share, NULL, @@ -512,6 +511,7 @@ void fs__open(uv_fs_t* req) { SET_REQ_WIN32_ERROR(req, GetLastError()); else SET_REQ_WIN32_ERROR(req, UV_UNKNOWN); + CloseHandle(file); return; } @@ -523,7 +523,7 @@ void fs__open(uv_fs_t* req) { } void fs__close(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; int result; VERIFY_FD(fd, req); @@ -534,8 +534,8 @@ void fs__close(uv_fs_t* req) { void fs__read(uv_fs_t* req) { - int fd = req->fd; - int64_t offset = req->offset; + int fd = req->file.fd; + int64_t offset = req->fs.info.offset; HANDLE handle; OVERLAPPED overlapped, *overlapped_ptr; LARGE_INTEGER offset_; @@ -572,13 +572,13 @@ void fs__read(uv_fs_t* req) { } result = ReadFile(handle, - req->bufs[index].base, - req->bufs[index].len, + req->fs.info.bufs[index].base, + req->fs.info.bufs[index].len, &incremental_bytes, overlapped_ptr); bytes += incremental_bytes; ++index; - } while (result && index < req->nbufs); + } while (result && index < req->fs.info.nbufs); if (result || bytes > 0) { SET_REQ_RESULT(req, bytes); @@ -594,8 +594,8 @@ void fs__read(uv_fs_t* req) { void fs__write(uv_fs_t* req) { - int fd = req->fd; - int64_t offset = req->offset; + int fd = req->file.fd; + int64_t offset = req->fs.info.offset; HANDLE handle; OVERLAPPED overlapped, *overlapped_ptr; LARGE_INTEGER offset_; @@ -630,13 +630,13 @@ void fs__write(uv_fs_t* req) { } result = WriteFile(handle, - req->bufs[index].base, - req->bufs[index].len, + req->fs.info.bufs[index].base, + req->fs.info.bufs[index].len, &incremental_bytes, overlapped_ptr); bytes += incremental_bytes; ++index; - } while (result && index < req->nbufs); + } while (result && index < req->fs.info.nbufs); if (result || bytes > 0) { SET_REQ_RESULT(req, bytes); @@ -647,13 +647,13 @@ void fs__write(uv_fs_t* req) { void fs__rmdir(uv_fs_t* req) { - int result = _wrmdir(req->pathw); + int result = _wrmdir(req->file.pathw); SET_REQ_RESULT(req, result); } void fs__unlink(uv_fs_t* req) { - const WCHAR* pathw = req->pathw; + const WCHAR* pathw = req->file.pathw; HANDLE handle; BY_HANDLE_FILE_INFORMATION info; FILE_DISPOSITION_INFORMATION disposition; @@ -661,7 +661,7 @@ void fs__unlink(uv_fs_t* req) { NTSTATUS status; handle = CreateFileW(pathw, - FILE_READ_ATTRIBUTES | DELETE, + FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, @@ -703,6 +703,24 @@ void fs__unlink(uv_fs_t* req) { } } + if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { + /* Remove read-only attribute */ + FILE_BASIC_INFORMATION basic = { 0 }; + + basic.FileAttributes = info.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY); + + status = pNtSetInformationFile(handle, + &iosb, + &basic, + sizeof basic, + FileBasicInformation); + if (!NT_SUCCESS(status)) { + SET_REQ_WIN32_ERROR(req, pRtlNtStatusToDosError(status)); + CloseHandle(handle); + return; + } + } + /* Try to set the delete flag. */ disposition.DeleteFile = TRUE; status = pNtSetInformationFile(handle, @@ -722,7 +740,7 @@ void fs__unlink(uv_fs_t* req) { void fs__mkdir(uv_fs_t* req) { /* TODO: use req->mode. */ - int result = _wmkdir(req->pathw); + int result = _wmkdir(req->file.pathw); SET_REQ_RESULT(req, result); } @@ -740,8 +758,8 @@ void fs__mkdtemp(uv_fs_t* req) { uint64_t v; BOOL released; - len = wcslen(req->pathw); - ep = req->pathw + len; + len = wcslen(req->file.pathw); + ep = req->file.pathw + len; if (len < num_x || wcsncmp(ep - num_x, L"XXXXXX", num_x)) { SET_REQ_UV_ERROR(req, UV_EINVAL, ERROR_INVALID_PARAMETER); return; @@ -766,7 +784,7 @@ void fs__mkdtemp(uv_fs_t* req) { v /= num_chars; } - if (_wmkdir(req->pathw) == 0) { + if (_wmkdir(req->file.pathw) == 0) { len = strlen(req->path); wcstombs((char*) req->path + len - num_x, ep - num_x, num_x); SET_REQ_RESULT(req, 0); @@ -810,7 +828,7 @@ void fs__scandir(uv_fs_t* req) { /* Open the directory. */ dir_handle = - CreateFileW(req->pathw, + CreateFileW(req->file.pathw, FILE_LIST_DIRECTORY | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, @@ -956,7 +974,7 @@ void fs__scandir(uv_fs_t* req) { SET_REQ_RESULT(req, dirents_used); /* `nbufs` will be used as index by uv_fs_scandir_next. */ - req->nbufs = 0; + req->fs.info.nbufs = 0; return; @@ -1125,7 +1143,7 @@ INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) { flags |= FILE_FLAG_OPEN_REPARSE_POINT; } - handle = CreateFileW(req->pathw, + handle = CreateFileW(req->file.pathw, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, @@ -1159,19 +1177,19 @@ INLINE static void fs__stat_impl(uv_fs_t* req, int do_lstat) { static void fs__stat(uv_fs_t* req) { - fs__stat_prepare_path(req->pathw); + fs__stat_prepare_path(req->file.pathw); fs__stat_impl(req, 0); } static void fs__lstat(uv_fs_t* req) { - fs__stat_prepare_path(req->pathw); + fs__stat_prepare_path(req->file.pathw); fs__stat_impl(req, 1); } static void fs__fstat(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; VERIFY_FD(fd, req); @@ -1194,7 +1212,7 @@ static void fs__fstat(uv_fs_t* req) { static void fs__rename(uv_fs_t* req) { - if (!MoveFileExW(req->pathw, req->new_pathw, MOVEFILE_REPLACE_EXISTING)) { + if (!MoveFileExW(req->file.pathw, req->fs.info.new_pathw, MOVEFILE_REPLACE_EXISTING)) { SET_REQ_WIN32_ERROR(req, GetLastError()); return; } @@ -1204,7 +1222,7 @@ static void fs__rename(uv_fs_t* req) { INLINE static void fs__sync_impl(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; int result; VERIFY_FD(fd, req); @@ -1229,7 +1247,7 @@ static void fs__fdatasync(uv_fs_t* req) { static void fs__ftruncate(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; NTSTATUS status; IO_STATUS_BLOCK io_status; @@ -1239,7 +1257,7 @@ static void fs__ftruncate(uv_fs_t* req) { handle = uv__get_osfhandle(fd); - eof_info.EndOfFile.QuadPart = req->offset; + eof_info.EndOfFile.QuadPart = req->fs.info.offset; status = pNtSetInformationFile(handle, &io_status, @@ -1256,9 +1274,9 @@ static void fs__ftruncate(uv_fs_t* req) { static void fs__sendfile(uv_fs_t* req) { - int fd_in = req->fd, fd_out = req->fd_out; - size_t length = req->bufsml[0].len; - int64_t offset = req->offset; + int fd_in = req->file.fd, fd_out = req->fs.info.fd_out; + size_t length = req->fs.info.bufsml[0].len; + int64_t offset = req->fs.info.offset; const size_t max_buf_size = 65536; size_t buf_size = length < max_buf_size ? length : max_buf_size; int n, result = 0; @@ -1303,32 +1321,39 @@ static void fs__sendfile(uv_fs_t* req) { static void fs__access(uv_fs_t* req) { - DWORD attr = GetFileAttributesW(req->pathw); + DWORD attr = GetFileAttributesW(req->file.pathw); if (attr == INVALID_FILE_ATTRIBUTES) { SET_REQ_WIN32_ERROR(req, GetLastError()); return; } - if ((req->flags & W_OK) && - ((attr & FILE_ATTRIBUTE_READONLY) || - (attr & FILE_ATTRIBUTE_DIRECTORY))) { + /* + * Access is possible if + * - write access wasn't requested, + * - or the file isn't read-only, + * - or it's a directory. + * (Directories cannot be read-only on Windows.) + */ + if (!(req->flags & W_OK) || + !(attr & FILE_ATTRIBUTE_READONLY) || + (attr & FILE_ATTRIBUTE_DIRECTORY)) { + SET_REQ_RESULT(req, 0); + } else { SET_REQ_WIN32_ERROR(req, UV_EPERM); - return; } - SET_REQ_RESULT(req, 0); } static void fs__chmod(uv_fs_t* req) { - int result = _wchmod(req->pathw, req->mode); + int result = _wchmod(req->file.pathw, req->fs.info.mode); SET_REQ_RESULT(req, result); } static void fs__fchmod(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; NTSTATUS nt_status; IO_STATUS_BLOCK io_status; @@ -1349,7 +1374,7 @@ static void fs__fchmod(uv_fs_t* req) { return; } - if (req->mode & _S_IWRITE) { + if (req->fs.info.mode & _S_IWRITE) { file_info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY; } else { file_info.FileAttributes |= FILE_ATTRIBUTE_READONLY; @@ -1387,7 +1412,7 @@ INLINE static int fs__utime_handle(HANDLE handle, double atime, double mtime) { static void fs__utime(uv_fs_t* req) { HANDLE handle; - handle = CreateFileW(req->pathw, + handle = CreateFileW(req->file.pathw, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, @@ -1400,7 +1425,7 @@ static void fs__utime(uv_fs_t* req) { return; } - if (fs__utime_handle(handle, req->atime, req->mtime) != 0) { + if (fs__utime_handle(handle, req->fs.time.atime, req->fs.time.mtime) != 0) { SET_REQ_WIN32_ERROR(req, GetLastError()); CloseHandle(handle); return; @@ -1413,7 +1438,7 @@ static void fs__utime(uv_fs_t* req) { static void fs__futime(uv_fs_t* req) { - int fd = req->fd; + int fd = req->file.fd; HANDLE handle; VERIFY_FD(fd, req); @@ -1424,7 +1449,7 @@ static void fs__futime(uv_fs_t* req) { return; } - if (fs__utime_handle(handle, req->atime, req->mtime) != 0) { + if (fs__utime_handle(handle, req->fs.time.atime, req->fs.time.mtime) != 0) { SET_REQ_WIN32_ERROR(req, GetLastError()); return; } @@ -1434,7 +1459,7 @@ static void fs__futime(uv_fs_t* req) { static void fs__link(uv_fs_t* req) { - DWORD r = CreateHardLinkW(req->new_pathw, req->pathw, NULL); + DWORD r = CreateHardLinkW(req->fs.info.new_pathw, req->file.pathw, NULL); if (r == 0) { SET_REQ_WIN32_ERROR(req, GetLastError()); } else { @@ -1614,9 +1639,9 @@ static void fs__create_junction(uv_fs_t* req, const WCHAR* path, static void fs__symlink(uv_fs_t* req) { - WCHAR* pathw = req->pathw; - WCHAR* new_pathw = req->new_pathw; - int flags = req->file_flags; + WCHAR* pathw = req->file.pathw; + WCHAR* new_pathw = req->fs.info.new_pathw; + int flags = req->fs.info.file_flags; int result; @@ -1640,7 +1665,7 @@ static void fs__symlink(uv_fs_t* req) { static void fs__readlink(uv_fs_t* req) { HANDLE handle; - handle = CreateFileW(req->pathw, + handle = CreateFileW(req->file.pathw, 0, 0, NULL, @@ -1739,14 +1764,14 @@ void uv_fs_req_cleanup(uv_fs_t* req) { return; if (req->flags & UV_FS_FREE_PATHS) - free(req->pathw); + free(req->file.pathw); if (req->flags & UV_FS_FREE_PTR) free(req->ptr); req->path = NULL; - req->pathw = NULL; - req->new_pathw = NULL; + req->file.pathw = NULL; + req->fs.info.new_pathw = NULL; req->ptr = NULL; req->flags |= UV_FS_CLEANEDUP; @@ -1764,8 +1789,8 @@ int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, return uv_translate_sys_error(err); } - req->file_flags = flags; - req->mode = mode; + req->fs.info.file_flags = flags; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1779,7 +1804,7 @@ int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_CLOSE, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1800,19 +1825,19 @@ int uv_fs_read(uv_loop_t* loop, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_READ, cb); - req->fd = fd; + req->file.fd = fd; - req->nbufs = nbufs; - req->bufs = req->bufsml; - if (nbufs > ARRAY_SIZE(req->bufsml)) - req->bufs = malloc(nbufs * sizeof(*bufs)); + req->fs.info.nbufs = nbufs; + req->fs.info.bufs = req->fs.info.bufsml; + if (nbufs > ARRAY_SIZE(req->fs.info.bufsml)) + req->fs.info.bufs = malloc(nbufs * sizeof(*bufs)); - if (req->bufs == NULL) + if (req->fs.info.bufs == NULL) return UV_ENOMEM; - memcpy(req->bufs, bufs, nbufs * sizeof(*bufs)); + memcpy(req->fs.info.bufs, bufs, nbufs * sizeof(*bufs)); - req->offset = offset; + req->fs.info.offset = offset; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1833,19 +1858,19 @@ int uv_fs_write(uv_loop_t* loop, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_WRITE, cb); - req->fd = fd; + req->file.fd = fd; - req->nbufs = nbufs; - req->bufs = req->bufsml; - if (nbufs > ARRAY_SIZE(req->bufsml)) - req->bufs = malloc(nbufs * sizeof(*bufs)); + req->fs.info.nbufs = nbufs; + req->fs.info.bufs = req->fs.info.bufsml; + if (nbufs > ARRAY_SIZE(req->fs.info.bufsml)) + req->fs.info.bufs = malloc(nbufs * sizeof(*bufs)); - if (req->bufs == NULL) + if (req->fs.info.bufs == NULL) return UV_ENOMEM; - memcpy(req->bufs, bufs, nbufs * sizeof(*bufs)); + memcpy(req->fs.info.bufs, bufs, nbufs * sizeof(*bufs)); - req->offset = offset; + req->fs.info.offset = offset; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1889,7 +1914,7 @@ int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, return uv_translate_sys_error(err); } - req->mode = mode; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1952,7 +1977,7 @@ int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, return uv_translate_sys_error(err); } - req->file_flags = flags; + req->fs.info.file_flags = flags; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -1996,7 +2021,7 @@ int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, return uv_translate_sys_error(err); } - req->file_flags = flags; + req->fs.info.file_flags = flags; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2106,7 +2131,7 @@ int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) { int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FSTAT, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2141,7 +2166,7 @@ int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FSYNC, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2155,7 +2180,7 @@ int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file fd, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FDATASYNC, cb); - req->fd = fd; + req->file.fd = fd; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2171,8 +2196,8 @@ int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file fd, int64_t offset, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FTRUNCATE, cb); - req->fd = fd; - req->offset = offset; + req->file.fd = fd; + req->fs.info.offset = offset; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2189,10 +2214,10 @@ int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file fd_out, uv_file fd_in, int64_t in_offset, size_t length, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_SENDFILE, cb); - req->fd = fd_in; - req->fd_out = fd_out; - req->offset = in_offset; - req->bufsml[0].len = length; + req->file.fd = fd_in; + req->fs.info.fd_out = fd_out; + req->fs.info.offset = in_offset; + req->fs.info.bufsml[0].len = length; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2240,7 +2265,7 @@ int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, return uv_translate_sys_error(err); } - req->mode = mode; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2256,8 +2281,8 @@ int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file fd, int mode, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FCHMOD, cb); - req->fd = fd; - req->mode = mode; + req->file.fd = fd; + req->fs.info.mode = mode; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2280,8 +2305,8 @@ int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, return uv_translate_sys_error(err); } - req->atime = atime; - req->mtime = mtime; + req->fs.time.atime = atime; + req->fs.time.mtime = mtime; if (cb) { QUEUE_FS_TP_JOB(loop, req); @@ -2297,9 +2322,9 @@ int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file fd, double atime, double mtime, uv_fs_cb cb) { uv_fs_req_init(loop, req, UV_FS_FUTIME, cb); - req->fd = fd; - req->atime = atime; - req->mtime = mtime; + req->file.fd = fd; + req->fs.time.atime = atime; + req->fs.time.mtime = mtime; if (cb) { QUEUE_FS_TP_JOB(loop, req); diff --git a/deps/uv/src/win/getaddrinfo.c b/deps/uv/src/win/getaddrinfo.c index f103f5fbd3418a..f3802cd5829208 100644 --- a/deps/uv/src/win/getaddrinfo.c +++ b/deps/uv/src/win/getaddrinfo.c @@ -20,7 +20,6 @@ */ #include -#include #include "uv.h" #include "internal.h" diff --git a/deps/uv/src/win/getnameinfo.c b/deps/uv/src/win/getnameinfo.c index b1d045c79bd9db..66b64b883248e3 100644 --- a/deps/uv/src/win/getnameinfo.c +++ b/deps/uv/src/win/getnameinfo.c @@ -20,7 +20,6 @@ */ #include -#include #include #include "uv.h" diff --git a/deps/uv/src/win/pipe.c b/deps/uv/src/win/pipe.c index 57fab065aa346b..5a0e5420847b12 100644 --- a/deps/uv/src/win/pipe.c +++ b/deps/uv/src/win/pipe.c @@ -95,15 +95,15 @@ int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) { handle->reqs_pending = 0; handle->handle = INVALID_HANDLE_VALUE; handle->name = NULL; - handle->ipc_pid = 0; - handle->remaining_ipc_rawdata_bytes = 0; - QUEUE_INIT(&handle->pending_ipc_info.queue); - handle->pending_ipc_info.queue_len = 0; + handle->pipe.conn.ipc_pid = 0; + handle->pipe.conn.remaining_ipc_rawdata_bytes = 0; + QUEUE_INIT(&handle->pipe.conn.pending_ipc_info.queue); + handle->pipe.conn.pending_ipc_info.queue_len = 0; handle->ipc = ipc; - handle->non_overlapped_writes_tail = NULL; - handle->readfile_thread = NULL; + handle->pipe.conn.non_overlapped_writes_tail = NULL; + handle->pipe.conn.readfile_thread = NULL; - uv_req_init(loop, (uv_req_t*) &handle->ipc_header_write_req); + uv_req_init(loop, (uv_req_t*) &handle->pipe.conn.ipc_header_write_req); return 0; } @@ -112,11 +112,11 @@ int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) { static void uv_pipe_connection_init(uv_pipe_t* handle) { uv_connection_init((uv_stream_t*) handle); handle->read_req.data = handle; - handle->eof_timer = NULL; + handle->pipe.conn.eof_timer = NULL; assert(!(handle->flags & UV_HANDLE_PIPESERVER)); if (pCancelSynchronousIo && handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) { - uv_mutex_init(&handle->readfile_mutex); + uv_mutex_init(&handle->pipe.conn.readfile_mutex); handle->flags |= UV_HANDLE_PIPE_READ_CANCELABLE; } } @@ -330,16 +330,16 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) { handle->flags &= ~UV_HANDLE_PIPE_READ_CANCELABLE; - uv_mutex_destroy(&handle->readfile_mutex); + uv_mutex_destroy(&handle->pipe.conn.readfile_mutex); } if ((handle->flags & UV_HANDLE_CONNECTION) && - handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { - req = handle->shutdown_req; + handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { + req = handle->stream.conn.shutdown_req; /* Clear the shutdown_req field so we don't go here again. */ - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; if (handle->flags & UV__HANDLE_CLOSING) { UNREGISTER_HANDLE_REQ(loop, handle, req); @@ -408,11 +408,11 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { if (handle->flags & UV_HANDLE_CONNECTION) { /* Free pending sockets */ - while (!QUEUE_EMPTY(&handle->pending_ipc_info.queue)) { + while (!QUEUE_EMPTY(&handle->pipe.conn.pending_ipc_info.queue)) { QUEUE* q; SOCKET socket; - q = QUEUE_HEAD(&handle->pending_ipc_info.queue); + q = QUEUE_HEAD(&handle->pipe.conn.pending_ipc_info.queue); QUEUE_REMOVE(q); item = QUEUE_DATA(q, uv__ipc_queue_item_t, member); @@ -428,7 +428,7 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { if (socket != INVALID_SOCKET) closesocket(socket); } - handle->pending_ipc_info.queue_len = 0; + handle->pipe.conn.pending_ipc_info.queue_len = 0; if (handle->flags & UV_HANDLE_EMULATE_IOCP) { if (handle->read_req.wait_handle != INVALID_HANDLE_VALUE) { @@ -443,9 +443,9 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { } if (handle->flags & UV_HANDLE_PIPESERVER) { - assert(handle->accept_reqs); - free(handle->accept_reqs); - handle->accept_reqs = NULL; + assert(handle->pipe.serv.accept_reqs); + free(handle->pipe.serv.accept_reqs); + handle->pipe.serv.accept_reqs = NULL; } uv__handle_close(handle); @@ -454,7 +454,7 @@ void uv_pipe_endgame(uv_loop_t* loop, uv_pipe_t* handle) { void uv_pipe_pending_instances(uv_pipe_t* handle, int count) { - handle->pending_instances = count; + handle->pipe.serv.pending_instances = count; handle->flags |= UV_HANDLE_PIPESERVER; } @@ -474,17 +474,17 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { } if (!(handle->flags & UV_HANDLE_PIPESERVER)) { - handle->pending_instances = default_pending_pipe_instances; + handle->pipe.serv.pending_instances = default_pending_pipe_instances; } - handle->accept_reqs = (uv_pipe_accept_t*) - malloc(sizeof(uv_pipe_accept_t) * handle->pending_instances); - if (!handle->accept_reqs) { + handle->pipe.serv.accept_reqs = (uv_pipe_accept_t*) + malloc(sizeof(uv_pipe_accept_t) * handle->pipe.serv.pending_instances); + if (!handle->pipe.serv.accept_reqs) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } - for (i = 0; i < handle->pending_instances; i++) { - req = &handle->accept_reqs[i]; + for (i = 0; i < handle->pipe.serv.pending_instances; i++) { + req = &handle->pipe.serv.accept_reqs[i]; uv_req_init(loop, (uv_req_t*) req); req->type = UV_ACCEPT; req->data = handle; @@ -508,13 +508,13 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { * Attempt to create the first pipe with FILE_FLAG_FIRST_PIPE_INSTANCE. * If this fails then there's already a pipe server for the given pipe name. */ - handle->accept_reqs[0].pipeHandle = CreateNamedPipeW(handle->name, + handle->pipe.serv.accept_reqs[0].pipeHandle = CreateNamedPipeW(handle->name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, NULL); - if (handle->accept_reqs[0].pipeHandle == INVALID_HANDLE_VALUE) { + if (handle->pipe.serv.accept_reqs[0].pipeHandle == INVALID_HANDLE_VALUE) { err = GetLastError(); if (err == ERROR_ACCESS_DENIED) { err = WSAEADDRINUSE; /* Translates to UV_EADDRINUSE. */ @@ -524,12 +524,15 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { goto error; } - if (uv_set_pipe_handle(loop, handle, handle->accept_reqs[0].pipeHandle, 0)) { + if (uv_set_pipe_handle(loop, + handle, + handle->pipe.serv.accept_reqs[0].pipeHandle, + 0)) { err = GetLastError(); goto error; } - handle->pending_accepts = NULL; + handle->pipe.serv.pending_accepts = NULL; handle->flags |= UV_HANDLE_PIPESERVER; handle->flags |= UV_HANDLE_BOUND; @@ -541,9 +544,9 @@ int uv_pipe_bind(uv_pipe_t* handle, const char* name) { handle->name = NULL; } - if (handle->accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE) { - CloseHandle(handle->accept_reqs[0].pipeHandle); - handle->accept_reqs[0].pipeHandle = INVALID_HANDLE_VALUE; + if (handle->pipe.serv.accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE) { + CloseHandle(handle->pipe.serv.accept_reqs[0].pipeHandle); + handle->pipe.serv.accept_reqs[0].pipeHandle = INVALID_HANDLE_VALUE; } return uv_translate_sys_error(err); @@ -677,15 +680,15 @@ void uv__pipe_pause_read(uv_pipe_t* handle) { any access to a NamedPipe to deadlock if any process has called ReadFile */ HANDLE h; - uv_mutex_lock(&handle->readfile_mutex); - h = handle->readfile_thread; + uv_mutex_lock(&handle->pipe.conn.readfile_mutex); + h = handle->pipe.conn.readfile_thread; while (h) { /* spinlock: we expect this to finish quickly, or we are probably about to deadlock anyways (in the kernel), so it doesn't matter */ pCancelSynchronousIo(h); SwitchToThread(); /* yield thread control briefly */ - h = handle->readfile_thread; + h = handle->pipe.conn.readfile_thread; } } } @@ -693,7 +696,7 @@ void uv__pipe_pause_read(uv_pipe_t* handle) { void uv__pipe_unpause_read(uv_pipe_t* handle) { if (handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) { - uv_mutex_unlock(&handle->readfile_mutex); + uv_mutex_unlock(&handle->pipe.conn.readfile_mutex); } } @@ -719,11 +722,11 @@ void uv_pipe_cleanup(uv_loop_t* loop, uv_pipe_t* handle) { } if (handle->flags & UV_HANDLE_PIPESERVER) { - for (i = 0; i < handle->pending_instances; i++) { - pipeHandle = handle->accept_reqs[i].pipeHandle; + for (i = 0; i < handle->pipe.serv.pending_instances; i++) { + pipeHandle = handle->pipe.serv.accept_reqs[i].pipeHandle; if (pipeHandle != INVALID_HANDLE_VALUE) { CloseHandle(pipeHandle); - handle->accept_reqs[i].pipeHandle = INVALID_HANDLE_VALUE; + handle->pipe.serv.accept_reqs[i].pipeHandle = INVALID_HANDLE_VALUE; } } } @@ -796,9 +799,9 @@ static void uv_pipe_queue_accept(uv_loop_t* loop, uv_pipe_t* handle, assert(req->pipeHandle != INVALID_HANDLE_VALUE); /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); - if (!ConnectNamedPipe(req->pipeHandle, &req->overlapped) && + if (!ConnectNamedPipe(req->pipeHandle, &req->u.io.overlapped) && GetLastError() != ERROR_IO_PENDING) { if (GetLastError() == ERROR_PIPE_CONNECTED) { SET_REQ_SUCCESS(req); @@ -826,14 +829,14 @@ int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) { int err; if (server->ipc) { - if (QUEUE_EMPTY(&server->pending_ipc_info.queue)) { + if (QUEUE_EMPTY(&server->pipe.conn.pending_ipc_info.queue)) { /* No valid pending sockets. */ return WSAEWOULDBLOCK; } - q = QUEUE_HEAD(&server->pending_ipc_info.queue); + q = QUEUE_HEAD(&server->pipe.conn.pending_ipc_info.queue); QUEUE_REMOVE(q); - server->pending_ipc_info.queue_len--; + server->pipe.conn.pending_ipc_info.queue_len--; item = QUEUE_DATA(q, uv__ipc_queue_item_t, member); err = uv_tcp_import((uv_tcp_t*)client, @@ -849,7 +852,7 @@ int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) { /* Find a connection instance that has been connected, but not yet */ /* accepted. */ - req = server->pending_accepts; + req = server->pipe.serv.pending_accepts; if (!req) { /* No valid connections found, so we error out. */ @@ -862,7 +865,7 @@ int uv_pipe_accept(uv_pipe_t* server, uv_stream_t* client) { pipe_client->flags |= UV_HANDLE_READABLE | UV_HANDLE_WRITABLE; /* Prepare the req to pick up a new connection */ - server->pending_accepts = req->next_pending; + server->pipe.serv.pending_accepts = req->next_pending; req->next_pending = NULL; req->pipeHandle = INVALID_HANDLE_VALUE; @@ -881,7 +884,7 @@ int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb) { int i; if (handle->flags & UV_HANDLE_LISTENING) { - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; } if (!(handle->flags & UV_HANDLE_BOUND)) { @@ -898,13 +901,13 @@ int uv_pipe_listen(uv_pipe_t* handle, int backlog, uv_connection_cb cb) { handle->flags |= UV_HANDLE_LISTENING; INCREASE_ACTIVE_COUNT(loop, handle); - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; /* First pipe handle should have already been created in uv_pipe_bind */ - assert(handle->accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE); + assert(handle->pipe.serv.accept_reqs[0].pipeHandle != INVALID_HANDLE_VALUE); - for (i = 0; i < handle->pending_instances; i++) { - uv_pipe_queue_accept(loop, handle, &handle->accept_reqs[i], i == 0); + for (i = 0; i < handle->pipe.serv.pending_instances; i++) { + uv_pipe_queue_accept(loop, handle, &handle->pipe.serv.accept_reqs[i], i == 0); } return 0; @@ -919,7 +922,7 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { uv_loop_t* loop = handle->loop; HANDLE hThread = NULL; DWORD err; - uv_mutex_t *m = &handle->readfile_mutex; + uv_mutex_t *m = &handle->pipe.conn.readfile_mutex; assert(req != NULL); assert(req->type == UV_READ); @@ -930,7 +933,7 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { if (DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hThread, 0, TRUE, DUPLICATE_SAME_ACCESS)) { - handle->readfile_thread = hThread; + handle->pipe.conn.readfile_thread = hThread; } else { hThread = NULL; } @@ -948,10 +951,10 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { handle->flags & UV_HANDLE_PIPE_READ_CANCELABLE) { if (handle->flags & UV_HANDLE_READING) { /* just a brief break to do something else */ - handle->readfile_thread = NULL; + handle->pipe.conn.readfile_thread = NULL; /* resume after it is finished */ uv_mutex_lock(m); - handle->readfile_thread = hThread; + handle->pipe.conn.readfile_thread = hThread; uv_mutex_unlock(m); goto restart_readfile; } else { @@ -960,9 +963,9 @@ static DWORD WINAPI uv_pipe_zero_readfile_thread_proc(void* parameter) { } } if (hThread) { - assert(hThread == handle->readfile_thread); + assert(hThread == handle->pipe.conn.readfile_thread); /* mutex does not control clearing readfile_thread */ - handle->readfile_thread = NULL; + handle->pipe.conn.readfile_thread = NULL; uv_mutex_lock(m); /* only when we hold the mutex lock is it safe to open or close the handle */ @@ -1017,9 +1020,9 @@ static void CALLBACK post_completion_read_wait(void* context, BOOLEAN timed_out) assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -1036,9 +1039,9 @@ static void CALLBACK post_completion_write_wait(void* context, BOOLEAN timed_out assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -1064,9 +1067,9 @@ static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) { goto error; } } else { - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { - req->overlapped.hEvent = (HANDLE) ((uintptr_t) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((uintptr_t) req->event_handle | 1); } /* Do 0-read */ @@ -1074,7 +1077,7 @@ static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) { &uv_zero_, 0, NULL, - &req->overlapped); + &req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { /* Make this req pending reporting an error. */ @@ -1091,7 +1094,7 @@ static void uv_pipe_queue_read(uv_loop_t* loop, uv_pipe_t* handle) { } if (req->wait_handle == INVALID_HANDLE_VALUE) { if (!RegisterWaitForSingleObject(&req->wait_handle, - req->overlapped.hEvent, post_completion_read_wait, (void*) req, + req->u.io.overlapped.hEvent, post_completion_read_wait, (void*) req, INFINITE, WT_EXECUTEINWAITTHREAD)) { SET_REQ_ERROR(req, GetLastError()); goto error; @@ -1135,14 +1138,14 @@ int uv_pipe_read_start(uv_pipe_t* handle, static void uv_insert_non_overlapped_write_req(uv_pipe_t* handle, uv_write_t* req) { req->next_req = NULL; - if (handle->non_overlapped_writes_tail) { + if (handle->pipe.conn.non_overlapped_writes_tail) { req->next_req = - handle->non_overlapped_writes_tail->next_req; - handle->non_overlapped_writes_tail->next_req = (uv_req_t*)req; - handle->non_overlapped_writes_tail = req; + handle->pipe.conn.non_overlapped_writes_tail->next_req; + handle->pipe.conn.non_overlapped_writes_tail->next_req = (uv_req_t*)req; + handle->pipe.conn.non_overlapped_writes_tail = req; } else { req->next_req = (uv_req_t*)req; - handle->non_overlapped_writes_tail = req; + handle->pipe.conn.non_overlapped_writes_tail = req; } } @@ -1150,13 +1153,13 @@ static void uv_insert_non_overlapped_write_req(uv_pipe_t* handle, static uv_write_t* uv_remove_non_overlapped_write_req(uv_pipe_t* handle) { uv_write_t* req; - if (handle->non_overlapped_writes_tail) { - req = (uv_write_t*)handle->non_overlapped_writes_tail->next_req; + if (handle->pipe.conn.non_overlapped_writes_tail) { + req = (uv_write_t*)handle->pipe.conn.non_overlapped_writes_tail->next_req; - if (req == handle->non_overlapped_writes_tail) { - handle->non_overlapped_writes_tail = NULL; + if (req == handle->pipe.conn.non_overlapped_writes_tail) { + handle->pipe.conn.non_overlapped_writes_tail = NULL; } else { - handle->non_overlapped_writes_tail->next_req = + handle->pipe.conn.non_overlapped_writes_tail->next_req = req->next_req; } @@ -1213,7 +1216,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, req->ipc_header = 0; req->event_handle = NULL; req->wait_handle = INVALID_HANDLE_VALUE; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); if (handle->ipc) { assert(!(handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE)); @@ -1223,7 +1226,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, if (send_handle) { tcp_send_handle = (uv_tcp_t*)send_handle; - err = uv_tcp_duplicate_socket(tcp_send_handle, handle->ipc_pid, + err = uv_tcp_duplicate_socket(tcp_send_handle, handle->pipe.conn.ipc_pid, &ipc_frame.socket_info_ex.socket_info); if (err) { return err; @@ -1255,8 +1258,8 @@ static int uv_pipe_write_impl(uv_loop_t* loop, * Try to use the preallocated write req if it's available. * Otherwise allocate a new one. */ - if (handle->ipc_header_write_req.type != UV_WRITE) { - ipc_header_req = (uv_write_t*)&handle->ipc_header_write_req; + if (handle->pipe.conn.ipc_header_write_req.type != UV_WRITE) { + ipc_header_req = (uv_write_t*)&handle->pipe.conn.ipc_header_write_req; } else { ipc_header_req = (uv_write_t*)malloc(sizeof(uv_write_t)); if (!ipc_header_req) { @@ -1272,12 +1275,13 @@ static int uv_pipe_write_impl(uv_loop_t* loop, } /* Write the header or the whole frame. */ - memset(&ipc_header_req->overlapped, 0, sizeof(ipc_header_req->overlapped)); + memset(&ipc_header_req->u.io.overlapped, 0, + sizeof(ipc_header_req->u.io.overlapped)); /* Using overlapped IO, but wait for completion before returning. This write is blocking because ipc_frame is on stack. */ - ipc_header_req->overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); - if (!ipc_header_req->overlapped.hEvent) { + ipc_header_req->u.io.overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); + if (!ipc_header_req->u.io.overlapped.hEvent) { uv_fatal_error(GetLastError(), "CreateEvent"); } @@ -1286,29 +1290,29 @@ static int uv_pipe_write_impl(uv_loop_t* loop, ipc_frame.header.flags & UV_IPC_TCP_SERVER ? sizeof(ipc_frame) : sizeof(ipc_frame.header), NULL, - &ipc_header_req->overlapped); + &ipc_header_req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { err = GetLastError(); - CloseHandle(ipc_header_req->overlapped.hEvent); + CloseHandle(ipc_header_req->u.io.overlapped.hEvent); return err; } if (!result) { /* Request not completed immediately. Wait for it.*/ - if (WaitForSingleObject(ipc_header_req->overlapped.hEvent, INFINITE) != + if (WaitForSingleObject(ipc_header_req->u.io.overlapped.hEvent, INFINITE) != WAIT_OBJECT_0) { err = GetLastError(); - CloseHandle(ipc_header_req->overlapped.hEvent); + CloseHandle(ipc_header_req->u.io.overlapped.hEvent); return err; } } - ipc_header_req->queued_bytes = 0; - CloseHandle(ipc_header_req->overlapped.hEvent); - ipc_header_req->overlapped.hEvent = NULL; + ipc_header_req->u.io.queued_bytes = 0; + CloseHandle(ipc_header_req->u.io.overlapped.hEvent); + ipc_header_req->u.io.overlapped.hEvent = NULL; REGISTER_HANDLE_REQ(loop, handle, ipc_header_req); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; /* If we don't have any raw data to write - we're done. */ if (!(ipc_frame.header.flags & UV_IPC_RAW_DATA)) { @@ -1331,28 +1335,28 @@ static int uv_pipe_write_impl(uv_loop_t* loop, return err; } else { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; } REGISTER_HANDLE_REQ(loop, handle, req); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; POST_COMPLETION_FOR_REQ(loop, req); return 0; } else if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) { req->write_buffer = bufs[0]; uv_insert_non_overlapped_write_req(handle, req); - if (handle->write_reqs_pending == 0) { + if (handle->stream.conn.write_reqs_pending == 0) { uv_queue_non_overlapped_write(handle); } /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); - handle->write_queue_size += req->queued_bytes; + req->u.io.queued_bytes = bufs[0].len; + handle->write_queue_size += req->u.io.queued_bytes; } else if (handle->flags & UV_HANDLE_BLOCKING_WRITES) { /* Using overlapped IO, but wait for completion before returning */ - req->overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); - if (!req->overlapped.hEvent) { + req->u.io.overlapped.hEvent = CreateEvent(NULL, 1, 0, NULL); + if (!req->u.io.overlapped.hEvent) { uv_fatal_error(GetLastError(), "CreateEvent"); } @@ -1360,40 +1364,40 @@ static int uv_pipe_write_impl(uv_loop_t* loop, bufs[0].base, bufs[0].len, NULL, - &req->overlapped); + &req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { err = GetLastError(); - CloseHandle(req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); return err; } if (result) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; } else { - assert(ipc_header_req != NULL); /* Request queued by the kernel. */ - if (WaitForSingleObject(ipc_header_req->overlapped.hEvent, INFINITE) != + req->u.io.queued_bytes = bufs[0].len; + handle->write_queue_size += req->u.io.queued_bytes; + if (WaitForSingleObject(req->u.io.overlapped.hEvent, INFINITE) != WAIT_OBJECT_0) { err = GetLastError(); - CloseHandle(ipc_header_req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); return uv_translate_sys_error(err); } } - CloseHandle(req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); REGISTER_HANDLE_REQ(loop, handle, req); handle->reqs_pending++; - handle->write_reqs_pending++; - POST_COMPLETION_FOR_REQ(loop, req); + handle->stream.conn.write_reqs_pending++; return 0; } else { result = WriteFile(handle->handle, bufs[0].base, bufs[0].len, NULL, - &req->overlapped); + &req->u.io.overlapped); if (!result && GetLastError() != ERROR_IO_PENDING) { return GetLastError(); @@ -1401,11 +1405,11 @@ static int uv_pipe_write_impl(uv_loop_t* loop, if (result) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; } else { /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); - handle->write_queue_size += req->queued_bytes; + req->u.io.queued_bytes = bufs[0].len; + handle->write_queue_size += req->u.io.queued_bytes; } if (handle->flags & UV_HANDLE_EMULATE_IOCP) { @@ -1414,7 +1418,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, uv_fatal_error(GetLastError(), "CreateEvent"); } if (!RegisterWaitForSingleObject(&req->wait_handle, - req->overlapped.hEvent, post_completion_write_wait, (void*) req, + req->u.io.overlapped.hEvent, post_completion_write_wait, (void*) req, INFINITE, WT_EXECUTEINWAITTHREAD)) { return GetLastError(); } @@ -1423,7 +1427,7 @@ static int uv_pipe_write_impl(uv_loop_t* loop, REGISTER_HANDLE_REQ(loop, handle, req); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; return 0; } @@ -1500,8 +1504,8 @@ void uv__pipe_insert_pending_socket(uv_pipe_t* handle, memcpy(&item->socket_info_ex, info, sizeof(item->socket_info_ex)); item->tcp_connection = tcp_connection; - QUEUE_INSERT_TAIL(&handle->pending_ipc_info.queue, &item->member); - handle->pending_ipc_info.queue_len++; + QUEUE_INSERT_TAIL(&handle->pipe.conn.pending_ipc_info.queue, &item->member); + handle->pipe.conn.pending_ipc_info.queue_len++; } @@ -1544,7 +1548,7 @@ void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle, if (handle->ipc) { /* Use the IPC framing protocol to read the incoming data. */ - if (handle->remaining_ipc_rawdata_bytes == 0) { + if (handle->pipe.conn.remaining_ipc_rawdata_bytes == 0) { /* We're reading a new frame. First, read the header. */ assert(avail >= sizeof(ipc_frame.header)); @@ -1587,12 +1591,12 @@ void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle, } if (ipc_frame.header.flags & UV_IPC_RAW_DATA) { - handle->remaining_ipc_rawdata_bytes = + handle->pipe.conn.remaining_ipc_rawdata_bytes = ipc_frame.header.raw_data_length; continue; } } else { - avail = min(avail, (DWORD)handle->remaining_ipc_rawdata_bytes); + avail = min(avail, (DWORD)handle->pipe.conn.remaining_ipc_rawdata_bytes); } } @@ -1610,9 +1614,9 @@ void uv_process_pipe_read_req(uv_loop_t* loop, uv_pipe_t* handle, NULL)) { /* Successful read */ if (handle->ipc) { - assert(handle->remaining_ipc_rawdata_bytes >= bytes); - handle->remaining_ipc_rawdata_bytes = - handle->remaining_ipc_rawdata_bytes - bytes; + assert(handle->pipe.conn.remaining_ipc_rawdata_bytes >= bytes); + handle->pipe.conn.remaining_ipc_rawdata_bytes = + handle->pipe.conn.remaining_ipc_rawdata_bytes - bytes; } handle->read_cb((uv_stream_t*)handle, bytes, &buf); @@ -1643,8 +1647,8 @@ void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle, assert(handle->type == UV_NAMED_PIPE); - assert(handle->write_queue_size >= req->queued_bytes); - handle->write_queue_size -= req->queued_bytes; + assert(handle->write_queue_size >= req->u.io.queued_bytes); + handle->write_queue_size -= req->u.io.queued_bytes; UNREGISTER_HANDLE_REQ(loop, handle, req); @@ -1660,7 +1664,7 @@ void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle, } if (req->ipc_header) { - if (req == &handle->ipc_header_write_req) { + if (req == &handle->pipe.conn.ipc_header_write_req) { req->type = UV_UNKNOWN_REQ; } else { free(req); @@ -1672,16 +1676,16 @@ void uv_process_pipe_write_req(uv_loop_t* loop, uv_pipe_t* handle, } } - handle->write_reqs_pending--; + handle->stream.conn.write_reqs_pending--; if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE && - handle->non_overlapped_writes_tail) { - assert(handle->write_reqs_pending > 0); + handle->pipe.conn.non_overlapped_writes_tail) { + assert(handle->stream.conn.write_reqs_pending > 0); uv_queue_non_overlapped_write(handle); } - if (handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + if (handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { uv_want_endgame(loop, (uv_handle_t*)handle); } @@ -1704,11 +1708,11 @@ void uv_process_pipe_accept_req(uv_loop_t* loop, uv_pipe_t* handle, if (REQ_SUCCESS(req)) { assert(req->pipeHandle != INVALID_HANDLE_VALUE); - req->next_pending = handle->pending_accepts; - handle->pending_accepts = req; + req->next_pending = handle->pipe.serv.pending_accepts; + handle->pipe.serv.pending_accepts = req; - if (handle->connection_cb) { - handle->connection_cb((uv_stream_t*)handle, 0); + if (handle->stream.serv.connection_cb) { + handle->stream.serv.connection_cb((uv_stream_t*)handle, 0); } } else { if (req->pipeHandle != INVALID_HANDLE_VALUE) { @@ -1781,23 +1785,23 @@ void uv_process_pipe_shutdown_req(uv_loop_t* loop, uv_pipe_t* handle, static void eof_timer_init(uv_pipe_t* pipe) { int r; - assert(pipe->eof_timer == NULL); + assert(pipe->pipe.conn.eof_timer == NULL); assert(pipe->flags & UV_HANDLE_CONNECTION); - pipe->eof_timer = (uv_timer_t*) malloc(sizeof *pipe->eof_timer); + pipe->pipe.conn.eof_timer = (uv_timer_t*) malloc(sizeof *pipe->pipe.conn.eof_timer); - r = uv_timer_init(pipe->loop, pipe->eof_timer); + r = uv_timer_init(pipe->loop, pipe->pipe.conn.eof_timer); assert(r == 0); /* timers can't fail */ - pipe->eof_timer->data = pipe; - uv_unref((uv_handle_t*) pipe->eof_timer); + pipe->pipe.conn.eof_timer->data = pipe; + uv_unref((uv_handle_t*) pipe->pipe.conn.eof_timer); } static void eof_timer_start(uv_pipe_t* pipe) { assert(pipe->flags & UV_HANDLE_CONNECTION); - if (pipe->eof_timer != NULL) { - uv_timer_start(pipe->eof_timer, eof_timer_cb, eof_timeout, 0); + if (pipe->pipe.conn.eof_timer != NULL) { + uv_timer_start(pipe->pipe.conn.eof_timer, eof_timer_cb, eof_timeout, 0); } } @@ -1805,8 +1809,8 @@ static void eof_timer_start(uv_pipe_t* pipe) { static void eof_timer_stop(uv_pipe_t* pipe) { assert(pipe->flags & UV_HANDLE_CONNECTION); - if (pipe->eof_timer != NULL) { - uv_timer_stop(pipe->eof_timer); + if (pipe->pipe.conn.eof_timer != NULL) { + uv_timer_stop(pipe->pipe.conn.eof_timer); } } @@ -1829,7 +1833,7 @@ static void eof_timer_cb(uv_timer_t* timer) { /* Therefore we check here if the read request has completed but will */ /* be processed later. */ if ((pipe->flags & UV_HANDLE_READ_PENDING) && - HasOverlappedIoCompleted(&pipe->read_req.overlapped)) { + HasOverlappedIoCompleted(&pipe->read_req.u.io.overlapped)) { return; } @@ -1850,9 +1854,9 @@ static void eof_timer_cb(uv_timer_t* timer) { static void eof_timer_destroy(uv_pipe_t* pipe) { assert(pipe->flags & UV_HANDLE_CONNECTION); - if (pipe->eof_timer) { - uv_close((uv_handle_t*) pipe->eof_timer, eof_timer_close_cb); - pipe->eof_timer = NULL; + if (pipe->pipe.conn.eof_timer) { + uv_close((uv_handle_t*) pipe->pipe.conn.eof_timer, eof_timer_close_cb); + pipe->pipe.conn.eof_timer = NULL; } } @@ -1903,8 +1907,8 @@ int uv_pipe_open(uv_pipe_t* pipe, uv_file file) { if (pipe->ipc) { assert(!(pipe->flags & UV_HANDLE_NON_OVERLAPPED_PIPE)); - pipe->ipc_pid = uv_parent_pid(); - assert(pipe->ipc_pid != -1); + pipe->pipe.conn.ipc_pid = uv_parent_pid(); + assert(pipe->pipe.conn.ipc_pid != -1); } return 0; } @@ -2027,7 +2031,7 @@ static int uv__pipe_getname(const uv_pipe_t* handle, char* buffer, size_t* size) int uv_pipe_pending_count(uv_pipe_t* handle) { if (!handle->ipc) return 0; - return handle->pending_ipc_info.queue_len; + return handle->pipe.conn.pending_ipc_info.queue_len; } @@ -2060,7 +2064,7 @@ int uv_pipe_getpeername(const uv_pipe_t* handle, char* buffer, size_t* size) { uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle) { if (!handle->ipc) return UV_UNKNOWN_HANDLE; - if (handle->pending_ipc_info.queue_len == 0) + if (handle->pipe.conn.pending_ipc_info.queue_len == 0) return UV_UNKNOWN_HANDLE; else return UV_TCP; diff --git a/deps/uv/src/win/poll.c b/deps/uv/src/win/poll.c index 4d8e1f99f65cb5..ce861d6ffc41eb 100644 --- a/deps/uv/src/win/poll.c +++ b/deps/uv/src/win/poll.c @@ -112,12 +112,12 @@ static void uv__fast_poll_submit_poll_req(uv_loop_t* loop, uv_poll_t* handle) { afd_poll_info->Handles[0].Events |= AFD_POLL_SEND | AFD_POLL_CONNECT_FAIL; } - memset(&req->overlapped, 0, sizeof req->overlapped); + memset(&req->u.io.overlapped, 0, sizeof req->u.io.overlapped); result = uv_msafd_poll((SOCKET) handle->peer_socket, afd_poll_info, afd_poll_info, - &req->overlapped); + &req->u.io.overlapped); if (result != 0 && WSAGetLastError() != WSA_IO_PENDING) { /* Queue this req, reporting an error. */ SET_REQ_ERROR(req, WSAGetLastError()); @@ -380,7 +380,7 @@ static DWORD WINAPI uv__slow_poll_thread_proc(void* arg) { } SET_REQ_SUCCESS(req); - req->overlapped.InternalHigh = (DWORD) reported_events; + req->u.io.overlapped.InternalHigh = (DWORD) reported_events; POST_COMPLETION_FOR_REQ(handle->loop, req); return 0; @@ -442,7 +442,7 @@ static void uv__slow_poll_process_poll_req(uv_loop_t* loop, uv_poll_t* handle, } } else { /* Got some events. */ - int events = req->overlapped.InternalHigh & handle->events & ~mask_events; + int events = req->u.io.overlapped.InternalHigh & handle->events & ~mask_events; if (events != 0) { handle->poll_cb(handle, 0, events); } diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c index 3a0106f82d63e3..887595f89cc9b6 100644 --- a/deps/uv/src/win/process.c +++ b/deps/uv/src/win/process.c @@ -707,7 +707,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { } /* second pass: copy to UTF-16 environment block */ - dst_copy = _malloca(env_len * sizeof(WCHAR)); + dst_copy = malloc(env_len * sizeof(WCHAR)); if (!dst_copy) { return ERROR_OUTOFMEMORY; } @@ -725,7 +725,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { (int) (env_len - (ptr - dst_copy))); if (len <= 0) { DWORD err = GetLastError(); - _freea(dst_copy); + free(dst_copy); return err; } *ptr_copy++ = ptr; @@ -767,7 +767,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { /* final pass: copy, in sort order, and inserting required variables */ dst = malloc((1+env_len) * sizeof(WCHAR)); if (!dst) { - _freea(dst_copy); + free(dst_copy); return ERROR_OUTOFMEMORY; } @@ -812,7 +812,7 @@ int make_program_env(char* env_block[], WCHAR** dst_ptr) { assert(env_len == (ptr - dst)); *ptr = L'\0'; - _freea(dst_copy); + free(dst_copy); *dst_ptr = dst; return 0; } @@ -1124,7 +1124,7 @@ int uv_spawn(uv_loop_t* loop, if (fdopt->flags & UV_CREATE_PIPE && fdopt->data.stream->type == UV_NAMED_PIPE && ((uv_pipe_t*) fdopt->data.stream)->ipc) { - ((uv_pipe_t*) fdopt->data.stream)->ipc_pid = info.dwProcessId; + ((uv_pipe_t*) fdopt->data.stream)->pipe.conn.ipc_pid = info.dwProcessId; } } diff --git a/deps/uv/src/win/req-inl.h b/deps/uv/src/win/req-inl.h index 46c7d9b106a869..b5e502eef5521a 100644 --- a/deps/uv/src/win/req-inl.h +++ b/deps/uv/src/win/req-inl.h @@ -29,7 +29,7 @@ #define SET_REQ_STATUS(req, status) \ - (req)->overlapped.Internal = (ULONG_PTR) (status) + (req)->u.io.overlapped.Internal = (ULONG_PTR) (status) #define SET_REQ_ERROR(req, error) \ SET_REQ_STATUS((req), NTSTATUS_FROM_WIN32((error))) @@ -38,7 +38,7 @@ SET_REQ_STATUS((req), STATUS_SUCCESS) #define GET_REQ_STATUS(req) \ - ((NTSTATUS) (req)->overlapped.Internal) + ((NTSTATUS) (req)->u.io.overlapped.Internal) #define REQ_SUCCESS(req) \ (NT_SUCCESS(GET_REQ_STATUS((req)))) @@ -74,7 +74,7 @@ if (!PostQueuedCompletionStatus((loop)->iocp, \ 0, \ 0, \ - &((req)->overlapped))) { \ + &((req)->u.io.overlapped))) { \ uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); \ } @@ -86,13 +86,24 @@ INLINE static void uv_req_init(uv_loop_t* loop, uv_req_t* req) { INLINE static uv_req_t* uv_overlapped_to_req(OVERLAPPED* overlapped) { - return CONTAINING_RECORD(overlapped, uv_req_t, overlapped); + return CONTAINING_RECORD(overlapped, uv_req_t, u.io.overlapped); } INLINE static void uv_insert_pending_req(uv_loop_t* loop, uv_req_t* req) { req->next_req = NULL; if (loop->pending_reqs_tail) { +#ifdef _DEBUG + /* Ensure the request is not already in the queue, or the queue + * will get corrupted. + */ + uv_req_t* current = loop->pending_reqs_tail; + do { + assert(req != current); + current = current->next_req; + } while(current != loop->pending_reqs_tail); +#endif + req->next_req = loop->pending_reqs_tail->next_req; loop->pending_reqs_tail->next_req = req; loop->pending_reqs_tail = req; diff --git a/deps/uv/src/win/stream-inl.h b/deps/uv/src/win/stream-inl.h index 97a6b90b50560a..b7a3c11958c274 100644 --- a/deps/uv/src/win/stream-inl.h +++ b/deps/uv/src/win/stream-inl.h @@ -41,7 +41,7 @@ INLINE static void uv_stream_init(uv_loop_t* loop, INLINE static void uv_connection_init(uv_stream_t* handle) { handle->flags |= UV_HANDLE_CONNECTION; - handle->write_reqs_pending = 0; + handle->stream.conn.write_reqs_pending = 0; uv_req_init(handle->loop, (uv_req_t*) &(handle->read_req)); handle->read_req.event_handle = NULL; @@ -49,7 +49,7 @@ INLINE static void uv_connection_init(uv_stream_t* handle) { handle->read_req.type = UV_READ; handle->read_req.data = handle; - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; } diff --git a/deps/uv/src/win/stream.c b/deps/uv/src/win/stream.c index 36d88d00bd9893..a2466e5e9db8ba 100644 --- a/deps/uv/src/win/stream.c +++ b/deps/uv/src/win/stream.c @@ -216,7 +216,7 @@ int uv_shutdown(uv_shutdown_t* req, uv_stream_t* handle, uv_shutdown_cb cb) { req->cb = cb; handle->flags &= ~UV_HANDLE_WRITABLE; - handle->shutdown_req = req; + handle->stream.conn.shutdown_req = req; handle->reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); diff --git a/deps/uv/src/win/tcp.c b/deps/uv/src/win/tcp.c index c5ddbed08f75ae..8b0e18c7cf3256 100644 --- a/deps/uv/src/win/tcp.c +++ b/deps/uv/src/win/tcp.c @@ -149,13 +149,13 @@ static int uv_tcp_set_socket(uv_loop_t* loop, uv_tcp_t* handle, int uv_tcp_init(uv_loop_t* loop, uv_tcp_t* handle) { uv_stream_init(loop, (uv_stream_t*) handle, UV_TCP); - handle->accept_reqs = NULL; - handle->pending_accepts = NULL; + handle->tcp.serv.accept_reqs = NULL; + handle->tcp.serv.pending_accepts = NULL; handle->socket = INVALID_SOCKET; handle->reqs_pending = 0; - handle->func_acceptex = NULL; - handle->func_connectex = NULL; - handle->processed_accepts = 0; + handle->tcp.serv.func_acceptex = NULL; + handle->tcp.conn.func_connectex = NULL; + handle->tcp.serv.processed_accepts = 0; handle->delayed_error = 0; return 0; @@ -168,10 +168,10 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { uv_tcp_accept_t* req; if (handle->flags & UV_HANDLE_CONNECTION && - handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { - UNREGISTER_HANDLE_REQ(loop, handle, handle->shutdown_req); + UNREGISTER_HANDLE_REQ(loop, handle, handle->stream.conn.shutdown_req); err = 0; if (handle->flags & UV__HANDLE_CLOSING) { @@ -180,12 +180,12 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { err = WSAGetLastError(); } - if (handle->shutdown_req->cb) { - handle->shutdown_req->cb(handle->shutdown_req, + if (handle->stream.conn.shutdown_req->cb) { + handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, uv_translate_sys_error(err)); } - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; DECREASE_PENDING_REQ_COUNT(handle); return; } @@ -200,10 +200,10 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { handle->flags |= UV_HANDLE_TCP_SOCKET_CLOSED; } - if (!(handle->flags & UV_HANDLE_CONNECTION) && handle->accept_reqs) { + if (!(handle->flags & UV_HANDLE_CONNECTION) && handle->tcp.serv.accept_reqs) { if (handle->flags & UV_HANDLE_EMULATE_IOCP) { for (i = 0; i < uv_simultaneous_server_accepts; i++) { - req = &handle->accept_reqs[i]; + req = &handle->tcp.serv.accept_reqs[i]; if (req->wait_handle != INVALID_HANDLE_VALUE) { UnregisterWait(req->wait_handle); req->wait_handle = INVALID_HANDLE_VALUE; @@ -215,8 +215,8 @@ void uv_tcp_endgame(uv_loop_t* loop, uv_tcp_t* handle) { } } - free(handle->accept_reqs); - handle->accept_reqs = NULL; + free(handle->tcp.serv.accept_reqs); + handle->tcp.serv.accept_reqs = NULL; } if (handle->flags & UV_HANDLE_CONNECTION && @@ -327,9 +327,9 @@ static void CALLBACK post_completion(void* context, BOOLEAN timed_out) { assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -346,9 +346,9 @@ static void CALLBACK post_write_completion(void* context, BOOLEAN timed_out) { assert(!timed_out); if (!PostQueuedCompletionStatus(handle->loop->iocp, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, 0, - &req->overlapped)) { + &req->u.io.overlapped)) { uv_fatal_error(GetLastError(), "PostQueuedCompletionStatus"); } } @@ -390,19 +390,19 @@ static void uv_tcp_queue_accept(uv_tcp_t* handle, uv_tcp_accept_t* req) { } /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { - req->overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); } - success = handle->func_acceptex(handle->socket, - accept_socket, - (void*)req->accept_buffer, - 0, - sizeof(struct sockaddr_storage), - sizeof(struct sockaddr_storage), - &bytes, - &req->overlapped); + success = handle->tcp.serv.func_acceptex(handle->socket, + accept_socket, + (void*)req->accept_buffer, + 0, + sizeof(struct sockaddr_storage), + sizeof(struct sockaddr_storage), + &bytes, + &req->u.io.overlapped); if (UV_SUCCEEDED_WITHOUT_IOCP(success)) { /* Process the req without IOCP. */ @@ -432,7 +432,7 @@ static void uv_tcp_queue_accept(uv_tcp_t* handle, uv_tcp_accept_t* req) { closesocket(accept_socket); /* Destroy the event handle */ if (handle->flags & UV_HANDLE_EMULATE_IOCP) { - CloseHandle(req->overlapped.hEvent); + CloseHandle(req->u.io.overlapped.hEvent); req->event_handle = NULL; } } @@ -449,7 +449,7 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { assert(!(handle->flags & UV_HANDLE_READ_PENDING)); req = &handle->read_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); /* * Preallocate a read buffer if the number of active streams is below @@ -457,13 +457,13 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { */ if (loop->active_tcp_streams < uv_active_tcp_streams_threshold) { handle->flags &= ~UV_HANDLE_ZERO_READ; - handle->alloc_cb((uv_handle_t*) handle, 65536, &handle->read_buffer); - if (handle->read_buffer.len == 0) { - handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &handle->read_buffer); + handle->alloc_cb((uv_handle_t*) handle, 65536, &handle->tcp.conn.read_buffer); + if (handle->tcp.conn.read_buffer.len == 0) { + handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, &handle->tcp.conn.read_buffer); return; } - assert(handle->read_buffer.base != NULL); - buf = handle->read_buffer; + assert(handle->tcp.conn.read_buffer.base != NULL); + buf = handle->tcp.conn.read_buffer; } else { handle->flags |= UV_HANDLE_ZERO_READ; buf.base = (char*) &uv_zero_; @@ -471,10 +471,10 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { } /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { assert(req->event_handle); - req->overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); } flags = 0; @@ -483,13 +483,13 @@ static void uv_tcp_queue_read(uv_loop_t* loop, uv_tcp_t* handle) { 1, &bytes, &flags, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Process the req without IOCP. */ handle->flags |= UV_HANDLE_READ_PENDING; - req->overlapped.InternalHigh = bytes; + req->u.io.overlapped.InternalHigh = bytes; handle->reqs_pending++; uv_insert_pending_req(loop, (uv_req_t*)req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { @@ -522,7 +522,7 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { assert(backlog > 0); if (handle->flags & UV_HANDLE_LISTENING) { - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; } if (handle->flags & UV_HANDLE_READING) { @@ -544,8 +544,8 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { return handle->delayed_error; } - if (!handle->func_acceptex) { - if (!uv_get_acceptex_function(handle->socket, &handle->func_acceptex)) { + if (!handle->tcp.serv.func_acceptex) { + if (!uv_get_acceptex_function(handle->socket, &handle->tcp.serv.func_acceptex)) { return WSAEAFNOSUPPORT; } } @@ -556,21 +556,21 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { } handle->flags |= UV_HANDLE_LISTENING; - handle->connection_cb = cb; + handle->stream.serv.connection_cb = cb; INCREASE_ACTIVE_COUNT(loop, handle); simultaneous_accepts = handle->flags & UV_HANDLE_TCP_SINGLE_ACCEPT ? 1 : uv_simultaneous_server_accepts; - if(!handle->accept_reqs) { - handle->accept_reqs = (uv_tcp_accept_t*) + if(!handle->tcp.serv.accept_reqs) { + handle->tcp.serv.accept_reqs = (uv_tcp_accept_t*) malloc(uv_simultaneous_server_accepts * sizeof(uv_tcp_accept_t)); - if (!handle->accept_reqs) { + if (!handle->tcp.serv.accept_reqs) { uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); } for (i = 0; i < simultaneous_accepts; i++) { - req = &handle->accept_reqs[i]; + req = &handle->tcp.serv.accept_reqs[i]; uv_req_init(loop, (uv_req_t*)req); req->type = UV_ACCEPT; req->accept_socket = INVALID_SOCKET; @@ -593,7 +593,7 @@ int uv_tcp_listen(uv_tcp_t* handle, int backlog, uv_connection_cb cb) { /* doesn't know how how many requests were initialized, so it will */ /* try to clean up {uv_simultaneous_server_accepts} requests. */ for (i = simultaneous_accepts; i < uv_simultaneous_server_accepts; i++) { - req = &handle->accept_reqs[i]; + req = &handle->tcp.serv.accept_reqs[i]; uv_req_init(loop, (uv_req_t*) req); req->type = UV_ACCEPT; req->accept_socket = INVALID_SOCKET; @@ -612,7 +612,7 @@ int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) { int err = 0; int family; - uv_tcp_accept_t* req = server->pending_accepts; + uv_tcp_accept_t* req = server->tcp.serv.pending_accepts; if (!req) { /* No valid connections found, so we error out. */ @@ -643,7 +643,7 @@ int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) { } /* Prepare the req to pick up a new connection */ - server->pending_accepts = req->next_pending; + server->tcp.serv.pending_accepts = req->next_pending; req->next_pending = NULL; req->accept_socket = INVALID_SOCKET; @@ -655,15 +655,15 @@ int uv_tcp_accept(uv_tcp_t* server, uv_tcp_t* client) { /* We better be switching to a single pending accept. */ assert(server->flags & UV_HANDLE_TCP_SINGLE_ACCEPT); - server->processed_accepts++; + server->tcp.serv.processed_accepts++; - if (server->processed_accepts >= uv_simultaneous_server_accepts) { - server->processed_accepts = 0; + if (server->tcp.serv.processed_accepts >= uv_simultaneous_server_accepts) { + server->tcp.serv.processed_accepts = 0; /* * All previously queued accept requests are now processed. * We now switch to queueing just a single accept. */ - uv_tcp_queue_accept(server, &server->accept_reqs[0]); + uv_tcp_queue_accept(server, &server->tcp.serv.accept_reqs[0]); server->flags &= ~UV_HANDLE_TCP_ACCEPT_STATE_CHANGING; server->flags |= UV_HANDLE_TCP_SINGLE_ACCEPT; } @@ -732,8 +732,8 @@ static int uv_tcp_try_connect(uv_connect_t* req, return handle->delayed_error; } - if (!handle->func_connectex) { - if (!uv_get_connectex_function(handle->socket, &handle->func_connectex)) { + if (!handle->tcp.conn.func_connectex) { + if (!uv_get_connectex_function(handle->socket, &handle->tcp.conn.func_connectex)) { return WSAEAFNOSUPPORT; } } @@ -742,15 +742,15 @@ static int uv_tcp_try_connect(uv_connect_t* req, req->type = UV_CONNECT; req->handle = (uv_stream_t*) handle; req->cb = cb; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); - success = handle->func_connectex(handle->socket, - addr, - addrlen, - NULL, - 0, - &bytes, - &req->overlapped); + success = handle->tcp.conn.func_connectex(handle->socket, + addr, + addrlen, + NULL, + 0, + &bytes, + &req->u.io.overlapped); if (UV_SUCCEEDED_WITHOUT_IOCP(success)) { /* Process the req without IOCP. */ @@ -828,13 +828,13 @@ int uv_tcp_write(uv_loop_t* loop, req->cb = cb; /* Prepare the overlapped structure. */ - memset(&(req->overlapped), 0, sizeof(req->overlapped)); + memset(&(req->u.io.overlapped), 0, sizeof(req->u.io.overlapped)); if (handle->flags & UV_HANDLE_EMULATE_IOCP) { req->event_handle = CreateEvent(NULL, 0, 0, NULL); if (!req->event_handle) { uv_fatal_error(GetLastError(), "CreateEvent"); } - req->overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); + req->u.io.overlapped.hEvent = (HANDLE) ((ULONG_PTR) req->event_handle | 1); req->wait_handle = INVALID_HANDLE_VALUE; } @@ -843,23 +843,23 @@ int uv_tcp_write(uv_loop_t* loop, nbufs, &bytes, 0, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); uv_insert_pending_req(loop, (uv_req_t*) req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); + req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs); handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); - handle->write_queue_size += req->queued_bytes; + handle->write_queue_size += req->u.io.queued_bytes; if (handle->flags & UV_HANDLE_EMULATE_IOCP && !RegisterWaitForSingleObject(&req->wait_handle, req->event_handle, post_write_completion, (void*) req, @@ -868,8 +868,13 @@ int uv_tcp_write(uv_loop_t* loop, uv_insert_pending_req(loop, (uv_req_t*)req); } } else { - /* Send failed due to an error. */ - return WSAGetLastError(); + /* Send failed due to an error, report it later */ + req->u.io.queued_bytes = 0; + handle->reqs_pending++; + handle->stream.conn.write_reqs_pending++; + REGISTER_HANDLE_REQ(loop, handle, req); + SET_REQ_ERROR(req, WSAGetLastError()); + uv_insert_pending_req(loop, (uv_req_t*) req); } return 0; @@ -882,7 +887,7 @@ int uv__tcp_try_write(uv_tcp_t* handle, int result; DWORD bytes; - if (handle->write_reqs_pending > 0) + if (handle->stream.conn.write_reqs_pending > 0) return UV_EAGAIN; result = WSASend(handle->socket, @@ -916,7 +921,7 @@ void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, handle->flags &= ~UV_HANDLE_READING; DECREASE_ACTIVE_COUNT(loop, handle); buf = (handle->flags & UV_HANDLE_ZERO_READ) ? - uv_buf_init(NULL, 0) : handle->read_buffer; + uv_buf_init(NULL, 0) : handle->tcp.conn.read_buffer; err = GET_REQ_SOCK_ERROR(req); @@ -934,13 +939,13 @@ void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, } else { if (!(handle->flags & UV_HANDLE_ZERO_READ)) { /* The read was done with a non-zero buffer length. */ - if (req->overlapped.InternalHigh > 0) { + if (req->u.io.overlapped.InternalHigh > 0) { /* Successful read */ handle->read_cb((uv_stream_t*)handle, - req->overlapped.InternalHigh, - &handle->read_buffer); + req->u.io.overlapped.InternalHigh, + &handle->tcp.conn.read_buffer); /* Read again only if bytes == buf.len */ - if (req->overlapped.InternalHigh < handle->read_buffer.len) { + if (req->u.io.overlapped.InternalHigh < handle->tcp.conn.read_buffer.len) { goto done; } } else { @@ -953,7 +958,7 @@ void uv_process_tcp_read_req(uv_loop_t* loop, uv_tcp_t* handle, buf.base = 0; buf.len = 0; - handle->read_cb((uv_stream_t*)handle, UV_EOF, &handle->read_buffer); + handle->read_cb((uv_stream_t*)handle, UV_EOF, &handle->tcp.conn.read_buffer); goto done; } } @@ -1032,8 +1037,8 @@ void uv_process_tcp_write_req(uv_loop_t* loop, uv_tcp_t* handle, assert(handle->type == UV_TCP); - assert(handle->write_queue_size >= req->queued_bytes); - handle->write_queue_size -= req->queued_bytes; + assert(handle->write_queue_size >= req->u.io.queued_bytes); + handle->write_queue_size -= req->u.io.queued_bytes; UNREGISTER_HANDLE_REQ(loop, handle, req); @@ -1057,9 +1062,9 @@ void uv_process_tcp_write_req(uv_loop_t* loop, uv_tcp_t* handle, req->cb(req, err); } - handle->write_reqs_pending--; - if (handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + handle->stream.conn.write_reqs_pending--; + if (handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { uv_want_endgame(loop, (uv_handle_t*)handle); } @@ -1082,10 +1087,10 @@ void uv_process_tcp_accept_req(uv_loop_t* loop, uv_tcp_t* handle, if (handle->flags & UV_HANDLE_LISTENING) { handle->flags &= ~UV_HANDLE_LISTENING; DECREASE_ACTIVE_COUNT(loop, handle); - if (handle->connection_cb) { + if (handle->stream.serv.connection_cb) { err = GET_REQ_SOCK_ERROR(req); - handle->connection_cb((uv_stream_t*)handle, - uv_translate_sys_error(err)); + handle->stream.serv.connection_cb((uv_stream_t*)handle, + uv_translate_sys_error(err)); } } } else if (REQ_SUCCESS(req) && @@ -1094,12 +1099,12 @@ void uv_process_tcp_accept_req(uv_loop_t* loop, uv_tcp_t* handle, SO_UPDATE_ACCEPT_CONTEXT, (char*)&handle->socket, sizeof(handle->socket)) == 0) { - req->next_pending = handle->pending_accepts; - handle->pending_accepts = req; + req->next_pending = handle->tcp.serv.pending_accepts; + handle->tcp.serv.pending_accepts = req; /* Accept and SO_UPDATE_ACCEPT_CONTEXT were successful. */ - if (handle->connection_cb) { - handle->connection_cb((uv_stream_t*)handle, 0); + if (handle->stream.serv.connection_cb) { + handle->stream.serv.connection_cb((uv_stream_t*)handle, 0); } } else { /* Error related to accepted socket is ignored because the server */ @@ -1357,7 +1362,7 @@ void uv_tcp_close(uv_loop_t* loop, uv_tcp_t* tcp) { } } else if ((tcp->flags & UV_HANDLE_SHARED_TCP_SOCKET) && - tcp->accept_reqs != NULL) { + tcp->tcp.serv.accept_reqs != NULL) { /* Under normal circumstances closesocket() will ensure that all pending */ /* accept reqs are canceled. However, when the socket is shared the */ /* presence of another reference to the socket in another process will */ @@ -1371,9 +1376,9 @@ void uv_tcp_close(uv_loop_t* loop, uv_tcp_t* tcp) { /* cause the connection to be aborted. */ unsigned int i; for (i = 0; i < uv_simultaneous_server_accepts; i++) { - uv_tcp_accept_t* req = &tcp->accept_reqs[i]; + uv_tcp_accept_t* req = &tcp->tcp.serv.accept_reqs[i]; if (req->accept_socket != INVALID_SOCKET && - !HasOverlappedIoCompleted(&req->overlapped)) { + !HasOverlappedIoCompleted(&req->u.io.overlapped)) { closesocket(req->accept_socket); req->accept_socket = INVALID_SOCKET; } diff --git a/deps/uv/src/win/tty.c b/deps/uv/src/win/tty.c index 603421045cac58..7b1e4ba0557fca 100644 --- a/deps/uv/src/win/tty.c +++ b/deps/uv/src/win/tty.c @@ -142,28 +142,28 @@ int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, uv_file fd, int readable) { if (readable) { /* Initialize TTY input specific fields. */ tty->flags |= UV_HANDLE_TTY_READABLE | UV_HANDLE_READABLE; - tty->read_line_handle = NULL; - tty->read_line_buffer = uv_null_buf_; - tty->read_raw_wait = NULL; + tty->tty.rd.read_line_handle = NULL; + tty->tty.rd.read_line_buffer = uv_null_buf_; + tty->tty.rd.read_raw_wait = NULL; /* Init keycode-to-vt100 mapper state. */ - tty->last_key_len = 0; - tty->last_key_offset = 0; - tty->last_utf16_high_surrogate = 0; - memset(&tty->last_input_record, 0, sizeof tty->last_input_record); + tty->tty.rd.last_key_len = 0; + tty->tty.rd.last_key_offset = 0; + tty->tty.rd.last_utf16_high_surrogate = 0; + memset(&tty->tty.rd.last_input_record, 0, sizeof tty->tty.rd.last_input_record); } else { /* TTY output specific fields. */ tty->flags |= UV_HANDLE_WRITABLE; /* Init utf8-to-utf16 conversion state. */ - tty->utf8_bytes_left = 0; - tty->utf8_codepoint = 0; + tty->tty.wr.utf8_bytes_left = 0; + tty->tty.wr.utf8_codepoint = 0; /* Initialize eol conversion state */ - tty->previous_eol = 0; + tty->tty.wr.previous_eol = 0; /* Init ANSI parser state. */ - tty->ansi_parser_state = ANSI_NORMAL; + tty->tty.wr.ansi_parser_state = ANSI_NORMAL; } return 0; @@ -268,8 +268,8 @@ static void CALLBACK uv_tty_post_raw_read(void* data, BOOLEAN didTimeout) { handle = (uv_tty_t*) req->data; loop = handle->loop; - UnregisterWait(handle->read_raw_wait); - handle->read_raw_wait = NULL; + UnregisterWait(handle->tty.rd.read_raw_wait); + handle->tty.rd.read_raw_wait = NULL; SET_REQ_SUCCESS(req); POST_COMPLETION_FOR_REQ(loop, req); @@ -285,19 +285,19 @@ static void uv_tty_queue_read_raw(uv_loop_t* loop, uv_tty_t* handle) { assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE); - handle->read_line_buffer = uv_null_buf_; + handle->tty.rd.read_line_buffer = uv_null_buf_; req = &handle->read_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); - r = RegisterWaitForSingleObject(&handle->read_raw_wait, + r = RegisterWaitForSingleObject(&handle->tty.rd.read_raw_wait, handle->handle, uv_tty_post_raw_read, (void*) req, INFINITE, WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE); if (!r) { - handle->read_raw_wait = NULL; + handle->tty.rd.read_raw_wait = NULL; SET_REQ_ERROR(req, GetLastError()); uv_insert_pending_req(loop, (uv_req_t*)req); } @@ -321,12 +321,12 @@ static DWORD CALLBACK uv_tty_line_read_thread(void* data) { handle = (uv_tty_t*) req->data; loop = handle->loop; - assert(handle->read_line_buffer.base != NULL); - assert(handle->read_line_buffer.len > 0); + assert(handle->tty.rd.read_line_buffer.base != NULL); + assert(handle->tty.rd.read_line_buffer.len > 0); /* ReadConsole can't handle big buffers. */ - if (handle->read_line_buffer.len < MAX_INPUT_BUFFER_LENGTH) { - bytes = handle->read_line_buffer.len; + if (handle->tty.rd.read_line_buffer.len < MAX_INPUT_BUFFER_LENGTH) { + bytes = handle->tty.rd.read_line_buffer.len; } else { bytes = MAX_INPUT_BUFFER_LENGTH; } @@ -335,7 +335,7 @@ static DWORD CALLBACK uv_tty_line_read_thread(void* data) { /* One utf-16 codeunit never takes more than 3 utf-8 codeunits to encode */ chars = bytes / 3; - if (ReadConsoleW(handle->read_line_handle, + if (ReadConsoleW(handle->tty.rd.read_line_handle, (void*) utf16, chars, &read_chars, @@ -344,12 +344,12 @@ static DWORD CALLBACK uv_tty_line_read_thread(void* data) { 0, utf16, read_chars, - handle->read_line_buffer.base, + handle->tty.rd.read_line_buffer.base, bytes, NULL, NULL); SET_REQ_SUCCESS(req); - req->overlapped.InternalHigh = read_bytes; + req->u.io.overlapped.InternalHigh = read_bytes; } else { SET_REQ_ERROR(req, GetLastError()); } @@ -368,30 +368,30 @@ static void uv_tty_queue_read_line(uv_loop_t* loop, uv_tty_t* handle) { assert(handle->handle && handle->handle != INVALID_HANDLE_VALUE); req = &handle->read_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); - handle->alloc_cb((uv_handle_t*) handle, 8192, &handle->read_line_buffer); - if (handle->read_line_buffer.len == 0) { + handle->alloc_cb((uv_handle_t*) handle, 8192, &handle->tty.rd.read_line_buffer); + if (handle->tty.rd.read_line_buffer.len == 0) { handle->read_cb((uv_stream_t*) handle, UV_ENOBUFS, - &handle->read_line_buffer); + &handle->tty.rd.read_line_buffer); return; } - assert(handle->read_line_buffer.base != NULL); + assert(handle->tty.rd.read_line_buffer.base != NULL); /* Duplicate the console handle, so if we want to cancel the read, we can */ /* just close this handle duplicate. */ - if (handle->read_line_handle == NULL) { + if (handle->tty.rd.read_line_handle == NULL) { HANDLE this_process = GetCurrentProcess(); r = DuplicateHandle(this_process, handle->handle, this_process, - &handle->read_line_handle, + &handle->tty.rd.read_line_handle, 0, 0, DUPLICATE_SAME_ACCESS); if (!r) { - handle->read_line_handle = NULL; + handle->tty.rd.read_line_handle = NULL; SET_REQ_ERROR(req, GetLastError()); uv_insert_pending_req(loop, (uv_req_t*)req); goto out; @@ -489,8 +489,8 @@ static const char* get_vt100_fn_key(DWORD code, char shift, char ctrl, void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, uv_req_t* req) { - /* Shortcut for handle->last_input_record.Event.KeyEvent. */ -#define KEV handle->last_input_record.Event.KeyEvent + /* Shortcut for handle->tty.rd.last_input_record.Event.KeyEvent. */ +#define KEV handle->tty.rd.last_input_record.Event.KeyEvent DWORD records_left, records_read; uv_buf_t buf; @@ -531,12 +531,12 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, buf = uv_null_buf_; buf_used = 0; - while ((records_left > 0 || handle->last_key_len > 0) && + while ((records_left > 0 || handle->tty.rd.last_key_len > 0) && (handle->flags & UV_HANDLE_READING)) { - if (handle->last_key_len == 0) { + if (handle->tty.rd.last_key_len == 0) { /* Read the next input record */ if (!ReadConsoleInputW(handle->handle, - &handle->last_input_record, + &handle->tty.rd.last_input_record, 1, &records_read)) { handle->flags &= ~UV_HANDLE_READING; @@ -551,7 +551,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, /* If the window was resized, recompute the virtual window size. This */ /* will trigger a SIGWINCH signal if the window size changed in an */ /* way that matters to libuv. */ - if (handle->last_input_record.EventType == WINDOW_BUFFER_SIZE_EVENT) { + if (handle->tty.rd.last_input_record.EventType == WINDOW_BUFFER_SIZE_EVENT) { CONSOLE_SCREEN_BUFFER_INFO info; EnterCriticalSection(&uv_tty_output_lock); @@ -567,7 +567,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, } /* Ignore other events that are not key or resize events. */ - if (handle->last_input_record.EventType != KEY_EVENT) { + if (handle->tty.rd.last_input_record.EventType != KEY_EVENT) { continue; } @@ -613,7 +613,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, if (KEV.uChar.UnicodeChar >= 0xD800 && KEV.uChar.UnicodeChar < 0xDC00) { /* UTF-16 high surrogate */ - handle->last_utf16_high_surrogate = KEV.uChar.UnicodeChar; + handle->tty.rd.last_utf16_high_surrogate = KEV.uChar.UnicodeChar; continue; } @@ -622,7 +622,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, if ((KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) && !(KEV.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) && KEV.bKeyDown) { - handle->last_key[0] = '\033'; + handle->tty.rd.last_key[0] = '\033'; prefix_len = 1; } else { prefix_len = 0; @@ -631,14 +631,14 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, if (KEV.uChar.UnicodeChar >= 0xDC00 && KEV.uChar.UnicodeChar < 0xE000) { /* UTF-16 surrogate pair */ - WCHAR utf16_buffer[2] = { handle->last_utf16_high_surrogate, + WCHAR utf16_buffer[2] = { handle->tty.rd.last_utf16_high_surrogate, KEV.uChar.UnicodeChar}; char_len = WideCharToMultiByte(CP_UTF8, 0, utf16_buffer, 2, - &handle->last_key[prefix_len], - sizeof handle->last_key, + &handle->tty.rd.last_key[prefix_len], + sizeof handle->tty.rd.last_key, NULL, NULL); } else { @@ -647,14 +647,14 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, 0, &KEV.uChar.UnicodeChar, 1, - &handle->last_key[prefix_len], - sizeof handle->last_key, + &handle->tty.rd.last_key[prefix_len], + sizeof handle->tty.rd.last_key, NULL, NULL); } /* Whatever happened, the last character wasn't a high surrogate. */ - handle->last_utf16_high_surrogate = 0; + handle->tty.rd.last_utf16_high_surrogate = 0; /* If the utf16 character(s) couldn't be converted something must */ /* be wrong. */ @@ -667,8 +667,8 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, goto out; } - handle->last_key_len = (unsigned char) (prefix_len + char_len); - handle->last_key_offset = 0; + handle->tty.rd.last_key_len = (unsigned char) (prefix_len + char_len); + handle->tty.rd.last_key_offset = 0; continue; } else { @@ -690,23 +690,23 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, /* Prefix with \x033 when the alt key was held. */ if (KEV.dwControlKeyState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) { - handle->last_key[0] = '\033'; + handle->tty.rd.last_key[0] = '\033'; prefix_len = 1; } else { prefix_len = 0; } /* Copy the vt100 sequence to the handle buffer. */ - assert(prefix_len + vt100_len < sizeof handle->last_key); - memcpy(&handle->last_key[prefix_len], vt100, vt100_len); + assert(prefix_len + vt100_len < sizeof handle->tty.rd.last_key); + memcpy(&handle->tty.rd.last_key[prefix_len], vt100, vt100_len); - handle->last_key_len = (unsigned char) (prefix_len + vt100_len); - handle->last_key_offset = 0; + handle->tty.rd.last_key_len = (unsigned char) (prefix_len + vt100_len); + handle->tty.rd.last_key_offset = 0; continue; } } else { /* Copy any bytes left from the last keypress to the user buffer. */ - if (handle->last_key_offset < handle->last_key_len) { + if (handle->tty.rd.last_key_offset < handle->tty.rd.last_key_len) { /* Allocate a buffer if needed */ if (buf_used == 0) { handle->alloc_cb((uv_handle_t*) handle, 1024, &buf); @@ -717,7 +717,7 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, assert(buf.base != NULL); } - buf.base[buf_used++] = handle->last_key[handle->last_key_offset++]; + buf.base[buf_used++] = handle->tty.rd.last_key[handle->tty.rd.last_key_offset++]; /* If the buffer is full, emit it */ if ((size_t) buf_used == buf.len) { @@ -731,11 +731,11 @@ void uv_process_tty_read_raw_req(uv_loop_t* loop, uv_tty_t* handle, /* Apply dwRepeat from the last input record. */ if (--KEV.wRepeatCount > 0) { - handle->last_key_offset = 0; + handle->tty.rd.last_key_offset = 0; continue; } - handle->last_key_len = 0; + handle->tty.rd.last_key_len = 0; continue; } } @@ -766,15 +766,15 @@ void uv_process_tty_read_line_req(uv_loop_t* loop, uv_tty_t* handle, assert(handle->type == UV_TTY); assert(handle->flags & UV_HANDLE_TTY_READABLE); - buf = handle->read_line_buffer; + buf = handle->tty.rd.read_line_buffer; handle->flags &= ~UV_HANDLE_READ_PENDING; - handle->read_line_buffer = uv_null_buf_; + handle->tty.rd.read_line_buffer = uv_null_buf_; if (!REQ_SUCCESS(req)) { /* Read was not successful */ if ((handle->flags & UV_HANDLE_READING) && - handle->read_line_handle != NULL) { + handle->tty.rd.read_line_handle != NULL) { /* Real error */ handle->flags &= ~UV_HANDLE_READING; DECREASE_ACTIVE_COUNT(loop, handle); @@ -789,7 +789,7 @@ void uv_process_tty_read_line_req(uv_loop_t* loop, uv_tty_t* handle, } else { /* Read successful */ /* TODO: read unicode, convert to utf-8 */ - DWORD bytes = req->overlapped.InternalHigh; + DWORD bytes = req->u.io.overlapped.InternalHigh; handle->read_cb((uv_stream_t*) handle, bytes, &buf); } @@ -811,7 +811,7 @@ void uv_process_tty_read_req(uv_loop_t* loop, uv_tty_t* handle, /* If the read_line_buffer member is zero, it must have been an raw read. */ /* Otherwise it was a line-buffered read. */ /* FIXME: This is quite obscure. Use a flag or something. */ - if (handle->read_line_buffer.len == 0) { + if (handle->tty.rd.read_line_buffer.len == 0) { uv_process_tty_read_raw_req(loop, handle, req); } else { uv_process_tty_read_line_req(loop, handle, req); @@ -840,7 +840,7 @@ int uv_tty_read_start(uv_tty_t* handle, uv_alloc_cb alloc_cb, /* Maybe the user stopped reading half-way while processing key events. */ /* Short-circuit if this could be the case. */ - if (handle->last_key_len > 0) { + if (handle->tty.rd.last_key_len > 0) { SET_REQ_SUCCESS(&handle->read_req); uv_insert_pending_req(handle->loop, (uv_req_t*) &handle->read_req); return 0; @@ -869,10 +869,10 @@ int uv_tty_read_stop(uv_tty_t* handle) { } /* Cancel line-buffered read */ - if (handle->read_line_handle != NULL) { + if (handle->tty.rd.read_line_handle != NULL) { /* Closing this handle will cancel the ReadConsole operation */ - CloseHandle(handle->read_line_handle); - handle->read_line_handle = NULL; + CloseHandle(handle->tty.rd.read_line_handle); + handle->tty.rd.read_line_handle = NULL; } @@ -1149,8 +1149,8 @@ static int uv_tty_clear(uv_tty_t* handle, int dir, char entire_screen, } while (0) static int uv_tty_set_style(uv_tty_t* handle, DWORD* error) { - unsigned short argc = handle->ansi_csi_argc; - unsigned short* argv = handle->ansi_csi_argv; + unsigned short argc = handle->tty.wr.ansi_csi_argc; + unsigned short* argv = handle->tty.wr.ansi_csi_argv; int i; CONSOLE_SCREEN_BUFFER_INFO info; @@ -1319,12 +1319,12 @@ static int uv_tty_save_state(uv_tty_t* handle, unsigned char save_attributes, uv_tty_update_virtual_window(&info); - handle->saved_position.X = info.dwCursorPosition.X; - handle->saved_position.Y = info.dwCursorPosition.Y - uv_tty_virtual_offset; + handle->tty.wr.saved_position.X = info.dwCursorPosition.X; + handle->tty.wr.saved_position.Y = info.dwCursorPosition.Y - uv_tty_virtual_offset; handle->flags |= UV_HANDLE_TTY_SAVED_POSITION; if (save_attributes) { - handle->saved_attributes = info.wAttributes & + handle->tty.wr.saved_attributes = info.wAttributes & (FOREGROUND_INTENSITY | BACKGROUND_INTENSITY); handle->flags |= UV_HANDLE_TTY_SAVED_ATTRIBUTES; } @@ -1344,9 +1344,9 @@ static int uv_tty_restore_state(uv_tty_t* handle, if (handle->flags & UV_HANDLE_TTY_SAVED_POSITION) { if (uv_tty_move_caret(handle, - handle->saved_position.X, + handle->tty.wr.saved_position.X, 0, - handle->saved_position.Y, + handle->tty.wr.saved_position.Y, 0, error) != 0) { return -1; @@ -1362,7 +1362,7 @@ static int uv_tty_restore_state(uv_tty_t* handle, new_attributes = info.wAttributes; new_attributes &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY); - new_attributes |= handle->saved_attributes; + new_attributes |= handle->tty.wr.saved_attributes; if (!SetConsoleTextAttribute(handle->handle, new_attributes)) { *error = GetLastError(); @@ -1412,10 +1412,10 @@ static int uv_tty_write_bufs(uv_tty_t* handle, } while (0) /* Cache for fast access */ - unsigned char utf8_bytes_left = handle->utf8_bytes_left; - unsigned int utf8_codepoint = handle->utf8_codepoint; - unsigned char previous_eol = handle->previous_eol; - unsigned char ansi_parser_state = handle->ansi_parser_state; + unsigned char utf8_bytes_left = handle->tty.wr.utf8_bytes_left; + unsigned int utf8_codepoint = handle->tty.wr.utf8_codepoint; + unsigned char previous_eol = handle->tty.wr.previous_eol; + unsigned char ansi_parser_state = handle->tty.wr.ansi_parser_state; /* Store the error here. If we encounter an error, stop trying to do i/o */ /* but keep parsing the buffer so we leave the parser in a consistent */ @@ -1492,7 +1492,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 0233: ansi_parser_state = ANSI_CSI; - handle->ansi_csi_argc = 0; + handle->tty.wr.ansi_csi_argc = 0; continue; } @@ -1500,7 +1500,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, switch (utf8_codepoint) { case '[': ansi_parser_state = ANSI_CSI; - handle->ansi_csi_argc = 0; + handle->tty.wr.ansi_csi_argc = 0; continue; case '^': @@ -1557,20 +1557,20 @@ static int uv_tty_write_bufs(uv_tty_t* handle, /* We were not currently parsing a number */ /* Check for too many arguments */ - if (handle->ansi_csi_argc >= ARRAY_SIZE(handle->ansi_csi_argv)) { + if (handle->tty.wr.ansi_csi_argc >= ARRAY_SIZE(handle->tty.wr.ansi_csi_argv)) { ansi_parser_state |= ANSI_IGNORE; continue; } ansi_parser_state |= ANSI_IN_ARG; - handle->ansi_csi_argc++; - handle->ansi_csi_argv[handle->ansi_csi_argc - 1] = + handle->tty.wr.ansi_csi_argc++; + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = (unsigned short) utf8_codepoint - '0'; continue; } else { /* We were already parsing a number. Parse next digit. */ uint32_t value = 10 * - handle->ansi_csi_argv[handle->ansi_csi_argc - 1]; + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1]; /* Check for overflow. */ if (value > UINT16_MAX) { @@ -1578,7 +1578,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, continue; } - handle->ansi_csi_argv[handle->ansi_csi_argc - 1] = + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = (unsigned short) value + (utf8_codepoint - '0'); continue; } @@ -1593,25 +1593,25 @@ static int uv_tty_write_bufs(uv_tty_t* handle, /* If ANSI_IN_ARG is not set, add another argument and */ /* default it to 0. */ /* Check for too many arguments */ - if (handle->ansi_csi_argc >= ARRAY_SIZE(handle->ansi_csi_argv)) { + if (handle->tty.wr.ansi_csi_argc >= ARRAY_SIZE(handle->tty.wr.ansi_csi_argv)) { ansi_parser_state |= ANSI_IGNORE; continue; } - handle->ansi_csi_argc++; - handle->ansi_csi_argv[handle->ansi_csi_argc - 1] = 0; + handle->tty.wr.ansi_csi_argc++; + handle->tty.wr.ansi_csi_argv[handle->tty.wr.ansi_csi_argc - 1] = 0; continue; } } else if (utf8_codepoint == '?' && !(ansi_parser_state & ANSI_IN_ARG) && - handle->ansi_csi_argc == 0) { + handle->tty.wr.ansi_csi_argc == 0) { /* Ignores '?' if it is the first character after CSI[ */ /* This is an extension character from the VT100 codeset */ /* that is supported and used by most ANSI terminals today. */ continue; } else if (utf8_codepoint >= '@' && utf8_codepoint <= '~' && - (handle->ansi_csi_argc > 0 || utf8_codepoint != '[')) { + (handle->tty.wr.ansi_csi_argc > 0 || utf8_codepoint != '[')) { int x, y, d; /* Command byte */ @@ -1619,50 +1619,50 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'A': /* cursor up */ FLUSH_TEXT(); - y = -(handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1); + y = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1); uv_tty_move_caret(handle, 0, 1, y, 1, error); break; case 'B': /* cursor down */ FLUSH_TEXT(); - y = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1; + y = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1; uv_tty_move_caret(handle, 0, 1, y, 1, error); break; case 'C': /* cursor forward */ FLUSH_TEXT(); - x = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1; + x = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1; uv_tty_move_caret(handle, x, 1, 0, 1, error); break; case 'D': /* cursor back */ FLUSH_TEXT(); - x = -(handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1); + x = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1); uv_tty_move_caret(handle, x, 1, 0, 1, error); break; case 'E': /* cursor next line */ FLUSH_TEXT(); - y = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1; + y = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1; uv_tty_move_caret(handle, 0, 0, y, 1, error); break; case 'F': /* cursor previous line */ FLUSH_TEXT(); - y = -(handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 1); + y = -(handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 1); uv_tty_move_caret(handle, 0, 0, y, 1, error); break; case 'G': /* cursor horizontal move absolute */ FLUSH_TEXT(); - x = (handle->ansi_csi_argc >= 1 && handle->ansi_csi_argv[0]) - ? handle->ansi_csi_argv[0] - 1 : 0; + x = (handle->tty.wr.ansi_csi_argc >= 1 && handle->tty.wr.ansi_csi_argv[0]) + ? handle->tty.wr.ansi_csi_argv[0] - 1 : 0; uv_tty_move_caret(handle, x, 0, 0, 1, error); break; @@ -1670,17 +1670,17 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'f': /* cursor move absolute */ FLUSH_TEXT(); - y = (handle->ansi_csi_argc >= 1 && handle->ansi_csi_argv[0]) - ? handle->ansi_csi_argv[0] - 1 : 0; - x = (handle->ansi_csi_argc >= 2 && handle->ansi_csi_argv[1]) - ? handle->ansi_csi_argv[1] - 1 : 0; + y = (handle->tty.wr.ansi_csi_argc >= 1 && handle->tty.wr.ansi_csi_argv[0]) + ? handle->tty.wr.ansi_csi_argv[0] - 1 : 0; + x = (handle->tty.wr.ansi_csi_argc >= 2 && handle->tty.wr.ansi_csi_argv[1]) + ? handle->tty.wr.ansi_csi_argv[1] - 1 : 0; uv_tty_move_caret(handle, x, 0, y, 0, error); break; case 'J': /* Erase screen */ FLUSH_TEXT(); - d = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 0; + d = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 0; if (d >= 0 && d <= 2) { uv_tty_clear(handle, d, 1, error); } @@ -1689,7 +1689,7 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'K': /* Erase line */ FLUSH_TEXT(); - d = handle->ansi_csi_argc ? handle->ansi_csi_argv[0] : 0; + d = handle->tty.wr.ansi_csi_argc ? handle->tty.wr.ansi_csi_argv[0] : 0; if (d >= 0 && d <= 2) { uv_tty_clear(handle, d, 0, error); } @@ -1715,8 +1715,8 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'l': /* Hide the cursor */ - if (handle->ansi_csi_argc == 1 && - handle->ansi_csi_argv[0] == 25) { + if (handle->tty.wr.ansi_csi_argc == 1 && + handle->tty.wr.ansi_csi_argv[0] == 25) { FLUSH_TEXT(); uv_tty_set_cursor_visibility(handle, 0, error); } @@ -1724,8 +1724,8 @@ static int uv_tty_write_bufs(uv_tty_t* handle, case 'h': /* Show the cursor */ - if (handle->ansi_csi_argc == 1 && - handle->ansi_csi_argv[0] == 25) { + if (handle->tty.wr.ansi_csi_argc == 1 && + handle->tty.wr.ansi_csi_argv[0] == 25) { FLUSH_TEXT(); uv_tty_set_cursor_visibility(handle, 1, error); } @@ -1830,10 +1830,10 @@ static int uv_tty_write_bufs(uv_tty_t* handle, FLUSH_TEXT(); /* Copy cached values back to struct. */ - handle->utf8_bytes_left = utf8_bytes_left; - handle->utf8_codepoint = utf8_codepoint; - handle->previous_eol = previous_eol; - handle->ansi_parser_state = ansi_parser_state; + handle->tty.wr.utf8_bytes_left = utf8_bytes_left; + handle->tty.wr.utf8_codepoint = utf8_codepoint; + handle->tty.wr.previous_eol = previous_eol; + handle->tty.wr.ansi_parser_state = ansi_parser_state; LeaveCriticalSection(&uv_tty_output_lock); @@ -1861,10 +1861,10 @@ int uv_tty_write(uv_loop_t* loop, req->cb = cb; handle->reqs_pending++; - handle->write_reqs_pending++; + handle->stream.conn.write_reqs_pending++; REGISTER_HANDLE_REQ(loop, handle, req); - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; if (!uv_tty_write_bufs(handle, bufs, nbufs, &error)) { SET_REQ_SUCCESS(req); @@ -1883,7 +1883,7 @@ int uv__tty_try_write(uv_tty_t* handle, unsigned int nbufs) { DWORD error; - if (handle->write_reqs_pending > 0) + if (handle->stream.conn.write_reqs_pending > 0) return UV_EAGAIN; if (uv_tty_write_bufs(handle, bufs, nbufs, &error)) @@ -1897,7 +1897,7 @@ void uv_process_tty_write_req(uv_loop_t* loop, uv_tty_t* handle, uv_write_t* req) { int err; - handle->write_queue_size -= req->queued_bytes; + handle->write_queue_size -= req->u.io.queued_bytes; UNREGISTER_HANDLE_REQ(loop, handle, req); if (req->cb) { @@ -1905,9 +1905,9 @@ void uv_process_tty_write_req(uv_loop_t* loop, uv_tty_t* handle, req->cb(req, uv_translate_sys_error(err)); } - handle->write_reqs_pending--; - if (handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { + handle->stream.conn.write_reqs_pending--; + if (handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { uv_want_endgame(loop, (uv_handle_t*)handle); } @@ -1933,20 +1933,20 @@ void uv_tty_close(uv_tty_t* handle) { void uv_tty_endgame(uv_loop_t* loop, uv_tty_t* handle) { if (!(handle->flags & UV_HANDLE_TTY_READABLE) && - handle->shutdown_req != NULL && - handle->write_reqs_pending == 0) { - UNREGISTER_HANDLE_REQ(loop, handle, handle->shutdown_req); + handle->stream.conn.shutdown_req != NULL && + handle->stream.conn.write_reqs_pending == 0) { + UNREGISTER_HANDLE_REQ(loop, handle, handle->stream.conn.shutdown_req); /* TTY shutdown is really just a no-op */ - if (handle->shutdown_req->cb) { + if (handle->stream.conn.shutdown_req->cb) { if (handle->flags & UV__HANDLE_CLOSING) { - handle->shutdown_req->cb(handle->shutdown_req, UV_ECANCELED); + handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, UV_ECANCELED); } else { - handle->shutdown_req->cb(handle->shutdown_req, 0); + handle->stream.conn.shutdown_req->cb(handle->stream.conn.shutdown_req, 0); } } - handle->shutdown_req = NULL; + handle->stream.conn.shutdown_req = NULL; DECREASE_PENDING_REQ_COUNT(handle); return; @@ -1957,12 +1957,12 @@ void uv_tty_endgame(uv_loop_t* loop, uv_tty_t* handle) { /* The console handle duplicate used for line reading should be destroyed */ /* by uv_tty_read_stop. */ assert(!(handle->flags & UV_HANDLE_TTY_READABLE) || - handle->read_line_handle == NULL); + handle->tty.rd.read_line_handle == NULL); /* The wait handle used for raw reading should be unregistered when the */ /* wait callback runs. */ assert(!(handle->flags & UV_HANDLE_TTY_READABLE) || - handle->read_raw_wait == NULL); + handle->tty.rd.read_raw_wait == NULL); assert(!(handle->flags & UV_HANDLE_CLOSED)); uv__handle_close(handle); diff --git a/deps/uv/src/win/udp.c b/deps/uv/src/win/udp.c index 73b5bd5e467b40..197e5d828f2ad4 100644 --- a/deps/uv/src/win/udp.c +++ b/deps/uv/src/win/udp.c @@ -244,7 +244,7 @@ static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) { assert(!(handle->flags & UV_HANDLE_READ_PENDING)); req = &handle->recv_req; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); /* * Preallocate a read buffer if the number of active streams is below @@ -272,13 +272,13 @@ static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) { &flags, (struct sockaddr*) &handle->recv_from, &handle->recv_from_len, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Process the req without IOCP. */ handle->flags |= UV_HANDLE_READ_PENDING; - req->overlapped.InternalHigh = bytes; + req->u.io.overlapped.InternalHigh = bytes; handle->reqs_pending++; uv_insert_pending_req(loop, req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { @@ -304,13 +304,13 @@ static void uv_udp_queue_recv(uv_loop_t* loop, uv_udp_t* handle) { 1, &bytes, &flags, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Process the req without IOCP. */ handle->flags |= UV_HANDLE_READ_PENDING; - req->overlapped.InternalHigh = bytes; + req->u.io.overlapped.InternalHigh = bytes; handle->reqs_pending++; uv_insert_pending_req(loop, req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { @@ -384,7 +384,7 @@ static int uv__send(uv_udp_send_t* req, req->type = UV_UDP_SEND; req->handle = handle; req->cb = cb; - memset(&req->overlapped, 0, sizeof(req->overlapped)); + memset(&req->u.io.overlapped, 0, sizeof(req->u.io.overlapped)); result = WSASendTo(handle->socket, (WSABUF*)bufs, @@ -393,22 +393,22 @@ static int uv__send(uv_udp_send_t* req, 0, addr, addrlen, - &req->overlapped, + &req->u.io.overlapped, NULL); if (UV_SUCCEEDED_WITHOUT_IOCP(result == 0)) { /* Request completed immediately. */ - req->queued_bytes = 0; + req->u.io.queued_bytes = 0; handle->reqs_pending++; - handle->send_queue_size += req->queued_bytes; + handle->send_queue_size += req->u.io.queued_bytes; handle->send_queue_count++; REGISTER_HANDLE_REQ(loop, handle, req); uv_insert_pending_req(loop, (uv_req_t*)req); } else if (UV_SUCCEEDED_WITH_IOCP(result == 0)) { /* Request queued by the kernel. */ - req->queued_bytes = uv__count_bufs(bufs, nbufs); + req->u.io.queued_bytes = uv__count_bufs(bufs, nbufs); handle->reqs_pending++; - handle->send_queue_size += req->queued_bytes; + handle->send_queue_size += req->u.io.queued_bytes; handle->send_queue_count++; REGISTER_HANDLE_REQ(loop, handle, req); } else { @@ -459,7 +459,7 @@ void uv_process_udp_recv_req(uv_loop_t* loop, uv_udp_t* handle, /* Successful read */ partial = !REQ_SUCCESS(req); handle->recv_cb(handle, - req->overlapped.InternalHigh, + req->u.io.overlapped.InternalHigh, &handle->recv_buffer, (const struct sockaddr*) &handle->recv_from, partial ? UV_UDP_PARTIAL : 0); @@ -536,9 +536,9 @@ void uv_process_udp_send_req(uv_loop_t* loop, uv_udp_t* handle, assert(handle->type == UV_UDP); - assert(handle->send_queue_size >= req->queued_bytes); + assert(handle->send_queue_size >= req->u.io.queued_bytes); assert(handle->send_queue_count >= 1); - handle->send_queue_size -= req->queued_bytes; + handle->send_queue_size -= req->u.io.queued_bytes; handle->send_queue_count--; UNREGISTER_HANDLE_REQ(loop, handle, req); diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c index 43d843ff5c42b5..3697d5aa6aaf20 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -535,14 +534,14 @@ int uv_uptime(double* uptime) { return uv_translate_sys_error(result); } - free(malloced_buffer); - buffer_size *= 2; /* Don't let the buffer grow infinitely. */ if (buffer_size > 1 << 20) { goto internalError; } + free(malloced_buffer); + buffer = malloced_buffer = (BYTE*) malloc(buffer_size); if (malloced_buffer == NULL) { *uptime = 0; diff --git a/deps/uv/test/benchmark-getaddrinfo.c b/deps/uv/test/benchmark-getaddrinfo.c index c7f99a2fcb8720..1dbc23ddba009d 100644 --- a/deps/uv/test/benchmark-getaddrinfo.c +++ b/deps/uv/test/benchmark-getaddrinfo.c @@ -83,8 +83,9 @@ BENCHMARK_IMPL(getaddrinfo) { ASSERT(calls_initiated == TOTAL_CALLS); ASSERT(calls_completed == TOTAL_CALLS); - LOGF("getaddrinfo: %.0f req/s\n", - (double) calls_completed / (double) (end_time - start_time) * 1000.0); + fprintf(stderr, "getaddrinfo: %.0f req/s\n", + (double) calls_completed / (double) (end_time - start_time) * 1000.0); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-loop-count.c b/deps/uv/test/benchmark-loop-count.c index 5cb813238d4f75..970a94c2fecb5c 100644 --- a/deps/uv/test/benchmark-loop-count.c +++ b/deps/uv/test/benchmark-loop-count.c @@ -62,10 +62,11 @@ BENCHMARK_IMPL(loop_count) { ASSERT(ticks == NUM_TICKS); - LOGF("loop_count: %d ticks in %.2fs (%.0f/s)\n", - NUM_TICKS, - ns / 1e9, - NUM_TICKS / (ns / 1e9)); + fprintf(stderr, "loop_count: %d ticks in %.2fs (%.0f/s)\n", + NUM_TICKS, + ns / 1e9, + NUM_TICKS / (ns / 1e9)); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; @@ -83,7 +84,8 @@ BENCHMARK_IMPL(loop_count_timed) { uv_run(loop, UV_RUN_DEFAULT); - LOGF("loop_count: %lu ticks (%.0f ticks/s)\n", ticks, ticks / 5.0); + fprintf(stderr, "loop_count: %lu ticks (%.0f ticks/s)\n", ticks, ticks / 5.0); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-million-timers.c b/deps/uv/test/benchmark-million-timers.c index 6027d6088aa789..60a308bef13d40 100644 --- a/deps/uv/test/benchmark-million-timers.c +++ b/deps/uv/test/benchmark-million-timers.c @@ -75,10 +75,11 @@ BENCHMARK_IMPL(million_timers) { ASSERT(close_cb_called == NUM_TIMERS); free(timers); - LOGF("%.2f seconds total\n", (after_all - before_all) / 1e9); - LOGF("%.2f seconds init\n", (before_run - before_all) / 1e9); - LOGF("%.2f seconds dispatch\n", (after_run - before_run) / 1e9); - LOGF("%.2f seconds cleanup\n", (after_all - after_run) / 1e9); + fprintf(stderr, "%.2f seconds total\n", (after_all - before_all) / 1e9); + fprintf(stderr, "%.2f seconds init\n", (before_run - before_all) / 1e9); + fprintf(stderr, "%.2f seconds dispatch\n", (after_run - before_run) / 1e9); + fprintf(stderr, "%.2f seconds cleanup\n", (after_all - after_run) / 1e9); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-ping-pongs.c b/deps/uv/test/benchmark-ping-pongs.c index bb560d7d21fd6b..646a7df9447036 100644 --- a/deps/uv/test/benchmark-ping-pongs.c +++ b/deps/uv/test/benchmark-ping-pongs.c @@ -80,7 +80,8 @@ static void pinger_close_cb(uv_handle_t* handle) { pinger_t* pinger; pinger = (pinger_t*)handle->data; - LOGF("ping_pongs: %d roundtrips/s\n", (1000 * pinger->pongs) / TIME); + fprintf(stderr, "ping_pongs: %d roundtrips/s\n", (1000 * pinger->pongs) / TIME); + fflush(stderr); free(pinger); diff --git a/deps/uv/test/benchmark-pound.c b/deps/uv/test/benchmark-pound.c index 587928549eac8a..79f36345037cd4 100644 --- a/deps/uv/test/benchmark-pound.c +++ b/deps/uv/test/benchmark-pound.c @@ -299,11 +299,12 @@ static int pound_it(int concurrency, /* Number of fractional seconds it took to run the benchmark. */ secs = (double)(end_time - start_time) / NANOSEC; - LOGF("%s-conn-pound-%d: %.0f accepts/s (%d failed)\n", - type, - concurrency, - closed_streams / secs, - conns_failed); + fprintf(stderr, "%s-conn-pound-%d: %.0f accepts/s (%d failed)\n", + type, + concurrency, + closed_streams / secs, + conns_failed); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/benchmark-pump.c b/deps/uv/test/benchmark-pump.c index d58f46a384b899..88f2dc5c658e27 100644 --- a/deps/uv/test/benchmark-pump.c +++ b/deps/uv/test/benchmark-pump.c @@ -90,9 +90,10 @@ static void show_stats(uv_timer_t* handle) { int i; #if PRINT_STATS - LOGF("connections: %d, write: %.1f gbit/s\n", - write_sockets, - gbit(nsent, STATS_INTERVAL)); + fprintf(stderr, "connections: %d, write: %.1f gbit/s\n", + write_sockets, + gbit(nsent, STATS_INTERVAL)); + fflush(stderr); #endif /* Exit if the show is over */ @@ -101,10 +102,11 @@ static void show_stats(uv_timer_t* handle) { uv_update_time(loop); diff = uv_now(loop) - start_time; - LOGF("%s_pump%d_client: %.1f gbit/s\n", - type == TCP ? "tcp" : "pipe", - write_sockets, - gbit(nsent_total, diff)); + fprintf(stderr, "%s_pump%d_client: %.1f gbit/s\n", + type == TCP ? "tcp" : "pipe", + write_sockets, + gbit(nsent_total, diff)); + fflush(stderr); for (i = 0; i < write_sockets; i++) { if (type == TCP) @@ -128,10 +130,11 @@ static void read_show_stats(void) { uv_update_time(loop); diff = uv_now(loop) - start_time; - LOGF("%s_pump%d_server: %.1f gbit/s\n", - type == TCP ? "tcp" : "pipe", - max_read_sockets, - gbit(nrecv_total, diff)); + fprintf(stderr, "%s_pump%d_server: %.1f gbit/s\n", + type == TCP ? "tcp" : "pipe", + max_read_sockets, + gbit(nrecv_total, diff)); + fflush(stderr); } @@ -213,7 +216,10 @@ static void do_write(uv_stream_t* stream) { static void connect_cb(uv_connect_t* req, int status) { int i; - if (status) LOG(uv_strerror(status)); + if (status) { + fprintf(stderr, "%s", uv_strerror(status)); + fflush(stderr); + } ASSERT(status == 0); write_sockets++; diff --git a/deps/uv/test/benchmark-sizes.c b/deps/uv/test/benchmark-sizes.c index 8ccf10ee475fb1..9bf42f91537d58 100644 --- a/deps/uv/test/benchmark-sizes.c +++ b/deps/uv/test/benchmark-sizes.c @@ -24,22 +24,23 @@ BENCHMARK_IMPL(sizes) { - LOGF("uv_shutdown_t: %u bytes\n", (unsigned int) sizeof(uv_shutdown_t)); - LOGF("uv_write_t: %u bytes\n", (unsigned int) sizeof(uv_write_t)); - LOGF("uv_connect_t: %u bytes\n", (unsigned int) sizeof(uv_connect_t)); - LOGF("uv_udp_send_t: %u bytes\n", (unsigned int) sizeof(uv_udp_send_t)); - LOGF("uv_tcp_t: %u bytes\n", (unsigned int) sizeof(uv_tcp_t)); - LOGF("uv_pipe_t: %u bytes\n", (unsigned int) sizeof(uv_pipe_t)); - LOGF("uv_tty_t: %u bytes\n", (unsigned int) sizeof(uv_tty_t)); - LOGF("uv_prepare_t: %u bytes\n", (unsigned int) sizeof(uv_prepare_t)); - LOGF("uv_check_t: %u bytes\n", (unsigned int) sizeof(uv_check_t)); - LOGF("uv_idle_t: %u bytes\n", (unsigned int) sizeof(uv_idle_t)); - LOGF("uv_async_t: %u bytes\n", (unsigned int) sizeof(uv_async_t)); - LOGF("uv_timer_t: %u bytes\n", (unsigned int) sizeof(uv_timer_t)); - LOGF("uv_fs_poll_t: %u bytes\n", (unsigned int) sizeof(uv_fs_poll_t)); - LOGF("uv_fs_event_t: %u bytes\n", (unsigned int) sizeof(uv_fs_event_t)); - LOGF("uv_process_t: %u bytes\n", (unsigned int) sizeof(uv_process_t)); - LOGF("uv_poll_t: %u bytes\n", (unsigned int) sizeof(uv_poll_t)); - LOGF("uv_loop_t: %u bytes\n", (unsigned int) sizeof(uv_loop_t)); + fprintf(stderr, "uv_shutdown_t: %u bytes\n", (unsigned int) sizeof(uv_shutdown_t)); + fprintf(stderr, "uv_write_t: %u bytes\n", (unsigned int) sizeof(uv_write_t)); + fprintf(stderr, "uv_connect_t: %u bytes\n", (unsigned int) sizeof(uv_connect_t)); + fprintf(stderr, "uv_udp_send_t: %u bytes\n", (unsigned int) sizeof(uv_udp_send_t)); + fprintf(stderr, "uv_tcp_t: %u bytes\n", (unsigned int) sizeof(uv_tcp_t)); + fprintf(stderr, "uv_pipe_t: %u bytes\n", (unsigned int) sizeof(uv_pipe_t)); + fprintf(stderr, "uv_tty_t: %u bytes\n", (unsigned int) sizeof(uv_tty_t)); + fprintf(stderr, "uv_prepare_t: %u bytes\n", (unsigned int) sizeof(uv_prepare_t)); + fprintf(stderr, "uv_check_t: %u bytes\n", (unsigned int) sizeof(uv_check_t)); + fprintf(stderr, "uv_idle_t: %u bytes\n", (unsigned int) sizeof(uv_idle_t)); + fprintf(stderr, "uv_async_t: %u bytes\n", (unsigned int) sizeof(uv_async_t)); + fprintf(stderr, "uv_timer_t: %u bytes\n", (unsigned int) sizeof(uv_timer_t)); + fprintf(stderr, "uv_fs_poll_t: %u bytes\n", (unsigned int) sizeof(uv_fs_poll_t)); + fprintf(stderr, "uv_fs_event_t: %u bytes\n", (unsigned int) sizeof(uv_fs_event_t)); + fprintf(stderr, "uv_process_t: %u bytes\n", (unsigned int) sizeof(uv_process_t)); + fprintf(stderr, "uv_poll_t: %u bytes\n", (unsigned int) sizeof(uv_poll_t)); + fprintf(stderr, "uv_loop_t: %u bytes\n", (unsigned int) sizeof(uv_loop_t)); + fflush(stderr); return 0; } diff --git a/deps/uv/test/benchmark-spawn.c b/deps/uv/test/benchmark-spawn.c index 9cae41a83afd61..ed9ad608f3790e 100644 --- a/deps/uv/test/benchmark-spawn.c +++ b/deps/uv/test/benchmark-spawn.c @@ -155,8 +155,9 @@ BENCHMARK_IMPL(spawn) { uv_update_time(loop); end_time = uv_now(loop); - LOGF("spawn: %.0f spawns/s\n", - (double) N / (double) (end_time - start_time) * 1000.0); + fprintf(stderr, "spawn: %.0f spawns/s\n", + (double) N / (double) (end_time - start_time) * 1000.0); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/run-benchmarks.c b/deps/uv/test/run-benchmarks.c index 8d4f549799e8b3..6e42623d54cdec 100644 --- a/deps/uv/test/run-benchmarks.c +++ b/deps/uv/test/run-benchmarks.c @@ -41,7 +41,8 @@ int main(int argc, char **argv) { case 2: return maybe_run_test(argc, argv); case 3: return run_test_part(argv[1], argv[2]); default: - LOGF("Too many arguments.\n"); + fprintf(stderr, "Too many arguments.\n"); + fflush(stderr); return EXIT_FAILURE; } diff --git a/deps/uv/test/run-tests.c b/deps/uv/test/run-tests.c index e92c93008e72ef..1f458745327398 100644 --- a/deps/uv/test/run-tests.c +++ b/deps/uv/test/run-tests.c @@ -56,7 +56,8 @@ int main(int argc, char **argv) { case 2: return maybe_run_test(argc, argv); case 3: return run_test_part(argv[1], argv[2]); default: - LOGF("Too many arguments.\n"); + fprintf(stderr, "Too many arguments.\n"); + fflush(stderr); return EXIT_FAILURE; } diff --git a/deps/uv/test/runner.c b/deps/uv/test/runner.c index e896d43b7627df..e094defc7e7de5 100644 --- a/deps/uv/test/runner.c +++ b/deps/uv/test/runner.c @@ -43,13 +43,14 @@ static void log_progress(int total, total = 1; progress = 100 * (passed + failed + skipped + todos) / total; - LOGF("[%% %3d|+ %3d|- %3d|T %3d|S %3d]: %s", - progress, - passed, - failed, - todos, - skipped, - name); + fprintf(stderr, "[%% %3d|+ %3d|- %3d|T %3d|S %3d]: %s", + progress, + passed, + failed, + todos, + skipped, + name); + fflush(stderr); } @@ -109,7 +110,8 @@ int run_tests(int benchmark_output) { } if (tap_output) { - LOGF("1..%d\n", total); + fprintf(stderr, "1..%d\n", total); + fflush(stderr); } /* Run all tests. */ @@ -184,7 +186,8 @@ void log_tap_result(int test_count, reason[0] = '\0'; } - LOGF("%s %d - %s%s%s\n", result, test_count, test, directive, reason); + fprintf(stderr, "%s %d - %s%s%s\n", result, test_count, test, directive, reason); + fflush(stderr); } @@ -320,49 +323,55 @@ int run_test(const char* test, /* Show error and output from processes if the test failed. */ if (status != 0 || task->show_output) { if (tap_output) { - LOGF("#"); + fprintf(stderr, "#"); } else if (status == TEST_TODO) { - LOGF("\n`%s` todo\n", test); + fprintf(stderr, "\n`%s` todo\n", test); } else if (status == TEST_SKIP) { - LOGF("\n`%s` skipped\n", test); + fprintf(stderr, "\n`%s` skipped\n", test); } else if (status != 0) { - LOGF("\n`%s` failed: %s\n", test, errmsg); + fprintf(stderr, "\n`%s` failed: %s\n", test, errmsg); } else { - LOGF("\n"); + fprintf(stderr, "\n"); } + fflush(stderr); for (i = 0; i < process_count; i++) { switch (process_output_size(&processes[i])) { case -1: - LOGF("Output from process `%s`: (unavailable)\n", - process_get_name(&processes[i])); + fprintf(stderr, "Output from process `%s`: (unavailable)\n", + process_get_name(&processes[i])); + fflush(stderr); break; case 0: - LOGF("Output from process `%s`: (no output)\n", - process_get_name(&processes[i])); + fprintf(stderr, "Output from process `%s`: (no output)\n", + process_get_name(&processes[i])); + fflush(stderr); break; default: - LOGF("Output from process `%s`:\n", process_get_name(&processes[i])); + fprintf(stderr, "Output from process `%s`:\n", process_get_name(&processes[i])); + fflush(stderr); process_copy_output(&processes[i], fileno(stderr)); break; } } if (!tap_output) { - LOG("=============================================================\n"); + fprintf(stderr, "=============================================================\n"); } /* In benchmark mode show concise output from the main process. */ } else if (benchmark_output) { switch (process_output_size(main_proc)) { case -1: - LOGF("%s: (unavailable)\n", test); + fprintf(stderr, "%s: (unavailable)\n", test); + fflush(stderr); break; case 0: - LOGF("%s: (no output)\n", test); + fprintf(stderr, "%s: (no output)\n", test); + fflush(stderr); break; default: @@ -397,7 +406,8 @@ int run_test_part(const char* test, const char* part) { } } - LOGF("No test part with that name: %s:%s\n", test, part); + fprintf(stderr, "No test part with that name: %s:%s\n", test, part); + fflush(stderr); return 255; } diff --git a/deps/uv/test/task.h b/deps/uv/test/task.h index 07584c52996f8c..ea0503e8feefe4 100644 --- a/deps/uv/test/task.h +++ b/deps/uv/test/task.h @@ -76,19 +76,6 @@ typedef enum { PIPE } stream_type; -/* Log to stderr. */ -#define LOG(...) \ - do { \ - fprintf(stderr, "%s", __VA_ARGS__); \ - fflush(stderr); \ - } while (0) - -#define LOGF(...) \ - do { \ - fprintf(stderr, __VA_ARGS__); \ - fflush(stderr); \ - } while (0) - /* Die with fatal error. */ #define FATAL(msg) \ do { \ @@ -158,13 +145,15 @@ enum test_status { #define RETURN_TODO(explanation) \ do { \ - LOGF("%s\n", explanation); \ + fprintf(stderr, "%s\n", explanation); \ + fflush(stderr); \ return TEST_TODO; \ } while (0) #define RETURN_SKIP(explanation) \ do { \ - LOGF("%s\n", explanation); \ + fprintf(stderr, "%s\n", explanation); \ + fflush(stderr); \ return TEST_SKIP; \ } while (0) @@ -190,10 +179,15 @@ enum test_status { #include +/* Define inline for MSVC */ +# ifdef _MSC_VER +# define inline __inline +# endif + /* Emulate snprintf() on Windows, _snprintf() doesn't zero-terminate the buffer * on overflow... */ -static int snprintf(char* buf, size_t len, const char* fmt, ...) { +inline int snprintf(char* buf, size_t len, const char* fmt, ...) { va_list ap; int n; diff --git a/deps/uv/test/test-fs.c b/deps/uv/test/test-fs.c index cc5dc744501ec4..a0600b30797dd9 100644 --- a/deps/uv/test/test-fs.c +++ b/deps/uv/test/test-fs.c @@ -1094,7 +1094,8 @@ TEST_IMPL(fs_fstat) { #elif defined(__sun) || \ defined(_BSD_SOURCE) || \ defined(_SVID_SOURCE) || \ - defined(_XOPEN_SOURCE) + defined(_XOPEN_SOURCE) || \ + defined(_DEFAULT_SOURCE) ASSERT(s->st_atim.tv_sec == t.st_atim.tv_sec); ASSERT(s->st_atim.tv_nsec == t.st_atim.tv_nsec); ASSERT(s->st_mtim.tv_sec == t.st_mtim.tv_sec); @@ -1155,6 +1156,7 @@ TEST_IMPL(fs_access) { /* Setup. */ unlink("test_file"); + rmdir("test_dir"); loop = uv_default_loop(); @@ -1198,6 +1200,16 @@ TEST_IMPL(fs_access) { ASSERT(req.result == 0); uv_fs_req_cleanup(&req); + /* Directory access */ + r = uv_fs_mkdir(loop, &req, "test_dir", 0777, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&req); + + r = uv_fs_access(loop, &req, "test_dir", W_OK, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + /* * Run the loop just to check we don't have make any extraneous uv_ref() * calls. This should drop out immediately. @@ -1206,6 +1218,7 @@ TEST_IMPL(fs_access) { /* Cleanup. */ unlink("test_file"); + rmdir("test_dir"); MAKE_VALGRIND_HAPPY(); return 0; @@ -1310,6 +1323,65 @@ TEST_IMPL(fs_chmod) { } +TEST_IMPL(fs_unlink_readonly) { + int r; + uv_fs_t req; + uv_file file; + + /* Setup. */ + unlink("test_file"); + + loop = uv_default_loop(); + + r = uv_fs_open(loop, + &req, + "test_file", + O_RDWR | O_CREAT, + S_IWUSR | S_IRUSR, + NULL); + ASSERT(r >= 0); + ASSERT(req.result >= 0); + file = req.result; + uv_fs_req_cleanup(&req); + + iov = uv_buf_init(test_buf, sizeof(test_buf)); + r = uv_fs_write(loop, &req, file, &iov, 1, -1, NULL); + ASSERT(r == sizeof(test_buf)); + ASSERT(req.result == sizeof(test_buf)); + uv_fs_req_cleanup(&req); + + close(file); + + /* Make the file read-only */ + r = uv_fs_chmod(loop, &req, "test_file", 0400, NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + check_permission("test_file", 0400); + + /* Try to unlink the file */ + r = uv_fs_unlink(loop, &req, "test_file", NULL); + ASSERT(r == 0); + ASSERT(req.result == 0); + uv_fs_req_cleanup(&req); + + /* + * Run the loop just to check we don't have make any extraneous uv_ref() + * calls. This should drop out immediately. + */ + uv_run(loop, UV_RUN_DEFAULT); + + /* Cleanup. */ + uv_fs_chmod(loop, &req, "test_file", 0600, NULL); + uv_fs_req_cleanup(&req); + unlink("test_file"); + + MAKE_VALGRIND_HAPPY(); + return 0; +} + + TEST_IMPL(fs_chown) { int r; uv_fs_t req; diff --git a/deps/uv/test/test-handle-fileno.c b/deps/uv/test/test-handle-fileno.c index df5e984ab74338..3fe933adebdd87 100644 --- a/deps/uv/test/test-handle-fileno.c +++ b/deps/uv/test/test-handle-fileno.c @@ -102,7 +102,8 @@ TEST_IMPL(handle_fileno) { tty_fd = get_tty_fd(); if (tty_fd < 0) { - LOGF("Cannot open a TTY fd"); + fprintf(stderr, "Cannot open a TTY fd"); + fflush(stderr); } else { r = uv_tty_init(loop, &tty, tty_fd, 0); ASSERT(r == 0); diff --git a/deps/uv/test/test-idle.c b/deps/uv/test/test-idle.c index 0e991c368cfd81..f49d1964827278 100644 --- a/deps/uv/test/test-idle.c +++ b/deps/uv/test/test-idle.c @@ -46,7 +46,8 @@ static void timer_cb(uv_timer_t* handle) { uv_close((uv_handle_t*) &timer_handle, close_cb); timer_cb_called++; - LOGF("timer_cb %d\n", timer_cb_called); + fprintf(stderr, "timer_cb %d\n", timer_cb_called); + fflush(stderr); } @@ -54,7 +55,8 @@ static void idle_cb(uv_idle_t* handle) { ASSERT(handle == &idle_handle); idle_cb_called++; - LOGF("idle_cb %d\n", idle_cb_called); + fprintf(stderr, "idle_cb %d\n", idle_cb_called); + fflush(stderr); } @@ -62,7 +64,8 @@ static void check_cb(uv_check_t* handle) { ASSERT(handle == &check_handle); check_cb_called++; - LOGF("check_cb %d\n", check_cb_called); + fprintf(stderr, "check_cb %d\n", check_cb_called); + fflush(stderr); } diff --git a/deps/uv/test/test-ip6-addr.c b/deps/uv/test/test-ip6-addr.c index cf8491fb1b4d15..869b099e0fccaf 100644 --- a/deps/uv/test/test-ip6-addr.c +++ b/deps/uv/test/test-ip6-addr.c @@ -77,14 +77,16 @@ TEST_IMPL(ip6_addr_link_local) { device_name); #endif - LOGF("Testing link-local address %s " - "(iface_index: 0x%02x, device_name: %s)\n", - scoped_addr, - iface_index, - device_name); + fprintf(stderr, "Testing link-local address %s " + "(iface_index: 0x%02x, device_name: %s)\n", + scoped_addr, + iface_index, + device_name); + fflush(stderr); ASSERT(0 == uv_ip6_addr(scoped_addr, TEST_PORT, &addr)); - LOGF("Got scope_id 0x%02x\n", addr.sin6_scope_id); + fprintf(stderr, "Got scope_id 0x%02x\n", addr.sin6_scope_id); + fflush(stderr); ASSERT(iface_index == addr.sin6_scope_id); } diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index aac15e0d9df0b7..1e3c13d5e9267d 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -43,6 +43,7 @@ TEST_DECLARE (semaphore_1) TEST_DECLARE (semaphore_2) TEST_DECLARE (semaphore_3) TEST_DECLARE (tty) +TEST_DECLARE (tty_file) TEST_DECLARE (stdio_over_pipes) TEST_DECLARE (ip6_pton) TEST_DECLARE (ipc_listen_before_write) @@ -61,6 +62,7 @@ TEST_DECLARE (multiple_listen) TEST_DECLARE (tcp_write_after_connect) #endif TEST_DECLARE (tcp_writealot) +TEST_DECLARE (tcp_write_fail) TEST_DECLARE (tcp_try_write) TEST_DECLARE (tcp_write_queue_order) TEST_DECLARE (tcp_open) @@ -195,6 +197,9 @@ TEST_DECLARE (fail_always) TEST_DECLARE (pass_always) TEST_DECLARE (socket_buffer_size) TEST_DECLARE (spawn_fails) +#ifndef _WIN32 +TEST_DECLARE (spawn_fails_check_for_waitpid_cleanup) +#endif TEST_DECLARE (spawn_exit_code) TEST_DECLARE (spawn_stdout) TEST_DECLARE (spawn_stdin) @@ -209,6 +214,8 @@ TEST_DECLARE (spawn_setuid_fails) TEST_DECLARE (spawn_setgid_fails) TEST_DECLARE (spawn_stdout_to_file) TEST_DECLARE (spawn_stdout_and_stderr_to_file) +TEST_DECLARE (spawn_stdout_and_stderr_to_file2) +TEST_DECLARE (spawn_stdout_and_stderr_to_file_swap) TEST_DECLARE (spawn_auto_unref) TEST_DECLARE (spawn_closed_process_io) TEST_DECLARE (spawn_reads_child_path) @@ -227,6 +234,7 @@ TEST_DECLARE (fs_mkdtemp) TEST_DECLARE (fs_fstat) TEST_DECLARE (fs_access) TEST_DECLARE (fs_chmod) +TEST_DECLARE (fs_unlink_readonly) TEST_DECLARE (fs_chown) TEST_DECLARE (fs_link) TEST_DECLARE (fs_readlink) @@ -343,6 +351,7 @@ TASK_LIST_START #endif TEST_ENTRY (pipe_set_non_blocking) TEST_ENTRY (tty) + TEST_ENTRY (tty_file) TEST_ENTRY (stdio_over_pipes) TEST_ENTRY (ip6_pton) TEST_ENTRY (ipc_listen_before_write) @@ -372,6 +381,9 @@ TASK_LIST_START TEST_ENTRY (tcp_writealot) TEST_HELPER (tcp_writealot, tcp4_echo_server) + TEST_ENTRY (tcp_write_fail) + TEST_HELPER (tcp_write_fail, tcp4_echo_server) + TEST_ENTRY (tcp_try_write) TEST_ENTRY (tcp_write_queue_order) @@ -551,6 +563,9 @@ TASK_LIST_START TEST_ENTRY (socket_buffer_size) TEST_ENTRY (spawn_fails) +#ifndef _WIN32 + TEST_ENTRY (spawn_fails_check_for_waitpid_cleanup) +#endif TEST_ENTRY (spawn_exit_code) TEST_ENTRY (spawn_stdout) TEST_ENTRY (spawn_stdin) @@ -565,6 +580,8 @@ TASK_LIST_START TEST_ENTRY (spawn_setgid_fails) TEST_ENTRY (spawn_stdout_to_file) TEST_ENTRY (spawn_stdout_and_stderr_to_file) + TEST_ENTRY (spawn_stdout_and_stderr_to_file2) + TEST_ENTRY (spawn_stdout_and_stderr_to_file_swap) TEST_ENTRY (spawn_auto_unref) TEST_ENTRY (spawn_closed_process_io) TEST_ENTRY (spawn_reads_child_path) @@ -611,6 +628,7 @@ TASK_LIST_START TEST_ENTRY (fs_fstat) TEST_ENTRY (fs_access) TEST_ENTRY (fs_chmod) + TEST_ENTRY (fs_unlink_readonly) TEST_ENTRY (fs_chown) TEST_ENTRY (fs_utime) TEST_ENTRY (fs_futime) diff --git a/deps/uv/test/test-loop-handles.c b/deps/uv/test/test-loop-handles.c index 0986de52981e1b..c3e8498ae90a6b 100644 --- a/deps/uv/test/test-loop-handles.c +++ b/deps/uv/test/test-loop-handles.c @@ -113,7 +113,8 @@ static void timer_cb(uv_timer_t* handle) { static void idle_2_close_cb(uv_handle_t* handle) { - LOG("IDLE_2_CLOSE_CB\n"); + fprintf(stderr, "%s", "IDLE_2_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&idle_2_handle); @@ -125,7 +126,8 @@ static void idle_2_close_cb(uv_handle_t* handle) { static void idle_2_cb(uv_idle_t* handle) { - LOG("IDLE_2_CB\n"); + fprintf(stderr, "%s", "IDLE_2_CB\n"); + fflush(stderr); ASSERT(handle == &idle_2_handle); @@ -138,7 +140,8 @@ static void idle_2_cb(uv_idle_t* handle) { static void idle_1_cb(uv_idle_t* handle) { int r; - LOG("IDLE_1_CB\n"); + fprintf(stderr, "%s", "IDLE_1_CB\n"); + fflush(stderr); ASSERT(handle != NULL); ASSERT(idles_1_active > 0); @@ -164,7 +167,8 @@ static void idle_1_cb(uv_idle_t* handle) { static void idle_1_close_cb(uv_handle_t* handle) { - LOG("IDLE_1_CLOSE_CB\n"); + fprintf(stderr, "%s", "IDLE_1_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle != NULL); @@ -173,7 +177,8 @@ static void idle_1_close_cb(uv_handle_t* handle) { static void prepare_1_close_cb(uv_handle_t* handle) { - LOG("PREPARE_1_CLOSE_CB"); + fprintf(stderr, "%s", "PREPARE_1_CLOSE_CB"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&prepare_1_handle); prepare_1_close_cb_called++; @@ -181,7 +186,8 @@ static void prepare_1_close_cb(uv_handle_t* handle) { static void check_close_cb(uv_handle_t* handle) { - LOG("CHECK_CLOSE_CB\n"); + fprintf(stderr, "%s", "CHECK_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&check_handle); check_close_cb_called++; @@ -189,7 +195,8 @@ static void check_close_cb(uv_handle_t* handle) { static void prepare_2_close_cb(uv_handle_t* handle) { - LOG("PREPARE_2_CLOSE_CB\n"); + fprintf(stderr, "%s", "PREPARE_2_CLOSE_CB\n"); + fflush(stderr); ASSERT(handle == (uv_handle_t*)&prepare_2_handle); prepare_2_close_cb_called++; @@ -199,8 +206,8 @@ static void prepare_2_close_cb(uv_handle_t* handle) { static void check_cb(uv_check_t* handle) { int i, r; - LOG("CHECK_CB\n"); - + fprintf(stderr, "%s", "CHECK_CB\n"); + fflush(stderr); ASSERT(handle == &check_handle); if (loop_iteration < ITERATIONS) { @@ -235,8 +242,8 @@ static void check_cb(uv_check_t* handle) { static void prepare_2_cb(uv_prepare_t* handle) { int r; - LOG("PREPARE_2_CB\n"); - + fprintf(stderr, "%s", "PREPARE_2_CB\n"); + fflush(stderr); ASSERT(handle == &prepare_2_handle); /* prepare_2 gets started by prepare_1 when (loop_iteration % 2 == 0), */ @@ -255,8 +262,8 @@ static void prepare_2_cb(uv_prepare_t* handle) { static void prepare_1_cb(uv_prepare_t* handle) { int r; - LOG("PREPARE_1_CB\n"); - + fprintf(stderr, "%s", "PREPARE_1_CB\n"); + fflush(stderr); ASSERT(handle == &prepare_1_handle); if (loop_iteration % 2 == 0) { diff --git a/deps/uv/test/test-osx-select.c b/deps/uv/test/test-osx-select.c index 6ccf603483488a..a0afda9181ebd9 100644 --- a/deps/uv/test/test-osx-select.c +++ b/deps/uv/test/test-osx-select.c @@ -39,6 +39,7 @@ static void alloc_cb(uv_handle_t* handle, size_t size, uv_buf_t* buf) { static void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { fprintf(stdout, "got data %d\n", ++read_count); + fflush(stdout); if (read_count == 3) uv_close((uv_handle_t*) stream, NULL); @@ -55,7 +56,8 @@ TEST_IMPL(osx_select) { fd = open("/dev/tty", O_RDONLY); if (fd < 0) { - LOGF("Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } @@ -107,7 +109,8 @@ TEST_IMPL(osx_select_many_fds) { fd = open("/dev/tty", O_RDONLY); if (fd < 0) { - LOGF("Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } diff --git a/deps/uv/test/test-pipe-set-non-blocking.c b/deps/uv/test/test-pipe-set-non-blocking.c index 5cf2c19e7fbd29..fcc9fc0da85e99 100644 --- a/deps/uv/test/test-pipe-set-non-blocking.c +++ b/deps/uv/test/test-pipe-set-non-blocking.c @@ -88,8 +88,8 @@ TEST_IMPL(pipe_set_non_blocking) { uv_close((uv_handle_t*) &pipe_handle, NULL); ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); - ASSERT(0 == close(fd[1])); /* fd[0] is closed by uv_close(). */ ASSERT(0 == uv_thread_join(&thread)); + ASSERT(0 == close(fd[1])); /* fd[0] is closed by uv_close(). */ uv_barrier_destroy(&ctx.barrier); MAKE_VALGRIND_HAPPY(); diff --git a/deps/uv/test/test-spawn.c b/deps/uv/test/test-spawn.c index 9b0030029c187c..d01862abe1d97a 100644 --- a/deps/uv/test/test-spawn.c +++ b/deps/uv/test/test-spawn.c @@ -21,6 +21,7 @@ #include "uv.h" #include "task.h" +#include #include #include #include @@ -34,6 +35,7 @@ # include #else # include +# include #endif @@ -180,6 +182,37 @@ TEST_IMPL(spawn_fails) { } +#ifndef _WIN32 +TEST_IMPL(spawn_fails_check_for_waitpid_cleanup) { + int r; + int status; + int err; + + init_process_options("", fail_cb); + options.file = options.args[0] = "program-that-had-better-not-exist"; + + r = uv_spawn(uv_default_loop(), &process, &options); + ASSERT(r == UV_ENOENT || r == UV_EACCES); + ASSERT(0 == uv_is_active((uv_handle_t*) &process)); + ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); + + /* verify the child is successfully cleaned up within libuv */ + do + err = waitpid(process.pid, &status, 0); + while (err == -1 && errno == EINTR); + + ASSERT(err == -1); + ASSERT(errno == ECHILD); + + uv_close((uv_handle_t*) &process, NULL); + ASSERT(0 == uv_run(uv_default_loop(), UV_RUN_DEFAULT)); + + MAKE_VALGRIND_HAPPY(); + return 0; +} +#endif + + TEST_IMPL(spawn_exit_code) { int r; @@ -342,6 +375,163 @@ TEST_IMPL(spawn_stdout_and_stderr_to_file) { } +TEST_IMPL(spawn_stdout_and_stderr_to_file2) { +#ifndef _WIN32 + int r; + uv_file file; + uv_fs_t fs_req; + uv_stdio_container_t stdio[3]; + uv_buf_t buf; + + /* Setup. */ + unlink("stdout_file"); + + init_process_options("spawn_helper6", exit_cb); + + /* Replace stderr with our file */ + r = uv_fs_open(uv_default_loop(), + &fs_req, + "stdout_file", + O_CREAT | O_RDWR, + S_IRUSR | S_IWUSR, + NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + file = dup2(r, STDERR_FILENO); + ASSERT(file != -1); + + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_INHERIT_FD; + options.stdio[1].data.fd = file; + options.stdio[2].flags = UV_INHERIT_FD; + options.stdio[2].data.fd = file; + options.stdio_count = 3; + + r = uv_spawn(uv_default_loop(), &process, &options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + buf = uv_buf_init(output, sizeof(output)); + r = uv_fs_read(uv_default_loop(), &fs_req, file, &buf, 1, 0, NULL); + ASSERT(r == 27); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strcmp("hello world\nhello errworld\n", output) == 0); + + /* Cleanup. */ + unlink("stdout_file"); + + MAKE_VALGRIND_HAPPY(); + return 0; +#else + RETURN_SKIP("Unix only test"); +#endif +} + + +TEST_IMPL(spawn_stdout_and_stderr_to_file_swap) { +#ifndef _WIN32 + int r; + uv_file stdout_file; + uv_file stderr_file; + uv_fs_t fs_req; + uv_stdio_container_t stdio[3]; + uv_buf_t buf; + + /* Setup. */ + unlink("stdout_file"); + unlink("stderr_file"); + + init_process_options("spawn_helper6", exit_cb); + + /* open 'stdout_file' and replace STDOUT_FILENO with it */ + r = uv_fs_open(uv_default_loop(), + &fs_req, + "stdout_file", + O_CREAT | O_RDWR, + S_IRUSR | S_IWUSR, + NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + stdout_file = dup2(r, STDOUT_FILENO); + ASSERT(stdout_file != -1); + + /* open 'stderr_file' and replace STDERR_FILENO with it */ + r = uv_fs_open(uv_default_loop(), &fs_req, "stderr_file", O_CREAT | O_RDWR, + S_IRUSR | S_IWUSR, NULL); + ASSERT(r != -1); + uv_fs_req_cleanup(&fs_req); + stderr_file = dup2(r, STDERR_FILENO); + ASSERT(stderr_file != -1); + + /* now we're going to swap them: the child process' stdout will be our + * stderr_file and vice versa */ + options.stdio = stdio; + options.stdio[0].flags = UV_IGNORE; + options.stdio[1].flags = UV_INHERIT_FD; + options.stdio[1].data.fd = stderr_file; + options.stdio[2].flags = UV_INHERIT_FD; + options.stdio[2].data.fd = stdout_file; + options.stdio_count = 3; + + r = uv_spawn(uv_default_loop(), &process, &options); + ASSERT(r == 0); + + r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); + ASSERT(r == 0); + + ASSERT(exit_cb_called == 1); + ASSERT(close_cb_called == 1); + + buf = uv_buf_init(output, sizeof(output)); + + /* check the content of stdout_file */ + r = uv_fs_read(uv_default_loop(), &fs_req, stdout_file, &buf, 1, 0, NULL); + ASSERT(r >= 15); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, stdout_file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strncmp("hello errworld\n", output, 15) == 0); + + /* check the content of stderr_file */ + r = uv_fs_read(uv_default_loop(), &fs_req, stderr_file, &buf, 1, 0, NULL); + ASSERT(r >= 12); + uv_fs_req_cleanup(&fs_req); + + r = uv_fs_close(uv_default_loop(), &fs_req, stderr_file, NULL); + ASSERT(r == 0); + uv_fs_req_cleanup(&fs_req); + + printf("output is: %s", output); + ASSERT(strncmp("hello world\n", output, 12) == 0); + + /* Cleanup. */ + unlink("stdout_file"); + unlink("stderr_file"); + + MAKE_VALGRIND_HAPPY(); + return 0; +#else + RETURN_SKIP("Unix only test"); +#endif +} + + TEST_IMPL(spawn_stdin) { int r; uv_pipe_t out; @@ -1007,7 +1197,7 @@ TEST_IMPL(environment_creation) { return 0; } -// Regression test for issue #909 +/* Regression test for issue #909 */ TEST_IMPL(spawn_with_an_odd_path) { int r; diff --git a/deps/uv/test/test-tcp-write-fail.c b/deps/uv/test/test-tcp-write-fail.c new file mode 100644 index 00000000000000..2840d8161032be --- /dev/null +++ b/deps/uv/test/test-tcp-write-fail.c @@ -0,0 +1,115 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "task.h" +#include +#include +#ifndef _WIN32 +# include +#endif + + +static int connect_cb_called = 0; +static int write_cb_called = 0; +static int close_cb_called = 0; + +static uv_connect_t connect_req; +static uv_write_t write_req; + + +static void close_socket(uv_tcp_t* sock) { + uv_os_fd_t fd; + int r; + + r = uv_fileno((uv_handle_t*)sock, &fd); + ASSERT(r == 0); +#ifdef _WIN32 + r = closesocket(fd); +#else + r = close(fd); +#endif + ASSERT(r == 0); +} + + +static void close_cb(uv_handle_t* handle) { + ASSERT(handle != NULL); + close_cb_called++; +} + + +static void write_cb(uv_write_t* req, int status) { + ASSERT(req != NULL); + + ASSERT(status != 0); + fprintf(stderr, "uv_write error: %s\n", uv_strerror(status)); + write_cb_called++; + + uv_close((uv_handle_t*)(req->handle), close_cb); +} + + +static void connect_cb(uv_connect_t* req, int status) { + uv_buf_t buf; + uv_stream_t* stream; + int r; + + ASSERT(req == &connect_req); + ASSERT(status == 0); + + stream = req->handle; + connect_cb_called++; + + /* close the socket, the hard way */ + close_socket((uv_tcp_t*)stream); + + buf = uv_buf_init("hello\n", 6); + r = uv_write(&write_req, stream, &buf, 1, write_cb); + ASSERT(r == 0); +} + + +TEST_IMPL(tcp_write_fail) { + struct sockaddr_in addr; + uv_tcp_t client; + int r; + + ASSERT(0 == uv_ip4_addr("127.0.0.1", TEST_PORT, &addr)); + + r = uv_tcp_init(uv_default_loop(), &client); + ASSERT(r == 0); + + r = uv_tcp_connect(&connect_req, + &client, + (const struct sockaddr*) &addr, + connect_cb); + ASSERT(r == 0); + + uv_run(uv_default_loop(), UV_RUN_DEFAULT); + + ASSERT(connect_cb_called == 1); + ASSERT(write_cb_called == 1); + ASSERT(close_cb_called == 1); + + MAKE_VALGRIND_HAPPY(); + return 0; +} diff --git a/deps/uv/test/test-timer-again.c b/deps/uv/test/test-timer-again.c index 095cd9e707baa8..f93c509be5dc0a 100644 --- a/deps/uv/test/test-timer-again.c +++ b/deps/uv/test/test-timer-again.c @@ -47,8 +47,9 @@ static void repeat_1_cb(uv_timer_t* handle) { ASSERT(handle == &repeat_1); ASSERT(uv_timer_get_repeat((uv_timer_t*)handle) == 50); - LOGF("repeat_1_cb called after %ld ms\n", - (long int)(uv_now(uv_default_loop()) - start_time)); + fprintf(stderr, "repeat_1_cb called after %ld ms\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + fflush(stderr); repeat_1_cb_called++; @@ -69,8 +70,9 @@ static void repeat_2_cb(uv_timer_t* handle) { ASSERT(handle == &repeat_2); ASSERT(repeat_2_cb_allowed); - LOGF("repeat_2_cb called after %ld ms\n", - (long int)(uv_now(uv_default_loop()) - start_time)); + fprintf(stderr, "repeat_2_cb called after %ld ms\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + fflush(stderr); repeat_2_cb_called++; @@ -80,8 +82,9 @@ static void repeat_2_cb(uv_timer_t* handle) { return; } - LOGF("uv_timer_get_repeat %ld ms\n", - (long int)uv_timer_get_repeat(&repeat_2)); + fprintf(stderr, "uv_timer_get_repeat %ld ms\n", + (long int)uv_timer_get_repeat(&repeat_2)); + fflush(stderr); ASSERT(uv_timer_get_repeat(&repeat_2) == 100); /* This shouldn't take effect immediately. */ @@ -129,8 +132,9 @@ TEST_IMPL(timer_again) { ASSERT(repeat_2_cb_called == 2); ASSERT(close_cb_called == 2); - LOGF("Test took %ld ms (expected ~700 ms)\n", - (long int)(uv_now(uv_default_loop()) - start_time)); + fprintf(stderr, "Test took %ld ms (expected ~700 ms)\n", + (long int)(uv_now(uv_default_loop()) - start_time)); + fflush(stderr); MAKE_VALGRIND_HAPPY(); return 0; diff --git a/deps/uv/test/test-tty.c b/deps/uv/test/test-tty.c index 7e1ce2668899f8..81e612c1d6ae1c 100644 --- a/deps/uv/test/test-tty.c +++ b/deps/uv/test/test-tty.c @@ -66,13 +66,15 @@ TEST_IMPL(tty) { #else /* unix */ ttyin_fd = open("/dev/tty", O_RDONLY, 0); if (ttyin_fd < 0) { - LOGF("Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as read-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } ttyout_fd = open("/dev/tty", O_WRONLY, 0); if (ttyout_fd < 0) { - LOGF("Cannot open /dev/tty as write-only: %s\n", strerror(errno)); + fprintf(stderr, "Cannot open /dev/tty as write-only: %s\n", strerror(errno)); + fflush(stderr); return TEST_SKIP; } #endif @@ -111,13 +113,20 @@ TEST_IMPL(tty) { ASSERT(height > 10); /* Turn on raw mode. */ - r = uv_tty_set_mode(&tty_in, 1); + r = uv_tty_set_mode(&tty_in, UV_TTY_MODE_RAW); ASSERT(r == 0); /* Turn off raw mode. */ - r = uv_tty_set_mode(&tty_in, 0); + r = uv_tty_set_mode(&tty_in, UV_TTY_MODE_NORMAL); ASSERT(r == 0); + /* Calling uv_tty_reset_mode() repeatedly should not clobber errno. */ + errno = 0; + ASSERT(0 == uv_tty_reset_mode()); + ASSERT(0 == uv_tty_reset_mode()); + ASSERT(0 == uv_tty_reset_mode()); + ASSERT(0 == errno); + /* TODO check the actual mode! */ uv_close((uv_handle_t*) &tty_in, NULL); @@ -128,3 +137,45 @@ TEST_IMPL(tty) { MAKE_VALGRIND_HAPPY(); return 0; } + + +TEST_IMPL(tty_file) { +#ifndef _WIN32 + uv_loop_t loop; + uv_tty_t tty; + int fd; + + ASSERT(0 == uv_loop_init(&loop)); + + fd = open("test/fixtures/empty_file", O_RDONLY); + if (fd != -1) { + ASSERT(UV_EINVAL == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + } + + fd = open("/dev/random", O_RDONLY); + if (fd != -1) { + ASSERT(UV_EINVAL == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + } + + fd = open("/dev/zero", O_RDONLY); + if (fd != -1) { + ASSERT(UV_EINVAL == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + } + + fd = open("/dev/tty", O_RDONLY); + if (fd != -1) { + ASSERT(0 == uv_tty_init(&loop, &tty, fd, 1)); + ASSERT(0 == close(fd)); + uv_close((uv_handle_t*) &tty, NULL); + } + + ASSERT(0 == uv_run(&loop, UV_RUN_DEFAULT)); + ASSERT(0 == uv_loop_close(&loop)); + + MAKE_VALGRIND_HAPPY(); +#endif + return 0; +} diff --git a/deps/uv/uv.gyp b/deps/uv/uv.gyp index 1ef8c05adc6496..acaed862d7c66e 100644 --- a/deps/uv/uv.gyp +++ b/deps/uv/uv.gyp @@ -39,7 +39,7 @@ '_FILE_OFFSET_BITS=64', ], }], - ['OS == "mac"', { + ['OS in "mac ios"', { 'defines': [ '_DARWIN_USE_64_BIT_INODE=1' ], }], ['OS == "linux"', { @@ -167,18 +167,17 @@ 'cflags': [ '-fPIC' ], }], ['uv_library=="shared_library" and OS!="mac"', { - 'link_settings': { - # Must correspond with UV_VERSION_MAJOR and UV_VERSION_MINOR - # in include/uv-version.h - 'libraries': [ '-Wl,-soname,libuv.so.1.0' ], - }, + # This will cause gyp to set soname + # Must correspond with UV_VERSION_MAJOR + # in include/uv-version.h + 'product_extension': 'so.1', }], ], }], - [ 'OS in "linux mac android"', { + [ 'OS in "linux mac ios android"', { 'sources': [ 'src/unix/proctitle.c' ], }], - [ 'OS=="mac"', { + [ 'OS in "mac ios"', { 'sources': [ 'src/unix/darwin.c', 'src/unix/fsevents.c', @@ -261,7 +260,7 @@ 'libraries': [ '-lkvm' ], }, }], - [ 'OS in "mac freebsd dragonflybsd openbsd netbsd".split()', { + [ 'OS in "ios mac freebsd dragonflybsd openbsd netbsd".split()', { 'sources': [ 'src/unix/kqueue.c' ], }], ['uv_library=="shared_library"', { @@ -364,6 +363,7 @@ 'test/test-tcp-write-to-half-open-connection.c', 'test/test-tcp-write-after-connect.c', 'test/test-tcp-writealot.c', + 'test/test-tcp-write-fail.c', 'test/test-tcp-try-write.c', 'test/test-tcp-unexpected-read.c', 'test/test-tcp-oob.c', diff --git a/deps/uv/vcbuild.bat b/deps/uv/vcbuild.bat index d3b7aa154eec6a..084ab9578fe10d 100644 --- a/deps/uv/vcbuild.bat +++ b/deps/uv/vcbuild.bat @@ -90,8 +90,8 @@ if defined noprojgen goto msbuild @rem Generate the VS project. if exist build\gyp goto have_gyp -echo git clone https://git.chromium.org/external/gyp.git build/gyp -git clone https://git.chromium.org/external/gyp.git build/gyp +echo git clone https://chromium.googlesource.com/external/gyp build/gyp +git clone https://chromium.googlesource.com/external/gyp build/gyp if errorlevel 1 goto gyp_install_failed goto have_gyp diff --git a/doc/api/tls.markdown b/doc/api/tls.markdown index 38649b55085313..e2922558040ef5 100644 --- a/doc/api/tls.markdown +++ b/doc/api/tls.markdown @@ -141,14 +141,37 @@ automatically set as a listener for the [secureConnection][] event. The - `ciphers`: A string describing the ciphers to use or exclude, seperated by `:`. The default cipher suite is: - ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256: - DHE-RSA-AES256-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256: - HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA - - The default cipher suite prefers ECDHE and DHE ciphers for Perfect Forward - secrecy, while offering *some* backward compatibiltity. Old clients which - rely on insecure and deprecated RC4 or DES-based ciphers (like Internet - Explorer 6) aren't able to complete the handshake with the default + ECDHE-RSA-AES128-GCM-SHA256: + ECDHE-ECDSA-AES128-GCM-SHA256: + ECDHE-RSA-AES256-GCM-SHA384: + ECDHE-ECDSA-AES256-GCM-SHA384: + DHE-RSA-AES128-GCM-SHA256: + ECDHE-RSA-AES128-SHA256: + DHE-RSA-AES128-SHA256: + ECDHE-RSA-AES256-SHA384: + DHE-RSA-AES256-SHA384: + ECDHE-RSA-AES256-SHA256: + DHE-RSA-AES256-SHA256: + HIGH: + !aNULL: + !eNULL: + !EXPORT: + !DES: + !RC4: + !MD5: + !PSK: + !SRP: + !CAMELLIA + + The default cipher suite prefers GCM ciphers for [Chrome's 'modern + cryptography' setting] and also prefers ECDHE and DHE ciphers for Perfect + Forward secrecy, while offering *some* backward compatibiltity. + + 128 bit AES is preferred over 192 and 256 bit AES in light of [specific + attacks affecting larger AES key sizes]. + + Old clients that rely on insecure and deprecated RC4 or DES-based ciphers + (like Internet Explorer 6) aren't able to complete the handshake with the default configuration. If you absolutely must support these clients, the [TLS recommendations] may offer a compatible cipher suite. For more details on the format, see the [OpenSSL cipher list format documentation]. @@ -160,8 +183,10 @@ automatically set as a listener for the [secureConnection][] event. The - `dhparam`: A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create it. - If omitted or invalid, it is silently discarded and DHE ciphers won't be - available. + Its key length should be greater than or equal to 1024 bits, otherwise + it throws an error. It is strongly recommended to use 2048 bits or + more for stronger security. If omitted or invalid, it is silently + discarded and DHE ciphers won't be available. - `handshakeTimeout`: Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds. The default is 120 seconds. @@ -784,6 +809,8 @@ The string representation of the local IP address. The numeric representation of the local port. [OpenSSL cipher list format documentation]: http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT +[Chrome's 'modern cryptography' setting]: http://www.chromium.org/Home/chromium-security/education/tls#TOC-Deprecation-of-TLS-Features-Algorithms-in-Chrome +[specific attacks affecting larger AES key sizes]: https://www.schneier.com/blog/archives/2009/07/another_new_aes.html [BEAST attacks]: http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html [tls.createServer]: #tls_tls_createserver_options_secureconnectionlistener [tls.createSecurePair]: #tls_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized diff --git a/doc/api/v8.markdown b/doc/api/v8.markdown index adced82685eea4..cedd5c86d9b008 100644 --- a/doc/api/v8.markdown +++ b/doc/api/v8.markdown @@ -20,7 +20,7 @@ Returns an object with the following properties } ``` -## setFlagsFromString() +## setFlagsFromString(string) Set additional V8 command line flags. Use with care; changing settings after the VM has started may result in unpredictable behavior, including diff --git a/lib/_debugger.js b/lib/_debugger.js index f1885b2e32f467..4c503d2f5480e9 100644 --- a/lib/_debugger.js +++ b/lib/_debugger.js @@ -101,7 +101,7 @@ Protocol.prototype.execute = function(d) { if (len - this.bodyStartByteIndex < this.contentLength) { break; } - // pass thru + // falls through case 'body': var resRawByteLength = Buffer.byteLength(res.raw, 'utf8'); @@ -125,7 +125,6 @@ Protocol.prototype.execute = function(d) { default: throw new Error('Unknown state'); - break; } }; @@ -262,7 +261,7 @@ Client.prototype.req = function(req, cb) { Client.prototype.reqVersion = function(cb) { cb = cb || function() {}; - this.req({ command: 'version' } , function(err, body, res) { + this.req({ command: 'version' }, function(err, body, res) { if (err) return cb(err); cb(null, res.body.body.V8Version, res.body.running); }); @@ -398,7 +397,7 @@ Client.prototype.reqFrameEval = function(expression, frame, cb) { // reqBacktrace(cb) // TODO: from, to, bottom Client.prototype.reqBacktrace = function(cb) { - this.req({ command: 'backtrace', arguments: { inlineRefs: true } } , cb); + this.req({ command: 'backtrace', arguments: { inlineRefs: true } }, cb); }; @@ -432,7 +431,7 @@ Client.prototype.reqScripts = function(cb) { var self = this; cb = cb || function() {}; - this.req({ command: 'scripts' } , function(err, res) { + this.req({ command: 'scripts' }, function(err, res) { if (err) return cb(err); for (var i = 0; i < res.length; i++) { diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 41ece371cdfbe6..aea665e80973c9 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -137,8 +137,10 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { } break; + /* eslint-disable max-len */ // list is taken from: // https://mxr.mozilla.org/mozilla/source/netwerk/protocol/http/src/nsHttpHeaderArray.cpp + /* eslint-enable max-len */ case 'content-type': case 'content-length': case 'user-agent': @@ -158,9 +160,9 @@ IncomingMessage.prototype._addHeaderLine = function(field, value, dest) { default: // make comma-separated list - if (dest[field] !== undefined) + if (dest[field] !== undefined) { dest[field] += ', ' + value; - else { + } else { dest[field] = value; } } diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 88590551c9defb..bfebef21b69af6 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -85,8 +85,9 @@ OutgoingMessage.prototype.setTimeout = function(msecs, callback) { this.once('socket', function(socket) { socket.setTimeout(msecs); }); - } else + } else { this.socket.setTimeout(msecs); + } }; diff --git a/lib/_http_server.js b/lib/_http_server.js index 99903024c26d14..ae2bba035c8763 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -221,9 +221,11 @@ function Server(requestListener) { this.addListener('request', requestListener); } + /* eslint-disable max-len */ // Similar option to this. Too lazy to write my own docs. // http://www.squid-cache.org/Doc/config/half_closed_clients/ // http://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F + /* eslint-enable max-len */ this.httpAllowHalfOpen = false; this.addListener('connection', connectionListener); diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 1de55597123d1b..bebbc80e2bf8dc 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -234,8 +234,9 @@ function howMuchToRead(n, state) { if (!state.ended) { state.needReadable = true; return 0; - } else + } else { return state.length; + } } return n; @@ -774,7 +775,7 @@ Readable.prototype.wrap = function(stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function(method) { return function() { return stream[method].apply(stream, arguments); - }}(i); + }; }(i); } } diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index da65ddb90ae5ca..54f751abdf24ee 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -9,7 +9,6 @@ Writable.WritableState = WritableState; const util = require('util'); const Stream = require('stream'); -const debug = util.debuglog('stream'); util.inherits(Writable, Stream); @@ -273,9 +272,9 @@ function writeOrBuffer(stream, state, chunk, encoding, cb) { } else { state.bufferedRequest = state.lastBufferedRequest; } - } - else + } else { doWrite(stream, state, false, len, chunk, encoding, cb); + } return ret; } @@ -471,8 +470,9 @@ function finishMaybe(stream, state) { prefinish(stream, state); state.finished = true; stream.emit('finish'); - } else + } else { prefinish(stream, state); + } } return need; } diff --git a/lib/_tls_legacy.js b/lib/_tls_legacy.js index 3348d7f92d951c..0a0c7bca7b9024 100644 --- a/lib/_tls_legacy.js +++ b/lib/_tls_legacy.js @@ -646,7 +646,7 @@ function onnewsession(key, session) { if (self.ssl) self.ssl.newSessionDone(); - }; + } } diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 122c7042a4cf2f..5a35c3bd967b55 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -141,29 +141,23 @@ function onclienthello(hello) { if (err) return self.destroy(err); - // Servername came from SSL session - // NOTE: TLS Session ticket doesn't include servername information - // - // Another note, From RFC3546: - // - // If, on the other hand, the older - // session is resumed, then the server MUST ignore extensions appearing - // in the client hello, and send a server hello containing no - // extensions; in this case the extension functionality negotiated - // during the original session initiation is applied to the resumed - // session. - // - // Therefore we should account session loading when dealing with servername - var servername = session && session.servername || hello.servername; - loadSNI(self, servername, function(err, ctx) { + self._handle.endParser(); + }); +} + + +function oncertcb(info) { + var self = this; + var servername = info.servername; + + loadSNI(self, servername, function(err, ctx) { + if (err) + return self.destroy(err); + requestOCSP(self, info, ctx, function(err) { if (err) return self.destroy(err); - requestOCSP(self, hello, ctx, function(err) { - if (err) - return self.destroy(err); - self._handle.endParser(); - }); + self._handle.certCbDone(); }); }); } @@ -295,15 +289,22 @@ TLSSocket.prototype._wrapHandle = function(handle) { } }); - this.on('close', this._destroySSL); + this.on('close', function() { + this._destroySSL(); + res = null; + }); return res; }; TLSSocket.prototype._destroySSL = function _destroySSL() { + if (!this.ssl) return; this.ssl.destroySSL(); - if (this.ssl._secureContext.singleUse) + if (this.ssl._secureContext.singleUse) { this.ssl._secureContext.context.close(); + this.ssl._secureContext.context = null; + } + this.ssl = null; }; TLSSocket.prototype._init = function(socket, wrap) { @@ -333,15 +334,18 @@ TLSSocket.prototype._init = function(socket, wrap) { ssl.onhandshakestart = onhandshakestart.bind(this); ssl.onhandshakedone = onhandshakedone.bind(this); ssl.onclienthello = onclienthello.bind(this); + ssl.oncertcb = oncertcb.bind(this); ssl.onnewsession = onnewsession.bind(this); ssl.lastHandshakeTime = 0; ssl.handshakes = 0; - if (this.server && - (listenerCount(this.server, 'resumeSession') > 0 || - listenerCount(this.server, 'newSession') > 0 || - listenerCount(this.server, 'OCSPRequest') > 0)) { - ssl.enableSessionCallbacks(); + if (this.server) { + if (listenerCount(this.server, 'resumeSession') > 0 || + listenerCount(this.server, 'newSession') > 0) { + ssl.enableSessionCallbacks(); + } + if (listenerCount(this.server, 'OCSPRequest') > 0) + ssl.enableCertCb(); } } else { ssl.onhandshakestart = function() {}; @@ -358,7 +362,7 @@ TLSSocket.prototype._init = function(socket, wrap) { self._writableState.errorEmitted = true; // Destroy socket if error happened before handshake's finish - if (!this._secureEstablished) { + if (!self._secureEstablished) { self._tlsError(err); self.destroy(); } else if (options.isServer && @@ -382,7 +386,7 @@ TLSSocket.prototype._init = function(socket, wrap) { options.server._contexts.length)) { assert(typeof options.SNICallback === 'function'); this._SNICallback = options.SNICallback; - ssl.enableHelloParser(); + ssl.enableCertCb(); } if (process.features.tls_npn && options.NPNProtocols) diff --git a/lib/assert.js b/lib/assert.js index 4a01e5c7f0b356..70e784a50c34b9 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -323,4 +323,4 @@ assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; -assert.ifError = function(err) { if (err) {throw err;}}; +assert.ifError = function(err) { if (err) throw err; }; diff --git a/lib/buffer.js b/lib/buffer.js index 8f4e34d289fc27..dc2b656d7a7a33 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -247,6 +247,11 @@ Buffer.concat = function(list, length) { if (!Array.isArray(list)) throw new TypeError('list argument must be an Array of Buffers.'); + if (list.length === 0) + return new Buffer(0); + else if (list.length === 1) + return list[0]; + if (length === undefined) { length = 0; for (var i = 0; i < list.length; i++) @@ -255,11 +260,6 @@ Buffer.concat = function(list, length) { length = length >>> 0; } - if (list.length === 0) - return new Buffer(0); - else if (list.length === 1) - return list[0]; - var buffer = new Buffer(length); var pos = 0; for (var i = 0; i < list.length; i++) { diff --git a/lib/child_process.js b/lib/child_process.js index 99da7cfbde94dc..34ce359f5b0ec5 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -169,7 +169,7 @@ SocketListSend.prototype._request = function(msg, cmd, callback) { function onclose() { self.slave.removeListener('internalMessage', onreply); callback(new Error('Slave closed before reply')); - }; + } function onreply(msg) { if (!(msg.cmd === cmd && msg.key === self.key)) return; @@ -177,7 +177,7 @@ SocketListSend.prototype._request = function(msg, cmd, callback) { self.slave.removeListener('internalMessage', onreply); callback(null, msg); - }; + } this.slave.once('disconnect', onclose); this.slave.on('internalMessage', onreply); diff --git a/lib/cluster.js b/lib/cluster.js index 10a55996f15cc8..ca1005b738068f 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -11,7 +11,7 @@ const SCHED_RR = 2; const uv = process.binding('uv'); -const cluster = new EventEmitter; +const cluster = new EventEmitter(); module.exports = cluster; cluster.Worker = Worker; cluster.isWorker = ('NODE_UNIQUE_ID' in process.env); @@ -127,11 +127,10 @@ RoundRobinHandle.prototype.add = function(worker, send) { function done() { if (self.handle.getsockname) { var out = {}; - var err = self.handle.getsockname(out); + self.handle.getsockname(out); // TODO(bnoordhuis) Check err. send(null, { sockname: out }, null); - } - else { + } else { send(null, null, null); // UNIX socket. } self.handoff(worker); // In case there are connections pending. @@ -196,7 +195,7 @@ else function masterInit() { cluster.workers = {}; - var intercom = new EventEmitter; + var intercom = new EventEmitter(); cluster.settings = {}; // XXX(bnoordhuis) Fold cluster.schedulingPolicy into cluster.settings? @@ -511,6 +510,7 @@ function workerInit() { }); cluster.worker = worker; process.once('disconnect', function() { + worker.emit('disconnect'); if (!worker.suicide) { // Unexpected disconnect, master exited, or some such nastiness, so // worker exits immediately. diff --git a/lib/console.js b/lib/console.js index 63e3c5e0bf1aa4..f9032e24a0fa44 100644 --- a/lib/console.js +++ b/lib/console.js @@ -73,7 +73,7 @@ Console.prototype.timeEnd = function(label) { Console.prototype.trace = function trace() { // TODO probably can to do this better with V8's debug object once that is // exposed. - var err = new Error; + var err = new Error(); err.name = 'Trace'; err.message = util.format.apply(this, arguments); Error.captureStackTrace(err, trace); diff --git a/lib/crypto.js b/lib/crypto.js index 10ff71e8547606..7ce89482d54b14 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -320,7 +320,7 @@ function Verify(algorithm, options) { if (!(this instanceof Verify)) return new Verify(algorithm, options); - this._handle = new binding.Verify; + this._handle = new binding.Verify(); this._handle.init(algorithm); stream.Writable.call(this, options); diff --git a/lib/dgram.js b/lib/dgram.js index 7d2592819a8e87..1cce233eab808b 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -39,13 +39,13 @@ function lookup6(address, callback) { function newHandle(type) { if (type == 'udp4') { - var handle = new UDP; + var handle = new UDP(); handle.lookup = lookup4; return handle; } if (type == 'udp6') { - var handle = new UDP; + var handle = new UDP(); handle.lookup = lookup6; handle.bind = handle.bind6; handle.send = handle.send6; @@ -301,8 +301,7 @@ Socket.prototype.send = function(buffer, if (ex) { if (callback) callback(ex); self.emit('error', ex); - } - else if (self._handle) { + } else if (self._handle) { var req = new SendWrap(); req.buffer = buffer; // Keep reference alive. req.length = length; @@ -338,7 +337,10 @@ function afterSend(err) { if (err) { err = exceptionWithHostPort(err, 'send', this.address, this.port); } - this.callback(err, this.length); + var self = this; + setImmediate(function() { + self.callback(err, self.length); + }); } diff --git a/lib/dns.js b/lib/dns.js index 9334800e4da5c4..28f1607b44ece2 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -239,7 +239,7 @@ function resolver(bindingName) { if (err) throw errnoException(err, bindingName); callback.immediately = true; return req; - } + }; } diff --git a/lib/events.js b/lib/events.js index 064f3838b38ac9..3ea798b3bdb01a 100644 --- a/lib/events.js +++ b/lib/events.js @@ -140,7 +140,10 @@ EventEmitter.prototype.emit = function emit(type) { } else if (er instanceof Error) { throw er; // Unhandled 'error' event } else { - throw new Error('Uncaught, unspecified "error" event.'); + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; } return false; } @@ -307,8 +310,9 @@ EventEmitter.prototype.removeListener = if (--this._eventsCount === 0) { this._events = {}; return this; - } else + } else { delete events[type]; + } } else { spliceOne(list, position); } diff --git a/lib/fs.js b/lib/fs.js index b6b62265403ee8..4cdd0ef5e31456 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -40,7 +40,7 @@ function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. if (DEBUG) { - var backtrace = new Error; + var backtrace = new Error(); return function(err) { if (err) { backtrace.stack = err.name + ': ' + err.message + diff --git a/lib/net.js b/lib/net.js index 847e417e67f4ca..b261196119a9ed 100644 --- a/lib/net.js +++ b/lib/net.js @@ -201,6 +201,7 @@ function onSocketFinish() { var req = new ShutdownWrap(); req.oncomplete = afterShutdown; + req.handle = this._handle; var err = this._handle.shutdown(req); if (err) @@ -430,7 +431,7 @@ Socket.prototype._destroy = function(exception, cb) { }); self._writableState.errorEmitted = true; } - }; + } if (this.destroyed) { debug('already destroyed, fire error callbacks'); @@ -627,6 +628,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { } var req = new WriteWrap(); + req.handle = this._handle; req.oncomplete = afterWrite; req.async = false; var err; @@ -1319,7 +1321,7 @@ Server.prototype.listen = function() { Server.prototype.address = function() { if (this._handle && this._handle.getsockname) { var out = {}; - var err = this._handle.getsockname(out); + this._handle.getsockname(out); // TODO(bnoordhuis) Check err and throw? return out; } else if (this._pipeName) { diff --git a/lib/querystring.js b/lib/querystring.js index 09220a919e3edc..6aa188725ae25a 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -28,7 +28,7 @@ QueryString.unescapeBuffer = function(s, decodeSpaces) { break; case charCode('+'): if (decodeSpaces) c = charCode(' '); - // pass thru + // falls through default: out[outIndex++] = c; break; diff --git a/lib/readline.js b/lib/readline.js index a6845010dae661..5b9637b6f5455a 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -883,15 +883,25 @@ exports.Interface = Interface; * accepts a readable Stream instance and makes it emit "keypress" events */ +const KEYPRESS_DECODER = Symbol('keypress-decoder'); +const ESCAPE_DECODER = Symbol('escape-decoder'); + function emitKeypressEvents(stream) { - if (stream._keypressDecoder) return; + if (stream[KEYPRESS_DECODER]) return; var StringDecoder = require('string_decoder').StringDecoder; // lazy load - stream._keypressDecoder = new StringDecoder('utf8'); + stream[KEYPRESS_DECODER] = new StringDecoder('utf8'); + + stream[ESCAPE_DECODER] = emitKeys(stream); + stream[ESCAPE_DECODER].next(); function onData(b) { if (EventEmitter.listenerCount(stream, 'keypress') > 0) { - var r = stream._keypressDecoder.write(b); - if (r) emitKeys(stream, r); + var r = stream[KEYPRESS_DECODER].write(b); + if (r) { + for (var i = 0; i < r.length; i++) { + stream[ESCAPE_DECODER].next(r[i]); + } + } } else { // Nobody's watching anyway stream.removeListener('data', onData); @@ -944,102 +954,130 @@ exports.emitKeypressEvents = emitKeypressEvents; // Regexes used for ansi escape code splitting const metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/; -const metaKeyCodeRe = new RegExp('^' + metaKeyCodeReAnywhere.source + '$'); const functionKeyCodeReAnywhere = new RegExp('(?:\x1b+)(O|N|\\[|\\[\\[)(?:' + [ '(\\d+)(?:;(\\d+))?([~^$])', '(?:M([@ #!a`])(.)(.))', // mouse '(?:1;)?(\\d+)?([a-zA-Z])' ].join('|') + ')'); -const functionKeyCodeRe = new RegExp('^' + functionKeyCodeReAnywhere.source); -const escapeCodeReAnywhere = new RegExp([ - functionKeyCodeReAnywhere.source, metaKeyCodeReAnywhere.source, /\x1b./.source -].join('|')); - -function emitKeys(stream, s) { - if (s instanceof Buffer) { - if (s[0] > 127 && s[1] === undefined) { - s[0] -= 128; - s = '\x1b' + s.toString(stream.encoding || 'utf-8'); - } else { - s = s.toString(stream.encoding || 'utf-8'); - } - } - var buffer = []; - var match; - while (match = escapeCodeReAnywhere.exec(s)) { - buffer = buffer.concat(s.slice(0, match.index).split('')); - buffer.push(match[0]); - s = s.slice(match.index + match[0].length); - } - buffer = buffer.concat(s.split('')); - - buffer.forEach(function(s) { - var ch, - key = { - sequence: s, - name: undefined, - ctrl: false, - meta: false, - shift: false - }, - parts; - - if (s === '\r') { - // carriage return - key.name = 'return'; - } else if (s === '\n') { - // enter, should have been called linefeed - key.name = 'enter'; +function* emitKeys(stream) { + while (true) { + var ch = yield; + var s = ch; + var escaped = false; + var key = { + sequence: null, + name: undefined, + ctrl: false, + meta: false, + shift: false + }; + + if (ch === '\x1b') { + escaped = true; + s += (ch = yield); + + if (ch === '\x1b') { + s += (ch = yield); + } + } - } else if (s === '\t') { - // tab - key.name = 'tab'; + if (escaped && (ch === 'O' || ch === '[')) { + // ansi escape sequence + var code = ch; + var modifier = 0; - } else if (s === '\b' || s === '\x7f' || - s === '\x1b\x7f' || s === '\x1b\b') { - // backspace or ctrl+h - key.name = 'backspace'; - key.meta = (s.charAt(0) === '\x1b'); + if (ch === 'O') { + // ESC O letter + // ESC O modifier letter + s += (ch = yield); - } else if (s === '\x1b' || s === '\x1b\x1b') { - // escape key - key.name = 'escape'; - key.meta = (s.length === 2); + if (ch >= '0' && ch <= '9') { + modifier = (ch >> 0) - 1; + s += (ch = yield); + } - } else if (s === ' ' || s === '\x1b ') { - key.name = 'space'; - key.meta = (s.length === 2); + code += ch; - } else if (s.length === 1 && s <= '\x1a') { - // ctrl+letter - key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); - key.ctrl = true; + } else if (ch === '[') { + // ESC [ letter + // ESC [ modifier letter + // ESC [ [ modifier letter + // ESC [ [ num char + s += (ch = yield); - } else if (s.length === 1 && s >= 'a' && s <= 'z') { - // lowercase letter - key.name = s; + if (ch === '[') { + // \x1b[[A + // ^--- escape codes might have a second bracket + code += ch; + s += (ch = yield); + } - } else if (s.length === 1 && s >= 'A' && s <= 'Z') { - // shift+letter - key.name = s.toLowerCase(); - key.shift = true; + /* + * Here and later we try to buffer just enough data to get + * a complete ascii sequence. + * + * We have basically two classes of ascii characters to process: + * + * + * 1. `\x1b[24;5~` should be parsed as { code: '[24~', modifier: 5 } + * + * This particular example is featuring Ctrl+F12 in xterm. + * + * - `;5` part is optional, e.g. it could be `\x1b[24~` + * - first part can contain one or two digits + * + * So the generic regexp is like /^\d\d?(;\d)?[~^$]$/ + * + * + * 2. `\x1b[1;5H` should be parsed as { code: '[H', modifier: 5 } + * + * This particular example is featuring Ctrl+Home in xterm. + * + * - `1;5` part is optional, e.g. it could be `\x1b[H` + * - `1;` part is optional, e.g. it could be `\x1b[5H` + * + * So the generic regexp is like /^((\d;)?\d)?[A-Za-z]$/ + * + */ + const cmdStart = s.length - 1; + + // skip one or two leading digits + if (ch >= '0' && ch <= '9') { + s += (ch = yield); + + if (ch >= '0' && ch <= '9') { + s += (ch = yield); + } + } - } else if (parts = metaKeyCodeRe.exec(s)) { - // meta+character key - key.name = parts[1].toLowerCase(); - key.meta = true; - key.shift = /^[A-Z]$/.test(parts[1]); + // skip modifier + if (ch === ';') { + s += (ch = yield); - } else if (parts = functionKeyCodeRe.exec(s)) { - // ansi escape sequence + if (ch >= '0' && ch <= '9') { + s += (ch = yield); + } + } - // reassemble the key code leaving out leading \x1b's, - // the modifier key bitflag and any meaningless "1;" sequence - var code = (parts[1] || '') + (parts[2] || '') + - (parts[4] || '') + (parts[9] || ''), - modifier = (parts[3] || parts[8] || 1) - 1; + /* + * We buffered enough data, now trying to extract code + * and modifier from it + */ + const cmd = s.slice(cmdStart); + var match; + + if ((match = cmd.match(/^(\d\d?)(;(\d))?([~^$])$/))) { + code += match[1] + match[4]; + modifier = (match[3] || 1) - 1; + } else if ((match = cmd.match(/^((\d;)?(\d))?([A-Za-z])$/))) { + code += match[4]; + modifier = (match[3] || 1) - 1; + } else { + code += cmd; + } + } // Parse the key modifier key.ctrl = !!(modifier & 4); @@ -1142,23 +1180,58 @@ function emitKeys(stream, s) { /* misc. */ case '[Z': key.name = 'tab'; key.shift = true; break; default: key.name = 'undefined'; break; - } - } - // Don't emit a key if no name was found - if (key.name === undefined) { - key = undefined; - } + } else if (ch === '\r') { + // carriage return + key.name = 'return'; + + } else if (ch === '\n') { + // enter, should have been called linefeed + key.name = 'enter'; + + } else if (ch === '\t') { + // tab + key.name = 'tab'; - if (s.length === 1) { - ch = s; + } else if (ch === '\b' || ch === '\x7f') { + // backspace or ctrl+h + key.name = 'backspace'; + key.meta = escaped; + + } else if (ch === '\x1b') { + // escape key + key.name = 'escape'; + key.meta = escaped; + + } else if (ch === ' ') { + key.name = 'space'; + key.meta = escaped; + + } else if (!escaped && ch <= '\x1a') { + // ctrl+letter + key.name = String.fromCharCode(ch.charCodeAt(0) + 'a'.charCodeAt(0) - 1); + key.ctrl = true; + + } else if (/^[0-9A-Za-z]$/.test(ch)) { + // letter, number, shift+letter + key.name = ch.toLowerCase(); + key.shift = /^[A-Z]$/.test(ch); + key.meta = escaped; } - if (key || ch) { - stream.emit('keypress', ch, key); + key.sequence = s; + + if (key.name !== undefined) { + /* Named character or sequence */ + stream.emit('keypress', escaped ? undefined : s, key); + } else if (s.length === 1) { + /* Single unnamed character, e.g. "." */ + stream.emit('keypress', s); + } else { + /* Unrecognized or broken escape sequence, don't emit anything */ } - }); + } } diff --git a/lib/repl.js b/lib/repl.js index 036b561f9c2a94..ddf3fecdfd56ea 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -318,7 +318,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) { // Display prompt again self.displayPrompt(); - }; + } }); self.on('SIGCONT', function() { diff --git a/lib/tls.js b/lib/tls.js index 3ae7a8f58b11a1..10c82860ba826e 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -15,12 +15,17 @@ exports.CLIENT_RENEG_WINDOW = 600; exports.SLAB_BUFFER_SIZE = 10 * 1024 * 1024; exports.DEFAULT_CIPHERS = [ + 'ECDHE-RSA-AES128-GCM-SHA256', + 'ECDHE-ECDSA-AES128-GCM-SHA256', + 'ECDHE-RSA-AES256-GCM-SHA384', + 'ECDHE-ECDSA-AES256-GCM-SHA384', + 'DHE-RSA-AES128-GCM-SHA256', + 'ECDHE-RSA-AES128-SHA256', + 'DHE-RSA-AES128-SHA256', 'ECDHE-RSA-AES256-SHA384', 'DHE-RSA-AES256-SHA384', 'ECDHE-RSA-AES256-SHA256', 'DHE-RSA-AES256-SHA256', - 'ECDHE-RSA-AES128-SHA256', - 'DHE-RSA-AES128-SHA256', 'HIGH', '!aNULL', '!eNULL', diff --git a/lib/url.js b/lib/url.js index 1683f905037c52..8da2f025dc8ca2 100644 --- a/lib/url.js +++ b/lib/url.js @@ -80,7 +80,7 @@ const querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url instanceof Url) return url; - var u = new Url; + var u = new Url(); u.parse(url, parseQueryString, slashesDenoteHost); return u; } diff --git a/lib/util.js b/lib/util.js index a04c19c7353fdf..4dbc59376dcefe 100644 --- a/lib/util.js +++ b/lib/util.js @@ -12,6 +12,8 @@ exports.format = function(f) { return objects.join(' '); } + if (arguments.length === 1) return f; + var i = 1; var args = arguments; var len = args.length; @@ -27,6 +29,7 @@ exports.format = function(f) { } catch (_) { return '[Circular]'; } + // falls through default: return x; } diff --git a/src/async-wrap-inl.h b/src/async-wrap-inl.h index b08f791c2e7635..0518cd3b7ce002 100644 --- a/src/async-wrap-inl.h +++ b/src/async-wrap-inl.h @@ -17,43 +17,30 @@ inline AsyncWrap::AsyncWrap(Environment* env, v8::Handle object, ProviderType provider, AsyncWrap* parent) - : BaseObject(env, object), bits_(static_cast(provider) << 1) { + : BaseObject(env, object, provider), + bits_(static_cast(provider) << 1) { // Check user controlled flag to see if the init callback should run. if (!env->using_asyncwrap()) return; - if (!env->call_async_init_hook() && parent == nullptr) - return; - // TODO(trevnorris): Until it's verified all passed object's are not weak, - // add a HandleScope to make sure there's no leak. - v8::HandleScope scope(env->isolate()); + // If callback hooks have not been enabled, and there is no parent, return. + if (!env->async_wrap_callbacks_enabled() && parent == nullptr) + return; - v8::Local parent_obj; + // If callback hooks have not been enabled and parent has no queue, return. + if (!env->async_wrap_callbacks_enabled() && !parent->has_async_queue()) + return; + v8::HandleScope scope(env->isolate()); v8::TryCatch try_catch; - // If a parent value was sent then call its pre/post functions to let it know - // a conceptual "child" is being instantiated (e.g. that a server has - // received a connection). - if (parent != nullptr) { - parent_obj = parent->object(); - env->async_hooks_pre_function()->Call(parent_obj, 0, nullptr); - if (try_catch.HasCaught()) - FatalError("node::AsyncWrap::AsyncWrap", "parent pre hook threw"); - } - - env->async_hooks_init_function()->Call(object, 0, nullptr); + v8::Local n = v8::Int32::New(env->isolate(), provider); + env->async_hooks_init_function()->Call(object, 1, &n); if (try_catch.HasCaught()) FatalError("node::AsyncWrap::AsyncWrap", "init hook threw"); bits_ |= 1; // has_async_queue() is true now. - - if (parent != nullptr) { - env->async_hooks_post_function()->Call(parent_obj, 0, nullptr); - if (try_catch.HasCaught()) - FatalError("node::AsyncWrap::AsyncWrap", "parent post hook threw"); - } } diff --git a/src/async-wrap.cc b/src/async-wrap.cc index 5710c43146060b..2da6b102934fa7 100644 --- a/src/async-wrap.cc +++ b/src/async-wrap.cc @@ -23,32 +23,28 @@ using v8::kExternalUint32Array; namespace node { +static void EnableHooksJS(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + env->async_hooks()->set_enable_callbacks(1); +} + + +static void DisableHooksJS(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + env->async_hooks()->set_enable_callbacks(0); +} + + static void SetupHooks(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args.GetIsolate()); + Environment* env = Environment::GetCurrent(args); - CHECK(args[0]->IsObject()); + CHECK(args[0]->IsFunction()); CHECK(args[1]->IsFunction()); CHECK(args[2]->IsFunction()); - CHECK(args[3]->IsFunction()); - - // Attach Fields enum from Environment::AsyncHooks. - // Flags attached to this object are: - // - kCallInitHook (0): Tells the AsyncWrap constructor whether it should - // make a call to the init JS callback. This is disabled by default, so - // even after setting the callbacks the flag will have to be set to - // non-zero to have those callbacks called. This only affects the init - // callback. If the init callback was called, then the pre/post callbacks - // will automatically be called. - Local async_hooks_obj = args[0].As(); - Environment::AsyncHooks* async_hooks = env->async_hooks(); - async_hooks_obj->SetIndexedPropertiesToExternalArrayData( - async_hooks->fields(), - kExternalUint32Array, - async_hooks->fields_count()); - - env->set_async_hooks_init_function(args[1].As()); - env->set_async_hooks_pre_function(args[2].As()); - env->set_async_hooks_post_function(args[3].As()); + + env->set_async_hooks_init_function(args[0].As()); + env->set_async_hooks_pre_function(args[1].As()); + env->set_async_hooks_post_function(args[2].As()); env->set_using_asyncwrap(true); } @@ -61,7 +57,9 @@ static void Initialize(Handle target, Isolate* isolate = env->isolate(); HandleScope scope(isolate); - NODE_SET_METHOD(target, "setupHooks", SetupHooks); + env->SetMethod(target, "setupHooks", SetupHooks); + env->SetMethod(target, "disable", DisableHooksJS); + env->SetMethod(target, "enable", EnableHooksJS); Local async_providers = Object::New(isolate); #define V(PROVIDER) \ diff --git a/src/base-object-inl.h b/src/base-object-inl.h index db0daa1e82f559..775b07342edee9 100644 --- a/src/base-object-inl.h +++ b/src/base-object-inl.h @@ -10,10 +10,15 @@ namespace node { -inline BaseObject::BaseObject(Environment* env, v8::Local handle) +inline BaseObject::BaseObject(Environment* env, + v8::Local handle, + const uint16_t class_id) : handle_(env->isolate(), handle), env_(env) { CHECK_EQ(false, handle.IsEmpty()); + // Shift value 8 bits over to try avoiding conflict with anything else. + if (class_id != 0) + handle_.SetWrapperClassId(class_id << 8); } diff --git a/src/base-object.h b/src/base-object.h index 5a7b95827e8f11..90abee4333fcb1 100644 --- a/src/base-object.h +++ b/src/base-object.h @@ -9,7 +9,9 @@ class Environment; class BaseObject { public: - BaseObject(Environment* env, v8::Local handle); + BaseObject(Environment* env, + v8::Local handle, + const uint16_t class_id = 0); virtual ~BaseObject(); // Returns the wrapped object. Returns an empty handle when diff --git a/src/env-inl.h b/src/env-inl.h index 237da7159d1ecf..a0815acaccb926 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -66,8 +66,12 @@ inline int Environment::AsyncHooks::fields_count() const { return kFieldsCount; } -inline bool Environment::AsyncHooks::call_init_hook() { - return fields_[kCallInitHook] != 0; +inline bool Environment::AsyncHooks::callbacks_enabled() { + return fields_[kEnableCallbacks] != 0; +} + +inline void Environment::AsyncHooks::set_enable_callbacks(uint32_t flag) { + fields_[kEnableCallbacks] = flag; } inline Environment::DomainFlag::DomainFlag() { @@ -214,9 +218,9 @@ inline v8::Isolate* Environment::isolate() const { return isolate_; } -inline bool Environment::call_async_init_hook() const { +inline bool Environment::async_wrap_callbacks_enabled() const { // The const_cast is okay, it doesn't violate conceptual const-ness. - return const_cast(this)->async_hooks()->call_init_hook(); + return const_cast(this)->async_hooks()->callbacks_enabled(); } inline bool Environment::in_domain() const { diff --git a/src/env.h b/src/env.h index 9099b3b931717a..e327786e36b907 100644 --- a/src/env.h +++ b/src/env.h @@ -55,6 +55,7 @@ namespace node { V(bytes_parsed_string, "bytesParsed") \ V(callback_string, "callback") \ V(change_string, "change") \ + V(oncertcb_string, "oncertcb") \ V(onclose_string, "_onclose") \ V(code_string, "code") \ V(compare_string, "compare") \ @@ -268,7 +269,8 @@ class Environment { public: inline uint32_t* fields(); inline int fields_count() const; - inline bool call_init_hook(); + inline bool callbacks_enabled(); + inline void set_enable_callbacks(uint32_t flag); private: friend class Environment; // So we can call the constructor. @@ -276,7 +278,7 @@ class Environment { enum Fields { // Set this to not zero if the init hook should be called. - kCallInitHook, + kEnableCallbacks, kFieldsCount }; @@ -373,7 +375,7 @@ class Environment { inline v8::Isolate* isolate() const; inline uv_loop_t* event_loop() const; - inline bool call_async_init_hook() const; + inline bool async_wrap_callbacks_enabled() const; inline bool in_domain() const; inline uint32_t watched_providers() const; diff --git a/src/js_stream.cc b/src/js_stream.cc index 7fcdfd9a94d9fd..6b7c4063e05a2a 100644 --- a/src/js_stream.cc +++ b/src/js_stream.cc @@ -71,6 +71,7 @@ int JSStream::DoShutdown(ShutdownWrap* req_wrap) { req_wrap->object() }; + req_wrap->Dispatched(); Local res = MakeCallback(env()->onshutdown_string(), ARRAY_SIZE(argv), argv); @@ -88,13 +89,14 @@ int JSStream::DoWrite(WriteWrap* w, Local bufs_arr = Array::New(env()->isolate(), count); for (size_t i = 0; i < count; i++) - bufs_arr->Set(i, Buffer::New(env(), bufs[0].base, bufs[0].len)); + bufs_arr->Set(i, Buffer::New(env(), bufs[i].base, bufs[i].len)); Local argv[] = { w->object(), bufs_arr }; + w->Dispatched(); Local res = MakeCallback(env()->onwrite_string(), ARRAY_SIZE(argv), argv); diff --git a/src/node.h b/src/node.h index 28b40aa0721b3a..acdfe5740740ef 100644 --- a/src/node.h +++ b/src/node.h @@ -42,7 +42,35 @@ #include "v8.h" // NOLINT(build/include_order) #include "node_version.h" // NODE_MODULE_VERSION -#define NODE_DEPRECATED(msg, fn) V8_DEPRECATED(msg, fn) +#define IOJS_MAKE_VERSION(major, minor, patch) \ + ((major) * 0x1000 + (minor) * 0x100 + (patch)) + +#ifdef __clang__ +# define IOJS_CLANG_AT_LEAST(major, minor, patch) \ + (IOJS_MAKE_VERSION(major, minor, patch) <= \ + IOJS_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)) +#else +# define IOJS_CLANG_AT_LEAST(major, minor, patch) (0) +#endif + +#ifdef __GNUC__ +# define IOJS_GNUC_AT_LEAST(major, minor, patch) \ + (IOJS_MAKE_VERSION(major, minor, patch) <= \ + IOJS_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)) +#else +# define IOJS_GNUC_AT_LEAST(major, minor, patch) (0) +#endif + +#if IOJS_CLANG_AT_LEAST(2, 9, 0) || IOJS_GNUC_AT_LEAST(4, 5, 0) +# define NODE_DEPRECATED(message, declarator) \ + __attribute__((deprecated(message))) declarator +#elif defined(_MSC_VER) +# define NODE_DEPRECATED(message, declarator) \ + __declspec(deprecated) declarator +#else +# define NODE_DEPRECATED(message, declarator) \ + declarator +#endif // Forward-declare libuv loop struct uv_loop_s; @@ -237,9 +265,10 @@ inline void NODE_SET_PROTOTYPE_METHOD(v8::Handle recv, #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -enum encoding ParseEncoding(v8::Isolate* isolate, - v8::Handle encoding_v, - enum encoding default_encoding = BINARY); +NODE_EXTERN enum encoding ParseEncoding( + v8::Isolate* isolate, + v8::Handle encoding_v, + enum encoding default_encoding = BINARY); NODE_DEPRECATED("Use ParseEncoding(isolate, ...)", inline enum encoding ParseEncoding( v8::Handle encoding_v, diff --git a/src/node.js b/src/node.js index e4167cb2d1cfbf..e3285cd2220690 100644 --- a/src/node.js +++ b/src/node.js @@ -82,16 +82,9 @@ delete process.env.NODE_UNIQUE_ID; } - // Load any preload modules - if (process._preload_modules) { - var Module = NativeModule.require('module'); - process._preload_modules.forEach(function(module) { - Module._load(module); - }); - } - if (process._eval != null) { // User passed '-e' or '--eval' arguments to Node. + startup.preloadModules(); evalScript('[eval]'); } else if (process.argv[1]) { // make process.argv[1] into a full path @@ -99,7 +92,7 @@ process.argv[1] = path.resolve(process.argv[1]); var Module = NativeModule.require('module'); - + startup.preloadModules(); if (global.v8debug && process.execArgv.some(function(arg) { return arg.match(/^--debug-brk(=[0-9]*)?$/); @@ -329,22 +322,33 @@ // Run callbacks that have no domain. // Using domains will cause this to be overridden. function _tickCallback() { - var callback, threw, tock; + var callback, args, tock; do { while (tickInfo[kIndex] < tickInfo[kLength]) { tock = nextTickQueue[tickInfo[kIndex]++]; callback = tock.callback; - threw = true; - try { - if (tock.args === undefined) - callback(); - else - callback.apply(null, tock.args); - threw = false; - } finally { - if (threw) - tickDone(); + args = tock.args; + // Using separate callback execution functions helps to limit the + // scope of DEOPTs caused by using try blocks and allows direct + // callback invocation with small numbers of arguments to avoid the + // performance hit associated with using `fn.apply()` + if (args === undefined) { + doNTCallback0(callback); + } else { + switch (args.length) { + case 1: + doNTCallback1(callback, args[0]); + break; + case 2: + doNTCallback2(callback, args[0], args[1]); + break; + case 3: + doNTCallback3(callback, args[0], args[1], args[2]); + break; + default: + doNTCallbackMany(callback, args); + } } if (1e4 < tickInfo[kIndex]) tickDone(); @@ -356,25 +360,36 @@ } function _tickDomainCallback() { - var callback, domain, threw, tock; + var callback, domain, args, tock; do { while (tickInfo[kIndex] < tickInfo[kLength]) { tock = nextTickQueue[tickInfo[kIndex]++]; callback = tock.callback; domain = tock.domain; + args = tock.args; if (domain) domain.enter(); - threw = true; - try { - if (tock.args === undefined) - callback(); - else - callback.apply(null, tock.args); - threw = false; - } finally { - if (threw) - tickDone(); + // Using separate callback execution functions helps to limit the + // scope of DEOPTs caused by using try blocks and allows direct + // callback invocation with small numbers of arguments to avoid the + // performance hit associated with using `fn.apply()` + if (args === undefined) { + doNTCallback0(callback); + } else { + switch (args.length) { + case 1: + doNTCallback1(callback, args[0]); + break; + case 2: + doNTCallback2(callback, args[0], args[1]); + break; + case 3: + doNTCallback3(callback, args[0], args[1], args[2]); + break; + default: + doNTCallbackMany(callback, args); + } } if (1e4 < tickInfo[kIndex]) tickDone(); @@ -387,6 +402,61 @@ } while (tickInfo[kLength] !== 0); } + function doNTCallback0(callback) { + var threw = true; + try { + callback(); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallback1(callback, arg1) { + var threw = true; + try { + callback(arg1); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallback2(callback, arg1, arg2) { + var threw = true; + try { + callback(arg1, arg2); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallback3(callback, arg1, arg2, arg3) { + var threw = true; + try { + callback(arg1, arg2, arg3); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + + function doNTCallbackMany(callback, args) { + var threw = true; + try { + callback.apply(null, args); + threw = false; + } finally { + if (threw) + tickDone(); + } + } + function TickObject(c, args) { this.callback = c; this.domain = process.domain || null; @@ -398,7 +468,7 @@ if (process._exiting) return; - var args = undefined; + var args; if (arguments.length > 1) { args = []; for (var i = 1; i < arguments.length; i++) @@ -419,8 +489,9 @@ if (!process.emit('unhandledRejection', reason, promise)) { // Nobody is listening. // TODO(petkaantonov) Take some default action, see #830 - } else + } else { hadListeners = true; + } } } return hadListeners; @@ -779,6 +850,16 @@ }; }; + // Load preload modules + startup.preloadModules = function() { + if (process._preload_modules) { + var Module = NativeModule.require('module'); + process._preload_modules.forEach(function(module) { + Module._load(module); + }); + } + }; + // Below you find a minimal module system, which is used to load the node // core modules found in lib/*.js. All core modules are compiled into the // node binary, so they can be loaded faster. diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 8a473847f285f2..bd02279212583a 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -98,7 +98,7 @@ Local New(Isolate* isolate, Handle string, enum encoding enc) { size_t length = StringBytes::Size(isolate, string, enc); - Local buf = New(length); + Local buf = New(isolate, length); char* data = Buffer::Data(buf); StringBytes::Write(isolate, data, length, string, enc); diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 1d112001e88a0b..44c43b72a0e937 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -132,6 +132,8 @@ template int SSLWrap::SelectNextProtoCallback( #endif template int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg); template void SSLWrap::DestroySSL(); +template int SSLWrap::SSLCertCallback(SSL* s, void* arg); +template void SSLWrap::WaitForCertCb(CertCb cb, void* arg); static void crypto_threadid_cb(CRYPTO_THREADID* tid) { @@ -511,7 +513,8 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx, } while ((ca = PEM_read_bio_X509(in, nullptr, CryptoPemCallback, nullptr))) { - r = SSL_CTX_add_extra_chain_cert(ctx, ca); + // NOTE: Increments reference count on `ca` + r = SSL_CTX_add1_chain_cert(ctx, ca); if (!r) { X509_free(ca); @@ -754,6 +757,12 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo& args) { if (dh == nullptr) return; + const int keylen = BN_num_bits(dh->p); + if (keylen < 1024) + return env->ThrowError("DH parameter is less than 1024 bits"); + else if (keylen < 2048) + fprintf(stderr, "WARNING: DH parameter is less than 2048 bits\n"); + SSL_CTX_set_options(sc->ctx_, SSL_OP_SINGLE_DH_USE); int r = SSL_CTX_set_tmp_dh(sc->ctx_, dh); DH_free(dh); @@ -987,6 +996,7 @@ void SSLWrap::AddMethods(Environment* env, Handle t) { env->SetProtoMethod(t, "verifyError", VerifyError); env->SetProtoMethod(t, "getCurrentCipher", GetCurrentCipher); env->SetProtoMethod(t, "endParser", EndParser); + env->SetProtoMethod(t, "certCbDone", CertCbDone); env->SetProtoMethod(t, "renegotiate", Renegotiate); env->SetProtoMethod(t, "shutdownSSL", Shutdown); env->SetProtoMethod(t, "getTLSTicket", GetTLSTicket); @@ -1869,6 +1879,122 @@ int SSLWrap::TLSExtStatusCallback(SSL* s, void* arg) { #endif // NODE__HAVE_TLSEXT_STATUS_CB +template +void SSLWrap::WaitForCertCb(CertCb cb, void* arg) { + cert_cb_ = cb; + cert_cb_arg_ = arg; +} + + +template +int SSLWrap::SSLCertCallback(SSL* s, void* arg) { + Base* w = static_cast(SSL_get_app_data(s)); + + if (!w->is_server()) + return 1; + + if (!w->is_waiting_cert_cb()) + return 1; + + if (w->cert_cb_running_) + return -1; + + Environment* env = w->env(); + HandleScope handle_scope(env->isolate()); + Context::Scope context_scope(env->context()); + w->cert_cb_running_ = true; + + Local info = Object::New(env->isolate()); + + SSL_SESSION* sess = SSL_get_session(s); + if (sess != nullptr) { + if (sess->tlsext_hostname == nullptr) { + info->Set(env->servername_string(), String::Empty(env->isolate())); + } else { + Local servername = OneByteString(env->isolate(), + sess->tlsext_hostname, + strlen(sess->tlsext_hostname)); + info->Set(env->servername_string(), servername); + } + info->Set(env->tls_ticket_string(), + Boolean::New(env->isolate(), sess->tlsext_ticklen != 0)); + } + bool ocsp = s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp; + info->Set(env->ocsp_request_string(), Boolean::New(env->isolate(), ocsp)); + + Local argv[] = { info }; + w->MakeCallback(env->oncertcb_string(), ARRAY_SIZE(argv), argv); + + if (!w->cert_cb_running_) + return 1; + + // Performing async action, wait... + return -1; +} + + +template +void SSLWrap::CertCbDone(const FunctionCallbackInfo& args) { + Base* w = Unwrap(args.Holder()); + Environment* env = w->env(); + + CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_); + + Local object = w->object(); + Local ctx = object->Get(env->sni_context_string()); + Local cons = env->secure_context_constructor_template(); + + // Not an object, probably undefined or null + if (!ctx->IsObject()) + goto fire_cb; + + if (cons->HasInstance(ctx)) { + SecureContext* sc = Unwrap(ctx.As()); + w->sni_context_.Reset(); + w->sni_context_.Reset(env->isolate(), ctx); + + int rv; + + // NOTE: reference count is not increased by this API methods + X509* x509 = SSL_CTX_get0_certificate(sc->ctx_); + EVP_PKEY* pkey = SSL_CTX_get0_privatekey(sc->ctx_); + STACK_OF(X509)* chain; + + rv = SSL_CTX_get0_chain_certs(sc->ctx_, &chain); + if (rv) + rv = SSL_use_certificate(w->ssl_, x509); + if (rv) + rv = SSL_use_PrivateKey(w->ssl_, pkey); + if (rv && chain != nullptr) + rv = SSL_set1_chain(w->ssl_, chain); + if (!rv) { + unsigned long err = ERR_get_error(); + if (!err) + return env->ThrowError("CertCbDone"); + return ThrowCryptoError(env, err); + } + } else { + // Failure: incorrect SNI context object + Local err = Exception::TypeError(env->sni_context_err_string()); + w->MakeCallback(env->onerror_string(), 1, &err); + return; + } + + fire_cb: + CertCb cb; + void* arg; + + cb = w->cert_cb_; + arg = w->cert_cb_arg_; + + w->cert_cb_running_ = false; + w->cert_cb_ = nullptr; + w->cert_cb_arg_ = nullptr; + + cb(arg); +} + + template void SSLWrap::SSLGetter(Local property, const PropertyCallbackInfo& info) { @@ -1975,6 +2101,10 @@ int Connection::HandleSSLError(const char* func, DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func); return 0; + } else if (err == SSL_ERROR_WANT_X509_LOOKUP) { + DEBUG_PRINT("[%p] SSL: %s want x509 lookup\n", ssl_, func); + return 0; + } else if (err == SSL_ERROR_ZERO_RETURN) { HandleScope scope(ssl_env()->isolate()); @@ -2140,7 +2270,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) { // Call the SNI callback and use its return value as context if (!conn->sniObject_.IsEmpty()) { - conn->sniContext_.Reset(); + conn->sni_context_.Reset(); Local arg = PersistentToLocal(env->isolate(), conn->servername_); Local ret = conn->MakeCallback(env->onselect_string(), 1, &arg); @@ -2149,7 +2279,7 @@ int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) { Local secure_context_constructor_template = env->secure_context_constructor_template(); if (secure_context_constructor_template->HasInstance(ret)) { - conn->sniContext_.Reset(env->isolate(), ret); + conn->sni_context_.Reset(env->isolate(), ret); SecureContext* sc = Unwrap(ret.As()); InitNPN(sc); SSL_set_SSL_CTX(s, sc->ctx_); @@ -2188,6 +2318,8 @@ void Connection::New(const FunctionCallbackInfo& args) { InitNPN(sc); + SSL_set_cert_cb(conn->ssl_, SSLWrap::SSLCertCallback, conn); + #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB if (is_server) { SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_); @@ -4613,7 +4745,7 @@ void RandomBytesCheck(RandomBytesRequest* req, Local argv[2]) { size_t size; req->return_memory(&data, &size); argv[0] = Null(req->env()->isolate()); - argv[1] = Buffer::Use(data, size); + argv[1] = Buffer::Use(req->env()->isolate(), data, size); } } diff --git a/src/node_crypto.h b/src/node_crypto.h index f6069f88410c0b..179543bd50124a 100644 --- a/src/node_crypto.h +++ b/src/node_crypto.h @@ -143,7 +143,10 @@ class SSLWrap { kind_(kind), next_sess_(nullptr), session_callbacks_(false), - new_session_wait_(false) { + new_session_wait_(false), + cert_cb_(nullptr), + cert_cb_arg_(nullptr), + cert_cb_running_(false) { ssl_ = SSL_new(sc->ctx_); env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize); CHECK_NE(ssl_, nullptr); @@ -160,6 +163,9 @@ class SSLWrap { npn_protos_.Reset(); selected_npn_proto_.Reset(); #endif +#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB + sni_context_.Reset(); +#endif #ifdef NODE__HAVE_TLSEXT_STATUS_CB ocsp_response_.Reset(); #endif // NODE__HAVE_TLSEXT_STATUS_CB @@ -170,8 +176,11 @@ class SSLWrap { inline bool is_server() const { return kind_ == kServer; } inline bool is_client() const { return kind_ == kClient; } inline bool is_waiting_new_session() const { return new_session_wait_; } + inline bool is_waiting_cert_cb() const { return cert_cb_ != nullptr; } protected: + typedef void (*CertCb)(void* arg); + // Size allocated by OpenSSL: one for SSL structure, one for SSL3_STATE and // some for buffers. // NOTE: Actually it is much more than this @@ -199,6 +208,7 @@ class SSLWrap { static void VerifyError(const v8::FunctionCallbackInfo& args); static void GetCurrentCipher(const v8::FunctionCallbackInfo& args); static void EndParser(const v8::FunctionCallbackInfo& args); + static void CertCbDone(const v8::FunctionCallbackInfo& args); static void Renegotiate(const v8::FunctionCallbackInfo& args); static void Shutdown(const v8::FunctionCallbackInfo& args); static void GetTLSTicket(const v8::FunctionCallbackInfo& args); @@ -227,10 +237,12 @@ class SSLWrap { void* arg); #endif // OPENSSL_NPN_NEGOTIATED static int TLSExtStatusCallback(SSL* s, void* arg); + static int SSLCertCallback(SSL* s, void* arg); static void SSLGetter(v8::Local property, const v8::PropertyCallbackInfo& info); void DestroySSL(); + void WaitForCertCb(CertCb cb, void* arg); inline Environment* ssl_env() const { return env_; @@ -242,6 +254,12 @@ class SSLWrap { SSL* ssl_; bool session_callbacks_; bool new_session_wait_; + + // SSL_set_cert_cb + CertCb cert_cb_; + void* cert_cb_arg_; + bool cert_cb_running_; + ClientHelloParser hello_parser_; #ifdef NODE__HAVE_TLSEXT_STATUS_CB @@ -253,6 +271,10 @@ class SSLWrap { v8::Persistent selected_npn_proto_; #endif // OPENSSL_NPN_NEGOTIATED +#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB + v8::Persistent sni_context_; +#endif + friend class SecureContext; }; @@ -264,7 +286,6 @@ class Connection : public SSLWrap, public AsyncWrap { ~Connection() override { #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB sniObject_.Reset(); - sniContext_.Reset(); servername_.Reset(); #endif } @@ -279,7 +300,6 @@ class Connection : public SSLWrap, public AsyncWrap { #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB v8::Persistent sniObject_; - v8::Persistent sniContext_; v8::Persistent servername_; #endif diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index f71302d3130a16..6c5d76ecf6cc95 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -554,7 +554,9 @@ const struct http_parser_settings Parser::settings = { Parser::on_header_value, Parser::on_headers_complete, Parser::on_body, - Parser::on_message_complete + Parser::on_message_complete, + nullptr, // on_chunk_header + nullptr // on_chunk_complete }; diff --git a/src/node_v8.cc b/src/node_v8.cc index f3bdda409d0f6e..2834a21496bbdb 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -60,6 +60,13 @@ void GetHeapStatistics(const FunctionCallbackInfo& args) { void SetFlagsFromString(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + + if (args.Length() < 1) + return env->ThrowTypeError("v8 flag is required"); + if (!args[0]->IsString()) + return env->ThrowTypeError("v8 flag must be a string"); + String::Utf8Value flags(args[0]); V8::SetFlagsFromString(*flags, flags.length()); } diff --git a/src/spawn_sync.cc b/src/spawn_sync.cc index b014bae40dffc9..901a4a001df051 100644 --- a/src/spawn_sync.cc +++ b/src/spawn_sync.cc @@ -165,9 +165,9 @@ void SyncProcessStdioPipe::Close() { } -Local SyncProcessStdioPipe::GetOutputAsBuffer() const { +Local SyncProcessStdioPipe::GetOutputAsBuffer(Isolate* isolate) const { size_t length = OutputLength(); - Local js_buffer = Buffer::New(length); + Local js_buffer = Buffer::New(isolate, length); CopyOutput(Buffer::Data(js_buffer)); return js_buffer; } @@ -679,7 +679,7 @@ Local SyncProcessRunner::BuildOutputArray() { for (uint32_t i = 0; i < stdio_count_; i++) { SyncProcessStdioPipe* h = stdio_pipes_[i]; if (h != nullptr && h->writable()) - js_output->Set(i, h->GetOutputAsBuffer()); + js_output->Set(i, h->GetOutputAsBuffer(env()->isolate())); else js_output->Set(i, Null(env()->isolate())); } diff --git a/src/spawn_sync.h b/src/spawn_sync.h index 4a71b75202b5b2..9a544fa0576402 100644 --- a/src/spawn_sync.h +++ b/src/spawn_sync.h @@ -72,7 +72,7 @@ class SyncProcessStdioPipe { int Start(); void Close(); - Local GetOutputAsBuffer() const; + Local GetOutputAsBuffer(Isolate* isolate) const; inline bool readable() const; inline bool writable() const; diff --git a/src/stream_base.cc b/src/stream_base.cc index 3a9f30f279bd2c..b2518404a8fe62 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -60,7 +60,6 @@ int StreamBase::Shutdown(const FunctionCallbackInfo& args) { AfterShutdown); int err = DoShutdown(req_wrap); - req_wrap->Dispatched(); if (err) delete req_wrap; return err; @@ -181,7 +180,6 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { if (bufs != bufs_) delete[] bufs; - req_wrap->Dispatched(); req_wrap->object()->Set(env->async(), True(env->isolate())); req_wrap->object()->Set(env->bytes_string(), Number::New(env->isolate(), bytes)); @@ -228,7 +226,6 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { req_wrap = WriteWrap::New(env, req_wrap_obj, this, AfterWrite); err = DoWrite(req_wrap, bufs, count, nullptr); - req_wrap->Dispatched(); req_wrap_obj->Set(env->async(), True(env->isolate())); if (err) @@ -347,7 +344,6 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { reinterpret_cast(send_handle)); } - req_wrap->Dispatched(); req_wrap->object()->Set(env->async(), True(env->isolate())); if (err) diff --git a/src/stream_wrap.cc b/src/stream_wrap.cc index be5757d4a60bd1..540639d458050c 100644 --- a/src/stream_wrap.cc +++ b/src/stream_wrap.cc @@ -279,7 +279,10 @@ void StreamWrap::SetBlocking(const FunctionCallbackInfo& args) { int StreamWrap::DoShutdown(ShutdownWrap* req_wrap) { - return uv_shutdown(&req_wrap->req_, stream(), AfterShutdown); + int err; + err = uv_shutdown(&req_wrap->req_, stream(), AfterShutdown); + req_wrap->Dispatched(); + return err; } @@ -353,6 +356,7 @@ int StreamWrap::DoWrite(WriteWrap* w, } } + w->Dispatched(); UpdateWriteQueueSize(); return r; diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index c013bf935eb9cb..30768640eb99e2 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -150,6 +150,8 @@ void TLSWrap::InitSSL() { InitNPN(sc_); + SSL_set_cert_cb(ssl_, SSLWrap::SSLCertCallback, this); + if (is_server()) { SSL_set_accept_state(ssl_); } else if (is_client()) { @@ -309,7 +311,6 @@ void TLSWrap::EncOut() { for (size_t i = 0; i < count; i++) buf[i] = uv_buf_init(data[i], size[i]); int err = stream_->DoWrite(write_req, buf, count, nullptr); - write_req->Dispatched(); // Ignore errors, this should be already handled in js if (err) { @@ -351,11 +352,16 @@ void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) { Local TLSWrap::GetSSLError(int status, int* err, const char** msg) { EscapableHandleScope scope(env()->isolate()); + // ssl_ is already destroyed in reading EOF by close notify alert. + if (ssl_ == nullptr) + return Local(); + *err = SSL_get_error(ssl_, status); switch (*err) { case SSL_ERROR_NONE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: + case SSL_ERROR_WANT_X509_LOOKUP: break; case SSL_ERROR_ZERO_RETURN: return scope.Escape(env()->zero_return_string()); @@ -430,7 +436,10 @@ void TLSWrap::ClearOut() { OnRead(UV_EOF, nullptr); } - if (read == -1) { + // We need to check whether an error occurred or the connection was + // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0. + // See iojs#1642 and SSL_read(3SSL) for details. + if (read <= 0) { int err; Local arg = GetSSLError(read, &err, nullptr); @@ -565,6 +574,7 @@ int TLSWrap::DoWrite(WriteWrap* w, // Queue callback to execute it on next tick write_item_queue_.PushBack(new WriteItem(w)); + w->Dispatched(); // Write queued data if (empty) { @@ -738,12 +748,6 @@ void TLSWrap::EnableSessionCallbacks( const FunctionCallbackInfo& args) { TLSWrap* wrap = Unwrap(args.Holder()); wrap->enable_session_callbacks(); - EnableHelloParser(args); -} - - -void TLSWrap::EnableHelloParser(const FunctionCallbackInfo& args) { - TLSWrap* wrap = Unwrap(args.Holder()); NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength); wrap->hello_parser_.Start(SSLWrap::OnClientHello, OnClientHelloParseEnd, @@ -759,6 +763,12 @@ void TLSWrap::DestroySSL(const FunctionCallbackInfo& args) { } +void TLSWrap::EnableCertCb(const FunctionCallbackInfo& args) { + TLSWrap* wrap = Unwrap(args.Holder()); + wrap->WaitForCertCb(OnClientHelloParseEnd, wrap); +} + + void TLSWrap::OnClientHelloParseEnd(void* arg) { TLSWrap* c = static_cast(arg); c->Cycle(); @@ -857,8 +867,8 @@ void TLSWrap::Initialize(Handle target, env->SetProtoMethod(t, "start", Start); env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode); env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks); - env->SetProtoMethod(t, "enableHelloParser", EnableHelloParser); env->SetProtoMethod(t, "destroySSL", DestroySSL); + env->SetProtoMethod(t, "enableCertCb", EnableCertCb); StreamBase::AddMethods(env, t, StreamBase::kFlagHasWritev); SSLWrap::AddMethods(env, t); diff --git a/src/tls_wrap.h b/src/tls_wrap.h index 25088d30261189..a30447519083c2 100644 --- a/src/tls_wrap.h +++ b/src/tls_wrap.h @@ -130,7 +130,7 @@ class TLSWrap : public crypto::SSLWrap, static void SetVerifyMode(const v8::FunctionCallbackInfo& args); static void EnableSessionCallbacks( const v8::FunctionCallbackInfo& args); - static void EnableHelloParser( + static void EnableCertCb( const v8::FunctionCallbackInfo& args); static void DestroySSL(const v8::FunctionCallbackInfo& args); @@ -159,10 +159,6 @@ class TLSWrap : public crypto::SSLWrap, // If true - delivered EOF to the js-land, either after `close_notify`, or // after the `UV_EOF` on socket. bool eof_; - -#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB - v8::Persistent sni_context_; -#endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB }; } // namespace node diff --git a/src/util.cc b/src/util.cc index f382b3d565a8cf..a793368c2cdfa8 100644 --- a/src/util.cc +++ b/src/util.cc @@ -13,7 +13,7 @@ Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Handle value) return; // Allocate enough space to include the null terminator - size_t len = StringBytes::StorageSize(string, UTF8) + 1; + size_t len = StringBytes::StorageSize(isolate, string, UTF8) + 1; if (len > sizeof(str_st_)) { str_ = static_cast(malloc(len)); CHECK_NE(str_, nullptr); diff --git a/test/.eslintrc b/test/.eslintrc new file mode 100644 index 00000000000000..d5d95584ea6811 --- /dev/null +++ b/test/.eslintrc @@ -0,0 +1,5 @@ +## Test-specific linter rules + +rules: + ## allow unreachable code + no-unreachable: 0 diff --git a/test/addons/async-hello-world/test.js b/test/addons/async-hello-world/test.js index 83f5e7206ec073..a284a019f01a8b 100644 --- a/test/addons/async-hello-world/test.js +++ b/test/addons/async-hello-world/test.js @@ -1,15 +1,16 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); var called = false; -process.on('exit', function () { +process.on('exit', function() { assert(called); }); -binding(5, function (err, val) { +binding(5, function(err, val) { assert.equal(null, err); assert.equal(10, val); - process.nextTick(function () { + process.nextTick(function() { called = true; }); }); diff --git a/test/addons/at-exit/test.js b/test/addons/at-exit/test.js index 4466b898afe597..c36f59b976e983 100644 --- a/test/addons/at-exit/test.js +++ b/test/addons/at-exit/test.js @@ -1 +1,2 @@ +'use strict'; var binding = require('./build/Release/binding'); diff --git a/test/addons/hello-world-function-export/test.js b/test/addons/hello-world-function-export/test.js index 238e105381dd54..1056386583faf1 100644 --- a/test/addons/hello-world-function-export/test.js +++ b/test/addons/hello-world-function-export/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); assert.equal('world', binding()); diff --git a/test/addons/hello-world/test.js b/test/addons/hello-world/test.js index 18008db58124b2..c0492292fd7250 100644 --- a/test/addons/hello-world/test.js +++ b/test/addons/hello-world/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); assert.equal('world', binding.hello()); diff --git a/test/addons/repl-domain-abort/test.js b/test/addons/repl-domain-abort/test.js index f0d968d173f005..a520df03805ccb 100644 --- a/test/addons/repl-domain-abort/test.js +++ b/test/addons/repl-domain-abort/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var repl = require('repl'); var stream = require('stream'); diff --git a/test/addons/smalloc-alloc/test.js b/test/addons/smalloc-alloc/test.js index 47197be631ed17..76648e04c4ce07 100644 --- a/test/addons/smalloc-alloc/test.js +++ b/test/addons/smalloc-alloc/test.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var binding = require('./build/Release/binding'); var obj = binding.alloc(16); diff --git a/test/common.js b/test/common.js index ec0b387328d6b7..94d6f2109576b9 100644 --- a/test/common.js +++ b/test/common.js @@ -1,3 +1,4 @@ +'use strict'; var path = require('path'); var fs = require('fs'); var assert = require('assert'); @@ -107,8 +108,8 @@ if (process.env.NODE_COMMON_PIPE) { if (process.platform === 'win32') { exports.faketimeCli = false; } else { - exports.faketimeCli = path.join(__dirname, "..", "tools", "faketime", "src", - "faketime"); + exports.faketimeCli = path.join(__dirname, '..', 'tools', 'faketime', 'src', + 'faketime'); } var ifaces = os.networkInterfaces(); @@ -307,7 +308,7 @@ exports.mustCall = function(fn, expected) { var context = { expected: expected, actual: 0, - stack: (new Error).stack, + stack: (new Error()).stack, name: fn.name || '' }; @@ -345,11 +346,11 @@ if (process.platform === 'win32') { */ exports.getServiceName = function getServiceName(port, protocol) { if (port == null) { - throw new Error("Missing port number"); + throw new Error('Missing port number'); } if (typeof protocol !== 'string') { - throw new Error("Protocol must be a string"); + throw new Error('Protocol must be a string'); } /* @@ -360,10 +361,10 @@ exports.getServiceName = function getServiceName(port, protocol) { try { /* - * I'm not a big fan of readFileSync, but reading /etc/services asynchronously - * here would require implementing a simple line parser, which seems overkill - * for a simple utility function that is not running concurrently with any - * other one. + * I'm not a big fan of readFileSync, but reading /etc/services + * asynchronously here would require implementing a simple line parser, + * which seems overkill for a simple utility function that is not running + * concurrently with any other one. */ var servicesContent = fs.readFileSync(etcServicesFileName, { encoding: 'utf8'}); @@ -380,7 +381,7 @@ exports.getServiceName = function getServiceName(port, protocol) { } return serviceName; -} +}; exports.hasMultiLocalhost = function hasMultiLocalhost() { var TCP = process.binding('tcp_wrap').TCP; @@ -397,7 +398,7 @@ exports.isValidHostname = function(str) { '(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$'); return !!str.match(re) && str.length <= 255; -} +}; exports.fileExists = function(pathname) { try { diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index c3f219874e43af..714a22c2a22fdc 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_DEBUGGER_TIMEOUT = 2000; var common = require('../common'); var assert = require('assert'); @@ -55,7 +56,7 @@ function startDebugger(scriptToDebug) { quitCalled = true; child.stdin.write('quit'); child.kill('SIGTERM'); - } + }; setTimeout(function() { console.error('dying badly buffer=%j', buffer); diff --git a/test/debugger/test-debug-break-on-uncaught.js b/test/debugger/test-debug-break-on-uncaught.js index 57095d93abf9a0..397c4225d27f7e 100644 --- a/test/debugger/test-debug-break-on-uncaught.js +++ b/test/debugger/test-debug-break-on-uncaught.js @@ -1,3 +1,4 @@ +'use strict'; var path = require('path'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -44,7 +45,7 @@ function runScenario(scriptName, throwsInFile, throwsOnLine, next) { child.on('close', function() { assert(asserted, 'debugger did not pause on exception'); if (next) next(); - }) + }); var exceptions = []; diff --git a/test/debugger/test-debugger-client.js b/test/debugger/test-debugger-client.js index 4bb27c277eab72..972c94707ee56b 100644 --- a/test/debugger/test-debugger-client.js +++ b/test/debugger/test-debugger-client.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_DEBUGGER_TIMEOUT = 2000; var common = require('../common'); var assert = require('assert'); @@ -66,7 +67,7 @@ var d = 'Content-Length: 466\r\n\r\n' + '{"seq":10,"type":"event","event":"afterCompile","success":true,' + '"body":{"script":{"handle":1,"type":"script","name":"dns.js",' + '"id":34,"lineOffset":0,"columnOffset":0,"lineCount":241,' + - '"sourceStart":"(function (module, exports, require) {' + + '"sourceStart":"(function(module, exports, require) {' + 'var dns = process.binding(\'cares\')' + ';\\nvar ne","sourceLength":6137,"scriptType":2,"compilationType":0,' + '"context":{"ref":0},"text":"dns.js (lines: 241)"}},"refs":' + @@ -127,8 +128,8 @@ addTest(function(client, done) { var connectCount = 0; -var script = 'setTimeout(function () { console.log("blah"); });' + - 'setInterval(function () {}, 1000000);'; +var script = 'setTimeout(function() { console.log("blah"); });' + + 'setInterval(function() {}, 1000000);'; var nodeProcess; diff --git a/test/debugger/test-debugger-debug-brk.js b/test/debugger/test-debugger-debug-brk.js index 7bf7d639f5362c..3b54f853bc8de3 100644 --- a/test/debugger/test-debugger-debug-brk.js +++ b/test/debugger/test-debugger-debug-brk.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/debugger/test-debugger-remote.js b/test/debugger/test-debugger-remote.js index 641199a1714af7..abb67c19cbf0cd 100644 --- a/test/debugger/test-debugger-remote.js +++ b/test/debugger/test-debugger-remote.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/debugger/test-debugger-repl-break-in-module.js b/test/debugger/test-debugger-repl-break-in-module.js index 8d33d126438064..995f6fe0db3a3d 100644 --- a/test/debugger/test-debugger-repl-break-in-module.js +++ b/test/debugger/test-debugger-repl-break-in-module.js @@ -1,3 +1,4 @@ +'use strict'; var repl = require('./helper-debugger-repl.js'); repl.startDebugger('break-in-module/main.js'); diff --git a/test/debugger/test-debugger-repl-restart.js b/test/debugger/test-debugger-repl-restart.js index 9d83d67188a63c..d3b2c169dea0a8 100644 --- a/test/debugger/test-debugger-repl-restart.js +++ b/test/debugger/test-debugger-repl-restart.js @@ -1,3 +1,4 @@ +'use strict'; var repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); @@ -7,7 +8,7 @@ var linesWithBreakpoint = [ // We slice here, because addTest will change the given array. repl.addTest('sb(6)', linesWithBreakpoint.slice()); -var initialLines = repl.initialLines.slice() +var initialLines = repl.initialLines.slice(); initialLines.splice(2, 0, /Restoring/, /Warning/); // Restart the debugged script diff --git a/test/debugger/test-debugger-repl-term.js b/test/debugger/test-debugger-repl-term.js index a42a253c5a9aee..741adf682ab1dd 100644 --- a/test/debugger/test-debugger-repl-term.js +++ b/test/debugger/test-debugger-repl-term.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_FORCE_READLINE = 1; var repl = require('./helper-debugger-repl.js'); diff --git a/test/debugger/test-debugger-repl-utf8.js b/test/debugger/test-debugger-repl-utf8.js index 0fccf2477b03ab..c32216e5d6dc66 100644 --- a/test/debugger/test-debugger-repl-utf8.js +++ b/test/debugger/test-debugger-repl-utf8.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var script = common.fixturesDir + '/breakpoints_utf8.js'; process.env.NODE_DEBUGGER_TEST_SCRIPT = script; diff --git a/test/debugger/test-debugger-repl.js b/test/debugger/test-debugger-repl.js index 788ea9cb6a273f..2e44da55d72859 100644 --- a/test/debugger/test-debugger-repl.js +++ b/test/debugger/test-debugger-repl.js @@ -1,3 +1,4 @@ +'use strict'; var repl = require('./helper-debugger-repl.js'); repl.startDebugger('breakpoints.js'); diff --git a/test/disabled/GH-670.js b/test/disabled/GH-670.js index af65bbdc0ffc95..28f90a72ad487a 100644 --- a/test/disabled/GH-670.js +++ b/test/disabled/GH-670.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var https = require('https'); diff --git a/test/disabled/test-cat.js b/test/disabled/test-cat.js index 02d2d41a6663c8..e37820ba4b338c 100644 --- a/test/disabled/test-cat.js +++ b/test/disabled/test-cat.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common.js'); var assert = require('assert'); var http = require('http'); diff --git a/test/disabled/test-child-process-custom-fds.js b/test/disabled/test-child-process-custom-fds.js index d64586c508d9f1..12087684727dbf 100644 --- a/test/disabled/test-child-process-custom-fds.js +++ b/test/disabled/test-child-process-custom-fds.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-child-process-customfd-bounded.js b/test/disabled/test-child-process-customfd-bounded.js index 203e6acaf379c5..98da4ef4d1391e 100644 --- a/test/disabled/test-child-process-customfd-bounded.js +++ b/test/disabled/test-child-process-customfd-bounded.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var bigish = Array(200); diff --git a/test/disabled/test-child-process-uid-gid.js b/test/disabled/test-child-process-uid-gid.js index 5ab570b813f48f..90708bc2ca4016 100644 --- a/test/disabled/test-child-process-uid-gid.js +++ b/test/disabled/test-child-process-uid-gid.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-debug-brk-file.js b/test/disabled/test-debug-brk-file.js index ca2af1b7121811..4b5823f56a64e1 100644 --- a/test/disabled/test-debug-brk-file.js +++ b/test/disabled/test-debug-brk-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-debug-brk-no-arg.js b/test/disabled/test-debug-brk-no-arg.js index 547cd1b287a9ed..7e678a76dfc8f8 100644 --- a/test/disabled/test-debug-brk-no-arg.js +++ b/test/disabled/test-debug-brk-no-arg.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-dgram-multicast.js b/test/disabled/test-dgram-multicast.js index d66bd63e50dcbe..f2668d24c9a51a 100644 --- a/test/disabled/test-dgram-multicast.js +++ b/test/disabled/test-dgram-multicast.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-dgram-send-error.js b/test/disabled/test-dgram-send-error.js index 00901dd563f7d8..1ed594a389a8c4 100644 --- a/test/disabled/test-dgram-send-error.js +++ b/test/disabled/test-dgram-send-error.js @@ -1,3 +1,4 @@ +'use strict'; // Some operating systems report errors when an UDP message is sent to an // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. diff --git a/test/disabled/test-dgram-unix-anon.js b/test/disabled/test-dgram-unix-anon.js index 1a8b5e3a57bd73..417ff8c2915f32 100644 --- a/test/disabled/test-dgram-unix-anon.js +++ b/test/disabled/test-dgram-unix-anon.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-dgram-unix.js b/test/disabled/test-dgram-unix.js index f2a24a9c361c8e..d8ebd81a92da9d 100644 --- a/test/disabled/test-dgram-unix.js +++ b/test/disabled/test-dgram-unix.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-eio-race.js b/test/disabled/test-eio-race.js index b9e14f76b22f5d..32585894d0d7c3 100644 --- a/test/disabled/test-eio-race.js +++ b/test/disabled/test-eio-race.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -36,7 +37,7 @@ function tryToKillEventLoop() { // Generate a lot of thread pool events var pos = 0; -fs.open(filename, 'r', 0666, function(err, fd) { +fs.open(filename, 'r', 0o666, function(err, fd) { if (err) throw err; function readChunk() { diff --git a/test/disabled/test-eio-race2.js b/test/disabled/test-eio-race2.js index 487486a15d8245..16c0468775adf8 100644 --- a/test/disabled/test-eio-race2.js +++ b/test/disabled/test-eio-race2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/disabled/test-eio-race3.js b/test/disabled/test-eio-race3.js index 820128ae463fcd..872a105dd5ac90 100644 --- a/test/disabled/test-eio-race3.js +++ b/test/disabled/test-eio-race3.js @@ -1,3 +1,4 @@ +'use strict'; /* XXX Can this test be modified to not call the now-removed wait()? */ var common = require('../common'); diff --git a/test/disabled/test-eio-race4.js b/test/disabled/test-eio-race4.js index e8a2e591362d83..d22c4225b1544e 100644 --- a/test/disabled/test-eio-race4.js +++ b/test/disabled/test-eio-race4.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/disabled/test-fs-largefile.js b/test/disabled/test-fs-largefile.js index 21406e3aad0431..498bfa45a06dda 100644 --- a/test/disabled/test-fs-largefile.js +++ b/test/disabled/test-fs-largefile.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), diff --git a/test/disabled/test-http-abort-stream-end.js b/test/disabled/test-http-abort-stream-end.js index b0a23d92defe26..cfa531cedf5523 100644 --- a/test/disabled/test-http-abort-stream-end.js +++ b/test/disabled/test-http-abort-stream-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-http-agent2.js b/test/disabled/test-http-agent2.js index c1ccd70a1e4fd4..928194757b3a5d 100644 --- a/test/disabled/test-http-agent2.js +++ b/test/disabled/test-http-agent2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/disabled/test-http-big-proxy-responses.js b/test/disabled/test-http-big-proxy-responses.js index fe70473f587a30..9727edbb80639f 100644 --- a/test/disabled/test-http-big-proxy-responses.js +++ b/test/disabled/test-http-big-proxy-responses.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'), diff --git a/test/disabled/test-http-head-request.js b/test/disabled/test-http-head-request.js index 2dfe20bc3d06d8..c6fa78fe2b7309 100644 --- a/test/disabled/test-http-head-request.js +++ b/test/disabled/test-http-head-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-http-stress.js b/test/disabled/test-http-stress.js index 09a0b7e48a9e47..e4b51e07ca31df 100644 --- a/test/disabled/test-http-stress.js +++ b/test/disabled/test-http-stress.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-http-tls.js b/test/disabled/test-http-tls.js index 384849d00df140..867c3a076aefdc 100644 --- a/test/disabled/test-http-tls.js +++ b/test/disabled/test-http-tls.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-https-loop-to-google.js b/test/disabled/test-https-loop-to-google.js index cb29f2c226fb14..e498895ed23be0 100644 --- a/test/disabled/test-https-loop-to-google.js +++ b/test/disabled/test-https-loop-to-google.js @@ -1,3 +1,4 @@ +'use strict'; // Failing test for https // Will fail with "socket hang up" for 4 out of 10 requests @@ -7,26 +8,20 @@ var common = require('../common'); var https = require('https'); -for (var i = 0; i < 10; ++i) -{ - https.get( - { - host: 'www.google.com', - path: '/accounts/o8/id', - port: 443 - }, function(res) - { - var data = ''; - res.on('data', function(chunk) - { - data += chunk; - }); - res.on('end', function() - { - console.log(res.statusCode); - }); - }).on('error', function(error) - { - console.log(error); - }); +for (var i = 0; i < 10; ++i) { + https.get({ + host: 'www.google.com', + path: '/accounts/o8/id', + port: 443 + }, function(res) { + var data = ''; + res.on('data', function(chunk) { + data += chunk; + }); + res.on('end', function() { + console.log(res.statusCode); + }); + }).on('error', function(error) { + console.log(error); + }); } diff --git a/test/disabled/test-idle-watcher.js b/test/disabled/test-idle-watcher.js index b1038d56fd1b9e..6cf78ad1740953 100644 --- a/test/disabled/test-idle-watcher.js +++ b/test/disabled/test-idle-watcher.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-net-fd-passing.js b/test/disabled/test-net-fd-passing.js index 7b73056393ec3f..380032a2e66b5b 100644 --- a/test/disabled/test-net-fd-passing.js +++ b/test/disabled/test-net-fd-passing.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/disabled/test-net-tls-pummel.js b/test/disabled/test-net-tls-pummel.js index 0312d70ea722cb..0fb63d33f441fe 100644 --- a/test/disabled/test-net-tls-pummel.js +++ b/test/disabled/test-net-tls-pummel.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-net-tls.js b/test/disabled/test-net-tls.js index 9783b7ee3c81a1..01797fc689f44f 100644 --- a/test/disabled/test-net-tls.js +++ b/test/disabled/test-net-tls.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/disabled/test-process-title.js b/test/disabled/test-process-title.js index 1cd361dd87c572..629d78d72373a7 100644 --- a/test/disabled/test-process-title.js +++ b/test/disabled/test-process-title.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/disabled/test-readline.js b/test/disabled/test-readline.js index 1572036a8749d9..9bb9943bd2a403 100644 --- a/test/disabled/test-readline.js +++ b/test/disabled/test-readline.js @@ -1,3 +1,4 @@ +'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. // Yet another use-case for require('tty').spawn ? var common = require('../common'); @@ -36,10 +37,10 @@ var readlineFakeStream = function() { } }); var _stdoutWrite = process.stdout.write; - process.stdout.write = function (data) { + process.stdout.write = function(data) { data.split('').forEach(rl.written_bytes.push.bind(rl.written_bytes)); _stdoutWrite.apply(this, arguments); - } + }; rl.written_bytes = written_bytes; return rl; }; @@ -49,7 +50,7 @@ var written_bytes_length, refreshed; rl.write('foo'); assert.equal(3, rl.cursor); -[key.xterm, key.rxvt, key.gnome, key.putty].forEach(function (key) { +[key.xterm, key.rxvt, key.gnome, key.putty].forEach(function(key) { rl.write.apply(rl, key.home); assert.equal(0, rl.cursor); rl.write.apply(rl, key.end); @@ -72,7 +73,7 @@ rl.write.apply(rl, key.xterm.home); {cursor: 7, key: key.xterm.metab}, {cursor: 4, key: key.xterm.metab}, {cursor: 0, key: key.xterm.metab}, -].forEach(function (action) { +].forEach(function(action) { written_bytes_length = rl.written_bytes.length; rl.write.apply(rl, action.key); assert.equal(action.cursor, rl.cursor); @@ -83,7 +84,14 @@ rl.write.apply(rl, key.xterm.home); rl = readlineFakeStream(); rl.write('foo bar.hop/zoo'); rl.write.apply(rl, key.xterm.home); -['bar.hop/zoo', '.hop/zoo', 'hop/zoo', '/zoo', 'zoo', ''].forEach(function (expectedLine) { +[ + 'bar.hop/zoo', + '.hop/zoo', + 'hop/zoo', + '/zoo', + 'zoo', + '' +].forEach(function(expectedLine) { rl.write.apply(rl, key.xterm.metad); assert.equal(0, rl.cursor); assert.equal(expectedLine, rl.line); diff --git a/test/disabled/test-remote-module-loading.js b/test/disabled/test-remote-module-loading.js index c4d90fb80d0c50..d589ecf35be4b7 100644 --- a/test/disabled/test-remote-module-loading.js +++ b/test/disabled/test-remote-module-loading.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-sendfd.js b/test/disabled/test-sendfd.js index 0e1dd6f1bff37a..4eefbeab549685 100644 --- a/test/disabled/test-sendfd.js +++ b/test/disabled/test-sendfd.js @@ -1,3 +1,4 @@ +'use strict'; // Test sending and receiving a file descriptor. // // This test is pretty complex. It ends up spawning test/fixtures/recvfd.js diff --git a/test/disabled/test-setuidgid.js b/test/disabled/test-setuidgid.js index 90923b922d7711..bf3726ab006d36 100644 --- a/test/disabled/test-setuidgid.js +++ b/test/disabled/test-setuidgid.js @@ -1,3 +1,4 @@ +'use strict'; // Requires special privileges var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/test-tls-large-push.js b/test/disabled/test-tls-large-push.js index a5e206e477bef2..80a3cf52209a2f 100644 --- a/test/disabled/test-tls-large-push.js +++ b/test/disabled/test-tls-large-push.js @@ -1,3 +1,5 @@ +/* eslint-disable no-debugger */ +'use strict'; // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. var common = require('../common'); @@ -39,7 +41,7 @@ server.listen(common.PORT, function() { /* client.pause(); - process.nextTick(function () { + process.nextTick(function() { client.resume(); }); */ diff --git a/test/disabled/test-tls-server.js b/test/disabled/test-tls-server.js index 20cc3f9fc79c39..c1e62bf01cea20 100644 --- a/test/disabled/test-tls-server.js +++ b/test/disabled/test-tls-server.js @@ -1,3 +1,4 @@ +'use strict'; // Example of new TLS API. Test with: // // $> openssl s_client -connect localhost:12346 \ diff --git a/test/disabled/test-tty-stdio.js b/test/disabled/test-tty-stdio.js index 0d963958abb5bd..57d7ee67759d5a 100644 --- a/test/disabled/test-tty-stdio.js +++ b/test/disabled/test-tty-stdio.js @@ -1,3 +1,4 @@ +'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/tls-client.js b/test/disabled/tls-client.js index 48c715b29baf47..b47b681f95d026 100644 --- a/test/disabled/tls-client.js +++ b/test/disabled/tls-client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var tls = require('tls'); var fs = require('fs'); diff --git a/test/disabled/tls_client.js b/test/disabled/tls_client.js index 65d18dd7f21256..425cb54a5910fd 100644 --- a/test/disabled/tls_client.js +++ b/test/disabled/tls_client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/disabled/tls_server.js b/test/disabled/tls_server.js index 1174b8f6d04fcc..b3f43b564d067a 100644 --- a/test/disabled/tls_server.js +++ b/test/disabled/tls_server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/fixtures/child-process-persistent.js b/test/fixtures/child-process-persistent.js index 226ab3329d91d4..45a50f5a263ad6 100644 --- a/test/fixtures/child-process-persistent.js +++ b/test/fixtures/child-process-persistent.js @@ -1 +1 @@ -setInterval(function () {}, 500); +setInterval(function() {}, 500); diff --git a/test/fixtures/keys/Makefile b/test/fixtures/keys/Makefile index a096431a8c3307..1e3d40ebf1f91a 100644 --- a/test/fixtures/keys/Makefile +++ b/test/fixtures/keys/Makefile @@ -17,6 +17,28 @@ ca2-cert.pem: ca2.cnf echo '01' > ca2-serial touch ca2-database.txt +# +# Create Subordinate Certificate Authority: ca3 +# ('password' is used for the CA password.) +# +ca3-key.pem: + openssl genrsa -out ca3-key.pem 1024 + +ca3-csr.pem: ca3.cnf ca3-key.pem + openssl req -new \ + -extensions v3_ca -config ca3.cnf -key ca3-key.pem -out ca3-csr.pem + +ca3-cert.pem: ca3-csr.pem ca3-key.pem ca3.cnf ca1-cert.pem ca1-key.pem + openssl x509 -req \ + -extfile ca3.cnf \ + -extensions v3_ca \ + -days 9999 \ + -passin "pass:password" \ + -in ca3-csr.pem \ + -CA ca1-cert.pem \ + -CAkey ca1-key.pem \ + -CAcreateserial \ + -out ca3-cert.pem # # agent1 is signed by ca1. @@ -157,6 +179,31 @@ agent5-cert.pem: agent5-csr.pem ca2-cert.pem ca2-key.pem agent5-verify: agent5-cert.pem ca2-cert.pem openssl verify -CAfile ca2-cert.pem agent5-cert.pem +# +# agent6 is signed by ca3 +# + +agent6-key.pem: + openssl genrsa -out agent6-key.pem 1024 + +agent6-csr.pem: agent6.cnf agent6-key.pem + openssl req -new -config agent6.cnf -key agent6-key.pem -out agent6-csr.pem + +agent6-cert.pem: agent6-csr.pem ca3-cert.pem ca3-key.pem + openssl x509 -req \ + -days 9999 \ + -passin "pass:password" \ + -in agent6-csr.pem \ + -CA ca3-cert.pem \ + -CAkey ca3-key.pem \ + -CAcreateserial \ + -extfile agent6.cnf \ + -out agent6-cert.pem + cat ca3-cert.pem >> agent6-cert.pem + +agent6-verify: agent6-cert.pem ca3-cert.pem + openssl verify -CAfile ca3-cert.pem agent6-cert.pem + ec-key.pem: openssl ecparam -genkey -out ec-key.pem -name prime256v1 diff --git a/test/fixtures/keys/agent1-cert.pem b/test/fixtures/keys/agent1-cert.pem index c5bfb18e089e85..9c5c2ca4c62ed2 100644 --- a/test/fixtures/keys/agent1-cert.pem +++ b/test/fixtures/keys/agent1-cert.pem @@ -1,9 +1,9 @@ -----BEGIN CERTIFICATE----- -MIIC1jCCAj+gAwIBAgIJAJqEq8+4pyq+MA0GCSqGSIb3DQEBBQUAMHoxCzAJBgNV -BAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzANBgNVBAoTBkpveWVu -dDEQMA4GA1UECxMHTm9kZS5qczEMMAoGA1UEAxMDY2ExMSAwHgYJKoZIhvcNAQkB -FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNDA0MTUyMTMxMzFaFw00MTA4MzAyMTMx -MzFaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzAN +MIIC1jCCAj+gAwIBAgIJAJqEq8+4pyrAMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI5MDhaFw00MjA5MDIxMzI5 +MDhaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTELMAkGA1UEBxMCU0YxDzAN BgNVBAoTBkpveWVudDEQMA4GA1UECxMHTm9kZS5qczEPMA0GA1UEAxMGYWdlbnQx MSAwHgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0B AQEFAAOBjQAwgYkCgYEAuOs3hW8rF+7xx5iB9wjmIgd+HTqRFUeKxG+mWV35Hl6A @@ -11,8 +11,8 @@ AQEFAAOBjQAwgYkCgYEAuOs3hW8rF+7xx5iB9wjmIgd+HTqRFUeKxG+mWV35Hl6A lRxqJGXTjx+vG/0nDCXLBhoDKO00zEccdjGS8xEjjieQQr+KeASmIm0kQmuN5YcC AwEAAaNhMF8wXQYIKwYBBQUHAQEEUTBPMCMGCCsGAQUFBzABhhdodHRwOi8vb2Nz cC5ub2RlanMub3JnLzAoBggrBgEFBQcwAoYcaHR0cDovL2NhLm5vZGVqcy5vcmcv -Y2EuY2VydDANBgkqhkiG9w0BAQUFAAOBgQAx6rhnYbPygJwIm6nidyx+ydJQC4Gk -JD+pzbdJkTS+01r+xjVY/Wckn4JAsIlo/MMn055rs2cfdjoQtlj6yjEU6AP/7bfr -Mju4lBxDLACJ2y5/rfj3wO4q4Knd4Q4mPWjlS2SwmkHZ21QOqJ6Ig9ps6HPM7syw -ZYQ3WQ1LOPAxMg== +Y2EuY2VydDANBgkqhkiG9w0BAQsFAAOBgQA45MmH28Gns+1yu9w9MR/oR8hKDMnG +E4yDZ+9SofWdqRsGe5MNeMbp9c+FxIxODcNmdhV5Ao6+ZCRX4N9GjLqUL1jQoFAs +pT/U80ZU+4bz2EwGMBQt7CJZb/u+j8/vXheyGFZkCWEQj6AgZQFTniRRQJLwbiy5 +uDktGqnhvamyrg== -----END CERTIFICATE----- diff --git a/test/fixtures/keys/agent6-cert.pem b/test/fixtures/keys/agent6-cert.pem new file mode 100644 index 00000000000000..b6c03990f4c740 --- /dev/null +++ b/test/fixtures/keys/agent6-cert.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIICajCCAdOgAwIBAgIJAMTNiT75p13MMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2EzMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHQxCzAJBgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDERMA8GA1UECgwI +VHJlc29yaXQxFjAUBgNVBAMMDcOBZMOhbSBMaXBwYWkxJzAlBgkqhkiG9w0BCQEW +GGFkYW0ubGlwcGFpQHRyZXNvcml0LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAw +gYkCgYEA3Iwmwd6gdWH1AlSFeuVsEY/2MQm3XluOyHR9HNtXkWqwcQqVL8FX3NHt +//1jaSTMJjkR4FhC9R0hX6wyUuBp11J4GzoDqd02JUkCeUISq/3/2G+ynaZCx5Eo +GNHhcN0gALTCET/1QMD9h4aBjRbij3iHUghcbgverfkasp59WWcCAwEAATANBgkq +hkiG9w0BAQsFAAOBgQAmfrCJY+FPeOraPTUQTYf9rXqfVRQEVc/yyVygPbtg3gtA +yST0wI/g6sBjQ6Mm39yMf4rkWmwOKGtrKcqs9o9NdM5g5QQSWeg925Ex6aB+REgz +qjaAsLM88BJ0QU76VPi6K0hDSpeuQ6Zrcp93VkdGdVZzna3FSCMTNRnSq/GuMQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICgjCCAeugAwIBAgIJAJqEq8+4pyq/MA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHoxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzAN +BgNVBAoMBkpveWVudDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2EzMSAw +HgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAqs4MKn9saUIu/9EfHQPouC3kL9Mo5sd1WR6RBeSd8cqeFxXW +EWEq/P0hUeAH1sY0u8RFOccJmSJg8KTyRGc+VZzWimopz17mTuQY4hPW4bFzqmQm +7STfJz5eHzynBTU8jk5omi8hjbnRA38jOm4D7rN/vqtB+RG+vEhxONnq4DMCAwEA +AaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQBo8rX1uZWHvKHG +gWw+LXrY24Pkg8NdDRmfqEVyuaR4GoGGOXCqlVaFa6x+4/eqOUzHoC9uGfPtjrvW +BYQ1o/l0JZWW4KZYuXoVuMUSj+sel82mf9zLDeq5WYTPECgJDMfgVpXOmhHfyezn +SkUTX7XJUohjET+X5BqTFlqRT/RfIw== +-----END CERTIFICATE----- diff --git a/test/fixtures/keys/agent6-csr.pem b/test/fixtures/keys/agent6-csr.pem new file mode 100644 index 00000000000000..9d1925682b3903 --- /dev/null +++ b/test/fixtures/keys/agent6-csr.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIB2TCCAUICAQAwdDELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MREw +DwYDVQQKDAhUcmVzb3JpdDEWMBQGA1UEAwwNw4Fkw6FtIExpcHBhaTEnMCUGCSqG +SIb3DQEJARYYYWRhbS5saXBwYWlAdHJlc29yaXQuY29tMIGfMA0GCSqGSIb3DQEB +AQUAA4GNADCBiQKBgQDcjCbB3qB1YfUCVIV65WwRj/YxCbdeW47IdH0c21eRarBx +CpUvwVfc0e3//WNpJMwmORHgWEL1HSFfrDJS4GnXUngbOgOp3TYlSQJ5QhKr/f/Y +b7KdpkLHkSgY0eFw3SAAtMIRP/VAwP2HhoGNFuKPeIdSCFxuC96t+Rqynn1ZZwID +AQABoCUwIwYJKoZIhvcNAQkHMRYMFEEgY2hhbGxlbmdlIHBhc3N3b3JkMA0GCSqG +SIb3DQEBCwUAA4GBAEU4gmRyeeh5TMYG3bI0biXr+9CvkYBaHwZD5o4TUo8AenIR +NTrJdy9Pg9B23eOnEnCDB+KMfl08UuaPxbKRXRtYm1rTC8v5wmJEpZdWxum4c3hL +3o7J8/LmjRGQImr5vnS5zmsVrBLtjW+jVpSg5xnXFKQmpXPfgRwhvbu0lXf7 +-----END CERTIFICATE REQUEST----- diff --git a/test/fixtures/keys/agent6-key.pem b/test/fixtures/keys/agent6-key.pem new file mode 100644 index 00000000000000..e42fa2d1d1bd33 --- /dev/null +++ b/test/fixtures/keys/agent6-key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDcjCbB3qB1YfUCVIV65WwRj/YxCbdeW47IdH0c21eRarBxCpUv +wVfc0e3//WNpJMwmORHgWEL1HSFfrDJS4GnXUngbOgOp3TYlSQJ5QhKr/f/Yb7Kd +pkLHkSgY0eFw3SAAtMIRP/VAwP2HhoGNFuKPeIdSCFxuC96t+Rqynn1ZZwIDAQAB +AoGBAIL3AsjbL8OksL56fG0XMY5YQ6SpFWeFzQsCCY2KPrzOcwodc6vRDyDE1KTP +zimQvV3xQ8lKADDX5IqQka2fL5mgF+LighVvGHDm6M4ILJb46SDbuINwnqqvVuye ++OwjHBGEmKu18K+eL/YoCh3+sFTKP/18F7c7DGskCyzyub5RAkEA+Fs1ROx5w8AH +cbIH4fMU/QBGQVnuKgNXGSPcT6NHqFLbrhvNn5HwoF1SiJKkML1h3gVpj3T8kquw +Y1FcTVB9eQJBAONV1qXFo7i5gl2FyPuXvpgdzIXxzzr6q3seDkCR7q/vfBo+kKAx +zyG2xjJrCc9+ox4Vh257qK9b57W6R6sWNd8CQQCeAHjNVpzI2nxh6t908k8h/nCz +1uDcPa/FwLjCuaA3CC/Wfr28jP5HJ9gAJzrp/zIqK8tShxzAuxXGudY9Ib4RAkEA +v+3elIIx4WktOQwUTOUmEoNGAufOD3tGf2E2oykRnRPRcM7Vh4nF2C7ZUgOweq/t +wx5mAs7/8VzkWTb1/ul3fQJACLBXTChgyA77i5C/035tLwQbeLOjexLblEI0dgkW +HIa8q4ZL0M7L+/oziQ8zIT0bTAqEG1Q00PgFLl3m8gDuNg== +-----END RSA PRIVATE KEY----- diff --git a/test/fixtures/keys/agent6.cnf b/test/fixtures/keys/agent6.cnf new file mode 100644 index 00000000000000..1b66c9b0d7bac1 --- /dev/null +++ b/test/fixtures/keys/agent6.cnf @@ -0,0 +1,18 @@ +[ req ] +string_mask = utf8only +utf8 = yes +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no + +[ req_distinguished_name ] +C = HU +L = Budapest +O = Tresorit +CN = Ádám Lippai +emailAddress = adam.lippai@tresorit.com + +[ req_attributes ] +challengePassword = A challenge password diff --git a/test/fixtures/keys/ca1-cert.pem b/test/fixtures/keys/ca1-cert.pem index 638c803c7fb3fb..8e45f8891c14e0 100644 --- a/test/fixtures/keys/ca1-cert.pem +++ b/test/fixtures/keys/ca1-cert.pem @@ -1,15 +1,16 @@ -----BEGIN CERTIFICATE----- -MIICazCCAdQCCQC1CQyJn8L/kzANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV -UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO -BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqGSIb3DQEJARYRcnlA -dGlueWNsb3Vkcy5vcmcwHhcNMTQwNDE1MjEzMTMxWhcNNDEwODMwMjEzMTMxWjB6 -MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK -EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMTEgMB4GCSqG -SIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0A -MIGJAoGBALBXMk/xFR2GN2v/wKreZKyIitGphxYGoJ2d//s/wM6qqyIW94aiq3sm -1zpmOTPTorT9Pk32A7uKKHfrafB+yA07QXgCYXgzcn17nfFInncDyGdggNFGAO13 -5JuC3JC8pRJpEokkMszpHJxPdR6gKXIT05blUnpwGT/AmYJ8S59lAgMBAAEwDQYJ -KoZIhvcNAQEFBQADgYEAAb+Pye0I+k927Qi2+cUowLS5MtmrEosUbTYwI4rqYSR2 -aiibqmC3Z55N72ktQ2pJKP8I1t3Rk+j8/yIKWzSn5Jd2GT4ZzqbANrdLKeAsfVDK -pnsUR1IV/sdIvuELm+P4kyK5wafJytUjD+A4SH2oWN4EozDR1OidAhJrraXQksw= +MIICgjCCAeugAwIBAgIJAI3yHAFGivOTMA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHoxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzAN +BgNVBAoMBkpveWVudDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAw +HgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAwbF7gKfk7nGLcH0lbok1UJEBpMiQ49YxUqT/oIfXBaRjMODX +RknQxpARWw4R8qj+Zeu9zZZ8Hzv3dAxtcpnMTgeoPUL3HCStk0bK8QrFdkFrBxQD +mF92r9Mgr/fz+x7rSZuCIKhATwB5iJOz63fRctTL5tBmzG15JUG1GN5HPZECAwEA +AaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQAnAHtchz5FGqod +8twiFF3yQdGN3WE3VC3A6VrcmjKUp+M7f0uRDYw4uKUhadyZdYhMn39fe9DVN6rC +6wUUoe4hSs+0SWi6Ora7DFpCbm6fNpooSr0K0OUMZ2opwDmAEPdVOSPRhzQJ/cNp +s3mxIrkAQ5kgJSSGlPETMEumQmXDfA== -----END CERTIFICATE----- diff --git a/test/fixtures/keys/ca1-cert.srl b/test/fixtures/keys/ca1-cert.srl index ab9c1c224ad882..c9650b0529c100 100644 --- a/test/fixtures/keys/ca1-cert.srl +++ b/test/fixtures/keys/ca1-cert.srl @@ -1 +1 @@ -9A84ABCFB8A72ABE +9A84ABCFB8A72AC0 diff --git a/test/fixtures/keys/ca1-key.pem b/test/fixtures/keys/ca1-key.pem index a253989934ce10..3a619fbf2484ff 100644 --- a/test/fixtures/keys/ca1-key.pem +++ b/test/fixtures/keys/ca1-key.pem @@ -1,17 +1,17 @@ -----BEGIN ENCRYPTED PRIVATE KEY----- -MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIJ36Z9tFiv2oCAggA -MBQGCCqGSIb3DQMHBAjCAyUwdFh+7gSCAoD9Sv9009MmLb8+wHhYhxmrPrpeYZOt -W8xfELfal/2XWFe41WV41Qsa2HyN03VeyQjb+cnKvZX6HUCe5zVMUsf+B91yQBqR -jOZgsgoflEC3tFrhW5ogmRnjuok3CbTYLx0f8GMucSRNa9ZPhpfUjrVcCUrKKRJ+ -owk0VxWQkRqMF/8WJJgHxnm8/jLbNKuHbwY8SSQO/pStyKxqx5rBXAA/YCrAx7EZ -aDvc2q9EwRHX+hWIhpIkYna7PwnNAX03Ghv4iiwUlwHoomvgxExdUc9T8HBQu/xP -2pmUqwTglAdRb0tNiYrF+yIesAlqBc1qoi7tv2SM3gTowdw2PeHq5MA/ShV21oC8 -51bc0OxRkEFsHGLIs1v5qzs21JhX0IKvb5LDHAaze2RwODfnCTcQb8jYaFZNmwpt -ZrHgBQBwOHSvZ9CCqInDDtGBhYRlQIQRGgj9Ju5fruRYycn8vE58OcIfF52dwLKB -7sjTFX0O0b58wpiQSJzbHGbjNlQNRXxdk9v1qfP8vx8rFHLoFSScaZomavp4uijU -yLKVwquzEOVOMP8cC+yRk+zkcb9EE2pE1CqG0Mj6MHH1Lha98kakTIAS/VG59/Mp -EqZoRtJ6n/DzscrRpHIm+170ufLGmivmTeOXcMyHv1pGp35c5VbmUTZCxcE7A/0f -WPLVB3lBPgsvR/4NVx9A6mvXbkp2yngdfbvQgzRDG6pfrE1xeiUAyRCts7dR3Q9/ -dNHIM2wsiO3A/8Up1vrY6d/dcJt7cwjHRkx2eQFbpeE+a4CCNZ7gXFcwHLigBH8G -uTTVZf4HJavjXiYlkY3OFnPuz4KzanJzuqluKeIdJwSEkp9Kra/Id0eO +MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQI4tZeEUDNwLoCAggA +MBQGCCqGSIb3DQMHBAglCttpxF+UrASCAoCOiXoMG1+CJFtRnovzp0wSCeEtieI3 +jntJkCBF+NNUZrbWaQqWO+Id8KjXNFQdUo7lYT0d0w5lf52OHTyswjN0ILCOp/WN +eVMDfgmaJXtaah2l++hDFhcbGsOdRcwM0+yComF02Qxr13ftYnIPzUH4+Ix1i1Tr +6eBGDBJv0eXDZj/dLrploA7/pepKlytRw2stIL99TSICR54UQ7fyZ/oS6NvoQU7U +iBCVsrkjyE6jHJZ6vNe/ZjM8ZdLM9K2inoldpFaavDTh6GwHC6e3e9FJuJk6X30e +s2lhrVLOmxLuFS168iApyA8XvVTg/RG08DvkzUUFv8+HNETH0Qkb5kpJM+pPzwyu +c5et2fX8YuQRc8SdIdd+Z0lZJga1IciEXlsfzGeUtcZKUjBZ5yPTx+1InfcNFDKR +wCU2p0Haj9OCcvSBzU53I57RYXkENMEHQ46/FytGULXHimIoIR/SEbrqbKX0xDmT +rc/4c4vI5+tQPYMjo0rqydLAb5YjWCivrXDVXVHrG0YFsAoJkvTBLXlPiqTcnkea +KACuq7B+ymdVmpjV891OLuN3Yah+HgrvTkMlNexsFWvGpis03UYwpI6bppe4dHtt +rLBlgtyxFLJ9hu/YnkR6HcrjKaW5kGFDX06elAZBdPD/6foghzTb4jw3OK6a4ue0 +PE/zF6d7QWW+w5xKtNO62WWKABi9OtLhdUNVAFyBlaA43zYbnXkyfmv0l7LXPZ9t +Ps+BmG4r/gxO6GmZZ40sRXFjpkj230bTjbN6sUrU3WgOszMy0uFAph+zBUIMZWSP +wqZWmQi8MHQ4+Qm8N5GdXUTXw32eZ60bj82QGPso/NNxzDQsk5wd+bR3 -----END ENCRYPTED PRIVATE KEY----- diff --git a/test/fixtures/keys/ca1.cnf b/test/fixtures/keys/ca1.cnf index ea4312752d303f..afd3066eb9daa8 100644 --- a/test/fixtures/keys/ca1.cnf +++ b/test/fixtures/keys/ca1.cnf @@ -5,6 +5,7 @@ distinguished_name = req_distinguished_name attributes = req_attributes prompt = no output_password = password +x509_extensions = v3_ca [ req_distinguished_name ] C = US @@ -18,3 +19,5 @@ emailAddress = ry@tinyclouds.org [ req_attributes ] challengePassword = A challenge password +[ v3_ca ] +basicConstraints = CA:TRUE diff --git a/test/fixtures/keys/ca3-cert.pem b/test/fixtures/keys/ca3-cert.pem new file mode 100644 index 00000000000000..2c1cec87194426 --- /dev/null +++ b/test/fixtures/keys/ca3-cert.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICgjCCAeugAwIBAgIJAJqEq8+4pyq/MA0GCSqGSIb3DQEBCwUAMHoxCzAJBgNV +BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzANBgNVBAoMBkpveWVu +dDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2ExMSAwHgYJKoZIhvcNAQkB +FhFyeUB0aW55Y2xvdWRzLm9yZzAeFw0xNTA0MTgxMzI4NDFaFw00MjA5MDIxMzI4 +NDFaMHoxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDzAN +BgNVBAoMBkpveWVudDEQMA4GA1UECwwHTm9kZS5qczEMMAoGA1UEAwwDY2EzMSAw +HgYJKoZIhvcNAQkBFhFyeUB0aW55Y2xvdWRzLm9yZzCBnzANBgkqhkiG9w0BAQEF +AAOBjQAwgYkCgYEAqs4MKn9saUIu/9EfHQPouC3kL9Mo5sd1WR6RBeSd8cqeFxXW +EWEq/P0hUeAH1sY0u8RFOccJmSJg8KTyRGc+VZzWimopz17mTuQY4hPW4bFzqmQm +7STfJz5eHzynBTU8jk5omi8hjbnRA38jOm4D7rN/vqtB+RG+vEhxONnq4DMCAwEA +AaMQMA4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQBo8rX1uZWHvKHG +gWw+LXrY24Pkg8NdDRmfqEVyuaR4GoGGOXCqlVaFa6x+4/eqOUzHoC9uGfPtjrvW +BYQ1o/l0JZWW4KZYuXoVuMUSj+sel82mf9zLDeq5WYTPECgJDMfgVpXOmhHfyezn +SkUTX7XJUohjET+X5BqTFlqRT/RfIw== +-----END CERTIFICATE----- diff --git a/test/fixtures/keys/ca3-cert.srl b/test/fixtures/keys/ca3-cert.srl new file mode 100644 index 00000000000000..ecab7285d692e7 --- /dev/null +++ b/test/fixtures/keys/ca3-cert.srl @@ -0,0 +1 @@ +C4CD893EF9A75DCC diff --git a/test/fixtures/keys/ca3-csr.pem b/test/fixtures/keys/ca3-csr.pem new file mode 100644 index 00000000000000..4daa2302ab249b --- /dev/null +++ b/test/fixtures/keys/ca3-csr.pem @@ -0,0 +1,13 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIB3zCCAUgCAQAwejELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQswCQYDVQQH +DAJTRjEPMA0GA1UECgwGSm95ZW50MRAwDgYDVQQLDAdOb2RlLmpzMQwwCgYDVQQD +DANjYTMxIDAeBgkqhkiG9w0BCQEWEXJ5QHRpbnljbG91ZHMub3JnMIGfMA0GCSqG +SIb3DQEBAQUAA4GNADCBiQKBgQCqzgwqf2xpQi7/0R8dA+i4LeQv0yjmx3VZHpEF +5J3xyp4XFdYRYSr8/SFR4AfWxjS7xEU5xwmZImDwpPJEZz5VnNaKainPXuZO5Bji +E9bhsXOqZCbtJN8nPl4fPKcFNTyOTmiaLyGNudEDfyM6bgPus3++q0H5Eb68SHE4 +2ergMwIDAQABoCUwIwYJKoZIhvcNAQkHMRYMFEEgY2hhbGxlbmdlIHBhc3N3b3Jk +MA0GCSqGSIb3DQEBCwUAA4GBABMaKC7NVVdfoQeKwIy5lYo17mOr4WcWHPNRcoIy +rAHLcAzFOp0RCSZ7ROVRR6O/QIBYapUmPmdYRhKfz1g35xCX3+T28cWXngALV5v0 +XzMYJiew+97/LlNnBwoTRafAorviugdbFgJeMpYHRkG7/zXQsBz+hwgymKZnHW9D +Dl4h +-----END CERTIFICATE REQUEST----- diff --git a/test/fixtures/keys/ca3-key.pem b/test/fixtures/keys/ca3-key.pem new file mode 100644 index 00000000000000..6c2b067abed06d --- /dev/null +++ b/test/fixtures/keys/ca3-key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQCqzgwqf2xpQi7/0R8dA+i4LeQv0yjmx3VZHpEF5J3xyp4XFdYR +YSr8/SFR4AfWxjS7xEU5xwmZImDwpPJEZz5VnNaKainPXuZO5BjiE9bhsXOqZCbt +JN8nPl4fPKcFNTyOTmiaLyGNudEDfyM6bgPus3++q0H5Eb68SHE42ergMwIDAQAB +AoGBAJkcc5N0/j2s8mynjXh5FJhlqvOkGjol+m+VEvNxaJRiySxwiqCxtdNrJf87 +EEvbCVJ4MoYEgfof8z5E3lerJRgqrhY2RSfiQrSUA89Lw9uYzcx28zhWpwwmuLHY +5gjz+LCDDS5okLsXnl2awHXADEmcx29sZnRS6dGRFcf8F0FhAkEA1c7HrW8Vghu2 +FlRaY6LOuoFNAHM++ugoWrC85/moYevLG8wAJCuSIp/RuWrx1FdJoa7rfhyS649v +cMGN0m1yHwJBAMyC1S1QoqXSdoqN8OrXyHJmaSbWG8IMLcT2FXA8Mk3Tk0zWSjiz +sk/O85NsmUQQnkRgbtSS+w0Kc0OMWXbfl20CQH+igFsNjEZuaoXr90WxhD2cQK57 +HebEvopdJXhJ9nX2P/qpDpCJHiTjSVyp9hFvxjnp5RUU07QhnUIvmY073rsCQFMN +ovNHNvZutVNpd3h372B+NJ/f/d/dQE0nvucYmzk9/ikLMZM7buO4YPTy+n9I3G1a +WEgd9LSEFPFOsxpyjTUCQGn9XTyeSo1EoVuV21DE0Cnx30YsnPKMT1YRS7QgjDPK +RA3fSsvnhtTzT53kfJ/ZurBV+RKbePL1JVqDtGvJVeE= +-----END RSA PRIVATE KEY----- diff --git a/test/fixtures/keys/ca3.cnf b/test/fixtures/keys/ca3.cnf new file mode 100644 index 00000000000000..53855e1419617c --- /dev/null +++ b/test/fixtures/keys/ca3.cnf @@ -0,0 +1,23 @@ +[ req ] +default_bits = 1024 +days = 999 +distinguished_name = req_distinguished_name +attributes = req_attributes +prompt = no +output_password = password +x509_extensions = v3_ca + +[ req_distinguished_name ] +C = US +ST = CA +L = SF +O = Joyent +OU = Node.js +CN = ca3 +emailAddress = ry@tinyclouds.org + +[ req_attributes ] +challengePassword = A challenge password + +[ v3_ca ] +basicConstraints = CA:TRUE diff --git a/test/gc/node_modules/weak/lib/weak.js b/test/gc/node_modules/weak/lib/weak.js index 8081a76c45f9f1..535caf615c648e 100644 --- a/test/gc/node_modules/weak/lib/weak.js +++ b/test/gc/node_modules/weak/lib/weak.js @@ -1,3 +1,4 @@ +'use strict'; var bindings try { bindings = require('../build/Release/weakref.node') @@ -13,6 +14,6 @@ module.exports = bindings.create // backwards-compat with node-weakref bindings.weaken = bindings.create -Object.keys(bindings).forEach(function (name) { +Object.keys(bindings).forEach(function(name) { module.exports[name] = bindings[name] }) diff --git a/test/gc/test-http-client-connaborted.js b/test/gc/test-http-client-connaborted.js index c58b4d5f752457..20a4b38481ae0c 100644 --- a/test/gc/test-http-client-connaborted.js +++ b/test/gc/test-http-client-connaborted.js @@ -1,3 +1,4 @@ +'use strict'; // just like test/gc/http-client.js, // but aborting every connection that comes in. @@ -15,7 +16,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -25,9 +26,9 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { - done+=1; + done += 1; statusLater(); } @@ -39,7 +40,7 @@ function getall() { count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -47,7 +48,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-http-client-onerror.js b/test/gc/test-http-client-onerror.js index bf9fb7c1fba9f8..98d046e180f11b 100644 --- a/test/gc/test-http-client-onerror.js +++ b/test/gc/test-http-client-onerror.js @@ -1,3 +1,4 @@ +'use strict'; // just like test/gc/http-client.js, // but with an on('error') handler that does nothing. @@ -17,7 +18,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -27,10 +28,10 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { res.resume(); - done+=1; + done += 1; statusLater(); } function onerror(er) { @@ -45,7 +46,7 @@ function getall() { count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -53,7 +54,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-http-client-timeout.js b/test/gc/test-http-client-timeout.js index 727d133f711ad8..5bb2d2b05b4fb0 100644 --- a/test/gc/test-http-client-timeout.js +++ b/test/gc/test-http-client-timeout.js @@ -1,10 +1,11 @@ +'use strict'; // just like test/gc/http-client.js, // but with a timeout set function serverHandler(req, res) { - setTimeout(function () { + setTimeout(function() { req.resume(); - res.writeHead(200) + res.writeHead(200); res.end('hello\n'); }, 100); } @@ -19,7 +20,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -29,10 +30,10 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { res.resume(); - done+=1; + done += 1; statusLater(); } @@ -42,13 +43,13 @@ function getall() { port: PORT }, cb); req.on('error', cb); - req.setTimeout(10, function(){ - console.log('timeout (expected)') + req.setTimeout(10, function() { + console.log('timeout (expected)'); }); count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -56,7 +57,7 @@ function getall() { for(var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-http-client.js b/test/gc/test-http-client.js index 6aedda7edef755..7c3259d38b0ba1 100644 --- a/test/gc/test-http-client.js +++ b/test/gc/test-http-client.js @@ -1,3 +1,4 @@ +'use strict'; // just a simple http server and client. function serverHandler(req, res) { @@ -15,7 +16,7 @@ var http = require('http'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var http = require('http'); var server = http.createServer(serverHandler); @@ -26,11 +27,11 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { function cb(res) { res.resume(); - console.error('in cb') - done+=1; + console.error('in cb'); + done += 1; res.on('end', gc); } @@ -38,11 +39,11 @@ function getall() { hostname: 'localhost', pathname: '/', port: PORT - }, cb) + }, cb); count++; weak(req, afterGC); - })() + })(); setImmediate(getall); } @@ -50,7 +51,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/gc/test-net-timeout.js b/test/gc/test-net-timeout.js index 2ef03b2632d045..6c3b4f245be452 100644 --- a/test/gc/test-net-timeout.js +++ b/test/gc/test-net-timeout.js @@ -1,3 +1,4 @@ +'use strict'; // just like test/gc/http-client-timeout.js, // but using a net server/client instead @@ -11,7 +12,7 @@ function serverHandler(sock) { sock.on('error', function(err) { assert.strictEqual(err.code, 'ECONNRESET'); }); - timer = setTimeout(function () { + timer = setTimeout(function() { sock.end('hello\n'); }, 100); } @@ -26,7 +27,7 @@ var net = require('net'), assert = require('assert'), PORT = common.PORT; -console.log('We should do '+ todo +' requests'); +console.log('We should do ' + todo + ' requests'); var server = net.createServer(serverHandler); server.listen(PORT, getall); @@ -35,7 +36,7 @@ function getall() { if (count >= todo) return; - (function(){ + (function() { var req = net.connect(PORT, '127.0.0.1'); req.resume(); req.setTimeout(10, function() { @@ -55,7 +56,7 @@ function getall() { for (var i = 0; i < 10; i++) getall(); -function afterGC(){ +function afterGC() { countGC ++; } diff --git a/test/internet/test-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index d60fb0bd3442c2..4cf5d7226f2c50 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), dgram = require('dgram'), @@ -144,7 +145,7 @@ if (process.argv[2] !== 'child') { // bind the address explicitly for sending // INADDR_BROADCAST to only one interface sendSocket.bind(common.PORT, bindAddress); - sendSocket.on('listening', function () { + sendSocket.on('listening', function() { sendSocket.setBroadcast(true); }); @@ -162,9 +163,7 @@ if (process.argv[2] !== 'child') { sendSocket.send(buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, function(err) { - if (err) throw err; - console.error('[PARENT] sent %s to %s:%s', util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT); diff --git a/test/internet/test-dgram-multicast-multi-process.js b/test/internet/test-dgram-multicast-multi-process.js index 66c92b285c2a4c..05acb844e54490 100644 --- a/test/internet/test-dgram-multicast-multi-process.js +++ b/test/internet/test-dgram-multicast-multi-process.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), dgram = require('dgram'), @@ -129,7 +130,7 @@ if (process.argv[2] !== 'child') { sendSocket.bind(); // The socket is actually created async now - sendSocket.on('listening', function () { + sendSocket.on('listening', function() { sendSocket.setTTL(1); sendSocket.setBroadcast(true); sendSocket.setMulticastTTL(1); @@ -206,7 +207,7 @@ if (process.argv[2] === 'child') { listenSocket.bind(common.PORT); - listenSocket.on('listening', function () { + listenSocket.on('listening', function() { listenSocket.addMembership(LOCAL_BROADCAST_HOST); }); } diff --git a/test/internet/test-dns-txt-sigsegv.js b/test/internet/test-dns-txt-sigsegv.js index 75d34c21c06dd8..eba5c66c464981 100644 --- a/test/internet/test-dns-txt-sigsegv.js +++ b/test/internet/test-dns-txt-sigsegv.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dns = require('dns'); diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index b980b822c112b4..eb7bab85475b2a 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'), dns = require('dns'), @@ -500,7 +501,8 @@ TEST(function test_lookup_null_all(done) { TEST(function test_lookup_all_ipv4(done) { - var req = dns.lookup('www.google.com', {all: true, family: 4}, function(err, ips) { + var req = dns.lookup('www.google.com', {all: true, family: 4}, + function(err, ips) { if (err) throw err; assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); @@ -518,7 +520,8 @@ TEST(function test_lookup_all_ipv4(done) { TEST(function test_lookup_all_ipv6(done) { - var req = dns.lookup('www.google.com', {all: true, family: 6}, function(err, ips) { + var req = dns.lookup('www.google.com', {all: true, family: 6}, + function(err, ips) { if (err) throw err; assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); diff --git a/test/internet/test-http-dns-fail.js b/test/internet/test-http-dns-fail.js index 7d1cfbf630472d..151597de14cb0e 100644 --- a/test/internet/test-http-dns-fail.js +++ b/test/internet/test-http-dns-fail.js @@ -1,3 +1,4 @@ +'use strict'; /* * Repeated requests for a domain that fails to resolve * should trigger the error event after each attempt. diff --git a/test/internet/test-http-https-default-ports.js b/test/internet/test-http-https-default-ports.js index 26732ee086f1fa..1133221e6b7d44 100644 --- a/test/internet/test-http-https-default-ports.js +++ b/test/internet/test-http-https-default-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/internet/test-net-connect-timeout.js b/test/internet/test-net-connect-timeout.js index a55cf5e4bbf260..d122229397fd75 100644 --- a/test/internet/test-net-connect-timeout.js +++ b/test/internet/test-net-connect-timeout.js @@ -1,3 +1,4 @@ +'use strict'; // This example attempts to time out before the connection is established // https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8 // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw diff --git a/test/internet/test-net-connect-unref.js b/test/internet/test-net-connect-unref.js index dc0462ffd0238b..a712490d31f566 100644 --- a/test/internet/test-net-connect-unref.js +++ b/test/internet/test-net-connect-unref.js @@ -1,9 +1,10 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); var client, killed = false, ended = false; -var TIMEOUT = 10 * 1000 +var TIMEOUT = 10 * 1000; client = net.createConnection(53, '8.8.8.8', function() { client.unref(); diff --git a/test/internet/test-tls-connnect-melissadata.js b/test/internet/test-tls-connnect-melissadata.js index 61239c89c80c3f..96ff41af30cbcc 100644 --- a/test/internet/test-tls-connnect-melissadata.js +++ b/test/internet/test-tls-connnect-melissadata.js @@ -1,3 +1,4 @@ +'use strict'; // Test for authorized access to the server which has a cross root // certification between Starfield Class 2 and ValiCert Class 2 var tls = require('tls'); diff --git a/test/internet/test-tls-reuse-host-from-socket.js b/test/internet/test-tls-reuse-host-from-socket.js index 2f6392ce83455a..f3864908155f0e 100644 --- a/test/internet/test-tls-reuse-host-from-socket.js +++ b/test/internet/test-tls-reuse-host-from-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/2100bytes.js b/test/message/2100bytes.js index 59fe3c152325ad..b05f5e9e1d7168 100644 --- a/test/message/2100bytes.js +++ b/test/message/2100bytes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); diff --git a/test/message/error_exit.js b/test/message/error_exit.js index 51c25697494878..7805fd21935377 100644 --- a/test/message/error_exit.js +++ b/test/message/error_exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/eval_messages.js b/test/message/eval_messages.js index 157cf881f60e6f..603acafe0936c4 100644 --- a/test/message/eval_messages.js +++ b/test/message/eval_messages.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); diff --git a/test/message/hello_world.js b/test/message/hello_world.js index 996e08d51a2e62..1e6b030393c6cf 100644 --- a/test/message/hello_world.js +++ b/test/message/hello_world.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/max_tick_depth.js b/test/message/max_tick_depth.js index 1e43cae1c1670d..cacd795810605a 100644 --- a/test/message/max_tick_depth.js +++ b/test/message/max_tick_depth.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); process.maxTickDepth = 10; diff --git a/test/message/nexttick_throw.js b/test/message/nexttick_throw.js index 21361edf333abb..3c0e2d8e379fd9 100644 --- a/test/message/nexttick_throw.js +++ b/test/message/nexttick_throw.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/nexttick_throw.out b/test/message/nexttick_throw.out index baced2ce879dea..1dd60694a892b8 100644 --- a/test/message/nexttick_throw.out +++ b/test/message/nexttick_throw.out @@ -4,6 +4,7 @@ ^ ReferenceError: undefined_reference_error_maker is not defined at *test*message*nexttick_throw.js:*:* + at doNTCallback0 (node.js:*:*) at process._tickCallback (node.js:*:*) at Function.Module.runMain (module.js:*:*) at startup (node.js:*:*) diff --git a/test/message/stack_overflow.js b/test/message/stack_overflow.js index f822afd22c5757..7d1033c3ab2b1a 100644 --- a/test/message/stack_overflow.js +++ b/test/message/stack_overflow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/stdin_messages.js b/test/message/stdin_messages.js index 8c4e47d00095e6..eefa9e756dc312 100644 --- a/test/message/stdin_messages.js +++ b/test/message/stdin_messages.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); diff --git a/test/message/stdin_messages.out b/test/message/stdin_messages.out index cbdc1fdb125626..92d09a0a144428 100644 --- a/test/message/stdin_messages.out +++ b/test/message/stdin_messages.out @@ -12,6 +12,7 @@ SyntaxError: Strict mode code may not include a with statement at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) + at doNTCallback2 (node.js:*:*) at process._tickCallback (node.js:*:*) 42 42 @@ -29,7 +30,7 @@ Error: hello at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) - at process._tickCallback (node.js:*:*) + at doNTCallback2 (node.js:*:*) [stdin]:1 throw new Error("hello") @@ -44,7 +45,7 @@ Error: hello at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) - at process._tickCallback (node.js:*:*) + at doNTCallback2 (node.js:*:*) 100 [stdin]:1 @@ -60,7 +61,7 @@ ReferenceError: y is not defined at emitNone (events.js:*:*) at Socket.emit (events.js:*:*) at endReadableNT (_stream_readable.js:*:*) - at process._tickCallback (node.js:*:*) + at doNTCallback2 (node.js:*:*) [stdin]:1 var ______________________________________________; throw 10 diff --git a/test/message/throw_custom_error.js b/test/message/throw_custom_error.js index 34a007920dafea..270b37d14ddead 100644 --- a/test/message/throw_custom_error.js +++ b/test/message/throw_custom_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_custom_error.out b/test/message/throw_custom_error.out index f003972940053c..bfb928d48dd08e 100644 --- a/test/message/throw_custom_error.out +++ b/test/message/throw_custom_error.out @@ -1,5 +1,5 @@ before -*test*message*throw_custom_error.js:7 +*test*message*throw_custom_error.js:8 throw ({ name: 'MyCustomError', message: 'This is a custom message' }); ^ MyCustomError: This is a custom message diff --git a/test/message/throw_in_line_with_tabs.js b/test/message/throw_in_line_with_tabs.js index dc035c42cade3d..50c69ca681019d 100644 --- a/test/message/throw_in_line_with_tabs.js +++ b/test/message/throw_in_line_with_tabs.js @@ -1,9 +1,11 @@ +/* eslint-disable indent */ +'use strict'; var common = require('../common'); var assert = require('assert'); console.error('before'); -(function () { +(function() { // these lines should contain tab! throw ({ foo: 'bar' }); })(); diff --git a/test/message/throw_in_line_with_tabs.out b/test/message/throw_in_line_with_tabs.out index 11eadab34bead1..e83b05768433b8 100644 --- a/test/message/throw_in_line_with_tabs.out +++ b/test/message/throw_in_line_with_tabs.out @@ -1,5 +1,5 @@ before -*test*message*throw_in_line_with_tabs.js:8 +*test*message*throw_in_line_with_tabs.js:10 throw ({ foo: 'bar' }); ^ [object Object] diff --git a/test/message/throw_non_error.js b/test/message/throw_non_error.js index 817b557906a512..33e0a051d65a1d 100644 --- a/test/message/throw_non_error.js +++ b/test/message/throw_non_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_non_error.out b/test/message/throw_non_error.out index 4b39de5acfa7e5..c859d5f16a511e 100644 --- a/test/message/throw_non_error.out +++ b/test/message/throw_non_error.out @@ -1,5 +1,5 @@ before -*test*message*throw_non_error.js:7 +*test*message*throw_non_error.js:8 throw ({ foo: 'bar' }); ^ [object Object] diff --git a/test/message/throw_null.js b/test/message/throw_null.js index 27e86a8ff0e1e7..ab8fb565a61e54 100644 --- a/test/message/throw_null.js +++ b/test/message/throw_null.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_null.out b/test/message/throw_null.out index be5cb3f7b8729a..eb3eeb1294e727 100644 --- a/test/message/throw_null.out +++ b/test/message/throw_null.out @@ -1,5 +1,5 @@ -*test*message*throw_null.js:4 +*test*message*throw_null.js:5 throw null; -^ +^ null diff --git a/test/message/throw_undefined.js b/test/message/throw_undefined.js index dcc54d74d2d3cc..f855cdd2f7dabd 100644 --- a/test/message/throw_undefined.js +++ b/test/message/throw_undefined.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/throw_undefined.out b/test/message/throw_undefined.out index 1aa6e15b37f4f5..27aedd9ee46f15 100644 --- a/test/message/throw_undefined.out +++ b/test/message/throw_undefined.out @@ -1,5 +1,5 @@ -*test*message*throw_undefined.js:4 +*test*message*throw_undefined.js:5 throw undefined; ^ undefined diff --git a/test/message/timeout_throw.js b/test/message/timeout_throw.js index 4ccf0bdd27dfce..aaf3fbc8d2f48f 100644 --- a/test/message/timeout_throw.js +++ b/test/message/timeout_throw.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/message/undefined_reference_in_new_context.js b/test/message/undefined_reference_in_new_context.js index 01d9698f22b257..7256c0d8e36088 100644 --- a/test/message/undefined_reference_in_new_context.js +++ b/test/message/undefined_reference_in_new_context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/message/vm_display_runtime_error.js b/test/message/vm_display_runtime_error.js index 22c10d6022bd92..d01ab0b540b3cb 100644 --- a/test/message/vm_display_runtime_error.js +++ b/test/message/vm_display_runtime_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/message/vm_display_syntax_error.js b/test/message/vm_display_syntax_error.js index b0172264e71ffc..179263478b84b8 100644 --- a/test/message/vm_display_syntax_error.js +++ b/test/message/vm_display_syntax_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/message/vm_dont_display_runtime_error.js b/test/message/vm_dont_display_runtime_error.js index 7aa81844b8f4ed..6b4c824cbe5eff 100644 --- a/test/message/vm_dont_display_runtime_error.js +++ b/test/message/vm_dont_display_runtime_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -5,17 +6,17 @@ var vm = require('vm'); console.error('beginning'); try { - vm.runInThisContext('throw new Error("boo!")', { - filename: 'test.vm', - displayErrors: false - }); + vm.runInThisContext('throw new Error("boo!")', { + filename: 'test.vm', + displayErrors: false + }); } catch (e) {} console.error('middle'); vm.runInThisContext('throw new Error("boo!")', { - filename: 'test.vm', - displayErrors: false + filename: 'test.vm', + displayErrors: false }); console.error('end'); diff --git a/test/message/vm_dont_display_syntax_error.js b/test/message/vm_dont_display_syntax_error.js index 724bea22148fdd..42b1ab14cba76f 100644 --- a/test/message/vm_dont_display_syntax_error.js +++ b/test/message/vm_dont_display_syntax_error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -5,17 +6,17 @@ var vm = require('vm'); console.error('beginning'); try { - vm.runInThisContext('var 5;', { - filename: 'test.vm', - displayErrors: false - }); + vm.runInThisContext('var 5;', { + filename: 'test.vm', + displayErrors: false + }); } catch (e) {} console.error('middle'); vm.runInThisContext('var 5;', { - filename: 'test.vm', - displayErrors: false + filename: 'test.vm', + displayErrors: false }); console.error('end'); diff --git a/test/parallel/test-arm-math-exp-regress-1376.js b/test/parallel/test-arm-math-exp-regress-1376.js index fa3e3bfae15881..2b81f599a753b2 100644 --- a/test/parallel/test-arm-math-exp-regress-1376.js +++ b/test/parallel/test-arm-math-exp-regress-1376.js @@ -1,4 +1,9 @@ +<<<<<<< HEAD // See https://github.com/iojs/io.js/issues/1376 +======= +'use strict'; +// See https://github.com/nodejs/io.js/issues/1376 +>>>>>>> f29762f... test: enable linting for tests // and https://code.google.com/p/v8/issues/detail?id=4019 Math.abs(-0.5); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 1e2e8e6d557807..ce84eabc34e1d4 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var a = require('assert'); @@ -144,10 +145,14 @@ if (typeof Symbol === 'symbol') { } // primitive wrappers and object -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), {0: 'a'}), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}), a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), {0: 'a'}), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}), + a.AssertionError); +assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}), + a.AssertionError); //deepStrictEqual assert.doesNotThrow(makeBlock(a.deepStrictEqual, new Date(2000, 3, 14), @@ -313,9 +318,9 @@ try { assert.equal(true, threw, 'a.doesNotThrow is not catching type matching errors'); -assert.throws(function() {assert.ifError(new Error('test error'))}); -assert.doesNotThrow(function() {assert.ifError(null)}); -assert.doesNotThrow(function() {assert.ifError()}); +assert.throws(function() {assert.ifError(new Error('test error'));}); +assert.doesNotThrow(function() {assert.ifError(null);}); +assert.doesNotThrow(function() {assert.ifError();}); // make sure that validating using constructor really works threw = false; @@ -373,7 +378,7 @@ function testAssertionMessage(actual, expected) { } catch (e) { assert.equal(e.toString(), ['AssertionError:', expected, '==', '\'\''].join(' ')); - assert.ok(e.generatedMessage, "Message not marked as generated"); + assert.ok(e.generatedMessage, 'Message not marked as generated'); } } @@ -393,7 +398,7 @@ testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]'); testAssertionMessage(/a/, '/a/'); testAssertionMessage(/abc/gim, '/abc/gim'); testAssertionMessage(function f() {}, '[Function: f]'); -testAssertionMessage(function () {}, '[Function]'); +testAssertionMessage(function() {}, '[Function]'); testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); @@ -402,7 +407,7 @@ testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, // #2893 try { - assert.throws(function () { + assert.throws(function() { assert.ifError(null); }); } catch (e) { @@ -415,14 +420,14 @@ assert.ok(threw); try { assert.equal(1, 2); } catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2') + assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2'); assert.ok(e.generatedMessage, 'Message not marked as generated'); } try { assert.equal(1, 2, 'oh no'); } catch (e) { - assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no') + assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no'); assert.equal(e.generatedMessage, false, 'Message incorrectly marked as generated'); } diff --git a/test/parallel/test-bad-unicode.js b/test/parallel/test-bad-unicode.js index ba31ba3e234970..6dcabc8fd47b96 100644 --- a/test/parallel/test-bad-unicode.js +++ b/test/parallel/test-bad-unicode.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'), exception = null; diff --git a/test/parallel/test-beforeexit-event-exit.js b/test/parallel/test-beforeexit-event-exit.js index 8d0d43d45bb4d4..43d213a8f95055 100644 --- a/test/parallel/test-beforeexit-event-exit.js +++ b/test/parallel/test-beforeexit-event-exit.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); process.on('beforeExit', function() { diff --git a/test/parallel/test-beforeexit-event.js b/test/parallel/test-beforeexit-event.js index 8bfdbe108eccb1..f3bd127b408b08 100644 --- a/test/parallel/test-beforeexit-event.js +++ b/test/parallel/test-beforeexit-event.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var net = require('net'); var util = require('util'); @@ -19,7 +20,7 @@ function tryImmediate() { function tryTimer() { console.log('set a timeout'); - setTimeout(function () { + setTimeout(function() { console.log('timeout cb, do another once beforeExit'); revivals++; process.once('beforeExit', tryListen); diff --git a/test/parallel/test-buffer-ascii.js b/test/parallel/test-buffer-ascii.js index e7625f3a0c5458..efc3a72c662595 100644 --- a/test/parallel/test-buffer-ascii.js +++ b/test/parallel/test-buffer-ascii.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-concat.js b/test/parallel/test-buffer-concat.js index 54c4b13cb9dc90..b023dba4cdd3e3 100644 --- a/test/parallel/test-buffer-concat.js +++ b/test/parallel/test-buffer-concat.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -14,7 +15,7 @@ var flatLongLen = Buffer.concat(long, 40); assert(flatZero.length === 0); assert(flatOne.toString() === 'asdf'); assert(flatOne === one[0]); -assert(flatLong.toString() === (new Array(10+1).join('asdf'))); -assert(flatLongLen.toString() === (new Array(10+1).join('asdf'))); +assert(flatLong.toString() === (new Array(10 + 1).join('asdf'))); +assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf'))); -console.log("ok"); +console.log('ok'); diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 32748dcaaab727..7ffbae525f8984 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-inspect.js b/test/parallel/test-buffer-inspect.js index f663d23edce8dc..707f778255ad51 100644 --- a/test/parallel/test-buffer-inspect.js +++ b/test/parallel/test-buffer-inspect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-iterator.js b/test/parallel/test-buffer-iterator.js index ab02934bf9e794..05371d6d793fed 100644 --- a/test/parallel/test-buffer-iterator.js +++ b/test/parallel/test-buffer-iterator.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-buffer-slice.js b/test/parallel/test-buffer-slice.js index 3d8f9c62d2ce36..53434eab8e3f8f 100644 --- a/test/parallel/test-buffer-slice.js +++ b/test/parallel/test-buffer-slice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -7,5 +8,5 @@ var buff = new Buffer(Buffer.poolSize + 1); var slicedBuffer = buff.slice(); assert.equal(slicedBuffer.parent, buff, - "slicedBufffer should have its parent set to the original " + - " buffer"); + 'slicedBufffer should have its parent set to the original ' + + ' buffer'); diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 3cdd862880207a..428629139720dc 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -127,8 +128,8 @@ assert.strictEqual(Math.floor(c.length / 2), copied); for (var i = 0; i < Math.floor(c.length / 2); i++) { assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]); } -for (var i = Math.floor(c.length /2) + 1; i < c.length; i++) { - assert.strictEqual(c[c.length-1], c[i]); +for (var i = Math.floor(c.length / 2) + 1; i < c.length; i++) { + assert.strictEqual(c[c.length - 1], c[i]); } // try to copy 513 bytes, and check we don't overrun c @@ -843,7 +844,7 @@ Buffer(Buffer(0), 0, 0); // GH-5110 -(function () { +(function() { var buffer = new Buffer('test'), string = JSON.stringify(buffer); @@ -1068,7 +1069,7 @@ assert.equal(buf.readInt8(0), -1); // see https://github.com/joyent/node/issues/5881 SlowBuffer(0).slice(0, 1); // make sure a zero length slice doesn't set the .parent attribute - assert.equal(Buffer(5).slice(0,0).parent, undefined); + assert.equal(Buffer(5).slice(0, 0).parent, undefined); // and make sure a proper slice does have a parent assert.ok(typeof Buffer(5).slice(0, 5).parent === 'object'); })(); @@ -1087,7 +1088,7 @@ assert.throws(function() { (function() { var a = [0]; for (var i = 0; i < 7; ++i) a = a.concat(a); - a = a.map(function(_, i) { return i }); + a = a.map(function(_, i) { return i; }); var b = Buffer(a); var c = Buffer(b); assert.equal(b.length, a.length); @@ -1100,11 +1101,11 @@ assert.throws(function() { })(); -assert.throws(function () { +assert.throws(function() { new Buffer(smalloc.kMaxLength + 1); }, RangeError); -assert.throws(function () { +assert.throws(function() { new SlowBuffer(smalloc.kMaxLength + 1); }, RangeError); diff --git a/test/parallel/test-c-ares.js b/test/parallel/test-c-ares.js index 2c74a470443b42..739c3256fb33ae 100644 --- a/test/parallel/test-c-ares.js +++ b/test/parallel/test-c-ares.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-buffering.js b/test/parallel/test-child-process-buffering.js index 997e64248ababb..a37e1dbbbd7574 100644 --- a/test/parallel/test-child-process-buffering.js +++ b/test/parallel/test-child-process-buffering.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -23,7 +24,7 @@ function pwd(callback) { childExited = true; }); - child.on('close', function () { + child.on('close', function() { callback(output); pwd_called = true; childClosed = true; diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index 2ff459e9a33982..5d3f0d9496a313 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -26,7 +27,7 @@ function testCwd(options, forCode, forData) { assert.strictEqual(forCode, code); }); - child.on('close', function () { + child.on('close', function() { forData && assert.strictEqual(forData, data.replace(/[\s\r\n]+$/, '')); returns--; }); diff --git a/test/parallel/test-child-process-default-options.js b/test/parallel/test-child-process-default-options.js index ee0cb59842b9be..93165ded6d165d 100644 --- a/test/parallel/test-child-process-default-options.js +++ b/test/parallel/test-child-process-default-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-detached.js b/test/parallel/test-child-process-detached.js index 1cc2a5022ed49a..25b811a8caa991 100644 --- a/test/parallel/test-child-process-detached.js +++ b/test/parallel/test-child-process-detached.js @@ -1,23 +1,25 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); var spawn = require('child_process').spawn; -var childPath = path.join(__dirname, '..', 'fixtures', 'parent-process-nonpersistent.js'); +var childPath = path.join(__dirname, '..', 'fixtures', + 'parent-process-nonpersistent.js'); var persistentPid = -1; var child = spawn(process.execPath, [ childPath ]); -child.stdout.on('data', function (data) { +child.stdout.on('data', function(data) { persistentPid = parseInt(data, 10); }); -process.on('exit', function () { +process.on('exit', function() { assert(persistentPid !== -1); - assert.throws(function () { + assert.throws(function() { process.kill(child.pid); }); - assert.doesNotThrow(function () { + assert.doesNotThrow(function() { process.kill(persistentPid); }); }); diff --git a/test/parallel/test-child-process-disconnect.js b/test/parallel/test-child-process-disconnect.js index 95b26a7c4ad125..fd5153f3965b21 100644 --- a/test/parallel/test-child-process-disconnect.js +++ b/test/parallel/test-child-process-disconnect.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-double-pipe.js b/test/parallel/test-child-process-double-pipe.js index cf40dedd8a6eb1..17b05791315994 100644 --- a/test/parallel/test-child-process-double-pipe.js +++ b/test/parallel/test-child-process-double-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var is_windows = process.platform === 'win32'; var common = require('../common'); @@ -95,5 +96,5 @@ sed.stdout.on('data', function(data) { }); sed.stdout.on('end', function(code) { - assert.equal(result, 'hellO' + os.EOL + 'nOde' + os.EOL +'wOrld' + os.EOL); + assert.equal(result, 'hellO' + os.EOL + 'nOde' + os.EOL + 'wOrld' + os.EOL); }); diff --git a/test/parallel/test-child-process-env.js b/test/parallel/test-child-process-env.js index a6a164a66c4c72..6f2051f1282b84 100644 --- a/test/parallel/test-child-process-env.js +++ b/test/parallel/test-child-process-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-exec-buffer.js b/test/parallel/test-child-process-exec-buffer.js index b680e3b3c1ee5a..0ab05080a2cb87 100644 --- a/test/parallel/test-child-process-exec-buffer.js +++ b/test/parallel/test-child-process-exec-buffer.js @@ -1,3 +1,4 @@ +'use strict'; require('../common'); var assert = require('assert'); var exec = require('child_process').exec; @@ -8,7 +9,7 @@ var success_count = 0; var str = 'hello'; // default encoding -var child = exec("echo " + str, function(err, stdout, stderr) { +var child = exec('echo ' + str, function(err, stdout, stderr) { assert.ok('string', typeof(stdout), 'Expected stdout to be a string'); assert.ok('string', typeof(stderr), 'Expected stderr to be a string'); assert.equal(str + os.EOL, stdout); @@ -17,7 +18,7 @@ var child = exec("echo " + str, function(err, stdout, stderr) { }); // no encoding (Buffers expected) -var child = exec("echo " + str, { +var child = exec('echo ' + str, { encoding: null }, function(err, stdout, stderr) { assert.ok(stdout instanceof Buffer, 'Expected stdout to be a Buffer'); diff --git a/test/parallel/test-child-process-exec-cwd.js b/test/parallel/test-child-process-exec-cwd.js index c91a35de0b8c4b..9e7039990e9dfc 100644 --- a/test/parallel/test-child-process-exec-cwd.js +++ b/test/parallel/test-child-process-exec-cwd.js @@ -1,3 +1,4 @@ +'use strict'; require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-child-process-exec-env.js b/test/parallel/test-child-process-exec-env.js index 6c8410b9a61793..eb554b459cabd8 100644 --- a/test/parallel/test-child-process-exec-env.js +++ b/test/parallel/test-child-process-exec-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-child-process-exec-error.js b/test/parallel/test-child-process-exec-error.js index 7605af98549911..b141fc3f2c09cc 100644 --- a/test/parallel/test-child-process-exec-error.js +++ b/test/parallel/test-child-process-exec-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var child_process = require('child_process'); diff --git a/test/parallel/test-child-process-exit-code.js b/test/parallel/test-child-process-exit-code.js index 61f298633f8116..feb2fe217566be 100644 --- a/test/parallel/test-child-process-exit-code.js +++ b/test/parallel/test-child-process-exit-code.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-fork-and-spawn.js b/test/parallel/test-child-process-fork-and-spawn.js index 68e8af0fc3e19f..d5255bf83ca8e0 100644 --- a/test/parallel/test-child-process-fork-and-spawn.js +++ b/test/parallel/test-child-process-fork-and-spawn.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-fork-close.js b/test/parallel/test-child-process-fork-close.js index eddfec5d521436..12b64cc4ff82ac 100644 --- a/test/parallel/test-child-process-fork-close.js +++ b/test/parallel/test-child-process-fork-close.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'), common = require('../common'), fork = require('child_process').fork, diff --git a/test/parallel/test-child-process-fork-dgram.js b/test/parallel/test-child-process-fork-dgram.js index bd21f3f748155b..8858966fde4975 100644 --- a/test/parallel/test-child-process-fork-dgram.js +++ b/test/parallel/test-child-process-fork-dgram.js @@ -1,3 +1,4 @@ +'use strict'; /* * The purpose of this test is to make sure that when forking a process, * sending a fd representing a UDP socket to the child and sending messages @@ -30,7 +31,7 @@ if (process.argv[2] === 'child') { if (msg === 'server') { server = clusterServer; - server.on('message', function () { + server.on('message', function() { process.send('gotMessage'); }); @@ -50,14 +51,14 @@ if (process.argv[2] === 'child') { var childGotMessage = false; var parentGotMessage = false; - server.on('message', function (msg, rinfo) { + server.on('message', function(msg, rinfo) { parentGotMessage = true; }); - server.on('listening', function () { + server.on('listening', function() { child.send('server', server); - child.once('message', function (msg) { + child.once('message', function(msg) { if (msg === 'gotMessage') { childGotMessage = true; } @@ -66,8 +67,8 @@ if (process.argv[2] === 'child') { sendMessages(); }); - var sendMessages = function () { - var timer = setInterval(function () { + var sendMessages = function() { + var timer = setInterval(function() { client.send(msg, 0, msg.length, common.PORT, '127.0.0.1', function(err) { if (err) throw err; } @@ -85,7 +86,7 @@ if (process.argv[2] === 'child') { }, 1); }; - var shutdown = function () { + var shutdown = function() { child.send('stop'); server.close(); @@ -94,7 +95,7 @@ if (process.argv[2] === 'child') { server.bind(common.PORT, '127.0.0.1'); - process.once('exit', function () { + process.once('exit', function() { assert(parentGotMessage); assert(childGotMessage); }); diff --git a/test/parallel/test-child-process-fork-exec-argv.js b/test/parallel/test-child-process-fork-exec-argv.js index 34292c551112c1..94703a736a110e 100644 --- a/test/parallel/test-child-process-fork-exec-argv.js +++ b/test/parallel/test-child-process-fork-exec-argv.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var child_process = require('child_process'); var spawn = child_process.spawn; @@ -16,11 +17,11 @@ if (process.argv[2] === 'fork') { var child = spawn(process.execPath, execArgv.concat(args)); var out = ''; - child.stdout.on('data', function (chunk) { + child.stdout.on('data', function(chunk) { out += chunk; }); - child.on('exit', function () { + child.on('exit', function() { assert.deepEqual(JSON.parse(out), execArgv); }); } diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index 72bb69316814de..cffb5ca05a6a78 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cp = require('child_process'); var fs = require('fs'); diff --git a/test/parallel/test-child-process-fork-net.js b/test/parallel/test-child-process-fork-net.js index a16fb85041b95f..09ec8e24b9b46c 100644 --- a/test/parallel/test-child-process-fork-net.js +++ b/test/parallel/test-child-process-fork-net.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-fork-net2.js b/test/parallel/test-child-process-fork-net2.js index 150e9cfc4544e9..95ec26a88d0de2 100644 --- a/test/parallel/test-child-process-fork-net2.js +++ b/test/parallel/test-child-process-fork-net2.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js index aa38ad7a21c5ad..b4066641bae970 100644 --- a/test/parallel/test-child-process-fork-ref.js +++ b/test/parallel/test-child-process-fork-ref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; @@ -10,7 +11,7 @@ if (process.argv[2] === 'child') { process.send('2'); }, 200); - process.on('disconnect', function () { + process.on('disconnect', function() { process.stdout.write('3'); }); @@ -19,17 +20,17 @@ if (process.argv[2] === 'child') { var ipc = [], stdout = ''; - child.on('message', function (msg) { + child.on('message', function(msg) { ipc.push(msg); if (msg === '2') child.disconnect(); }); - child.stdout.on('data', function (chunk) { + child.stdout.on('data', function(chunk) { stdout += chunk; }); - child.once('exit', function () { + child.once('exit', function() { assert.deepEqual(ipc, ['1', '2']); assert.equal(stdout, '3'); }); diff --git a/test/parallel/test-child-process-fork-ref2.js b/test/parallel/test-child-process-fork-ref2.js index 3ccdfc18871055..8bc7e4c35541b2 100644 --- a/test/parallel/test-child-process-fork-ref2.js +++ b/test/parallel/test-child-process-fork-ref2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; @@ -8,17 +9,17 @@ if (process.argv[2] === 'child') { setTimeout(function() { console.log('child -> will this keep it alive?'); - process.on('message', function () { }); + process.on('message', function() { }); }, 400); } else { var child = fork(__filename, ['child']); - child.on('disconnect', function () { + child.on('disconnect', function() { console.log('parent -> disconnect'); }); - child.once('exit', function () { + child.once('exit', function() { console.log('parent -> exit'); }); } diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js index 2ec9f402dd5d39..c35510e60c76f4 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-fork3.js b/test/parallel/test-child-process-fork3.js index 8527257bc53684..fe0e68b6a6436e 100644 --- a/test/parallel/test-child-process-fork3.js +++ b/test/parallel/test-child-process-fork3.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var child_process = require('child_process'); diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index a1bb52f4b71185..c39dc93293aa8b 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-ipc.js b/test/parallel/test-child-process-ipc.js index 712b1ee0a5e54c..7d0447569ffe73 100644 --- a/test/parallel/test-child-process-ipc.js +++ b/test/parallel/test-child-process-ipc.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-kill.js b/test/parallel/test-child-process-kill.js index 7e46aada8bbfad..948348add4abb0 100644 --- a/test/parallel/test-child-process-kill.js +++ b/test/parallel/test-child-process-kill.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-recv-handle.js b/test/parallel/test-child-process-recv-handle.js index 7f2f04f831dbf1..b992445f186383 100644 --- a/test/parallel/test-child-process-recv-handle.js +++ b/test/parallel/test-child-process-recv-handle.js @@ -1,3 +1,4 @@ +'use strict'; // Test that a Linux specific quirk in the handle passing protocol is handled // correctly. See https://github.com/joyent/node/issues/5330 for details. diff --git a/test/parallel/test-child-process-send-utf8.js b/test/parallel/test-child-process-send-utf8.js index 825913dc2ae4c4..7ba76e9bd1ddc8 100644 --- a/test/parallel/test-child-process-send-utf8.js +++ b/test/parallel/test-child-process-send-utf8.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js index af831b720b2eb0..3f09388265b89a 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var ch = require('child_process'); diff --git a/test/parallel/test-child-process-silent.js b/test/parallel/test-child-process-silent.js index e1e03d0973011e..3714d3758d0f22 100644 --- a/test/parallel/test-child-process-silent.js +++ b/test/parallel/test-child-process-silent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var childProcess = require('child_process'); diff --git a/test/parallel/test-child-process-spawn-error.js b/test/parallel/test-child-process-spawn-error.js index fe279dc6e586af..1398dac165319c 100644 --- a/test/parallel/test-child-process-spawn-error.js +++ b/test/parallel/test-child-process-spawn-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fs = require('fs'); var spawn = require('child_process').spawn; @@ -10,7 +11,7 @@ var spawnargs = ['bar']; assert.equal(common.fileExists(enoentPath), false); var enoentChild = spawn(enoentPath, spawnargs); -enoentChild.on('error', function (err) { +enoentChild.on('error', function(err) { assert.equal(err.code, 'ENOENT'); assert.equal(err.errno, 'ENOENT'); assert.equal(err.syscall, 'spawn ' + enoentPath); diff --git a/test/parallel/test-child-process-spawn-typeerror.js b/test/parallel/test-child-process-spawn-typeerror.js index b95b208eb0c87e..35c190353bd1b8 100644 --- a/test/parallel/test-child-process-spawn-typeerror.js +++ b/test/parallel/test-child-process-spawn-typeerror.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var child_process = require('child_process'); var spawn = child_process.spawn; diff --git a/test/parallel/test-child-process-spawnsync-env.js b/test/parallel/test-child-process-spawnsync-env.js index 0ebc66a7459cfe..bc7c5aa3dd6c14 100644 --- a/test/parallel/test-child-process-spawnsync-env.js +++ b/test/parallel/test-child-process-spawnsync-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cp = require('child_process'); diff --git a/test/parallel/test-child-process-spawnsync-input.js b/test/parallel/test-child-process-spawnsync-input.js index e85e9da1fbade9..4118b74dc35f6c 100644 --- a/test/parallel/test-child-process-spawnsync-input.js +++ b/test/parallel/test-child-process-spawnsync-input.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js index f5b5987e4d1eaf..34c69a1fc597d2 100644 --- a/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -15,7 +16,8 @@ switch (process.argv[2]) { break; default: var start = Date.now(); - var ret = spawnSync(process.execPath, [__filename, 'child'], {timeout: TIMER}); + var ret = spawnSync(process.execPath, [__filename, 'child'], + {timeout: TIMER}); assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); console.log(ret); var end = Date.now() - start; diff --git a/test/parallel/test-child-process-spawnsync.js b/test/parallel/test-child-process-spawnsync.js index 67b07ed481889c..b6f4d31b5c158c 100644 --- a/test/parallel/test-child-process-spawnsync.js +++ b/test/parallel/test-child-process-spawnsync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -20,7 +21,8 @@ var ret = spawnSync('sleep', ['1']); var stop = process.hrtime(start); assert.strictEqual(ret.status, 0, 'exit status should be zero'); console.log('sleep exited', stop); -assert.strictEqual(stop[0], 1, 'sleep should not take longer or less than 1 second'); +assert.strictEqual(stop[0], 1, + 'sleep should not take longer or less than 1 second'); // Error test when command does not exist var ret_err = spawnSync('command_does_not_exist', ['bar']).error; diff --git a/test/parallel/test-child-process-stdin-ipc.js b/test/parallel/test-child-process-stdin-ipc.js index 2758087deac814..d2347849dd5b9b 100644 --- a/test/parallel/test-child-process-stdin-ipc.js +++ b/test/parallel/test-child-process-stdin-ipc.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-child-process-stdin.js b/test/parallel/test-child-process-stdin.js index f2a5e1836a6e1d..ba3ef0e0c1c689 100644 --- a/test/parallel/test-child-process-stdin.js +++ b/test/parallel/test-child-process-stdin.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -48,7 +49,7 @@ cat.on('exit', function(status) { exitStatus = status; }); -cat.on('close', function () { +cat.on('close', function() { closed = true; if (is_windows) { assert.equal('hello world\r\n', response); diff --git a/test/parallel/test-child-process-stdio-big-write-end.js b/test/parallel/test-child-process-stdio-big-write-end.js index 631cecc33d74b1..5ae85acc54d9dd 100644 --- a/test/parallel/test-child-process-stdio-big-write-end.js +++ b/test/parallel/test-child-process-stdio-big-write-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var BUFSIZE = 1024; diff --git a/test/parallel/test-child-process-stdio-inherit.js b/test/parallel/test-child-process-stdio-inherit.js index 15a504099263c8..8cf08a7bd5fa71 100644 --- a/test/parallel/test-child-process-stdio-inherit.js +++ b/test/parallel/test-child-process-stdio-inherit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-stdio.js b/test/parallel/test-child-process-stdio.js index 7292007f1a207e..1ff6e4d914f7ec 100644 --- a/test/parallel/test-child-process-stdio.js +++ b/test/parallel/test-child-process-stdio.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-child-process-stdout-flush-exit.js b/test/parallel/test-child-process-stdout-flush-exit.js index eba8927204f71c..0d4e3538ceb3f0 100644 --- a/test/parallel/test-child-process-stdout-flush-exit.js +++ b/test/parallel/test-child-process-stdout-flush-exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -21,14 +22,14 @@ if (process.argv[2] === 'child') { var gotBye = false; child.stderr.setEncoding('utf8'); - child.stderr.on('data', function (data) { + child.stderr.on('data', function(data) { console.log('parent stderr: ' + data); assert.ok(false); }); // check if we receive both 'hello' at start and 'goodbye' at end child.stdout.setEncoding('utf8'); - child.stdout.on('data', function (data) { + child.stdout.on('data', function(data) { if (data.slice(0, 6) == 'hello\n') { gotHello = true; } else if (data.slice(data.length - 8) == 'goodbye\n') { @@ -38,7 +39,7 @@ if (process.argv[2] === 'child') { } }); - child.on('close', function (data) { + child.on('close', function(data) { assert(gotHello); assert(gotBye); }); diff --git a/test/parallel/test-child-process-stdout-flush.js b/test/parallel/test-child-process-stdout-flush.js index 58d6a8f46a4b9d..8300f4bbc7cbf3 100644 --- a/test/parallel/test-child-process-stdout-flush.js +++ b/test/parallel/test-child-process-stdout-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index fd9cd410d5ea93..10a77c4a67b8a4 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -1,3 +1,4 @@ +'use strict'; if (module.parent) { // signal we've been loaded as a module console.log('Loaded as a module, exiting with status code 42.'); diff --git a/test/parallel/test-cluster-basic.js b/test/parallel/test-cluster-basic.js index 75ed9d3a155349..60bd27b24eee89 100644 --- a/test/parallel/test-cluster-basic.js +++ b/test/parallel/test-cluster-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-bind-privileged-port.js b/test/parallel/test-cluster-bind-privileged-port.js index 3a75250c53f811..b51367aa4229a3 100644 --- a/test/parallel/test-cluster-bind-privileged-port.js +++ b/test/parallel/test-cluster-bind-privileged-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-bind-twice.js b/test/parallel/test-cluster-bind-twice.js index db1ea8874f4d17..ec6faa83c1151b 100644 --- a/test/parallel/test-cluster-bind-twice.js +++ b/test/parallel/test-cluster-bind-twice.js @@ -1,3 +1,4 @@ +'use strict'; // This test starts two clustered HTTP servers on the same port. It expects the // first cluster to succeed and the second cluster to fail with EADDRINUSE. // diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js index dada58017f5130..bccc39637bb79a 100644 --- a/test/parallel/test-cluster-dgram-1.js +++ b/test/parallel/test-cluster-dgram-1.js @@ -1,3 +1,4 @@ +'use strict'; var NUM_WORKERS = 4; var PACKETS_PER_WORKER = 10; @@ -8,7 +9,7 @@ var dgram = require('dgram'); if (process.platform === 'win32') { - console.warn("dgram clustering is currently not supported on windows."); + console.warn('dgram clustering is currently not supported on windows.'); process.exit(0); } diff --git a/test/parallel/test-cluster-dgram-2.js b/test/parallel/test-cluster-dgram-2.js index 68de38e7c33c61..db4f986f2db64f 100644 --- a/test/parallel/test-cluster-dgram-2.js +++ b/test/parallel/test-cluster-dgram-2.js @@ -1,3 +1,4 @@ +'use strict'; var NUM_WORKERS = 4; var PACKETS_PER_WORKER = 10; @@ -8,7 +9,7 @@ var dgram = require('dgram'); if (process.platform === 'win32') { - console.warn("dgram clustering is currently not supported on windows."); + console.warn('dgram clustering is currently not supported on windows.'); process.exit(0); } @@ -61,5 +62,6 @@ function worker() { for (var i = 0; i < PACKETS_PER_WORKER; i++) socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1'); - console.log('worker %d sent %d packets', cluster.worker.id, PACKETS_PER_WORKER); + console.log('worker %d sent %d packets', cluster.worker.id, + PACKETS_PER_WORKER); } diff --git a/test/parallel/test-cluster-disconnect-before-exit.js b/test/parallel/test-cluster-disconnect-before-exit.js index d249296bab740a..8f63bcd1134310 100644 --- a/test/parallel/test-cluster-disconnect-before-exit.js +++ b/test/parallel/test-cluster-disconnect-before-exit.js @@ -1,3 +1,4 @@ +'use strict'; var cluster = require('cluster'); if (cluster.isMaster) { diff --git a/test/parallel/test-cluster-disconnect-idle-worker.js b/test/parallel/test-cluster-disconnect-idle-worker.js index 28cdd2de4eaf50..e18c05004467b7 100644 --- a/test/parallel/test-cluster-disconnect-idle-worker.js +++ b/test/parallel/test-cluster-disconnect-idle-worker.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-disconnect-unshared-tcp.js b/test/parallel/test-cluster-disconnect-unshared-tcp.js index 6fccc58c095930..a927b5da9fe1b4 100644 --- a/test/parallel/test-cluster-disconnect-unshared-tcp.js +++ b/test/parallel/test-cluster-disconnect-unshared-tcp.js @@ -1,3 +1,4 @@ +'use strict'; process.env.NODE_CLUSTER_SCHED_POLICY = 'none'; var cluster = require('cluster'); @@ -16,7 +17,7 @@ if (cluster.isMaster) { } } else { if (process.env.BOUND === 'y') { - var source = net.createServer() + var source = net.createServer(); source.listen(0); } diff --git a/test/parallel/test-cluster-disconnect-unshared-udp.js b/test/parallel/test-cluster-disconnect-unshared-udp.js index a40c386918b156..f90152cf68f1a7 100644 --- a/test/parallel/test-cluster-disconnect-unshared-udp.js +++ b/test/parallel/test-cluster-disconnect-unshared-udp.js @@ -1,3 +1,4 @@ +'use strict'; if (process.platform === 'win32') { console.log('skipping test on windows, where clustered dgram is ENOTSUP'); process.exit(0); diff --git a/test/parallel/test-cluster-disconnect-with-no-workers.js b/test/parallel/test-cluster-disconnect-with-no-workers.js index e07f5af99ddf9f..1c99461bfa4fc5 100644 --- a/test/parallel/test-cluster-disconnect-with-no-workers.js +++ b/test/parallel/test-cluster-disconnect-with-no-workers.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-disconnect.js b/test/parallel/test-cluster-disconnect.js index c557256dcb3bfe..0f19d534aafd89 100644 --- a/test/parallel/test-cluster-disconnect.js +++ b/test/parallel/test-cluster-disconnect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-eaccess.js b/test/parallel/test-cluster-eaccess.js index 1be28a38559b0b..ad4de97e389ec5 100644 --- a/test/parallel/test-cluster-eaccess.js +++ b/test/parallel/test-cluster-eaccess.js @@ -1,5 +1,7 @@ -// test that errors propagated from cluster children are properly received in their master -// creates an EADDRINUSE condition by also forking a child process to listen on a socket +'use strict'; +// test that errors propagated from cluster children are properly +// received in their master creates an EADDRINUSE condition by also +// forking a child process to listen on a socket var common = require('../common'); var assert = require('assert'); @@ -27,7 +29,8 @@ if (cluster.isMaster) { assert.equal(gotError, 1); }); } else { - var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', { stdio: 'inherit' }); + var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', + { stdio: 'inherit' }); // message from the child indicates it's ready and listening cp.on('message', function() { diff --git a/test/parallel/test-cluster-eaddrinuse.js b/test/parallel/test-cluster-eaddrinuse.js index c43259c5631bcf..509dbb664e1d5d 100644 --- a/test/parallel/test-cluster-eaddrinuse.js +++ b/test/parallel/test-cluster-eaddrinuse.js @@ -1,3 +1,4 @@ +'use strict'; // Check that having a worker bind to a port that's already taken doesn't // leave the master process in a confused state. Releasing the port and // trying again should Just Work[TM]. diff --git a/test/parallel/test-cluster-fork-env.js b/test/parallel/test-cluster-fork-env.js index ddcf7d236c9482..7749e42f608c60 100644 --- a/test/parallel/test-cluster-fork-env.js +++ b/test/parallel/test-cluster-fork-env.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-http-pipe.js b/test/parallel/test-cluster-http-pipe.js index b9706699615ac1..42ed3bee1eed3c 100644 --- a/test/parallel/test-cluster-http-pipe.js +++ b/test/parallel/test-cluster-http-pipe.js @@ -1,3 +1,4 @@ +'use strict'; // It is not possible to send pipe handles over the IPC pipe on Windows. if (process.platform === 'win32') { process.exit(0); diff --git a/test/parallel/test-cluster-master-error.js b/test/parallel/test-cluster-master-error.js index e0e92e7cf9e2a4..e729963d7df6a9 100644 --- a/test/parallel/test-cluster-master-error.js +++ b/test/parallel/test-cluster-master-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-master-kill.js b/test/parallel/test-cluster-master-kill.js index a5c22855607104..89694ffd115bb4 100644 --- a/test/parallel/test-cluster-master-kill.js +++ b/test/parallel/test-cluster-master-kill.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-message.js b/test/parallel/test-cluster-message.js index 29c9e31159e62a..a72d1f079efaaa 100644 --- a/test/parallel/test-cluster-message.js +++ b/test/parallel/test-cluster-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-net-listen.js b/test/parallel/test-cluster-net-listen.js index 1d8e08c877481e..741cacc75897e3 100644 --- a/test/parallel/test-cluster-net-listen.js +++ b/test/parallel/test-cluster-net-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-net-send.js b/test/parallel/test-cluster-net-send.js index 17d77171c50534..6190fb517e4d1a 100644 --- a/test/parallel/test-cluster-net-send.js +++ b/test/parallel/test-cluster-net-send.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fork = require('child_process').fork; diff --git a/test/parallel/test-cluster-rr-domain-listen.js b/test/parallel/test-cluster-rr-domain-listen.js index fc26c93685a045..1328483abb72df 100644 --- a/test/parallel/test-cluster-rr-domain-listen.js +++ b/test/parallel/test-cluster-rr-domain-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var cluster = require('cluster'); var domain = require('domain'); @@ -7,7 +8,7 @@ var domain = require('domain'); if (cluster.isWorker) { var d = domain.create(); - d.run(function () { }); + d.run(function() { }); var http = require('http'); http.Server(function() { }).listen(common.PORT, '127.0.0.1'); diff --git a/test/parallel/test-cluster-send-deadlock.js b/test/parallel/test-cluster-send-deadlock.js index 7fd465db5feb13..90b8c91695359b 100644 --- a/test/parallel/test-cluster-send-deadlock.js +++ b/test/parallel/test-cluster-send-deadlock.js @@ -1,3 +1,4 @@ +'use strict'; // Testing mutual send of handles: from master to worker, and from worker to // master. diff --git a/test/parallel/test-cluster-send-handle-twice.js b/test/parallel/test-cluster-send-handle-twice.js index 2d2c2cc588eaf8..f1552d79265a0c 100644 --- a/test/parallel/test-cluster-send-handle-twice.js +++ b/test/parallel/test-cluster-send-handle-twice.js @@ -1,3 +1,4 @@ +'use strict'; // Testing to send an handle twice to the parent process. var common = require('../common'); diff --git a/test/parallel/test-cluster-setup-master-argv.js b/test/parallel/test-cluster-setup-master-argv.js index a8274be2e924cb..b406c76cbbfe0b 100644 --- a/test/parallel/test-cluster-setup-master-argv.js +++ b/test/parallel/test-cluster-setup-master-argv.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master-cumulative.js b/test/parallel/test-cluster-setup-master-cumulative.js index cf2d8e90daac36..0376546d286b51 100644 --- a/test/parallel/test-cluster-setup-master-cumulative.js +++ b/test/parallel/test-cluster-setup-master-cumulative.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master-emit.js b/test/parallel/test-cluster-setup-master-emit.js index bef10d8cb81ba3..8b463ec97bff45 100644 --- a/test/parallel/test-cluster-setup-master-emit.js +++ b/test/parallel/test-cluster-setup-master-emit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master-multiple.js b/test/parallel/test-cluster-setup-master-multiple.js index da0c03c7320bc9..8ee6d091cd524a 100644 --- a/test/parallel/test-cluster-setup-master-multiple.js +++ b/test/parallel/test-cluster-setup-master-multiple.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-setup-master.js b/test/parallel/test-cluster-setup-master.js index 7cf9631146682b..c32b3ea6d3b18b 100644 --- a/test/parallel/test-cluster-setup-master.js +++ b/test/parallel/test-cluster-setup-master.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-shared-handle-bind-error.js b/test/parallel/test-cluster-shared-handle-bind-error.js index f327de994a1fc6..a93b07ba30e27b 100644 --- a/test/parallel/test-cluster-shared-handle-bind-error.js +++ b/test/parallel/test-cluster-shared-handle-bind-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-shared-handle-bind-privileged-port.js b/test/parallel/test-cluster-shared-handle-bind-privileged-port.js index 3bbe9fbf2f9cda..4fc4b078ad6409 100644 --- a/test/parallel/test-cluster-shared-handle-bind-privileged-port.js +++ b/test/parallel/test-cluster-shared-handle-bind-privileged-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-uncaught-exception.js b/test/parallel/test-cluster-uncaught-exception.js index 9f98d626c8634e..ec42773ef55856 100644 --- a/test/parallel/test-cluster-uncaught-exception.js +++ b/test/parallel/test-cluster-uncaught-exception.js @@ -1,3 +1,4 @@ +'use strict'; // Installing a custom uncaughtException handler should override the default // one that the cluster module installs. // https://github.com/joyent/node/issues/2556 diff --git a/test/parallel/test-cluster-worker-constructor.js b/test/parallel/test-cluster-worker-constructor.js index 331ab777481e59..e29dc01561903d 100644 --- a/test/parallel/test-cluster-worker-constructor.js +++ b/test/parallel/test-cluster-worker-constructor.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-constructor.js // validates correct behavior of the cluster.Worker constructor diff --git a/test/parallel/test-cluster-worker-death.js b/test/parallel/test-cluster-worker-death.js index d19704c58b3868..88a0f887cc2cab 100644 --- a/test/parallel/test-cluster-worker-death.js +++ b/test/parallel/test-cluster-worker-death.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index 55ae0fc8c0c172..8e5ca63e13c6be 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -1,3 +1,4 @@ +'use strict'; /* * The goal of this test is to cover the Workers' implementation of * Worker.prototype.destroy. Worker.prototype.destroy is called within diff --git a/test/parallel/test-cluster-worker-disconnect.js b/test/parallel/test-cluster-worker-disconnect.js index 4bb9b163b64982..7f4038149cd7d1 100644 --- a/test/parallel/test-cluster-worker-disconnect.js +++ b/test/parallel/test-cluster-worker-disconnect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); @@ -8,6 +9,10 @@ if (cluster.isWorker) { }).listen(common.PORT, '127.0.0.1'); + cluster.worker.on('disconnect', function() { + process.exit(42); + }); + } else if (cluster.isMaster) { var checks = { @@ -18,6 +23,7 @@ if (cluster.isWorker) { }, worker: { emitDisconnect: false, + emitDisconnectInsideWorker: false, emitExit: false, state: false, suicideMode: false, @@ -59,9 +65,11 @@ if (cluster.isWorker) { }); // Check that the worker died - worker.once('exit', function() { + worker.once('exit', function(code) { checks.worker.emitExit = true; checks.worker.died = !alive(worker.process.pid); + checks.worker.emitDisconnectInsideWorker = code === 42; + process.nextTick(function() { process.exit(0); }); @@ -74,6 +82,8 @@ if (cluster.isWorker) { // events assert.ok(w.emitDisconnect, 'Disconnect event did not emit'); + assert.ok(w.emitDisconnectInsideWorker, + 'Disconnect event did not emit inside worker'); assert.ok(c.emitDisconnect, 'Disconnect event did not emit'); assert.ok(w.emitExit, 'Exit event did not emit'); assert.ok(c.emitExit, 'Exit event did not emit'); diff --git a/test/parallel/test-cluster-worker-events.js b/test/parallel/test-cluster-worker-events.js index fb3b8797e0deac..eb986556b69183 100644 --- a/test/parallel/test-cluster-worker-events.js +++ b/test/parallel/test-cluster-worker-events.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-cluster-worker-exit.js b/test/parallel/test-cluster-worker-exit.js index 1342a70d6f0c35..982b099cd1cfe1 100644 --- a/test/parallel/test-cluster-worker-exit.js +++ b/test/parallel/test-cluster-worker-exit.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-exit.js // verifies that, when a child process exits (by calling `process.exit(code)`) // - the parent receives the proper events in the proper order, no duplicates @@ -100,31 +101,31 @@ if (cluster.isWorker) { // some helper functions ... - function checkResults(expected_results, results) { - for (var k in expected_results) { - var actual = results[k], - expected = expected_results[k]; +function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; - if (typeof expected === 'function') { - expected(r[k]); + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); } else { - var msg = (expected[1] || '') + - (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); - - if (expected && expected.length) { - assert.equal(actual, expected[0], msg); - } else { - assert.equal(actual, expected, msg); - } + assert.equal(actual, expected, msg); } } } +} - function alive(pid) { - try { - process.kill(pid, 'SIGCONT'); - return true; - } catch (e) { - return false; - } +function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; } +} diff --git a/test/parallel/test-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js index 144eb0dd3a3be8..54d2ce8a478303 100644 --- a/test/parallel/test-cluster-worker-forced-exit.js +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -1,5 +1,6 @@ +'use strict'; var assert = require('assert'); -var cluster = require('cluster') +var cluster = require('cluster'); var net = require('net'); var SENTINEL = 42; diff --git a/test/parallel/test-cluster-worker-init.js b/test/parallel/test-cluster-worker-init.js index 87e0ce040af98f..38886af5279a6d 100644 --- a/test/parallel/test-cluster-worker-init.js +++ b/test/parallel/test-cluster-worker-init.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-init.js // verifies that, when a child process is forked, the cluster.worker // object can receive messages as expected diff --git a/test/parallel/test-cluster-worker-isconnected.js b/test/parallel/test-cluster-worker-isconnected.js index ed839d49630491..4477278e31330a 100644 --- a/test/parallel/test-cluster-worker-isconnected.js +++ b/test/parallel/test-cluster-worker-isconnected.js @@ -1,3 +1,4 @@ +'use strict'; var cluster = require('cluster'); var assert = require('assert'); var util = require('util'); @@ -6,32 +7,32 @@ if (cluster.isMaster) { var worker = cluster.fork(); assert.ok(worker.isConnected(), - "isConnected() should return true as soon as the worker has " + - "been created."); + 'isConnected() should return true as soon as the worker has ' + + 'been created.'); worker.on('disconnect', function() { assert.ok(!worker.isConnected(), - "After a disconnect event has been emitted, " + - "isConncted should return false"); + 'After a disconnect event has been emitted, ' + + 'isConncted should return false'); }); worker.on('message', function(msg) { if (msg === 'readyToDisconnect') { worker.disconnect(); } - }) + }); } else { assert.ok(cluster.worker.isConnected(), - "isConnected() should return true from within a worker at all " + - "times."); + 'isConnected() should return true from within a worker at all ' + + 'times.'); cluster.worker.process.on('disconnect', function() { assert.ok(!cluster.worker.isConnected(), - "isConnected() should return false from within a worker " + - "after its underlying process has been disconnected from " + - "the master"); - }) + 'isConnected() should return false from within a worker ' + + 'after its underlying process has been disconnected from ' + + 'the master'); + }); process.send('readyToDisconnect'); } diff --git a/test/parallel/test-cluster-worker-isdead.js b/test/parallel/test-cluster-worker-isdead.js index 11766c597f8297..045a620a9efab7 100644 --- a/test/parallel/test-cluster-worker-isdead.js +++ b/test/parallel/test-cluster-worker-isdead.js @@ -1,3 +1,4 @@ +'use strict'; var cluster = require('cluster'); var assert = require('assert'); var net = require('net'); @@ -5,23 +6,23 @@ var net = require('net'); if (cluster.isMaster) { var worker = cluster.fork(); assert.ok(!worker.isDead(), - "isDead() should return false right after the worker has been " + - "created."); + 'isDead() should return false right after the worker has been ' + + 'created.'); worker.on('exit', function() { - assert.ok(!worker.isConnected(), - "After an event has been emitted, " + - "isDead should return true"); - }) + assert.ok(!worker.isConnected(), + 'After an event has been emitted, ' + + 'isDead should return true'); + }); worker.on('message', function(msg) { - if (msg === 'readyToDie') { - worker.kill(); - } + if (msg === 'readyToDie') { + worker.kill(); + } }); } else if (cluster.isWorker) { assert.ok(!cluster.worker.isDead(), - "isDead() should return false when called from within a worker"); + 'isDead() should return false when called from within a worker'); process.send('readyToDie'); } diff --git a/test/parallel/test-cluster-worker-kill.js b/test/parallel/test-cluster-worker-kill.js index 01da15fdca6a18..c73cf2dbd5216e 100644 --- a/test/parallel/test-cluster-worker-kill.js +++ b/test/parallel/test-cluster-worker-kill.js @@ -1,3 +1,4 @@ +'use strict'; // test-cluster-worker-kill.js // verifies that, when a child process is killed (we use SIGKILL) // - the parent receives the proper events in the proper order, no duplicates @@ -23,14 +24,16 @@ if (cluster.isWorker) { cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"], cluster_emitExit: [1, "the cluster did not emit 'exit'"], cluster_exitCode: [null, 'the cluster exited w/ incorrect exitCode'], - cluster_signalCode: [KILL_SIGNAL, 'the cluster exited w/ incorrect signalCode'], + cluster_signalCode: [KILL_SIGNAL, + 'the cluster exited w/ incorrect signalCode'], worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"], worker_emitExit: [1, "the worker did not emit 'exit'"], worker_state: ['disconnected', 'the worker state is incorrect'], worker_suicideMode: [false, 'the worker.suicide flag is incorrect'], worker_died: [true, 'the worker is still running'], worker_exitCode: [null, 'the worker exited w/ incorrect exitCode'], - worker_signalCode: [KILL_SIGNAL, 'the worker exited w/ incorrect signalCode'] + worker_signalCode: [KILL_SIGNAL, + 'the worker exited w/ incorrect signalCode'] }, results = { cluster_emitDisconnect: 0, @@ -98,30 +101,30 @@ if (cluster.isWorker) { // some helper functions ... - function checkResults(expected_results, results) { - for (var k in expected_results) { - var actual = results[k], - expected = expected_results[k]; - - if (typeof expected === 'function') { - expected(r[k]); +function checkResults(expected_results, results) { + for (var k in expected_results) { + var actual = results[k], + expected = expected_results[k]; + + if (typeof expected === 'function') { + expected(r[k]); + } else { + var msg = (expected[1] || '') + + (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); + if (expected && expected.length) { + assert.equal(actual, expected[0], msg); } else { - var msg = (expected[1] || '') + - (' [expected: ' + expected[0] + ' / actual: ' + actual + ']'); - if (expected && expected.length) { - assert.equal(actual, expected[0], msg); - } else { - assert.equal(actual, expected, msg); - } + assert.equal(actual, expected, msg); } } } +} - function alive(pid) { - try { - process.kill(pid, 'SIGCONT'); - return true; - } catch (e) { - return false; - } +function alive(pid) { + try { + process.kill(pid, 'SIGCONT'); + return true; + } catch (e) { + return false; } +} diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js index 034a4952e88c59..b44831694c6bfa 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -1,5 +1,6 @@ +'use strict'; var assert = require('assert'); -var cluster = require('cluster') +var cluster = require('cluster'); var net = require('net'); var common = require('../common'); @@ -21,7 +22,7 @@ var server; if (cluster.isMaster) { server = net.createServer(function(conn) { server.close(); - worker.disconnect() + worker.disconnect(); worker.once('disconnect', function() { setTimeout(function() { conn.destroy(); diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index d15448bd36afff..7cbaf305d6e4f3 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-console-instance.js b/test/parallel/test-console-instance.js index a91410b4091d47..a80c6e57e4b151 100644 --- a/test/parallel/test-console-instance.js +++ b/test/parallel/test-console-instance.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Stream = require('stream'); @@ -15,7 +16,7 @@ assert.equal('function', typeof Console); // make sure that the Console constructor throws // when not given a writable stream instance -assert.throws(function () { +assert.throws(function() { new Console(); }, /Console expects a writable stream/); diff --git a/test/parallel/test-console-not-call-toString.js b/test/parallel/test-console-not-call-toString.js index 9612a0f6ec0ddc..7846dbf2778b9c 100644 --- a/test/parallel/test-console-not-call-toString.js +++ b/test/parallel/test-console-not-call-toString.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index 2e5060f38319d5..982c83851f072a 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -7,17 +8,17 @@ assert.ok(process.stderr.writable); assert.equal('number', typeof process.stdout.fd); assert.equal('number', typeof process.stderr.fd); -assert.throws(function () { +assert.throws(function() { console.timeEnd('no such label'); }); -assert.doesNotThrow(function () { +assert.doesNotThrow(function() { console.time('label'); console.timeEnd('label'); }); // an Object with a custom .inspect() function -var custom_inspect = { foo: 'bar', inspect: function () { return 'inspect'; } }; +var custom_inspect = { foo: 'bar', inspect: function() { return 'inspect'; } }; var stdout_write = global.process.stdout.write; var strings = []; diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index 0336871a56fa20..75d733ff98b9b1 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -16,27 +17,33 @@ crypto.DEFAULT_ENCODING = 'buffer'; // var TEST_CASES = [ - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + { algo: 'aes-128-gcm', + key: '6970787039613669314d623455536234', iv: '583673497131313748307652', plain: 'Hello World!', ct: '4BE13896F64DFA2C2D0F2C76', tag: '272B422F62EB545EAA15B5FF84092447', tampered: false }, - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + { algo: 'aes-128-gcm', + key: '6970787039613669314d623455536234', iv: '583673497131313748307652', plain: 'Hello World!', ct: '4BE13896F64DFA2C2D0F2C76', aad: '000000FF', tag: 'BA2479F66275665A88CB7B15F43EB005', tampered: false }, - { algo: 'aes-128-gcm', key: '6970787039613669314d623455536234', + { algo: 'aes-128-gcm', + key: '6970787039613669314d623455536234', iv: '583673497131313748307652', plain: 'Hello World!', ct: '4BE13596F64DFA2C2D0FAC76', tag: '272B422F62EB545EAA15B5FF84092447', tampered: true }, - { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', + { algo: 'aes-256-gcm', + key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', ct: '58E62CFE7B1D274111A82267EBB93866E72B6C2A', tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: false }, - { algo: 'aes-256-gcm', key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', + { algo: 'aes-256-gcm', + key: '337a54767a7233703637564336316a6d56353472495975313534357834546c59', iv: '36306950306836764a6f4561', plain: 'Hello node.js world!', ct: '58E62CFF7B1D274011A82267EBB93866E72B6C2B', tag: '9BB44F663BADABACAE9720881FB1EC7A', tampered: true }, - { algo: 'aes-192-gcm', key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', + { algo: 'aes-192-gcm', + key: '1ed2233fa2223ef5d7df08546049406c7305220bca40d4c9', iv: '0e1791e9db3bd21a9122c416', plain: 'Hello node.js world!', password: 'very bad password', aad: '63616c76696e', ct: 'DDA53A4059AA17B88756984995F7BBA3C636CC44', diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index dced72309371ab..8623ff477429da 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -1,3 +1,4 @@ +'use strict'; // This is the same as test/simple/test-crypto, but from before the shift // to use buffers by default. diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index 9c98fda2bd5120..ab0d4ca9dff0b3 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index e82a08d7031d0c..931cf339bbb612 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -137,13 +138,13 @@ testCipher4(new Buffer('0123456789abcd0123456789'), new Buffer('12345678')); // not assert. See #4886. (function() { var c = crypto.createCipher('aes-256-cbc', 'secret'); - try { c.final('xxx') } catch (e) { /* Ignore. */ } - try { c.final('xxx') } catch (e) { /* Ignore. */ } - try { c.final('xxx') } catch (e) { /* Ignore. */ } + try { c.final('xxx'); } catch (e) { /* Ignore. */ } + try { c.final('xxx'); } catch (e) { /* Ignore. */ } + try { c.final('xxx'); } catch (e) { /* Ignore. */ } var d = crypto.createDecipher('aes-256-cbc', 'secret'); - try { d.final('xxx') } catch (e) { /* Ignore. */ } - try { d.final('xxx') } catch (e) { /* Ignore. */ } - try { d.final('xxx') } catch (e) { /* Ignore. */ } + try { d.final('xxx'); } catch (e) { /* Ignore. */ } + try { d.final('xxx'); } catch (e) { /* Ignore. */ } + try { d.final('xxx'); } catch (e) { /* Ignore. */ } })(); // Regression test for #5482: string to Cipher#update() should not assert. diff --git a/test/parallel/test-crypto-dh-odd-key.js b/test/parallel/test-crypto-dh-odd-key.js index 46b3c3d8c65c23..1c7f4f69bb4b50 100644 --- a/test/parallel/test-crypto-dh-odd-key.js +++ b/test/parallel/test-crypto-dh-odd-key.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 9eccc2f357215c..4978ab2ebbcb1f 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var constants = require('constants'); @@ -58,7 +59,7 @@ assert.equal(secret1, secret3); // Run this one twice to make sure that the dh3 clears its error properly (function() { var c = crypto.createDecipher('aes-128-ecb', ''); - assert.throws(function() { c.final('utf8') }, /wrong final block length/); + assert.throws(function() { c.final('utf8'); }, /wrong final block length/); })(); assert.throws(function() { @@ -67,7 +68,7 @@ assert.throws(function() { (function() { var c = crypto.createDecipher('aes-128-ecb', ''); - assert.throws(function() { c.final('utf8') }, /wrong final block length/); + assert.throws(function() { c.final('utf8'); }, /wrong final block length/); })(); // Create a shared using a DH group. diff --git a/test/parallel/test-crypto-domain.js b/test/parallel/test-crypto-domain.js index 910e026d20c0ef..fe5e72982d53af 100644 --- a/test/parallel/test-crypto-domain.js +++ b/test/parallel/test-crypto-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js index eb5c77e12ca1eb..55c67b490dbae0 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var domain = require('domain'); var assert = require('assert'); var d = domain.create(); -var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes'] +var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; var errors = 0; if (!common.hasCrypto) { @@ -15,30 +16,30 @@ process.on('exit', function() { assert.equal(errors, 3); }); -d.on('error', function (e) { +d.on('error', function(e) { assert.equal(e.message, expect.shift()); errors += 1; }); -d.run(function () { +d.run(function() { one(); function one() { - crypto.pbkdf2('a', 'b', 1, 8, function () { + crypto.pbkdf2('a', 'b', 1, 8, function() { two(); throw new Error('pbkdf2'); }); } function two() { - crypto.randomBytes(4, function () { + crypto.randomBytes(4, function() { three(); throw new Error('randomBytes'); }); } function three() { - crypto.pseudoRandomBytes(4, function () { + crypto.pseudoRandomBytes(4, function() { throw new Error('pseudoRandomBytes'); }); } diff --git a/test/parallel/test-crypto-ecb.js b/test/parallel/test-crypto-ecb.js index f924dfd29b9bc3..f1541ddeb403dc 100644 --- a/test/parallel/test-crypto-ecb.js +++ b/test/parallel/test-crypto-ecb.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index ae450645dda610..4c8d7338dd9770 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -1,3 +1,4 @@ +'use strict'; // This is the same as test/simple/test-crypto, but from before the shift // to use buffers by default. diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js index 795abd49a0f597..23feccea3843ae 100644 --- a/test/parallel/test-crypto-hash-stream-pipe.js +++ b/test/parallel/test-crypto-hash-stream-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -7,7 +8,7 @@ if (!common.hasCrypto) { } var crypto = require('crypto'); -var stream = require('stream') +var stream = require('stream'); var s = new stream.PassThrough(); var h = crypto.createHash('sha1'); var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index af323ac4f6496e..5c542406cb7112 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index 1a90811fe87c9e..e234bd91606906 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -56,7 +57,7 @@ var wikipedia = [ '4292c5ad' } }, -] +]; for (var i = 0, l = wikipedia.length; i < l; i++) { for (var hash in wikipedia[i]['hmac']) { diff --git a/test/parallel/test-crypto-padding-aes256.js b/test/parallel/test-crypto-padding-aes256.js index de5fb7ca8732c1..db75a07c9e1617 100644 --- a/test/parallel/test-crypto-padding-aes256.js +++ b/test/parallel/test-crypto-padding-aes256.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -15,15 +16,15 @@ function aes256(decipherFinal) { '0123456789abcdef0123456789abcdef', 'hex'); function encrypt(val, pad) { - var c = crypto.createCipheriv('aes256', key, iv); - c.setAutoPadding(pad); - return c.update(val, 'utf8', 'binary') + c.final('binary'); + var c = crypto.createCipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'utf8', 'binary') + c.final('binary'); } function decrypt(val, pad) { - var c = crypto.createDecipheriv('aes256', key, iv); - c.setAutoPadding(pad); - return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); + var c = crypto.createDecipheriv('aes256', key, iv); + c.setAutoPadding(pad); + return c.update(val, 'binary', 'utf8') + c[decipherFinal]('utf8'); } // echo 0123456789abcdef0123456789abcdef \ diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js index 2cf78588f9da62..11b1729fde88cb 100644 --- a/test/parallel/test-crypto-padding.js +++ b/test/parallel/test-crypto-padding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index 440c6162e3b26a..88be15b68cb348 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index de1bfccf90d2fb..cac0c9b86cf2c1 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 65986b49c94789..127bbfb26df5dd 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index 5cac8948dbd02f..fb811e7f12d0fc 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index 75ea5b13a4c5df..fd970e061b00e1 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); @@ -14,24 +15,24 @@ function Stream2buffer(callback) { stream.Writable.call(this); this._buffers = []; - this.once('finish', function () { + this.once('finish', function() { callback(null, Buffer.concat(this._buffers)); }); } util.inherits(Stream2buffer, stream.Writable); -Stream2buffer.prototype._write = function (data, encodeing, done) { +Stream2buffer.prototype._write = function(data, encodeing, done) { this._buffers.push(data); return done(null); }; // Create an md5 hash of "Hallo world" var hasher1 = crypto.createHash('md5'); - hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { - assert.equal(err, null); - assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); - }))); - hasher1.end('Hallo world'); +hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { + assert.equal(err, null); + assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); +}))); +hasher1.end('Hallo world'); // Simpler check for unpipe, setEncoding, pause and resume crypto.createHash('md5').unpipe({}); diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js index 6190ae247dae2c..a4a9ec698197c0 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -23,11 +24,11 @@ var canSend = true; var server = tls.Server(options, function(socket) { setImmediate(function() { - console.log('sending'); - verify(); - setImmediate(function() { - socket.destroy(); - }); + console.log('sending'); + verify(); + setImmediate(function() { + socket.destroy(); + }); }); }); diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index d8a5099bbd80ea..e3557943c63d82 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -118,7 +119,7 @@ assert.throws(function() { }, /Bad input string/); assert.throws(function() { - var private = [ + var priv = [ '-----BEGIN RSA PRIVATE KEY-----', 'MIGrAgEAAiEA+3z+1QNF2/unumadiwEr+C5vfhezsb3hp4jAnCNRpPcCAwEAAQIgQNriSQK4', 'EFwczDhMZp2dvbcz7OUUyt36z3S4usFPHSECEQD/41K7SujrstBfoCPzwC1xAhEA+5kt4BJy', @@ -127,7 +128,7 @@ assert.throws(function() { '-----END RSA PRIVATE KEY-----', '' ].join('\n'); - crypto.createSign('RSA-SHA256').update('test').sign(private); + crypto.createSign('RSA-SHA256').update('test').sign(priv); }, /RSA_sign:digest too big for rsa key/); // Make sure memory isn't released before being returned diff --git a/test/parallel/test-cwd-enoent-repl.js b/test/parallel/test-cwd-enoent-repl.js index 64538f80b963df..5f47b84be5b2f0 100644 --- a/test/parallel/test-cwd-enoent-repl.js +++ b/test/parallel/test-cwd-enoent-repl.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-cwd-enoent.js b/test/parallel/test-cwd-enoent.js index 6e7b02c85d8d12..0d0fde24814e83 100644 --- a/test/parallel/test-cwd-enoent.js +++ b/test/parallel/test-cwd-enoent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-debug-port-cluster.js b/test/parallel/test-debug-port-cluster.js index 96a6f6e7f405b7..5bec9dc720599e 100644 --- a/test/parallel/test-debug-port-cluster.js +++ b/test/parallel/test-debug-port-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -16,7 +17,7 @@ child.stderr.on('data', function(data) { var lines = data.toString().replace(/\r/g, '').trim().split('\n'); var line = lines[0]; - lines.forEach(function(ln) { console.log('> ' + ln) } ); + lines.forEach(function(ln) { console.log('> ' + ln); } ); if (line === 'all workers are running') { assertOutputLines(); @@ -33,8 +34,8 @@ process.on('exit', function onExit() { var assertOutputLines = common.mustCall(function() { var expectedLines = [ 'Debugger listening on port ' + port, - 'Debugger listening on port ' + (port+1), - 'Debugger listening on port ' + (port+2), + 'Debugger listening on port ' + (port + 1), + 'Debugger listening on port ' + (port + 2), ]; // Do not assume any particular order of output messages, @@ -42,7 +43,7 @@ var assertOutputLines = common.mustCall(function() { // start up outputLines.sort(); - assert.equal(outputLines.length, expectedLines.length) + assert.equal(outputLines.length, expectedLines.length); for (var i = 0; i < expectedLines.length; i++) assert.equal(outputLines[i], expectedLines[i]); }); diff --git a/test/parallel/test-debug-port-from-cmdline.js b/test/parallel/test-debug-port-from-cmdline.js index 4ed2e84918c8f0..deb7ae241a55fd 100644 --- a/test/parallel/test-debug-port-from-cmdline.js +++ b/test/parallel/test-debug-port-from-cmdline.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-debug-signal-cluster.js b/test/parallel/test-debug-signal-cluster.js index 772ee6f1e6f454..6572ef50afe845 100644 --- a/test/parallel/test-debug-signal-cluster.js +++ b/test/parallel/test-debug-signal-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-delayed-require.js b/test/parallel/test-delayed-require.js index 161f3d2ffa79ae..5fa82f236c1dd9 100644 --- a/test/parallel/test-delayed-require.js +++ b/test/parallel/test-delayed-require.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dgram-address.js b/test/parallel/test-dgram-address.js index 6da1c6cda45c76..f128ce5110317b 100644 --- a/test/parallel/test-dgram-address.js +++ b/test/parallel/test-dgram-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-bind-default-address.js b/test/parallel/test-dgram-bind-default-address.js index 28db7d9fa61af1..03e8afb99132aa 100644 --- a/test/parallel/test-dgram-bind-default-address.js +++ b/test/parallel/test-dgram-bind-default-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-bind-shared-ports.js b/test/parallel/test-dgram-bind-shared-ports.js index 4cfe4b5f9af7f4..91a48a260fbd90 100644 --- a/test/parallel/test-dgram-bind-shared-ports.js +++ b/test/parallel/test-dgram-bind-shared-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-dgram-bind.js b/test/parallel/test-dgram-bind.js index 72f2f2c2b052bb..6d35534cb5eb56 100644 --- a/test/parallel/test-dgram-bind.js +++ b/test/parallel/test-dgram-bind.js @@ -1,10 +1,11 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var socket = dgram.createSocket('udp4'); -socket.on('listening', function () { +socket.on('listening', function() { socket.close(); }); diff --git a/test/parallel/test-dgram-bytes-length.js b/test/parallel/test-dgram-bytes-length.js index 9698a0b465e4b8..9f8c39eb04daaf 100644 --- a/test/parallel/test-dgram-bytes-length.js +++ b/test/parallel/test-dgram-bytes-length.js @@ -1,10 +1,12 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); var message = new Buffer('Some bytes'); var client = dgram.createSocket('udp4'); -client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) { +client.send(message, 0, message.length, 41234, 'localhost', + function(err, bytes) { assert.strictEqual(bytes, message.length); client.close(); }); diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index 94035af97027bb..6fc4901fa14404 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index bd4af66323c05b..7e9dd4ef52c402 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -1,3 +1,4 @@ +'use strict'; // Ensure that if a dgram socket is closed before the DNS lookup completes, it // won't crash. diff --git a/test/parallel/test-dgram-empty-packet.js b/test/parallel/test-dgram-empty-packet.js index a629df8e1bc564..797012b8839fb7 100644 --- a/test/parallel/test-dgram-empty-packet.js +++ b/test/parallel/test-dgram-empty-packet.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,15 +23,15 @@ function callback() { clearTimeout(timer); client.close(); } else if (callbacks > 2) { - throw new Error("the callbacks should be called only two times"); + throw new Error('the callbacks should be called only two times'); } } -client.on('message', function (buffer, bytes) { +client.on('message', function(buffer, bytes) { callback(); }); -client.send(new Buffer(1), 0, 0, common.PORT, "127.0.0.1", function (err, len) { +client.send(new Buffer(1), 0, 0, common.PORT, '127.0.0.1', function(err, len) { callback(); }); diff --git a/test/parallel/test-dgram-error-message-address.js b/test/parallel/test-dgram-error-message-address.js index 95b1e062e3f2a7..eca2ccce4f1b65 100644 --- a/test/parallel/test-dgram-error-message-address.js +++ b/test/parallel/test-dgram-error-message-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-exclusive-implicit-bind.js b/test/parallel/test-dgram-exclusive-implicit-bind.js index 057b891eb6d891..077e1812b99144 100644 --- a/test/parallel/test-dgram-exclusive-implicit-bind.js +++ b/test/parallel/test-dgram-exclusive-implicit-bind.js @@ -1,3 +1,4 @@ +'use strict'; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js index adf6f52b4974a0..8b78bd66c6f313 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-listen-after-bind.js b/test/parallel/test-dgram-listen-after-bind.js index c5f09b84677872..2aac7ae9cf7588 100644 --- a/test/parallel/test-dgram-listen-after-bind.js +++ b/test/parallel/test-dgram-listen-after-bind.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); @@ -7,16 +8,16 @@ var socket = dgram.createSocket('udp4'); socket.bind(); var fired = false; -var timer = setTimeout(function () { +var timer = setTimeout(function() { socket.close(); }, 100); -socket.on('listening', function () { +socket.on('listening', function() { clearTimeout(timer); fired = true; socket.close(); }); -socket.on('close', function () { +socket.on('close', function() { assert(fired, 'listening should fire after bind'); }); diff --git a/test/parallel/test-dgram-msgsize.js b/test/parallel/test-dgram-msgsize.js index 474ab82f44a47f..6330e2a82bdcc5 100644 --- a/test/parallel/test-dgram-msgsize.js +++ b/test/parallel/test-dgram-msgsize.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-multicast-setTTL.js b/test/parallel/test-dgram-multicast-setTTL.js index d849945fab7837..f48fc7118ec3c1 100644 --- a/test/parallel/test-dgram-multicast-setTTL.js +++ b/test/parallel/test-dgram-multicast-setTTL.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), dgram = require('dgram'), @@ -5,7 +6,7 @@ var common = require('../common'), socket = dgram.createSocket('udp4'); socket.bind(common.PORT); -socket.on('listening', function () { +socket.on('listening', function() { socket.setMulticastTTL(16); //Try to set an invalid TTL (valid ttl is > 0 and < 256) diff --git a/test/parallel/test-dgram-oob-buffer.js b/test/parallel/test-dgram-oob-buffer.js index bbbdc4dafeee19..b64c7236afd4bc 100644 --- a/test/parallel/test-dgram-oob-buffer.js +++ b/test/parallel/test-dgram-oob-buffer.js @@ -1,3 +1,4 @@ +'use strict'; // Some operating systems report errors when an UDP message is sent to an // unreachable host. This error can be reported by sendto() and even by // recvfrom(). Node should not propagate this error to the user. diff --git a/test/parallel/test-dgram-pingpong.js b/test/parallel/test-dgram-pingpong.js index b7d7a0067e89e7..29ab92757bd817 100644 --- a/test/parallel/test-dgram-pingpong.js +++ b/test/parallel/test-dgram-pingpong.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Buffer = require('buffer').Buffer; diff --git a/test/parallel/test-dgram-ref.js b/test/parallel/test-dgram-ref.js index 8d100eb0783f55..d689a45e36dfa2 100644 --- a/test/parallel/test-dgram-ref.js +++ b/test/parallel/test-dgram-ref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-regress-4496.js b/test/parallel/test-dgram-regress-4496.js index a200716c0fb8d8..fcb8d026bc547e 100644 --- a/test/parallel/test-dgram-regress-4496.js +++ b/test/parallel/test-dgram-regress-4496.js @@ -1,3 +1,4 @@ +'use strict'; // Remove this test once we support sending strings. var common = require('../common'); @@ -6,6 +7,6 @@ var dgram = require('dgram'); // Should throw but not crash. var socket = dgram.createSocket('udp4'); -assert.throws(function() { socket.send(true, 0, 1, 1, 'host') }, TypeError); -assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host') }, TypeError); +assert.throws(function() { socket.send(true, 0, 1, 1, 'host'); }, TypeError); +assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host'); }, TypeError); socket.close(); diff --git a/test/parallel/test-dgram-send-bad-arguments.js b/test/parallel/test-dgram-send-bad-arguments.js index ab18784ccc6905..ccd10e00555384 100644 --- a/test/parallel/test-dgram-send-bad-arguments.js +++ b/test/parallel/test-dgram-send-bad-arguments.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dgram = require('dgram'); diff --git a/test/parallel/test-dgram-send-callback-buffer-length.js b/test/parallel/test-dgram-send-callback-buffer-length.js index 5596a7242f3a6a..a34c5e2eb6b8db 100644 --- a/test/parallel/test-dgram-send-callback-buffer-length.js +++ b/test/parallel/test-dgram-send-callback-buffer-length.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -15,11 +16,11 @@ offset = 20; len = buf.length - offset; -client.send(buf, offset, len, common.PORT, "127.0.0.1", function (err, bytes) { - assert.notEqual(bytes, buf.length); - assert.equal(bytes, buf.length - offset); - clearTimeout(timer); - client.close(); +client.send(buf, offset, len, common.PORT, '127.0.0.1', function(err, bytes) { + assert.notEqual(bytes, buf.length); + assert.equal(bytes, buf.length - offset); + clearTimeout(timer); + client.close(); }); timer = setTimeout(function() { diff --git a/test/parallel/test-dgram-send-callback-recursive.js b/test/parallel/test-dgram-send-callback-recursive.js new file mode 100644 index 00000000000000..046545deff6da3 --- /dev/null +++ b/test/parallel/test-dgram-send-callback-recursive.js @@ -0,0 +1,39 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); + +const dgram = require('dgram'); +const client = dgram.createSocket('udp4'); +const chunk = 'abc'; +var recursiveCount = 0; +var received = 0; +const limit = 10; +const recursiveLimit = limit + 1; + +function onsend() { + if (recursiveCount > recursiveLimit) { + throw new Error('infinite loop detected'); + } + if (received < limit) { + client.send( + chunk, 0, chunk.length, common.PORT, common.localhostIPv4, onsend); + } + recursiveCount++; +} + +client.on('listening', function() { + onsend(); +}); + +client.on('message', function(buf, info) { + received++; + if (received === limit) { + client.close(); + } +}); + +client.on('close', common.mustCall(function() { + assert.equal(received, limit); +})); + +client.bind(common.PORT); diff --git a/test/parallel/test-dgram-send-empty-buffer.js b/test/parallel/test-dgram-send-empty-buffer.js index e2ca937d6afbb3..ab66e0545e611d 100644 --- a/test/parallel/test-dgram-send-empty-buffer.js +++ b/test/parallel/test-dgram-send-empty-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -16,13 +17,13 @@ client = dgram.createSocket('udp4'); client.bind(common.PORT); -client.on('message', function (buffer, bytes) { +client.on('message', function(buffer, bytes) { clearTimeout(timer); client.close(); }); buf = new Buffer(0); -client.send(buf, 0, 0, common.PORT, "127.0.0.1", function (err, len) { }); +client.send(buf, 0, 0, common.PORT, '127.0.0.1', function(err, len) { }); timer = setTimeout(function() { throw new Error('Timeout'); diff --git a/test/parallel/test-dgram-udp4.js b/test/parallel/test-dgram-udp4.js index cde49c1b1bc063..f81dec398f72d1 100644 --- a/test/parallel/test-dgram-udp4.js +++ b/test/parallel/test-dgram-udp4.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js index 94f7ba739c740c..2add3d28c49760 100644 --- a/test/parallel/test-dgram-unref.js +++ b/test/parallel/test-dgram-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dh-padding.js b/test/parallel/test-dh-padding.js index 3e30fd34e7713d..872653763239c4 100644 --- a/test/parallel/test-dh-padding.js +++ b/test/parallel/test-dh-padding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-dns-cares-domains.js b/test/parallel/test-dns-cares-domains.js index 5c6d07cfe5322a..cb651c5f5afb86 100644 --- a/test/parallel/test-dns-cares-domains.js +++ b/test/parallel/test-dns-cares-domains.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dns = require('dns'); @@ -13,13 +14,13 @@ var methods = [ 'resolveSrv', 'resolveNaptr', 'resolveSoa' -] +]; methods.forEach(function(method) { var d = domain.create(); d.run(function() { dns[method]('google.com', function() { - assert.strictEqual(process.domain, d, method + ' retains domain') + assert.strictEqual(process.domain, d, method + ' retains domain'); }); }); }); diff --git a/test/parallel/test-dns-lookup-cb-error.js b/test/parallel/test-dns-lookup-cb-error.js index 2aa9ffe7d6301f..330dfb5d57092a 100644 --- a/test/parallel/test-dns-lookup-cb-error.js +++ b/test/parallel/test-dns-lookup-cb-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cares = process.binding('cares_wrap'); diff --git a/test/parallel/test-dns-regress-6244.js b/test/parallel/test-dns-regress-6244.js index 8bed54f1b297f5..7ed7a892069870 100644 --- a/test/parallel/test-dns-regress-6244.js +++ b/test/parallel/test-dns-regress-6244.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var dns = require('dns'); diff --git a/test/parallel/test-dns-regress-7070.js b/test/parallel/test-dns-regress-7070.js index 79f0d7d9e0ca00..1fbd7f07a9d520 100644 --- a/test/parallel/test-dns-regress-7070.js +++ b/test/parallel/test-dns-regress-7070.js @@ -1,7 +1,8 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var dns = require('dns'); // Should not raise assertion error. Issue #7070 -assert.throws(function () { dns.resolveNs([]); }); // bad name -assert.throws(function () { dns.resolveNs(''); }); // bad callback +assert.throws(function() { dns.resolveNs([]); }); // bad name +assert.throws(function() { dns.resolveNs(''); }); // bad callback diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index 1de9bbfdf77977..abc7edbf598097 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -12,16 +13,16 @@ var goog = [ '8.8.8.8', '8.8.4.4', ]; -assert.doesNotThrow(function () { dns.setServers(goog) }); +assert.doesNotThrow(function() { dns.setServers(goog); }); assert.deepEqual(dns.getServers(), goog); -assert.throws(function () { dns.setServers(['foobar']) }); +assert.throws(function() { dns.setServers(['foobar']); }); assert.deepEqual(dns.getServers(), goog); var goog6 = [ '2001:4860:4860::8888', '2001:4860:4860::8844', ]; -assert.doesNotThrow(function () { dns.setServers(goog6) }); +assert.doesNotThrow(function() { dns.setServers(goog6); }); assert.deepEqual(dns.getServers(), goog6); goog6.push('4.4.4.4'); @@ -39,7 +40,7 @@ var portsExpected = [ dns.setServers(ports); assert.deepEqual(dns.getServers(), portsExpected); -assert.doesNotThrow(function () { dns.setServers([]); }); +assert.doesNotThrow(function() { dns.setServers([]); }); assert.deepEqual(dns.getServers(), []); assert.throws(function() { diff --git a/test/parallel/test-domain-abort-on-uncaught.js b/test/parallel/test-domain-abort-on-uncaught.js index e11bbcc6bc755f..f4884aa8f33421 100644 --- a/test/parallel/test-domain-abort-on-uncaught.js +++ b/test/parallel/test-domain-abort-on-uncaught.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --abort_on_uncaught_exception var common = require('../common'); @@ -18,7 +19,7 @@ process.on('exit', function() { assert.equal(errors, tests.length); }); -tests.forEach(function(test) { test(); }) +tests.forEach(function(test) { test(); }); function nextTick() { var d = domain.create(); @@ -84,10 +85,10 @@ function netServer() { conn.pipe(conn); }); server.listen(common.PORT, '0.0.0.0', function() { - var conn = net.connect(common.PORT, '0.0.0.0') + var conn = net.connect(common.PORT, '0.0.0.0'); conn.once('data', function() { throw new Error('ok'); - }) + }); conn.end('ok'); server.close(); }); diff --git a/test/parallel/test-domain-crypto.js b/test/parallel/test-domain-crypto.js index dc183b7bda1760..96047474956e73 100644 --- a/test/parallel/test-domain-crypto.js +++ b/test/parallel/test-domain-crypto.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ try { var crypto = require('crypto'); } catch (e) { diff --git a/test/parallel/test-domain-enter-exit.js b/test/parallel/test-domain-enter-exit.js index 32ec0ca2472c8c..5cf0d9c54a3122 100644 --- a/test/parallel/test-domain-enter-exit.js +++ b/test/parallel/test-domain-enter-exit.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure the domain stack is a stack var assert = require('assert'); @@ -5,7 +6,7 @@ var domain = require('domain'); function names(array) { return array.map(function(d) { - return d.name + return d.name; }).join(', '); } diff --git a/test/parallel/test-domain-exit-dispose-again.js b/test/parallel/test-domain-exit-dispose-again.js index c651181092737b..d7046481d112ea 100644 --- a/test/parallel/test-domain-exit-dispose-again.js +++ b/test/parallel/test-domain-exit-dispose-again.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); @@ -6,7 +7,7 @@ var disposalFailed = false; // no matter what happens, we should increment a 10 times. var a = 0; log(); -function log(){ +function log() { console.log(a++, process.domain); if (a < 10) setTimeout(log, 20); } @@ -16,7 +17,7 @@ var secondTimerRan = false; // in 50ms we'll throw an error. setTimeout(err, 50); setTimeout(secondTimer, 50); -function err(){ +function err() { var d = domain.create(); d.on('error', handle); d.run(err2); diff --git a/test/parallel/test-domain-exit-dispose.js b/test/parallel/test-domain-exit-dispose.js index a01cee5c73cb0c..90e7210ce21aea 100644 --- a/test/parallel/test-domain-exit-dispose.js +++ b/test/parallel/test-domain-exit-dispose.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); @@ -6,14 +7,14 @@ var disposalFailed = false; // no matter what happens, we should increment a 10 times. var a = 0; log(); -function log(){ +function log() { console.log(a++, process.domain); if (a < 10) setTimeout(log, 20); } // in 50ms we'll throw an error. setTimeout(err, 50); -function err(){ +function err() { var d = domain.create(); d.on('error', handle); d.run(err2); diff --git a/test/parallel/test-domain-from-timer.js b/test/parallel/test-domain-from-timer.js index 91dff3875cd7a2..93661b419b0bbf 100644 --- a/test/parallel/test-domain-from-timer.js +++ b/test/parallel/test-domain-from-timer.js @@ -1,3 +1,4 @@ +'use strict'; // Simple tests of most basic domain functionality. var common = require('../common'); @@ -10,7 +11,7 @@ setTimeout(function() { var d = domain.create(); d.run(function() { process.nextTick(function() { - console.trace('in nexttick', process.domain === d) + console.trace('in nexttick', process.domain === d); assert.equal(process.domain, d); }); }); diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js index 77e10911716fb0..7cabf205e8f51c 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -1,3 +1,4 @@ +'use strict'; var domain = require('domain'); var http = require('http'); var assert = require('assert'); diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js index 4a00b9a17ad5db..fd21dcafe0858f 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -1,3 +1,4 @@ +'use strict'; // Simple tests of most basic domain functionality. var common = require('../common'); diff --git a/test/parallel/test-domain-multi.js b/test/parallel/test-domain-multi.js index 270ecde4962241..e5f9f6748b178e 100644 --- a/test/parallel/test-domain-multi.js +++ b/test/parallel/test-domain-multi.js @@ -1,3 +1,4 @@ +'use strict'; // Tests of multiple domains happening at once. var common = require('../common'); @@ -20,7 +21,7 @@ a.on('error', function(er) { var http = require('http'); -var server = http.createServer(function (req, res) { +var server = http.createServer(function(req, res) { // child domain of a. var b = domain.create(); a.add(b); @@ -31,9 +32,9 @@ var server = http.createServer(function (req, res) { b.add(req); b.add(res); - b.on('error', function (er) { + b.on('error', function(er) { caughtB = true; - console.error('Error encountered', er) + console.error('Error encountered', er); if (res) { res.writeHead(500); res.end('An error occurred'); @@ -52,7 +53,7 @@ var server = http.createServer(function (req, res) { }).listen(common.PORT); var c = domain.create(); -var req = http.get({ host: 'localhost', port: common.PORT }) +var req = http.get({ host: 'localhost', port: common.PORT }); // add the request to the C domain c.add(req); @@ -71,7 +72,7 @@ c.on('error', function(er) { process.on('exit', function() { assert.equal(caughtA, false); - assert.equal(caughtB, true) - assert.equal(caughtC, true) + assert.equal(caughtB, true); + assert.equal(caughtC, true); console.log('ok - Errors went where they were supposed to go'); }); diff --git a/test/parallel/test-domain-nested-throw.js b/test/parallel/test-domain-nested-throw.js index 87039bb3f939ce..0fba3001b543fb 100644 --- a/test/parallel/test-domain-nested-throw.js +++ b/test/parallel/test-domain-nested-throw.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -50,7 +51,7 @@ function throw2() { function inner(throw1, throw2) { var domain1 = domain.createDomain(); - domain1.on('error', function (err) { + domain1.on('error', function(err) { if (gotDomain1Error) { console.error('got domain 1 twice'); process.exit(1); @@ -60,7 +61,7 @@ function inner(throw1, throw2) { throw2(); }); - domain1.run(function () { + domain1.run(function() { throw1(); }); } @@ -68,7 +69,7 @@ function inner(throw1, throw2) { function outer() { var domain2 = domain.createDomain(); - domain2.on('error', function (err) { + domain2.on('error', function(err) { if (gotDomain2Error) { console.error('got domain 2 twice'); process.exit(1); @@ -76,7 +77,7 @@ function outer() { gotDomain2Error = true; }); - domain2.run(function () { + domain2.run(function() { inner(throw1, throw2); }); } diff --git a/test/parallel/test-domain-nested.js b/test/parallel/test-domain-nested.js index 9334c287baedc1..d0ef072339b8f9 100644 --- a/test/parallel/test-domain-nested.js +++ b/test/parallel/test-domain-nested.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure that the nested domains don't cause the domain stack to grow var assert = require('assert'); @@ -10,11 +11,11 @@ process.on('exit', function(c) { domain.create().run(function() { domain.create().run(function() { domain.create().run(function() { - domain.create().on("error", function(e) { + domain.create().on('error', function(e) { // Don't need to do anything here }).run(function() { - throw new Error("died") - }) - }) - }) -}) + throw new Error('died'); + }); + }); + }); +}); diff --git a/test/parallel/test-domain-safe-exit.js b/test/parallel/test-domain-safe-exit.js index 029687411a09b9..6661c577b30c87 100644 --- a/test/parallel/test-domain-safe-exit.js +++ b/test/parallel/test-domain-safe-exit.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure the domain stack doesn't get clobbered by un-matched .exit() var assert = require('assert'); diff --git a/test/parallel/test-domain-stack.js b/test/parallel/test-domain-stack.js index be611a872117ff..f9b5648a6619a7 100644 --- a/test/parallel/test-domain-stack.js +++ b/test/parallel/test-domain-stack.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure that the domain stack doesn't get out of hand. var common = require('../common'); diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index 5a34bc7449a951..7530c9edba40b1 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -1,3 +1,4 @@ +'use strict'; var domain = require('domain'); var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-domain.js b/test/parallel/test-domain.js index a3f7b76848a581..9cca05178ef10f 100644 --- a/test/parallel/test-domain.js +++ b/test/parallel/test-domain.js @@ -1,3 +1,4 @@ +'use strict'; // Simple tests of most basic domain functionality. var common = require('../common'); @@ -15,7 +16,7 @@ d.on('error', function(er) { console.error('caught', er && (er.message || er)); var er_message = er.message; - var er_path = er.path + var er_path = er.path; // On windows, error messages can contain full path names. If this is the // case, remove the directory part. @@ -58,7 +59,8 @@ d.on('error', function(er) { assert.equal(typeof er.errno, 'number'); break; - case "ENOENT: no such file or directory, open 'stream for nonexistent file'": + case + "ENOENT: no such file or directory, open 'stream for nonexistent file'": assert.equal(typeof er.errno, 'number'); assert.equal(er.code, 'ENOENT'); assert.equal(er_path, 'stream for nonexistent file'); @@ -129,7 +131,7 @@ expectCaught++; // set up while in the scope of the d domain. d.run(function() { process.nextTick(function() { - var i = setInterval(function () { + var i = setInterval(function() { clearInterval(i); setTimeout(function() { fs.stat('this file does not exist', function(er, stat) { @@ -178,7 +180,7 @@ expectCaught++; // intercepted should never pass first argument to callback function fn2(data) { - assert.equal(data, 'data', 'should not be null err argument') + assert.equal(data, 'data', 'should not be null err argument'); } var bound = d.intercept(fn2); @@ -220,7 +222,7 @@ expectCaught++; var implicit; d.run(function() { - implicit = new events.EventEmitter; + implicit = new events.EventEmitter(); }); setTimeout(function() { @@ -230,24 +232,24 @@ setTimeout(function() { expectCaught++; -var result = d.run(function () { +var result = d.run(function() { return 'return value'; }); assert.equal(result, 'return value'); // check if the executed function take in count the applied parameters -result = d.run(function (a, b) { +result = d.run(function(a, b) { return a + ' ' + b; }, 'return', 'value'); assert.equal(result, 'return value'); -var fst = fs.createReadStream('stream for nonexistent file') -d.add(fst) +var fst = fs.createReadStream('stream for nonexistent file'); +d.add(fst); expectCaught++; -[42, null, , false, function(){}, 'string'].forEach(function(something) { +[42, null, , false, function() {}, 'string'].forEach(function(something) { var d = new domain.Domain(); d.run(function() { process.nextTick(function() { diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js index 9caabe0d6160e2..0b5c7652871138 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-eval-require.js b/test/parallel/test-eval-require.js index eeaa624b396ab7..f966b5a98c80ba 100644 --- a/test/parallel/test-eval-require.js +++ b/test/parallel/test-eval-require.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-eval.js b/test/parallel/test-eval.js index e504ceca12678c..d3a83fbd5a7060 100644 --- a/test/parallel/test-eval.js +++ b/test/parallel/test-eval.js @@ -1,3 +1,4 @@ +'use strict'; require('../common'); var util = require('util'); var assert = require('assert'); diff --git a/test/parallel/test-event-emitter-add-listeners.js b/test/parallel/test-event-emitter-add-listeners.js index 7cc302e0b81695..cc30fd24add340 100644 --- a/test/parallel/test-event-emitter-add-listeners.js +++ b/test/parallel/test-event-emitter-add-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -53,7 +54,7 @@ process.on('exit', function() { var listen1 = function listen1() {}; var listen2 = function listen2() {}; -var e1 = new events.EventEmitter; +var e1 = new events.EventEmitter(); e1.once('newListener', function() { assert.deepEqual(e1.listeners('hello'), []); e1.once('newListener', function() { diff --git a/test/parallel/test-event-emitter-check-listener-leaks.js b/test/parallel/test-event-emitter-check-listener-leaks.js index 25e53d2c6a188f..90f686b5422c43 100644 --- a/test/parallel/test-event-emitter-check-listener-leaks.js +++ b/test/parallel/test-event-emitter-check-listener-leaks.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-errors.js b/test/parallel/test-event-emitter-errors.js new file mode 100644 index 00000000000000..49203961ac8d9a --- /dev/null +++ b/test/parallel/test-event-emitter-errors.js @@ -0,0 +1,9 @@ +'use strict'; +var EventEmitter = require('events'); +var assert = require('assert'); + +var EE = new EventEmitter(); + +assert.throws(function() { + EE.emit('error', 'Accepts a string'); +}, /Accepts a string/); diff --git a/test/parallel/test-event-emitter-get-max-listeners.js b/test/parallel/test-event-emitter-get-max-listeners.js index 57430a4e9bec37..0cad09fdb8b8ef 100644 --- a/test/parallel/test-event-emitter-get-max-listeners.js +++ b/test/parallel/test-event-emitter-get-max-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var EventEmitter = require('events'); diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js index 46eedf812d2b0e..de541c535ef0ed 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); @@ -7,7 +8,7 @@ var events = require('events'); var EventEmitter = require('events').EventEmitter; var assert = require('assert'); -var e = new EventEmitter; +var e = new EventEmitter(); var fl; // foo listeners fl = e.listeners('foo'); diff --git a/test/parallel/test-event-emitter-listeners.js b/test/parallel/test-event-emitter-listeners.js index 6baad62968f549..be6b83856249b4 100644 --- a/test/parallel/test-event-emitter-listeners.js +++ b/test/parallel/test-event-emitter-listeners.js @@ -1,3 +1,4 @@ +'use strict'; // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common'); diff --git a/test/parallel/test-event-emitter-max-listeners.js b/test/parallel/test-event-emitter-max-listeners.js index cea5fbf022ea2c..5e754698d0a018 100644 --- a/test/parallel/test-event-emitter-max-listeners.js +++ b/test/parallel/test-event-emitter-max-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -26,7 +27,7 @@ assert.throws(function() { }); assert.throws(function() { - e.setMaxListeners("and even this"); + e.setMaxListeners('and even this'); }); e.emit('maxListeners'); diff --git a/test/parallel/test-event-emitter-method-names.js b/test/parallel/test-event-emitter-method-names.js index 27061df4e4a66d..a260aa779855aa 100644 --- a/test/parallel/test-event-emitter-method-names.js +++ b/test/parallel/test-event-emitter-method-names.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-modify-in-emit.js b/test/parallel/test-event-emitter-modify-in-emit.js index 3b05a88a3e00a6..85845cc4443b32 100644 --- a/test/parallel/test-event-emitter-modify-in-emit.js +++ b/test/parallel/test-event-emitter-modify-in-emit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js index 5c50c32d489b24..e85361475f894e 100644 --- a/test/parallel/test-event-emitter-no-error-provided-to-error-event.js +++ b/test/parallel/test-event-emitter-no-error-provided-to-error-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -9,13 +10,13 @@ var e = new events.EventEmitter(); var d = domain.create(); d.add(e); -d.on('error', function (er) { +d.on('error', function(er) { assert(er instanceof Error, 'error created'); errorCatched = true; }); e.emit('error'); -process.on('exit', function () { +process.on('exit', function() { assert(errorCatched, 'error got caught'); }); diff --git a/test/parallel/test-event-emitter-num-args.js b/test/parallel/test-event-emitter-num-args.js index 20c003f3303a35..522fb2e2175d81 100644 --- a/test/parallel/test-event-emitter-num-args.js +++ b/test/parallel/test-event-emitter-num-args.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js index c5cd007ea265da..1085e7942a59bf 100644 --- a/test/parallel/test-event-emitter-once.js +++ b/test/parallel/test-event-emitter-once.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -29,12 +30,12 @@ process.on('exit', function() { var times_recurse_emitted = 0; e.once('e', function() { - e.emit('e'); - times_recurse_emitted++; + e.emit('e'); + times_recurse_emitted++; }); e.once('e', function() { - times_recurse_emitted++; + times_recurse_emitted++; }); e.emit('e'); diff --git a/test/parallel/test-event-emitter-remove-all-listeners.js b/test/parallel/test-event-emitter-remove-all-listeners.js index 8c6d68ec5fa2ee..54dedfa1362d29 100644 --- a/test/parallel/test-event-emitter-remove-all-listeners.js +++ b/test/parallel/test-event-emitter-remove-all-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -9,7 +10,7 @@ function expect(expected) { assert.deepEqual(actual.sort(), expected.sort()); }); function listener(name) { - actual.push(name) + actual.push(name); } return common.mustCall(listener, expected.length); } @@ -63,9 +64,9 @@ var expectLength = 2; e4.on('removeListener', function(name, listener) { assert.equal(expectLength--, this.listeners('baz').length); }); -e4.on('baz', function(){}); -e4.on('baz', function(){}); -e4.on('baz', function(){}); -assert.equal(e4.listeners('baz').length, expectLength+1); +e4.on('baz', function() {}); +e4.on('baz', function() {}); +e4.on('baz', function() {}); +assert.equal(e4.listeners('baz').length, expectLength + 1); e4.removeAllListeners('baz'); assert.equal(e4.listeners('baz').length, 0); diff --git a/test/parallel/test-event-emitter-remove-listeners.js b/test/parallel/test-event-emitter-remove-listeners.js index 5d8acafc063d09..409ccbebe25b86 100644 --- a/test/parallel/test-event-emitter-remove-listeners.js +++ b/test/parallel/test-event-emitter-remove-listeners.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); diff --git a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js index d4842c395ee062..f09f130ab489ed 100644 --- a/test/parallel/test-event-emitter-set-max-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-set-max-listeners-side-effects.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var events = require('events'); -var e = new events.EventEmitter; +var e = new events.EventEmitter(); assert.deepEqual(e._events, {}); e.setMaxListeners(5); diff --git a/test/parallel/test-event-emitter-subclass.js b/test/parallel/test-event-emitter-subclass.js index d4be78481238ba..327738271184b0 100644 --- a/test/parallel/test-event-emitter-subclass.js +++ b/test/parallel/test-event-emitter-subclass.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; @@ -43,6 +44,6 @@ MyEE2.prototype = new EventEmitter(); var ee1 = new MyEE2(); var ee2 = new MyEE2(); -ee1.on('x', function () {}); +ee1.on('x', function() {}); assert.equal(EventEmitter.listenerCount(ee2, 'x'), 0); diff --git a/test/parallel/test-exception-handler.js b/test/parallel/test-exception-handler.js index 4a781a0a9cd074..9cc8106ea6f80a 100644 --- a/test/parallel/test-exception-handler.js +++ b/test/parallel/test-exception-handler.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-exception-handler2.js b/test/parallel/test-exception-handler2.js index 77f3eb1d5cfd77..58e84ad21ba4ee 100644 --- a/test/parallel/test-exception-handler2.js +++ b/test/parallel/test-exception-handler2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-exec-max-buffer.js b/test/parallel/test-exec-max-buffer.js index a5a24eabeae7cb..5cae35b69f95d5 100644 --- a/test/parallel/test-exec-max-buffer.js +++ b/test/parallel/test-exec-max-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var exec = require('child_process').exec; var assert = require('assert'); diff --git a/test/parallel/test-file-read-noexist.js b/test/parallel/test-file-read-noexist.js index ad8dd5dc664921..47c8d256e3ba18 100644 --- a/test/parallel/test-file-read-noexist.js +++ b/test/parallel/test-file-read-noexist.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-file-write-stream.js b/test/parallel/test-file-write-stream.js index 9f0d66a84f722e..7882d2370d99c9 100644 --- a/test/parallel/test-file-write-stream.js +++ b/test/parallel/test-file-write-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-file-write-stream2.js b/test/parallel/test-file-write-stream2.js index 049d7d25e1c029..2563b1a300f526 100644 --- a/test/parallel/test-file-write-stream2.js +++ b/test/parallel/test-file-write-stream2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-file-write-stream3.js b/test/parallel/test-file-write-stream3.js index 2acb7053042c87..7223bd43f5230b 100644 --- a/test/parallel/test-file-write-stream3.js +++ b/test/parallel/test-file-write-stream3.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-access.js b/test/parallel/test-fs-access.js index 1c9773867ca706..6ad28612e9bb1b 100644 --- a/test/parallel/test-fs-access.js +++ b/test/parallel/test-fs-access.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -20,8 +21,8 @@ var createFileWithPerms = function(file, mode) { fs.chmodSync(file, mode); }; -createFileWithPerms(readOnlyFile, 0444); -createFileWithPerms(readWriteFile, 0666); +createFileWithPerms(readOnlyFile, 0o444); +createFileWithPerms(readWriteFile, 0o666); /* * On non-Windows supported platforms, fs.access(readOnlyFile, W_OK, ...) @@ -112,7 +113,7 @@ assert.doesNotThrow(function() { assert.throws(function() { fs.accessSync(doesNotExist); -}, function (err) { +}, function(err) { return err.code === 'ENOENT' && err.path === doesNotExist; }); diff --git a/test/parallel/test-fs-append-file-sync.js b/test/parallel/test-fs-append-file-sync.js index 72cfdf75e23b27..5a38014399dd5f 100644 --- a/test/parallel/test-fs-append-file-sync.js +++ b/test/parallel/test-fs-append-file-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var join = require('path').join; @@ -55,13 +56,13 @@ var filename4 = join(common.tmpDir, 'append-sync4.txt'); fs.writeFileSync(filename4, currentFileData, { mode: m }); common.error('appending to ' + filename4); -var m = 0600; +var m = 0o600; fs.appendFileSync(filename4, num, { mode: m }); // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename4); - assert.equal(st.mode & 0700, m); + assert.equal(st.mode & 0o700, m); } var fileData4 = fs.readFileSync(filename4); diff --git a/test/parallel/test-fs-append-file.js b/test/parallel/test-fs-append-file.js index ba2d34e5a1f0a6..4cd75ccacc60d8 100644 --- a/test/parallel/test-fs-append-file.js +++ b/test/parallel/test-fs-append-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -80,7 +81,7 @@ fs.writeFileSync(filename4, currentFileData); common.error('appending to ' + filename4); -var m = 0600; +var m = 0o600; fs.appendFile(filename4, n, { mode: m }, function(e) { if (e) throw e; @@ -90,7 +91,7 @@ fs.appendFile(filename4, n, { mode: m }, function(e) { // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename4); - assert.equal(st.mode & 0700, m); + assert.equal(st.mode & 0o700, m); } fs.readFile(filename4, function(e, buffer) { diff --git a/test/parallel/test-fs-chmod.js b/test/parallel/test-fs-chmod.js index 55056125da980d..a9d694adeccc01 100644 --- a/test/parallel/test-fs-chmod.js +++ b/test/parallel/test-fs-chmod.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -44,11 +45,11 @@ function closeSync() { // On Windows chmod is only able to manipulate read-only bit if (is_windows) { - mode_async = 0400; // read-only - mode_sync = 0600; // read-write + mode_async = 0o400; // read-only + mode_sync = 0o600; // read-write } else { - mode_async = 0777; - mode_sync = 0644; + mode_async = 0o777; + mode_sync = 0o644; } var file1 = path.join(common.fixturesDir, 'a.js'), @@ -61,16 +62,16 @@ fs.chmod(file1, mode_async.toString(8), function(err) { console.log(fs.statSync(file1).mode); if (is_windows) { - assert.ok((fs.statSync(file1).mode & 0777) & mode_async); + assert.ok((fs.statSync(file1).mode & 0o777) & mode_async); } else { - assert.equal(mode_async, fs.statSync(file1).mode & 0777); + assert.equal(mode_async, fs.statSync(file1).mode & 0o777); } fs.chmodSync(file1, mode_sync); if (is_windows) { - assert.ok((fs.statSync(file1).mode & 0777) & mode_sync); + assert.ok((fs.statSync(file1).mode & 0o777) & mode_sync); } else { - assert.equal(mode_sync, fs.statSync(file1).mode & 0777); + assert.equal(mode_sync, fs.statSync(file1).mode & 0o777); } success_count++; } @@ -89,16 +90,16 @@ fs.open(file2, 'a', function(err, fd) { console.log(fs.fstatSync(fd).mode); if (is_windows) { - assert.ok((fs.fstatSync(fd).mode & 0777) & mode_async); + assert.ok((fs.fstatSync(fd).mode & 0o777) & mode_async); } else { - assert.equal(mode_async, fs.fstatSync(fd).mode & 0777); + assert.equal(mode_async, fs.fstatSync(fd).mode & 0o777); } fs.fchmodSync(fd, mode_sync); if (is_windows) { - assert.ok((fs.fstatSync(fd).mode & 0777) & mode_sync); + assert.ok((fs.fstatSync(fd).mode & 0o777) & mode_sync); } else { - assert.equal(mode_sync, fs.fstatSync(fd).mode & 0777); + assert.equal(mode_sync, fs.fstatSync(fd).mode & 0o777); } success_count++; fs.close(fd); @@ -120,10 +121,10 @@ if (fs.lchmod) { got_error = true; } else { console.log(fs.lstatSync(link).mode); - assert.equal(mode_async, fs.lstatSync(link).mode & 0777); + assert.equal(mode_async, fs.lstatSync(link).mode & 0o777); fs.lchmodSync(link, mode_sync); - assert.equal(mode_sync, fs.lstatSync(link).mode & 0777); + assert.equal(mode_sync, fs.lstatSync(link).mode & 0o777); success_count++; } }); diff --git a/test/parallel/test-fs-empty-readStream.js b/test/parallel/test-fs-empty-readStream.js index 0c470076da7df1..0863e0cdba4ddb 100644 --- a/test/parallel/test-fs-empty-readStream.js +++ b/test/parallel/test-fs-empty-readStream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -5,43 +6,43 @@ var fs = require('fs'); var emptyFile = path.join(common.fixturesDir, 'empty.txt'); -fs.open(emptyFile, 'r', function (error, fd) { +fs.open(emptyFile, 'r', function(error, fd) { assert.ifError(error); var read = fs.createReadStream(emptyFile, { 'fd': fd }); - read.once('data', function () { + read.once('data', function() { throw new Error('data event should not emit'); }); var readEmit = false; - read.once('end', function () { + read.once('end', function() { readEmit = true; console.error('end event 1'); }); - setTimeout(function () { + setTimeout(function() { assert.equal(readEmit, true); }, common.platformTimeout(50)); }); -fs.open(emptyFile, 'r', function (error, fd) { +fs.open(emptyFile, 'r', function(error, fd) { assert.ifError(error); var read = fs.createReadStream(emptyFile, { 'fd': fd }); read.pause(); - read.once('data', function () { + read.once('data', function() { throw new Error('data event should not emit'); }); var readEmit = false; - read.once('end', function () { + read.once('end', function() { readEmit = true; console.error('end event 2'); }); - setTimeout(function () { + setTimeout(function() { assert.equal(readEmit, false); }, common.platformTimeout(50)); }); diff --git a/test/parallel/test-fs-error-messages.js b/test/parallel/test-fs-error-messages.js index e174e1c023ff21..ca0684c1d71363 100644 --- a/test/parallel/test-fs-error-messages.js +++ b/test/parallel/test-fs-error-messages.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -55,7 +56,7 @@ fs.rmdir(fn, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); -fs.mkdir(existingFile, 0666, function(err) { +fs.mkdir(existingFile, 0o666, function(err) { assert.ok(0 <= err.message.indexOf(existingFile)); }); @@ -63,11 +64,11 @@ fs.rmdir(existingFile, function(err) { assert.ok(0 <= err.message.indexOf(existingFile)); }); -fs.chmod(fn, 0666, function(err) { +fs.chmod(fn, 0o666, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); -fs.open(fn, 'r', 0666, function(err) { +fs.open(fn, 'r', 0o666, function(err) { assert.ok(0 <= err.message.indexOf(fn)); }); @@ -90,7 +91,7 @@ try { try { ++expected; - fs.mkdirSync(existingFile, 0666); + fs.mkdirSync(existingFile, 0o666); } catch (err) { errors.push('mkdir'); assert.ok(0 <= err.message.indexOf(existingFile)); @@ -98,7 +99,7 @@ try { try { ++expected; - fs.chmodSync(fn, 0666); + fs.chmodSync(fn, 0o666); } catch (err) { errors.push('chmod'); assert.ok(0 <= err.message.indexOf(fn)); diff --git a/test/parallel/test-fs-exists.js b/test/parallel/test-fs-exists.js index 4eb14e1e3bc73f..fcbd729a5ed850 100644 --- a/test/parallel/test-fs-exists.js +++ b/test/parallel/test-fs-exists.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-fsync.js b/test/parallel/test-fs-fsync.js index 50c010a49a5b1b..661a73baefad77 100644 --- a/test/parallel/test-fs-fsync.js +++ b/test/parallel/test-fs-fsync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -9,7 +10,7 @@ var file = path.join(common.fixturesDir, 'a.js'); common.error('open ' + file); -fs.open(file, 'a', 0777, function(err, fd) { +fs.open(file, 'a', 0o777, function(err, fd) { common.error('fd ' + fd); if (err) throw err; diff --git a/test/parallel/test-fs-long-path.js b/test/parallel/test-fs-long-path.js index ae8a5669f8193e..158ba04f49df08 100644 --- a/test/parallel/test-fs-long-path.js +++ b/test/parallel/test-fs-long-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fs = require('fs'); var path = require('path'); diff --git a/test/parallel/test-fs-make-callback.js b/test/parallel/test-fs-make-callback.js index 91990015b8220c..a15a16404df003 100644 --- a/test/parallel/test-fs-make-callback.js +++ b/test/parallel/test-fs-make-callback.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index b8a688adc4c736..b5451d20576aac 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index 4d1dcb3972a7ba..77228521e6fc9d 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index bf4619d19d4f33..c7d53117d587fc 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-open.js b/test/parallel/test-fs-open.js index ea099d2e14c89f..59b605841b4440 100644 --- a/test/parallel/test-fs-open.js +++ b/test/parallel/test-fs-open.js @@ -1,3 +1,4 @@ +'use strict'; var constants = require('constants'); var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-read-buffer.js b/test/parallel/test-fs-read-buffer.js index 0dc7a851da3c73..57a28d477c6575 100644 --- a/test/parallel/test-fs-read-buffer.js +++ b/test/parallel/test-fs-read-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), diff --git a/test/parallel/test-fs-read-file-sync-hostname.js b/test/parallel/test-fs-read-file-sync-hostname.js index a2c8ac5da7ce61..c5c5264c0dde3b 100644 --- a/test/parallel/test-fs-read-file-sync-hostname.js +++ b/test/parallel/test-fs-read-file-sync-hostname.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-read-file-sync.js b/test/parallel/test-fs-read-file-sync.js index cf6ab72dbf5b77..d34bf7748cea89 100644 --- a/test/parallel/test-fs-read-file-sync.js +++ b/test/parallel/test-fs-read-file-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-read-stream-err.js b/test/parallel/test-fs-read-stream-err.js index a3d1457e610f7b..1eb6aa57906b05 100644 --- a/test/parallel/test-fs-read-stream-err.js +++ b/test/parallel/test-fs-read-stream-err.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-read-stream-fd-leak.js b/test/parallel/test-fs-read-stream-fd-leak.js index abd954506b19d4..ddbccda1b8bea3 100644 --- a/test/parallel/test-fs-read-stream-fd-leak.js +++ b/test/parallel/test-fs-read-stream-fd-leak.js @@ -1,3 +1,4 @@ +'use strict'; // Copyright io.js contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -34,12 +35,12 @@ var emptyTxt = path.join(common.fixturesDir, 'empty.txt'); fs.open = function() { openCount++; return _fsopen.apply(null, arguments); -} +}; fs.close = function() { openCount--; return _fsclose.apply(null, arguments); -} +}; function testLeak(endFn, callback) { console.log('testing for leaks from fs.createReadStream().%s()...', endFn); @@ -53,7 +54,8 @@ function testLeak(endFn, callback) { if (++i === loopCount) { clearTimeout(this); setTimeout(function() { - assert.equal(0, openCount, 'no leaked file descriptors using ' + endFn + '() (got ' + openCount + ')'); + assert.equal(0, openCount, 'no leaked file descriptors using ' + + endFn + '() (got ' + openCount + ')'); openCount = 0; callback && setTimeout(callback, 100); }, 100); diff --git a/test/parallel/test-fs-read-stream-fd.js b/test/parallel/test-fs-read-stream-fd.js index f57499ca397660..450c56eb8a96b8 100644 --- a/test/parallel/test-fs-read-stream-fd.js +++ b/test/parallel/test-fs-read-stream-fd.js @@ -1,3 +1,4 @@ +'use strict'; var fs = require('fs'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-read-stream-inherit.js b/test/parallel/test-fs-read-stream-inherit.js index c8da148e0486cd..3b53578397f96e 100644 --- a/test/parallel/test-fs-read-stream-inherit.js +++ b/test/parallel/test-fs-read-stream-inherit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -80,7 +81,8 @@ process.on('exit', function() { console.error('ok'); }); -var file4 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, start: 1, end: 2})); +var file4 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, + start: 1, end: 2})); assert.equal(file4.start, 1); assert.equal(file4.end, 2); var contentRead = ''; @@ -91,7 +93,8 @@ file4.on('end', function(data) { assert.equal(contentRead, 'yz'); }); -var file5 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, start: 1})); +var file5 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1, + start: 1})); assert.equal(file5.start, 1); file5.data = ''; file5.on('data', function(data) { @@ -102,7 +105,8 @@ file5.on('end', function() { }); // https://github.com/joyent/node/issues/2320 -var file6 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1.23, start: 1})); +var file6 = fs.createReadStream(rangeFile, Object.create({bufferSize: 1.23, + start: 1})); assert.equal(file6.start, 1); file6.data = ''; file6.on('data', function(data) { @@ -116,7 +120,8 @@ assert.throws(function() { fs.createReadStream(rangeFile, Object.create({start: 10, end: 2})); }, /start must be <= end/); -var stream = fs.createReadStream(rangeFile, Object.create({ start: 0, end: 0 })); +var stream = fs.createReadStream(rangeFile, Object.create({ start: 0, + end: 0 })); assert.equal(stream.start, 0); assert.equal(stream.end, 0); stream.data = ''; @@ -145,7 +150,7 @@ file7.on('end', function() { }); }); -function file7Next(){ +function file7Next() { // This will tell us if the fd is usable again or not. file7 = fs.createReadStream(null, Object.create({fd: file7.fd, start: 0 })); file7.data = ''; @@ -158,7 +163,8 @@ function file7Next(){ } // Just to make sure autoClose won't close the stream because of error. -var file8 = fs.createReadStream(null, Object.create({fd: 13337, autoClose: false })); +var file8 = fs.createReadStream(null, Object.create({fd: 13337, + autoClose: false })); file8.on('data', function() {}); file8.on('error', common.mustCall(function() {})); diff --git a/test/parallel/test-fs-read-stream-resume.js b/test/parallel/test-fs-read-stream-resume.js index c3c61c88cb1f64..9a2e2ee76f78bc 100644 --- a/test/parallel/test-fs-read-stream-resume.js +++ b/test/parallel/test-fs-read-stream-resume.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index 85032d49640cdd..490ae0866d9aa0 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -138,7 +139,7 @@ file7.on('end', function() { }); }); -function file7Next(){ +function file7Next() { // This will tell us if the fd is usable again or not. file7 = fs.createReadStream(null, {fd: file7.fd, start: 0 }); file7.data = ''; diff --git a/test/parallel/test-fs-read.js b/test/parallel/test-fs-read.js index 3182733d115251..8b0b6fe0a3844d 100644 --- a/test/parallel/test-fs-read.js +++ b/test/parallel/test-fs-read.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), diff --git a/test/parallel/test-fs-readfile-empty.js b/test/parallel/test-fs-readfile-empty.js index bf7da45fca93cc..2669ce1ad6b121 100644 --- a/test/parallel/test-fs-readfile-empty.js +++ b/test/parallel/test-fs-readfile-empty.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-readfile-error.js b/test/parallel/test-fs-readfile-error.js index bfe79ab80edb63..6d86ba1a7ec0f1 100644 --- a/test/parallel/test-fs-readfile-error.js +++ b/test/parallel/test-fs-readfile-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-fs-readfile-pipe-large.js b/test/parallel/test-fs-readfile-pipe-large.js index 3502cdd5f48778..b25073061002a1 100644 --- a/test/parallel/test-fs-readfile-pipe-large.js +++ b/test/parallel/test-fs-readfile-pipe-large.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-readfile-pipe.js b/test/parallel/test-fs-readfile-pipe.js index da0cd2952fdb05..b55bfb6a22ccd2 100644 --- a/test/parallel/test-fs-readfile-pipe.js +++ b/test/parallel/test-fs-readfile-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-fs-readfile-unlink.js b/test/parallel/test-fs-readfile-unlink.js index bdcf23380e4775..15491b71c433ed 100644 --- a/test/parallel/test-fs-readfile-unlink.js +++ b/test/parallel/test-fs-readfile-unlink.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'), common = require('../common'), fs = require('fs'), diff --git a/test/parallel/test-fs-readfile-zero-byte-liar.js b/test/parallel/test-fs-readfile-zero-byte-liar.js index 532459305c5d91..2c9c6e3db9a584 100644 --- a/test/parallel/test-fs-readfile-zero-byte-liar.js +++ b/test/parallel/test-fs-readfile-zero-byte-liar.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -26,12 +27,12 @@ var d = fs.readFileSync(__filename, 'utf8'); assert.equal(d, dataExpected); var called = false; -fs.readFile(__filename, 'utf8', function (er, d) { +fs.readFile(__filename, 'utf8', function(er, d) { assert.equal(d, dataExpected); called = true; }); process.on('exit', function() { assert(called); - console.log("ok"); + console.log('ok'); }); diff --git a/test/parallel/test-fs-readfilesync-pipe-large.js b/test/parallel/test-fs-readfilesync-pipe-large.js index e62d541a68053c..78dbc31bea9911 100644 --- a/test/parallel/test-fs-readfilesync-pipe-large.js +++ b/test/parallel/test-fs-readfilesync-pipe-large.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index f8299d8d05662b..f0f6d4499c49e0 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -38,7 +39,7 @@ function tmp(p) { var fixturesAbsDir = common.fixturesDir; var tmpAbsDir = common.tmpDir; -console.error("absolutes\n%s\n%s", fixturesAbsDir, tmpAbsDir); +console.error('absolutes\n%s\n%s', fixturesAbsDir, tmpAbsDir); function asynctest(testBlock, args, callback, assertBlock) { async_expected++; @@ -235,7 +236,7 @@ function test_cyclic_link_overprotection(callback) { var link = folder + '/cycles'; var testPath = cycles; for (var i = 0; i < 10; i++) testPath += '/folder/cycles'; - try {fs.unlinkSync(link)} catch (ex) {} + try {fs.unlinkSync(link);} catch (ex) {} fs.symlinkSync(cycles, link, 'dir'); unlink.push(link); assert.equal(fs.realpathSync(testPath), path.resolve(expected)); @@ -311,7 +312,7 @@ function test_deep_symlink_mix(callback) { var entry = tmp('node-test-realpath-f1'); try { fs.unlinkSync(tmp('node-test-realpath-d2/foo')); } catch (e) {} try { fs.rmdirSync(tmp('node-test-realpath-d2')); } catch (e) {} - fs.mkdirSync(tmp('node-test-realpath-d2'), 0700); + fs.mkdirSync(tmp('node-test-realpath-d2'), 0o700); try { [ [entry, '../' + common.tmpDirName + '/node-test-realpath-d1/foo'], @@ -369,12 +370,14 @@ function test_escape_cwd(cb) { console.log('test_escape_cwd'); asynctest(fs.realpath, ['..'], cb, function(er, uponeActual) { assert.equal(upone, uponeActual, - 'realpath("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + 'realpath("..") expected: ' + path.resolve(upone) + + ' actual:' + uponeActual); }); } var uponeActual = fs.realpathSync('..'); assert.equal(upone, uponeActual, - 'realpathSync("..") expected: ' + path.resolve(upone) + ' actual:' + uponeActual); + 'realpathSync("..") expected: ' + path.resolve(upone) + + ' actual:' + uponeActual); // going up with .. multiple times @@ -394,15 +397,15 @@ function test_up_multiple(cb) { ['a/b', 'a' ].forEach(function(folder) { - try {fs.rmdirSync(tmp(folder))} catch (ex) {} + try {fs.rmdirSync(tmp(folder));} catch (ex) {} }); } function setup() { cleanup(); } setup(); - fs.mkdirSync(tmp('a'), 0755); - fs.mkdirSync(tmp('a/b'), 0755); + fs.mkdirSync(tmp('a'), 0o755); + fs.mkdirSync(tmp('a/b'), 0o755); fs.symlinkSync('..', tmp('a/d'), 'dir'); unlink.push(tmp('a/d')); fs.symlinkSync('..', tmp('a/b/e'), 'dir'); @@ -416,10 +419,10 @@ function test_up_multiple(cb) { assert.equal(fs.realpathSync(abedabeda), abedabeda_real); assert.equal(fs.realpathSync(abedabed), abedabed_real); - fs.realpath(abedabeda, function (er, real) { + fs.realpath(abedabeda, function(er, real) { if (er) throw er; assert.equal(abedabeda_real, real); - fs.realpath(abedabed, function (er, real) { + fs.realpath(abedabed, function(er, real) { if (er) throw er; assert.equal(abedabed_real, real); cb(); @@ -451,14 +454,14 @@ function test_abs_with_kids(cb) { ['/a/b/c/x.txt', '/a/link' ].forEach(function(file) { - try {fs.unlinkSync(root + file)} catch (ex) {} + try {fs.unlinkSync(root + file);} catch (ex) {} }); ['/a/b/c', '/a/b', '/a', '' ].forEach(function(folder) { - try {fs.rmdirSync(root + folder)} catch (ex) {} + try {fs.rmdirSync(root + folder);} catch (ex) {} }); } function setup() { @@ -469,7 +472,7 @@ function test_abs_with_kids(cb) { '/a/b/c' ].forEach(function(folder) { console.log('mkdir ' + root + folder); - fs.mkdirSync(root + folder, 0700); + fs.mkdirSync(root + folder, 0o700); }); fs.writeFileSync(root + '/a/b/c/x.txt', 'foo'); fs.symlinkSync(root + '/a/b', root + '/a/link', type); @@ -575,7 +578,7 @@ function runTest() { var s; try { s = fs.statSync(t); } catch (ex) {} if (s) return; - fs.mkdirSync(t, 0700); + fs.mkdirSync(t, 0o700); }); fs.writeFileSync(tmp('cycles/root.js'), "console.error('roooot!');"); console.error('start tests'); diff --git a/test/parallel/test-fs-sir-writes-alot.js b/test/parallel/test-fs-sir-writes-alot.js index 9df95a77bdfedd..537e94b0acaa3d 100644 --- a/test/parallel/test-fs-sir-writes-alot.js +++ b/test/parallel/test-fs-sir-writes-alot.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fs = require('fs'); var assert = require('assert'); diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js index 88a965974d05ce..123d6608b4bb4f 100644 --- a/test/parallel/test-fs-stat.js +++ b/test/parallel/test-fs-stat.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-stream-double-close.js b/test/parallel/test-fs-stream-double-close.js index 5d772da4aac887..47d129c042b4ad 100644 --- a/test/parallel/test-fs-stream-double-close.js +++ b/test/parallel/test-fs-stream-double-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-symlink-dir-junction-relative.js b/test/parallel/test-fs-symlink-dir-junction-relative.js index 5e4ce38b916393..6bf9e3f5b2d14b 100644 --- a/test/parallel/test-fs-symlink-dir-junction-relative.js +++ b/test/parallel/test-fs-symlink-dir-junction-relative.js @@ -1,3 +1,4 @@ +'use strict'; // Test creating and resolving relative junction or symbolic link var common = require('../common'); diff --git a/test/parallel/test-fs-symlink-dir-junction.js b/test/parallel/test-fs-symlink-dir-junction.js index 27d3e5103d9124..84d6c066213f28 100644 --- a/test/parallel/test-fs-symlink-dir-junction.js +++ b/test/parallel/test-fs-symlink-dir-junction.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-symlink.js b/test/parallel/test-fs-symlink.js index 533f22672da001..e7faef930e4817 100644 --- a/test/parallel/test-fs-symlink.js +++ b/test/parallel/test-fs-symlink.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-sync-fd-leak.js b/test/parallel/test-fs-sync-fd-leak.js index ab851b1a16f333..5f2b63125a1d0f 100644 --- a/test/parallel/test-fs-sync-fd-leak.js +++ b/test/parallel/test-fs-sync-fd-leak.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js index 72dfa136916f87..866315434a0120 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-truncate-fd.js b/test/parallel/test-fs-truncate-fd.js index 6e9628db867371..ed3aedaee8c805 100644 --- a/test/parallel/test-fs-truncate-fd.js +++ b/test/parallel/test-fs-truncate-fd.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 7f1dcd0661e3f9..df353f630eb370 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-utimes.js b/test/parallel/test-fs-utimes.js index e877b3dfdc56d5..863d66d89e424b 100644 --- a/test/parallel/test-fs-utimes.js +++ b/test/parallel/test-fs-utimes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); diff --git a/test/parallel/test-fs-write-buffer.js b/test/parallel/test-fs-write-buffer.js index 7dfcc6cd355215..edf33552cb3253 100644 --- a/test/parallel/test-fs-write-buffer.js +++ b/test/parallel/test-fs-write-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'), @@ -9,7 +10,7 @@ var path = require('path'), writeCalled = 0; -fs.open(filename, 'w', 0644, function(err, fd) { +fs.open(filename, 'w', 0o644, function(err, fd) { openCalled++; if (err) throw err; diff --git a/test/parallel/test-fs-write-file-buffer.js b/test/parallel/test-fs-write-file-buffer.js index bdddba9524977e..c1c263d409d173 100644 --- a/test/parallel/test-fs-write-file-buffer.js +++ b/test/parallel/test-fs-write-file-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var join = require('path').join; var util = require('util'); diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index 343d179f2a6864..579ccd907c4206 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -15,14 +16,14 @@ fs._closeSync = fs.closeSync; fs.closeSync = closeSync; // Reset the umask for testing -var mask = process.umask(0000); +var mask = process.umask(0o000); // On Windows chmod is only able to manipulate read-only bit. Test if creating // the file in read-only mode works. if (isWindows) { - mode = 0444; + mode = 0o444; } else { - mode = 0755; + mode = 0o755; } // Test writeFileSync @@ -34,7 +35,7 @@ fs.writeFileSync(file1, '123', {mode: mode}); content = fs.readFileSync(file1, {encoding: 'utf8'}); assert.equal('123', content); -assert.equal(mode, fs.statSync(file1).mode & 0777); +assert.equal(mode, fs.statSync(file1).mode & 0o777); removeFile(file1); @@ -58,7 +59,7 @@ assert.equal(0, openCount); function removeFile(file) { try { if (isWindows) - fs.chmodSync(file, 0666); + fs.chmodSync(file, 0o666); fs.unlinkSync(file); } catch (err) { if (err && err.code !== 'ENOENT') diff --git a/test/parallel/test-fs-write-file.js b/test/parallel/test-fs-write-file.js index 4f43197fd6fb9f..b0c52f7a0ef5c7 100644 --- a/test/parallel/test-fs-write-file.js +++ b/test/parallel/test-fs-write-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -55,14 +56,14 @@ fs.writeFile(filename2, buf, function(e) { var filename3 = join(common.tmpDir, 'test3.txt'); common.error('writing to ' + filename3); -var m = 0600; +var m = 0o600; fs.writeFile(filename3, n, { mode: m }, function(e) { if (e) throw e; // windows permissions aren't unix if (process.platform !== 'win32') { var st = fs.statSync(filename3); - assert.equal(st.mode & 0700, m); + assert.equal(st.mode & 0o700, m); } ncallbacks++; diff --git a/test/parallel/test-fs-write-no-fd.js b/test/parallel/test-fs-write-no-fd.js index 143928e7836ea7..5b38ce6ba814c4 100644 --- a/test/parallel/test-fs-write-no-fd.js +++ b/test/parallel/test-fs-write-no-fd.js @@ -1,3 +1,4 @@ +'use strict'; const common = require('../common'); const fs = require('fs'); const assert = require('assert'); diff --git a/test/parallel/test-fs-write-stream-change-open.js b/test/parallel/test-fs-write-stream-change-open.js index ca02e3959cbbd0..43b57f5c72519e 100644 --- a/test/parallel/test-fs-write-stream-change-open.js +++ b/test/parallel/test-fs-write-stream-change-open.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -21,7 +22,7 @@ fs.close = function(fd) { assert.ok(fd, 'fs.close must not be called with an undefined fd.'); fs.close = _fs_close; fs.open = _fs_open; -} +}; stream.write('foo'); stream.end(); diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js index 886df63660d15c..1a4c0a89d693a7 100644 --- a/test/parallel/test-fs-write-stream-end.js +++ b/test/parallel/test-fs-write-stream-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-write-stream-err.js b/test/parallel/test-fs-write-stream-err.js index 61d6df5d5fb57e..f3a608b62dc577 100644 --- a/test/parallel/test-fs-write-stream-err.js +++ b/test/parallel/test-fs-write-stream-err.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-fs-write-stream.js b/test/parallel/test-fs-write-stream.js index ef7822af48a365..bf78b1ee521469 100644 --- a/test/parallel/test-fs-write-stream.js +++ b/test/parallel/test-fs-write-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -13,7 +14,7 @@ var file = path.join(common.tmpDir, 'write.txt'); fs.close = function(fd) { assert.ok(fd, 'fs.close must not be called without an undefined fd.'); fs.close = _fs_close; - } + }; stream.destroy(); })(); diff --git a/test/parallel/test-fs-write-string-coerce.js b/test/parallel/test-fs-write-string-coerce.js index 1320acca2c1b4c..32f73172b76e5f 100644 --- a/test/parallel/test-fs-write-string-coerce.js +++ b/test/parallel/test-fs-write-string-coerce.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -8,7 +9,7 @@ var data = true; var expected = data + ''; var found; -fs.open(fn, 'w', 0644, function(err, fd) { +fs.open(fn, 'w', 0o644, function(err, fd) { if (err) throw err; console.log('open done'); fs.write(fd, data, 0, 'utf8', function(err, written) { diff --git a/test/parallel/test-fs-write-sync.js b/test/parallel/test-fs-write-sync.js index 59e2f90f92d6dc..2cdce58d874978 100644 --- a/test/parallel/test-fs-write-sync.js +++ b/test/parallel/test-fs-write-sync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js index 49b4ec53169137..a3d4cf83f8c85e 100644 --- a/test/parallel/test-fs-write.js +++ b/test/parallel/test-fs-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -9,7 +10,7 @@ var expected = 'ümlaut.'; var constants = require('constants'); var found, found2; -fs.open(fn, 'w', 0644, function(err, fd) { +fs.open(fn, 'w', 0o644, function(err, fd) { if (err) throw err; console.log('open done'); fs.write(fd, '', 0, 'utf8', function(err, written) { @@ -28,7 +29,7 @@ fs.open(fn, 'w', 0644, function(err, fd) { }); -fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0644, +fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, function(err, fd) { if (err) throw err; console.log('open done'); diff --git a/test/parallel/test-global.js b/test/parallel/test-global.js index a1ddc72f6290eb..82d8ee054c5860 100644 --- a/test/parallel/test-global.js +++ b/test/parallel/test-global.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-handle-wrap-close-abort.js b/test/parallel/test-handle-wrap-close-abort.js index c1179f72a13946..8e2388fa84d809 100644 --- a/test/parallel/test-handle-wrap-close-abort.js +++ b/test/parallel/test-handle-wrap-close-abort.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); process.on('uncaughtException', function() { }); diff --git a/test/parallel/test-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js index b67b48969c81e2..eac0fe51e2206a 100644 --- a/test/parallel/test-http-1.0-keep-alive.js +++ b/test/parallel/test-http-1.0-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -96,7 +97,7 @@ function check(tests) { var ctx = test.responses[current]; console.error('< SERVER SENDING RESPONSE', ctx); res.writeHead(200, ctx.headers); - ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk) }); + ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk); }); res.end(ctx.chunks[ctx.chunks.length - 1]); } diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index f1408d2f53412a..bf55c616d91996 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-304.js b/test/parallel/test-http-304.js index a2cc95e57db60d..e206f5bb70a3e1 100644 --- a/test/parallel/test-http-304.js +++ b/test/parallel/test-http-304.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-abort-before-end.js b/test/parallel/test-http-abort-before-end.js index 351ec86c2b8b95..c0cee3886f4406 100644 --- a/test/parallel/test-http-abort-before-end.js +++ b/test/parallel/test-http-abort-before-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); diff --git a/test/parallel/test-http-abort-client.js b/test/parallel/test-http-abort-client.js index 40cf64c2cb0559..e24ded11d1a7ec 100644 --- a/test/parallel/test-http-abort-client.js +++ b/test/parallel/test-http-abort-client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); @@ -38,7 +39,7 @@ server.listen(common.PORT, function() { res.socket.on('close', function() { console.log('socket closed, but not res'); - }) + }); // it would be nice if this worked: res.on('close', function() { diff --git a/test/parallel/test-http-abort-queued.js b/test/parallel/test-http-abort-queued.js index 1ef24acd509c1a..f2b0120366c374 100644 --- a/test/parallel/test-http-abort-queued.js +++ b/test/parallel/test-http-abort-queued.js @@ -1,10 +1,11 @@ +'use strict'; var assert = require('assert'), common = require('../common'), http = require('http'); var complete; -var server = http.createServer(function (req, res) { +var server = http.createServer(function(req, res) { // We should not see the queued /thatotherone request within the server // as it should be aborted before it is sent. assert.equal(req.url, '/'); @@ -12,13 +13,13 @@ var server = http.createServer(function (req, res) { res.writeHead(200); res.write('foo'); - complete = complete || function () { + complete = complete || function() { res.end(); }; }); -server.listen(common.PORT, function () { +server.listen(common.PORT, function() { console.log('listen', server.address().port); var agent = new http.Agent({maxSockets: 1}); diff --git a/test/parallel/test-http-after-connect.js b/test/parallel/test-http-after-connect.js index bff9170a217b81..19011fcbcb4fc4 100644 --- a/test/parallel/test-http-after-connect.js +++ b/test/parallel/test-http-after-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent-destroyed-socket.js b/test/parallel/test-http-agent-destroyed-socket.js index a2fe54d1dc6848..954acc998c035d 100644 --- a/test/parallel/test-http-agent-destroyed-socket.js +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent-false.js b/test/parallel/test-http-agent-false.js index 95c375ac37c7d3..ad8de89f2038e9 100644 --- a/test/parallel/test-http-agent-false.js +++ b/test/parallel/test-http-agent-false.js @@ -1,10 +1,11 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); -// sending `agent: false` when `port: null` is also passed in (i.e. the result of -// a `url.parse()` call with the default port used, 80 or 443), should not result -// in an assertion error... +// sending `agent: false` when `port: null` is also passed in (i.e. the result +// of a `url.parse()` call with the default port used, 80 or 443), should not +// result in an assertion error... var opts = { host: '127.0.0.1', port: null, @@ -19,8 +20,8 @@ process.on('exit', function() { }); // we just want an "error" (no local HTTP server on port 80) or "response" -// to happen (user happens ot have HTTP server running on port 80). As long as the -// process doesn't crash from a C++ assertion then we're good. +// to happen (user happens ot have HTTP server running on port 80). +// As long as the process doesn't crash from a C++ assertion then we're good. var req = http.request(opts); req.on('response', function(res) { good = true; diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js index 7dfd6f789ed921..f82af380bce1a9 100644 --- a/test/parallel/test-http-agent-keepalive.js +++ b/test/parallel/test-http-agent-keepalive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -11,14 +12,14 @@ var agent = new Agent({ maxFreeSockets: 5 }); -var server = http.createServer(function (req, res) { +var server = http.createServer(function(req, res) { if (req.url === '/error') { res.destroy(); return; } else if (req.url === '/remote_close') { // cache the socket, close it after 100ms var socket = res.connection; - setTimeout(function () { + setTimeout(function() { socket.end(); }, 100); } @@ -44,13 +45,13 @@ function checkDataAndSockets(body) { function second() { // request second, use the same socket - get('/second', function (res) { + get('/second', function(res) { assert.equal(res.statusCode, 200); res.on('data', checkDataAndSockets); - res.on('end', function () { + res.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { + process.nextTick(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name].length, 1); remoteClose(); @@ -61,17 +62,17 @@ function second() { function remoteClose() { // mock remote server close the socket - get('/remote_close', function (res) { + get('/remote_close', function(res) { assert.deepEqual(res.statusCode, 200); res.on('data', checkDataAndSockets); - res.on('end', function () { + res.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { + process.nextTick(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name].length, 1); // waitting remote server close the socket - setTimeout(function () { + setTimeout(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name], undefined, 'freeSockets is not empty'); @@ -84,16 +85,16 @@ function remoteClose() { function remoteError() { // remove server will destroy ths socket - var req = get('/error', function (res) { + var req = get('/error', function(res) { throw new Error('should not call this function'); }); - req.on('error', function (err) { + req.on('error', function(err) { assert.ok(err); assert.equal(err.message, 'socket hang up'); assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); // Wait socket 'close' event emit - setTimeout(function () { + setTimeout(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name], undefined); done(); @@ -108,13 +109,13 @@ function done() { server.listen(common.PORT, function() { // request first, and keep alive - get('/first', function (res) { + get('/first', function(res) { assert.equal(res.statusCode, 200); res.on('data', checkDataAndSockets); - res.on('end', function () { + res.on('end', function() { assert.equal(agent.sockets[name].length, 1); assert.equal(agent.freeSockets[name], undefined); - process.nextTick(function () { + process.nextTick(function() { assert.equal(agent.sockets[name], undefined); assert.equal(agent.freeSockets[name].length, 1); second(); diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index 0f349eac549abf..e11aa2addad746 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent-no-protocol.js b/test/parallel/test-http-agent-no-protocol.js index 1f910c33e53932..d5b7e5e19440f9 100644 --- a/test/parallel/test-http-agent-no-protocol.js +++ b/test/parallel/test-http-agent-no-protocol.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -21,7 +22,7 @@ var server = http.createServer(function(req, res) { opts.agent = new http.Agent(); opts.agent.protocol = null; - http.get(opts, function (res) { + http.get(opts, function(res) { response++; res.resume(); server.close(); diff --git a/test/parallel/test-http-agent-null.js b/test/parallel/test-http-agent-null.js index 397a5e0f4bbd72..e118738f664083 100644 --- a/test/parallel/test-http-agent-null.js +++ b/test/parallel/test-http-agent-null.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-agent.js b/test/parallel/test-http-agent.js index a485bc996ae2d8..09ba9c34e2936d 100644 --- a/test/parallel/test-http-agent.js +++ b/test/parallel/test-http-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-allow-req-after-204-res.js b/test/parallel/test-http-allow-req-after-204-res.js index e671bec029e159..ba98138bdca568 100644 --- a/test/parallel/test-http-allow-req-after-204-res.js +++ b/test/parallel/test-http-allow-req-after-204-res.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); diff --git a/test/parallel/test-http-automatic-headers.js b/test/parallel/test-http-automatic-headers.js index 76e5a61318c75d..8c454517020460 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-bind-twice.js b/test/parallel/test-http-bind-twice.js index 187f35ab879e4f..4dde7c6d252c6a 100644 --- a/test/parallel/test-http-bind-twice.js +++ b/test/parallel/test-http-bind-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js index 1fb1e0af96bec7..00a94d0b839f42 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-buffer-sanity.js b/test/parallel/test-http-buffer-sanity.js index f55d36c770f277..4b120311d7dac9 100644 --- a/test/parallel/test-http-buffer-sanity.js +++ b/test/parallel/test-http-buffer-sanity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-byteswritten.js b/test/parallel/test-http-byteswritten.js index 00ba09143ec9c8..974f446dd436b4 100644 --- a/test/parallel/test-http-byteswritten.js +++ b/test/parallel/test-http-byteswritten.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-http-chunked-304.js b/test/parallel/test-http-chunked-304.js index 86e0b0d11d1dfd..0f979420488d60 100644 --- a/test/parallel/test-http-chunked-304.js +++ b/test/parallel/test-http-chunked-304.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-chunked.js b/test/parallel/test-http-chunked.js index b666e051cc07b1..74b6943ab41f41 100644 --- a/test/parallel/test-http-chunked.js +++ b/test/parallel/test-http-chunked.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -24,7 +25,7 @@ server.listen(common.PORT, function() { port: common.PORT }, function(x) { x.setEncoding('utf8'); - x.on('data', function(c) {data += c}); + x.on('data', function(c) {data += c;}); x.on('error', function(e) { throw e; }); @@ -36,7 +37,7 @@ server.listen(common.PORT, function() { server.close(); }); }); - get.on('error', function(e) {throw e}); + get.on('error', function(e) {throw e;}); get.end(); }); diff --git a/test/parallel/test-http-client-abort-event.js b/test/parallel/test-http-client-abort-event.js index 1549d06101a647..b428038028ad8e 100644 --- a/test/parallel/test-http-client-abort-event.js +++ b/test/parallel/test-http-client-abort-event.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var http = require('http'); var common = require('../common'); @@ -25,4 +26,4 @@ server.listen(common.PORT, function() { process.on('exit', function() { assert.equal(count, 1); -}) +}); diff --git a/test/parallel/test-http-client-abort.js b/test/parallel/test-http-client-abort.js index 1359df5a6c4b3d..c3353bb72201b6 100644 --- a/test/parallel/test-http-client-abort.js +++ b/test/parallel/test-http-client-abort.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-abort2.js b/test/parallel/test-http-client-abort2.js index c7c19acccf3ea5..3f7ae98fa25820 100644 --- a/test/parallel/test-http-client-abort2.js +++ b/test/parallel/test-http-client-abort2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-agent.js b/test/parallel/test-http-client-agent.js index e97a14720f4a0f..afe98902e5b6fc 100644 --- a/test/parallel/test-http-client-agent.js +++ b/test/parallel/test-http-client-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-default-headers-exist.js b/test/parallel/test-http-client-default-headers-exist.js index 02175384970de1..94106285beca97 100644 --- a/test/parallel/test-http-client-default-headers-exist.js +++ b/test/parallel/test-http-client-default-headers-exist.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-encoding.js b/test/parallel/test-http-client-encoding.js index a93b33620fe934..dd696f4dff608a 100644 --- a/test/parallel/test-http-client-encoding.js +++ b/test/parallel/test-http-client-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index 03fa3331e95160..1dd23143e46c68 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index 38f2628741dd93..43f85853b3bbeb 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-client-pipe-end.js b/test/parallel/test-http-client-pipe-end.js index 6f05d3093123b5..d794aae446c4fa 100644 --- a/test/parallel/test-http-client-pipe-end.js +++ b/test/parallel/test-http-client-pipe-end.js @@ -1,3 +1,4 @@ +'use strict'; // see https://github.com/joyent/node/issues/3257 var common = require('../common'); @@ -23,7 +24,7 @@ server.listen(common.PIPE, function() { req.write('.'); - sched(function() { req.end() }, 5); + sched(function() { req.end(); }, 5); }); // schedule a callback after `ticks` event loop ticks diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js index fabb2c50a86984..0a98e06c7bf062 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -79,7 +80,7 @@ server.on('listening', function() { req3.end(); req3.on('response', function(res3) { res3.setEncoding('utf8'); - res3.on('data', function(chunk) { body3 += chunk }); + res3.on('data', function(chunk) { body3 += chunk; }); res3.on('end', function() { server.close(); }); }); }); diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js index c284fbae773e68..11dcb7ae4ca89e 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-read-in-error.js b/test/parallel/test-http-client-read-in-error.js index 6568d7e28d0223..8d74aecb51b91c 100644 --- a/test/parallel/test-http-client-read-in-error.js +++ b/test/parallel/test-http-client-read-in-error.js @@ -1,3 +1,4 @@ +'use strict'; var net = require('net'); var http = require('http'); var util = require('util'); diff --git a/test/parallel/test-http-client-readable.js b/test/parallel/test-http-client-readable.js index e690ba7ba5afc8..ba9fdd658c3864 100644 --- a/test/parallel/test-http-client-readable.js +++ b/test/parallel/test-http-client-readable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js index 1c38a1a254eaf4..1637882a3c251d 100644 --- a/test/parallel/test-http-client-response-domain.js +++ b/test/parallel/test-http-client-response-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), http = require('http'), diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js index a928b12090e704..809742f5628df5 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -23,35 +24,35 @@ var server = http.createServer(function(req, res) { res.write(reqid.toString()); res.end(); } - request_number+=1; + request_number += 1; }); server.listen(options.port, options.host, function() { var req; - for (requests_sent = 0; requests_sent < 30; requests_sent+=1) { + for (requests_sent = 0; requests_sent < 30; requests_sent += 1) { options.path = '/' + requests_sent; req = http.request(options); req.id = requests_sent; req.on('response', function(res) { res.on('data', function(data) { - console.log('res#'+this.req.id+' data:'+data); + console.log('res#' + this.req.id + ' data:' + data); }); res.on('end', function(data) { - console.log('res#'+this.req.id+' end'); + console.log('res#' + this.req.id + ' end'); requests_done += 1; }); }); req.on('close', function() { - console.log('req#'+this.id+' close'); + console.log('req#' + this.id + ' close'); }); req.on('error', function() { - console.log('req#'+this.id+' error'); + console.log('req#' + this.id + ' error'); this.destroy(); }); - req.setTimeout(50, function () { + req.setTimeout(50, function() { var req = this; - console.log('req#'+this.id + ' timeout'); + console.log('req#' + this.id + ' timeout'); req.abort(); requests_done += 1; }); @@ -71,5 +72,6 @@ server.listen(options.port, options.host, function() { process.on('exit', function() { console.error('done=%j sent=%j', requests_done, requests_sent); - assert.ok(requests_done == requests_sent, 'timeout on http request called too much'); + assert.ok(requests_done == requests_sent, + 'timeout on http request called too much'); }); diff --git a/test/parallel/test-http-client-timeout-event.js b/test/parallel/test-http-client-timeout-event.js index c975d69d399745..c9d65941923408 100644 --- a/test/parallel/test-http-client-timeout-event.js +++ b/test/parallel/test-http-client-timeout-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -26,14 +27,14 @@ server.listen(options.port, options.host, function() { var timeout_events = 0; req.setTimeout(1); - req.on('timeout', function () { + req.on('timeout', function() { timeout_events += 1; }); - setTimeout(function () { + setTimeout(function() { req.destroy(); assert.equal(timeout_events, 1); }, 100); - setTimeout(function () { + setTimeout(function() { req.end(); }, 50); }); diff --git a/test/parallel/test-http-client-timeout-with-data.js b/test/parallel/test-http-client-timeout-with-data.js index accf8c1341b86c..0aefe62ef45055 100644 --- a/test/parallel/test-http-client-timeout-with-data.js +++ b/test/parallel/test-http-client-timeout-with-data.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -20,7 +21,7 @@ var options = { var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Length':'2'}); res.write('*'); - setTimeout(function() { res.end('*') }, 100); + setTimeout(function() { res.end('*'); }, 100); }); server.listen(options.port, options.host, function() { diff --git a/test/parallel/test-http-client-timeout.js b/test/parallel/test-http-client-timeout.js index 8ea36de41ec4c1..63ef5c067a5bd3 100644 --- a/test/parallel/test-http-client-timeout.js +++ b/test/parallel/test-http-client-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-unescaped-path.js b/test/parallel/test-http-client-unescaped-path.js index 51e1fc7828be86..1536916ae9b49c 100644 --- a/test/parallel/test-http-client-unescaped-path.js +++ b/test/parallel/test-http-client-unescaped-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index 5e544ccf518123..760f9c9562a678 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index 44fd5eabf23ab4..48ebfcc74de5ac 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index d340aa744c494a..2f047a2de4009a 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-connect.js b/test/parallel/test-http-connect.js index 5ba24df5c18a9a..92fed5a72556db 100644 --- a/test/parallel/test-http-connect.js +++ b/test/parallel/test-http-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-content-length.js b/test/parallel/test-http-content-length.js index 07180f26ad84ed..6c9576cdabf563 100644 --- a/test/parallel/test-http-content-length.js +++ b/test/parallel/test-http-content-length.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-contentLength0.js b/test/parallel/test-http-contentLength0.js index 9b565c5470a246..9004649d1d2057 100644 --- a/test/parallel/test-http-contentLength0.js +++ b/test/parallel/test-http-contentLength0.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); diff --git a/test/parallel/test-http-createConnection.js b/test/parallel/test-http-createConnection.js index 1da2d18f414bf8..48a7d7dbe68ea3 100644 --- a/test/parallel/test-http-createConnection.js +++ b/test/parallel/test-http-createConnection.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -14,7 +15,7 @@ var server = http.createServer(function(req, res) { res.end(); response++; }).listen(common.PORT, '127.0.0.1', function() { - http.get({ createConnection: createConnection }, function (res) { + http.get({ createConnection: createConnection }, function(res) { res.resume(); server.close(); }); diff --git a/test/parallel/test-http-curl-chunk-problem.js b/test/parallel/test-http-curl-chunk-problem.js index fcb186153dc933..55fce4ad5e60e4 100644 --- a/test/parallel/test-http-curl-chunk-problem.js +++ b/test/parallel/test-http-curl-chunk-problem.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); if (!common.opensslCli) { diff --git a/test/parallel/test-http-date-header.js b/test/parallel/test-http-date-header.js index 293a9b99291255..4c73800a8e908c 100644 --- a/test/parallel/test-http-date-header.js +++ b/test/parallel/test-http-date-header.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-default-encoding.js b/test/parallel/test-http-default-encoding.js index 6a2ac36ebd4b90..a40c8841eceab9 100644 --- a/test/parallel/test-http-default-encoding.js +++ b/test/parallel/test-http-default-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-default-port.js b/test/parallel/test-http-default-port.js index 5f702073121128..457424ecfa9397 100644 --- a/test/parallel/test-http-default-port.js +++ b/test/parallel/test-http-default-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'), PORT = common.PORT, diff --git a/test/parallel/test-http-destroyed-socket-write2.js b/test/parallel/test-http-destroyed-socket-write2.js index e7a47ca9cfe95f..5bbb3bbc946f7d 100644 --- a/test/parallel/test-http-destroyed-socket-write2.js +++ b/test/parallel/test-http-destroyed-socket-write2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-dns-error.js b/test/parallel/test-http-dns-error.js index 15547cd39450d1..55195e45b715ff 100644 --- a/test/parallel/test-http-dns-error.js +++ b/test/parallel/test-http-dns-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-end-throw-socket-handling.js b/test/parallel/test-http-end-throw-socket-handling.js index 92a5ae6a38d0fb..204c0f73335480 100644 --- a/test/parallel/test-http-end-throw-socket-handling.js +++ b/test/parallel/test-http-end-throw-socket-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -19,8 +20,8 @@ server.listen(common.PORT, function() { for (var i = 0; i < 10; i++) { var options = { port: common.PORT }; - var req = http.request(options, function (res) { - res.resume() + var req = http.request(options, function(res) { + res.resume(); res.on('end', function() { throw new Error('gleep glorp'); }); diff --git a/test/parallel/test-http-eof-on-connect.js b/test/parallel/test-http-eof-on-connect.js index a08ac9c7b0e6c9..e676643bab4911 100644 --- a/test/parallel/test-http-eof-on-connect.js +++ b/test/parallel/test-http-eof-on-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js index 6e0b5b9a6b8166..dc2d5583ddbaf9 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-exit-delay.js b/test/parallel/test-http-exit-delay.js index 191b96d28b1e74..b06b33b5948eaf 100644 --- a/test/parallel/test-http-exit-delay.js +++ b/test/parallel/test-http-exit-delay.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var http = require('http'); diff --git a/test/parallel/test-http-expect-continue.js b/test/parallel/test-http-expect-continue.js index ed6de310955383..aef4a98d84c9e2 100644 --- a/test/parallel/test-http-expect-continue.js +++ b/test/parallel/test-http-expect-continue.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index ac2d9b6157c967..bfd9b59462c685 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-flush-headers.js b/test/parallel/test-http-flush-headers.js index ede0fa52021233..da1bd24c54a884 100644 --- a/test/parallel/test-http-flush-headers.js +++ b/test/parallel/test-http-flush-headers.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); const server = http.createServer(); -server.on('request', function(req, res){ +server.on('request', function(req, res) { assert(req.headers['foo'], 'bar'); res.end('ok'); server.close(); diff --git a/test/parallel/test-http-flush.js b/test/parallel/test-http-flush.js index 8d5a593cd9d21d..cac1caf752bee6 100644 --- a/test/parallel/test-http-flush.js +++ b/test/parallel/test-http-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index 4f3ce63dd85bed..da1b6d7f223496 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // This test requires the program 'ab' diff --git a/test/parallel/test-http-get-pipeline-problem.js b/test/parallel/test-http-get-pipeline-problem.js index 4d36cd3f7ea6f2..9c51bd11912257 100644 --- a/test/parallel/test-http-get-pipeline-problem.js +++ b/test/parallel/test-http-get-pipeline-problem.js @@ -1,3 +1,4 @@ +'use strict'; // We are demonstrating a problem with http.get when queueing up many // transfers. The server simply introduces some delay and sends a file. // Note this is demonstrated with connection: close. diff --git a/test/parallel/test-http-head-request.js b/test/parallel/test-http-head-request.js index 2310a6f83162f3..5a6f90507cf303 100644 --- a/test/parallel/test-http-head-request.js +++ b/test/parallel/test-http-head-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-head-response-has-no-body-end.js b/test/parallel/test-http-head-response-has-no-body-end.js index 4f0fb5341ef10e..e0fdb131ed3378 100644 --- a/test/parallel/test-http-head-response-has-no-body-end.js +++ b/test/parallel/test-http-head-response-has-no-body-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-head-response-has-no-body.js b/test/parallel/test-http-head-response-has-no-body.js index 73fcf0b31f368d..ef1fc530db19c9 100644 --- a/test/parallel/test-http-head-response-has-no-body.js +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-header-read.js b/test/parallel/test-http-header-read.js index 0cba3d37415617..6266f8b11ffd2c 100644 --- a/test/parallel/test-http-header-read.js +++ b/test/parallel/test-http-header-read.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-header-response-splitting.js b/test/parallel/test-http-header-response-splitting.js index 148de1d245b040..b499ae33d157cc 100644 --- a/test/parallel/test-http-header-response-splitting.js +++ b/test/parallel/test-http-header-response-splitting.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), http = require('http'); diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index acce151b20af79..371bbe7a43cb75 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-host-headers.js b/test/parallel/test-http-host-headers.js index 10e50306609d67..b5c083dfdf6d15 100644 --- a/test/parallel/test-http-host-headers.js +++ b/test/parallel/test-http-host-headers.js @@ -1,3 +1,4 @@ +'use strict'; var http = require('http'), common = require('../common'), assert = require('assert'), diff --git a/test/parallel/test-http-incoming-pipelined-socket-destroy.js b/test/parallel/test-http-incoming-pipelined-socket-destroy.js index 26b704e6d5b5ba..21cd3e69dfd746 100644 --- a/test/parallel/test-http-incoming-pipelined-socket-destroy.js +++ b/test/parallel/test-http-incoming-pipelined-socket-destroy.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -42,7 +43,7 @@ function generator(seeds) { return 'GET /' + r + ' HTTP/1.1\r\n' + 'Host: localhost:' + common.PORT + '\r\n' + '\r\n' + - '\r\n' + '\r\n'; }).join(''); } diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js index 200f017a802d57..9ed6077b943aa8 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-keep-alive.js b/test/parallel/test-http-keep-alive.js index 58c7061059a90c..f89f7698c46ebd 100644 --- a/test/parallel/test-http-keep-alive.js +++ b/test/parallel/test-http-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-keepalive-client.js b/test/parallel/test-http-keepalive-client.js index 6bc459e3b96fd0..c573ac82d6f884 100644 --- a/test/parallel/test-http-keepalive-client.js +++ b/test/parallel/test-http-keepalive-client.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -66,6 +67,6 @@ function makeRequest(n) { } process.on('exit', function() { - assert.equal(actualRequests, expectRequests) + assert.equal(actualRequests, expectRequests); console.log('ok'); }); diff --git a/test/parallel/test-http-keepalive-maxsockets.js b/test/parallel/test-http-keepalive-maxsockets.js index e0e27f5e240cfe..a5382b6e328485 100644 --- a/test/parallel/test-http-keepalive-maxsockets.js +++ b/test/parallel/test-http-keepalive-maxsockets.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-keepalive-request.js b/test/parallel/test-http-keepalive-request.js index 51e9d66b1f739c..8736c9cd4f88ce 100644 --- a/test/parallel/test-http-keepalive-request.js +++ b/test/parallel/test-http-keepalive-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -66,6 +67,6 @@ function makeRequest(n) { } process.on('exit', function() { - assert.equal(actualRequests, expectRequests) + assert.equal(actualRequests, expectRequests); console.log('ok'); }); diff --git a/test/parallel/test-http-legacy.js b/test/parallel/test-http-legacy.js index 7a3ae3572519f6..039037114d37d4 100644 --- a/test/parallel/test-http-legacy.js +++ b/test/parallel/test-http-legacy.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 9ee8c1d74f950e..80c7cab7c8e1ad 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -6,7 +7,7 @@ var invalidLocalAddress = '1.2.3.4'; var gotError = false; var server = http.createServer(function(req, res) { - console.log("Connect from: " + req.connection.remoteAddress); + console.log('Connect from: ' + req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -15,7 +16,7 @@ var server = http.createServer(function(req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var req = http.request({ host: 'localhost', port: common.PORT, diff --git a/test/parallel/test-http-localaddress.js b/test/parallel/test-http-localaddress.js index 3cd821315253c9..9cc6a80d0b4974 100644 --- a/test/parallel/test-http-localaddress.js +++ b/test/parallel/test-http-localaddress.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'), assert = require('assert'); @@ -7,8 +8,8 @@ if (!common.hasMultiLocalhost()) { process.exit(); } -var server = http.createServer(function (req, res) { - console.log("Connect from: " + req.connection.remoteAddress); +var server = http.createServer(function(req, res) { + console.log('Connect from: ' + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { @@ -18,7 +19,7 @@ var server = http.createServer(function (req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var options = { host: 'localhost', port: common.PORT, path: '/', diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js index 26a0f340794cfc..5f65113afd4fc0 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-many-ended-pipelines.js b/test/parallel/test-http-many-ended-pipelines.js index 6824627151e741..4e0bc7e8ff736f 100644 --- a/test/parallel/test-http-many-ended-pipelines.js +++ b/test/parallel/test-http-many-ended-pipelines.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -28,7 +29,7 @@ server.listen(common.PORT); var client = net.connect({ port: common.PORT, allowHalfOpen: true }); for (var i = 0; i < numRequests; i++) { client.write('GET / HTTP/1.1\r\n' + - 'Host: some.host.name\r\n'+ + 'Host: some.host.name\r\n' + '\r\n\r\n'); } client.end(); diff --git a/test/parallel/test-http-max-headers-count.js b/test/parallel/test-http-max-headers-count.js index ed9b34297b5f39..18b160d0b6d8ed 100644 --- a/test/parallel/test-http-max-headers-count.js +++ b/test/parallel/test-http-max-headers-count.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-methods.js b/test/parallel/test-http-methods.js index 620db49434cdc2..348fd2e519ef64 100644 --- a/test/parallel/test-http-methods.js +++ b/test/parallel/test-http-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js index 44d696a5a0c1d6..0c36b7cbf3cac9 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-mutable-headers.js b/test/parallel/test-http-mutable-headers.js index 296b1622a03394..2a60117328c580 100644 --- a/test/parallel/test-http-mutable-headers.js +++ b/test/parallel/test-http-mutable-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -21,10 +22,10 @@ var cookies = [ var s = http.createServer(function(req, res) { switch (test) { case 'headers': - assert.throws(function() { res.setHeader() }); - assert.throws(function() { res.setHeader('someHeader') }); - assert.throws(function() { res.getHeader() }); - assert.throws(function() { res.removeHeader() }); + assert.throws(function() { res.setHeader(); }); + assert.throws(function() { res.setHeader('someHeader'); }); + assert.throws(function() { res.getHeader(); }); + assert.throws(function() { res.removeHeader(); }); res.setHeader('x-test-header', 'testing'); res.setHeader('X-TEST-HEADER2', 'testing'); diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js index 527ffb7d37b4e4..5752e5e924cd1b 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-outgoing-finish.js b/test/parallel/test-http-outgoing-finish.js index e25f8ab743ff1e..2140759139c8ed 100644 --- a/test/parallel/test-http-outgoing-finish.js +++ b/test/parallel/test-http-outgoing-finish.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-parser-bad-ref.js b/test/parallel/test-http-parser-bad-ref.js index 0e2a77bb3a3938..d409dc62d008d9 100644 --- a/test/parallel/test-http-parser-bad-ref.js +++ b/test/parallel/test-http-parser-bad-ref.js @@ -1,3 +1,4 @@ +'use strict'; // Run this program with valgrind or efence with --expose_gc to expose the // problem. diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js index 52df3836d790c0..af94d0c89c8f52 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index d8c181bf60f7ce..bb004f864cf468 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-pause-resume-one-end.js b/test/parallel/test-http-pause-resume-one-end.js index cc3e41f3e92c77..2a10aeb3beb9e6 100644 --- a/test/parallel/test-http-pause-resume-one-end.js +++ b/test/parallel/test-http-pause-resume-one-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-pause.js b/test/parallel/test-http-pause.js index cf318d024f0656..70a04657b81011 100644 --- a/test/parallel/test-http-pause.js +++ b/test/parallel/test-http-pause.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-pipe-fs.js b/test/parallel/test-http-pipe-fs.js index 76882d65650bfd..bfee9ce23f1365 100644 --- a/test/parallel/test-http-pipe-fs.js +++ b/test/parallel/test-http-pipe-fs.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index 8d27728a92ff34..fc8a753f2485ce 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-raw-headers.js b/test/parallel/test-http-raw-headers.js index b4c1401872ae8a..7ecaaa93cfb04e 100644 --- a/test/parallel/test-http-raw-headers.js +++ b/test/parallel/test-http-raw-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-remove-header-stays-removed.js b/test/parallel/test-http-remove-header-stays-removed.js index e963989385b336..904b8210103ebf 100644 --- a/test/parallel/test-http-remove-header-stays-removed.js +++ b/test/parallel/test-http-remove-header-stays-removed.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-request-end-twice.js b/test/parallel/test-http-request-end-twice.js index 5518a8140cf463..871880e51463d8 100644 --- a/test/parallel/test-http-request-end-twice.js +++ b/test/parallel/test-http-request-end-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-request-end.js b/test/parallel/test-http-request-end.js index d06c96d8777f5d..43d023028a4fd0 100644 --- a/test/parallel/test-http-request-end.js +++ b/test/parallel/test-http-request-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js index d0b474d712e34d..b29a6663ff6b26 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index 295d38aacb0e79..c8b3bf26e0804b 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index a4dcfcac0f1e41..0befd951f0cf16 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-close.js b/test/parallel/test-http-response-close.js index 1b3433d79ebe60..82fd782717371c 100644 --- a/test/parallel/test-http-response-close.js +++ b/test/parallel/test-http-response-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js index 5d18b6182cd785..888eb9ac4b87e2 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-readable.js b/test/parallel/test-http-response-readable.js index 0774b8ed9c963f..1f50137d7166fd 100644 --- a/test/parallel/test-http-response-readable.js +++ b/test/parallel/test-http-response-readable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-response-status-message.js b/test/parallel/test-http-response-status-message.js index abbae8818bfecd..a1e1f15697e468 100644 --- a/test/parallel/test-http-response-status-message.js +++ b/test/parallel/test-http-response-status-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -6,15 +7,24 @@ var net = require('net'); var testsComplete = 0; var testCases = [ - { path: "/200", statusMessage: "OK", response: 'HTTP/1.1 200 OK\r\n\r\n' }, - { path: "/500", statusMessage: "Internal Server Error", response: 'HTTP/1.1 500 Internal Server Error\r\n\r\n' }, - { path: "/302", statusMessage: "Moved Temporarily", response: 'HTTP/1.1 302 Moved Temporarily\r\n\r\n' }, - { path: "/missing", statusMessage: "", response: 'HTTP/1.1 200 \r\n\r\n' }, - { path: "/missing-no-space", statusMessage: "", response: 'HTTP/1.1 200\r\n\r\n' } + { path: '/200', statusMessage: 'OK', + response: 'HTTP/1.1 200 OK\r\n\r\n' }, + { path: '/500', statusMessage: 'Internal Server Error', + response: 'HTTP/1.1 500 Internal Server Error\r\n\r\n' }, + { path: '/302', statusMessage: 'Moved Temporarily', + response: 'HTTP/1.1 302 Moved Temporarily\r\n\r\n' }, + { path: '/missing', statusMessage: '', + response: 'HTTP/1.1 200 \r\n\r\n' }, + { path: '/missing-no-space', statusMessage: '', + response: 'HTTP/1.1 200\r\n\r\n' } ]; testCases.findByPath = function(path) { - var matching = this.filter(function(testCase) { return testCase.path === path; }); - if (matching.length === 0) { throw "failed to find test case with path " + path; } + var matching = this.filter(function(testCase) { + return testCase.path === path; + }); + if (matching.length === 0) { + throw 'failed to find test case with path ' + path; + } return matching[0]; }; diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index ac5849d075ec40..440e10533787fd 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the HTTP server implementation handles multiple instances // of the same header as per RFC2616: joining the handful of fields by ', ' // that support it, and dropping duplicates for other fields. diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js index 5a3b80c5cd8823..438e8ba759e8ba 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the HTTP server implementation handles multiple instances // of the same header as per RFC2616: joining the handful of fields by ', ' // that support it, and dropping duplicates for other fields. @@ -49,10 +50,12 @@ var multipleForbidden = [ var srv = http.createServer(function(req, res) { multipleForbidden.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], 'foo', 'header parsed incorrectly: ' + header); + assert.equal(req.headers[header.toLowerCase()], + 'foo', 'header parsed incorrectly: ' + header); }); multipleAllowed.forEach(function(header) { - assert.equal(req.headers[header.toLowerCase()], 'foo, bar', 'header parsed incorrectly: ' + header); + assert.equal(req.headers[header.toLowerCase()], + 'foo, bar', 'header parsed incorrectly: ' + header); }); assert.equal(req.headers['content-length'], 0); @@ -65,7 +68,7 @@ var srv = http.createServer(function(req, res) { function makeHeader(value) { return function(header) { return [header, value]; - } + }; } var headers = [] diff --git a/test/parallel/test-http-server-stale-close.js b/test/parallel/test-http-server-stale-close.js index aa834b1fae3ef3..a866d39c2cc735 100644 --- a/test/parallel/test-http-server-stale-close.js +++ b/test/parallel/test-http-server-stale-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js index b96b57998a2cb6..9ba13ddf96b6ec 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-set-cookies.js b/test/parallel/test-http-set-cookies.js index 1c03db01dba29e..9a43f82a39c12e 100644 --- a/test/parallel/test-http-set-cookies.js +++ b/test/parallel/test-http-set-cookies.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-set-timeout-server.js b/test/parallel/test-http-set-timeout-server.js index ccad6f1f3a398e..1f6c900da4f1a3 100644 --- a/test/parallel/test-http-set-timeout-server.js +++ b/test/parallel/test-http-set-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -16,8 +17,9 @@ function run() { if (fn) { console.log('# %s', fn.name); fn(run); - } else + } else { console.log('ok'); + } } test(function serverTimeout(cb) { diff --git a/test/parallel/test-http-set-timeout.js b/test/parallel/test-http-set-timeout.js index 1c547f06ee2200..be428d8970b27b 100644 --- a/test/parallel/test-http-set-timeout.js +++ b/test/parallel/test-http-set-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-set-trailers.js b/test/parallel/test-http-set-trailers.js index 98001afb66448f..6f5c02f5605969 100644 --- a/test/parallel/test-http-set-trailers.js +++ b/test/parallel/test-http-set-trailers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 3c2d2530833305..870223a37b6d44 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js index e862ed6076b447..19c36b0b2fd27f 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js index 8d79d1a5affe4c..e579b8e995e120 100644 --- a/test/parallel/test-http-status-message.js +++ b/test/parallel/test-http-status-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js index b4d64e459bfc12..0df485edc93f9c 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -14,7 +15,7 @@ var server = http.createServer(function(req, res) { }); server.listen(port, function() { - function callback(){} + function callback() {} var req = http.request({ port: port, @@ -26,7 +27,7 @@ server.listen(port, function() { res.on('end', function() { clientRequests++; server.close(); - }) + }); res.resume(); }); diff --git a/test/parallel/test-http-timeout.js b/test/parallel/test-http-timeout.js index 80393837f3201d..aab903420f0acc 100644 --- a/test/parallel/test-http-timeout.js +++ b/test/parallel/test-http-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -6,8 +7,8 @@ var http = require('http'); var port = common.PORT; var server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('OK'); + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.end('OK'); }); var agent = new http.Agent({maxSockets: 1}); @@ -18,13 +19,13 @@ server.listen(port, function() { createRequest().end(); } - function callback(){} + function callback() {} var count = 0; function createRequest() { - var req = http.request({port: port, path: '/', agent: agent}, function(res) { - + var req = http.request({port: port, path: '/', agent: agent}, + function(res) { req.clearTimeout(callback); res.on('end', function() { @@ -33,7 +34,7 @@ server.listen(port, function() { if (count == 11) { server.close(); } - }) + }); res.resume(); }); diff --git a/test/parallel/test-http-unix-socket.js b/test/parallel/test-http-unix-socket.js index 1c13dafd3b038b..9ec8c8a1572844 100644 --- a/test/parallel/test-http-unix-socket.js +++ b/test/parallel/test-http-unix-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js index b1655b7d0b41ae..84cfee90d528de 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to // the HTTP client. This test uses a raw TCP server to better control server // behavior. diff --git a/test/parallel/test-http-upgrade-client.js b/test/parallel/test-http-upgrade-client.js index 14e0b9ca6a117d..b8ba033f2e01cb 100644 --- a/test/parallel/test-http-upgrade-client.js +++ b/test/parallel/test-http-upgrade-client.js @@ -1,3 +1,4 @@ +'use strict'; // Verify that the 'upgrade' header causes an 'upgrade' event to be emitted to // the HTTP client. This test uses a raw TCP server to better control server // behavior. diff --git a/test/parallel/test-http-upgrade-client2.js b/test/parallel/test-http-upgrade-client2.js index d2b0f9c215b376..424d7c811c1a5a 100644 --- a/test/parallel/test-http-upgrade-client2.js +++ b/test/parallel/test-http-upgrade-client2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index 84a8de9fed1b9a..9b34fe42eb05b9 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js index 7af34c52719c4d..9a22df52c210be 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-auth-with-header-in-request.js b/test/parallel/test-http-url.parse-auth-with-header-in-request.js index 9df0f5f6cda912..bb5de74ff9dcad 100644 --- a/test/parallel/test-http-url.parse-auth-with-header-in-request.js +++ b/test/parallel/test-http-url.parse-auth-with-header-in-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-auth.js b/test/parallel/test-http-url.parse-auth.js index 7038efb552b031..d06c79a9e707a4 100644 --- a/test/parallel/test-http-url.parse-auth.js +++ b/test/parallel/test-http-url.parse-auth.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-basic.js b/test/parallel/test-http-url.parse-basic.js index 234082ad188b2a..efc375e97cbb62 100644 --- a/test/parallel/test-http-url.parse-basic.js +++ b/test/parallel/test-http-url.parse-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-https.request.js b/test/parallel/test-http-url.parse-https.request.js index 44287bc6b974dd..7fb749b069d140 100644 --- a/test/parallel/test-http-url.parse-https.request.js +++ b/test/parallel/test-http-url.parse-https.request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js index c8ae4ffeae97b2..5e49193181032c 100644 --- a/test/parallel/test-http-url.parse-only-support-http-https-protocol.js +++ b/test/parallel/test-http-url.parse-only-support-http-https-protocol.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -8,7 +9,8 @@ assert.throws(function() { http.request(url.parse('file:///whatever')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "file:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "file:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -17,7 +19,8 @@ assert.throws(function() { http.request(url.parse('mailto:asdf@asdf.com')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "mailto:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "mailto:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -26,7 +29,8 @@ assert.throws(function() { http.request(url.parse('ftp://www.example.com')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "ftp:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "ftp:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -35,7 +39,8 @@ assert.throws(function() { http.request(url.parse('javascript:alert(\'hello\');')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "javascript:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "javascript:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -44,7 +49,8 @@ assert.throws(function() { http.request(url.parse('xmpp:isaacschlueter@jabber.org')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "xmpp:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "xmpp:" not supported.' + + ' Expected "http:".'); return true; } }); @@ -53,7 +59,8 @@ assert.throws(function() { http.request(url.parse('f://some.host/path')); }, function(err) { if (err instanceof Error) { - assert.strictEqual(err.message, 'Protocol "f:" not supported. Expected "http:".'); + assert.strictEqual(err.message, 'Protocol "f:" not supported.' + + ' Expected "http:".'); return true; } }); diff --git a/test/parallel/test-http-url.parse-path.js b/test/parallel/test-http-url.parse-path.js index 2ff78755c1ed39..087f535fa99c83 100644 --- a/test/parallel/test-http-url.parse-path.js +++ b/test/parallel/test-http-url.parse-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-post.js b/test/parallel/test-http-url.parse-post.js index ae6a85da0ec395..b6a0fdeb255235 100644 --- a/test/parallel/test-http-url.parse-post.js +++ b/test/parallel/test-http-url.parse-post.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-url.parse-search.js b/test/parallel/test-http-url.parse-search.js index 16b65d2f94a3ea..04e5a72e8f913e 100644 --- a/test/parallel/test-http-url.parse-search.js +++ b/test/parallel/test-http-url.parse-search.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js index b79cf84078e157..78144ac6fbf7cb 100644 --- a/test/parallel/test-http-wget.js +++ b/test/parallel/test-http-wget.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-http-write-callbacks.js b/test/parallel/test-http-write-callbacks.js index a666e7ffe130a3..404396723e4416 100644 --- a/test/parallel/test-http-write-callbacks.js +++ b/test/parallel/test-http-write-callbacks.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index e0ddbe3c22add4..50a9f5d509f381 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js index acd2a6058dd526..79a8502c4f01b0 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-http-zero-length-write.js b/test/parallel/test-http-zero-length-write.js index 583b081a522873..1ba29ca1c4a9fb 100644 --- a/test/parallel/test-http-zero-length-write.js +++ b/test/parallel/test-http-zero-length-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,7 +23,7 @@ function getSrc() { var chunks = [ '', 'asdf', '', 'foo', '', 'bar', '' ]; var interval = setInterval(function() { if (paused) - return + return; var chunk = chunks.shift(); if (chunk !== undefined) { diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js index c1c55d2d525a34..daa746cdbe5b7a 100644 --- a/test/parallel/test-http.js +++ b/test/parallel/test-http.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/parallel/test-https-agent-servername.js b/test/parallel/test-https-agent-servername.js index 1647b0ee9a6ae8..5af9af9818008c 100644 --- a/test/parallel/test-https-agent-servername.js +++ b/test/parallel/test-https-agent-servername.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-agent.js b/test/parallel/test-https-agent.js index 15604f74e5fc75..a26882844e3e59 100644 --- a/test/parallel/test-https-agent.js +++ b/test/parallel/test-https-agent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-byteswritten.js b/test/parallel/test-https-byteswritten.js index 5c657b26076499..3e50b6f84dc265 100644 --- a/test/parallel/test-https-byteswritten.js +++ b/test/parallel/test-https-byteswritten.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-https-client-checkServerIdentity.js b/test/parallel/test-https-client-checkServerIdentity.js index c7bffc90002291..8f4aad7f5eff1e 100644 --- a/test/parallel/test-https-client-checkServerIdentity.js +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -17,12 +18,12 @@ var options = { var reqCount = 0; -var server = https.createServer(options, function (req, res) { +var server = https.createServer(options, function(req, res) { ++reqCount; res.writeHead(200); res.end(); req.resume(); -}).listen(common.PORT, function () { +}).listen(common.PORT, function() { authorized(); }); @@ -31,10 +32,10 @@ function authorized() { port: common.PORT, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] - }, function (res) { + }, function(res) { assert(false); }); - req.on('error', function (err) { + req.on('error', function(err) { override(); }); req.end(); @@ -45,21 +46,21 @@ function override() { port: common.PORT, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))], - checkServerIdentity: function (host, cert) { + checkServerIdentity: function(host, cert) { return false; } }; options.agent = new https.Agent(options); - var req = https.request(options, function (res) { + var req = https.request(options, function(res) { assert(req.socket.authorized); server.close(); }); - req.on('error', function (err) { + req.on('error', function(err) { throw err; }); req.end(); } -process.on('exit', function () { +process.on('exit', function() { assert.equal(reqCount, 1); }); diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 01cea20242e710..66c11cd2db34db 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -1,3 +1,4 @@ +'use strict'; // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; diff --git a/test/parallel/test-https-client-reject.js b/test/parallel/test-https-client-reject.js index d3fcae7befebb4..55c335289d4131 100644 --- a/test/parallel/test-https-client-reject.js +++ b/test/parallel/test-https-client-reject.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-client-resume.js b/test/parallel/test-https-client-resume.js index 974db0f59775cf..024c5fa17f6038 100644 --- a/test/parallel/test-https-client-resume.js +++ b/test/parallel/test-https-client-resume.js @@ -1,3 +1,4 @@ +'use strict'; // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. @@ -21,7 +22,7 @@ var options = { var connections = 0; // create server -var server = https.createServer(options, function(res, res) { +var server = https.createServer(options, function(req, res) { res.end('Goodbye'); connections++; }); diff --git a/test/parallel/test-https-connecting-to-http.js b/test/parallel/test-https-connecting-to-http.js index eb0ea40dc9c35a..64adb7760321bf 100644 --- a/test/parallel/test-https-connecting-to-http.js +++ b/test/parallel/test-https-connecting-to-http.js @@ -1,3 +1,4 @@ +'use strict'; // This tests the situation where you try to connect a https client // to an http server. You should get an error and exit. var common = require('../common'); diff --git a/test/parallel/test-https-drain.js b/test/parallel/test-https-drain.js index f2ea3fb4e44be2..0ce55b0849b585 100644 --- a/test/parallel/test-https-drain.js +++ b/test/parallel/test-https-drain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js index 14e087874e2285..78a2f3828cb9dd 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -1,3 +1,4 @@ +'use strict'; // I hate HTTP. One way of terminating an HTTP response is to not send // a content-length header, not send a transfer-encoding: chunked header, // and simply terminate the TCP connection. That is identity diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js index 9d8d34dd791a75..f9b382ad830d35 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-https-host-headers.js b/test/parallel/test-https-host-headers.js index b8bcb407f1bebb..6a828d4aabbe07 100644 --- a/test/parallel/test-https-host-headers.js +++ b/test/parallel/test-https-host-headers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 153233f1a691fb..21e630dee43404 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -17,7 +18,7 @@ var invalidLocalAddress = '1.2.3.4'; var gotError = false; var server = https.createServer(options, function(req, res) { - console.log("Connect from: " + req.connection.remoteAddress); + console.log('Connect from: ' + req.connection.remoteAddress); req.on('end', function() { res.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -26,7 +27,7 @@ var server = https.createServer(options, function(req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var req = https.request({ host: 'localhost', port: common.PORT, diff --git a/test/parallel/test-https-localaddress.js b/test/parallel/test-https-localaddress.js index b3b1d2cb942e07..0f3241c70b46ec 100644 --- a/test/parallel/test-https-localaddress.js +++ b/test/parallel/test-https-localaddress.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), fs = require('fs'), assert = require('assert'); @@ -18,8 +19,8 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, function (req, res) { - console.log("Connect from: " + req.connection.remoteAddress); +var server = https.createServer(options, function(req, res) { + console.log('Connect from: ' + req.connection.remoteAddress); assert.equal('127.0.0.2', req.connection.remoteAddress); req.on('end', function() { @@ -29,7 +30,7 @@ var server = https.createServer(options, function (req, res) { req.resume(); }); -server.listen(common.PORT, "127.0.0.1", function() { +server.listen(common.PORT, '127.0.0.1', function() { var options = { host: 'localhost', port: common.PORT, diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js index 30dbea6ad0975e..f3968588333b44 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -31,8 +32,8 @@ server.listen(options.port, options.host, function() { var data = ''; https.get(options, function(res) { - res.on('data', function(data_) { data += data_ }); - res.on('end', function() { server.close() }); + res.on('data', function(data_) { data += data_; }); + res.on('end', function() { server.close(); }); }); process.on('exit', function() { diff --git a/test/parallel/test-https-req-split.js b/test/parallel/test-https-req-split.js index 210363e430b9f1..4fd48eb16151fa 100644 --- a/test/parallel/test-https-req-split.js +++ b/test/parallel/test-https-req-split.js @@ -1,3 +1,4 @@ +'use strict'; // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js index 5ae8baee6940d7..2657b371e3c33b 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -28,8 +29,9 @@ function run() { if (fn) { console.log('# %s', fn.name); fn(run); - } else + } else { console.log('ok'); + } } test(function serverTimeout(cb) { diff --git a/test/parallel/test-https-simple.js b/test/parallel/test-https-simple.js index 840838b83e4787..c2b93fdef855a0 100644 --- a/test/parallel/test-https-simple.js +++ b/test/parallel/test-https-simple.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-socket-options.js b/test/parallel/test-https-socket-options.js index eef94765a52bf1..52e46bd20b7807 100644 --- a/test/parallel/test-https-socket-options.js +++ b/test/parallel/test-https-socket-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -43,7 +44,8 @@ server_http.listen(common.PORT, function() { req.end(); }); -// Then try https server (requires functions to be mirroed in tls.js's CryptoStream) +// Then try https server (requires functions to be +// mirroed in tls.js's CryptoStream) var server_https = https.createServer(options, function(req, res) { console.log('got HTTPS request'); @@ -51,7 +53,7 @@ var server_https = https.createServer(options, function(req, res) { res.end(body); }); -server_https.listen(common.PORT+1, function() { +server_https.listen(common.PORT + 1, function() { var req = https.request({ port: common.PORT + 1, rejectUnauthorized: false diff --git a/test/parallel/test-https-strict.js b/test/parallel/test-https-strict.js index b2620fa88b236c..7ab5c3ee8200be 100644 --- a/test/parallel/test-https-strict.js +++ b/test/parallel/test-https-strict.js @@ -1,3 +1,4 @@ +'use strict'; // disable strict server certificate validation by the client process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; @@ -100,7 +101,7 @@ function listening() { if (listenWait === 0) { allListening(); } - } + }; } function makeReq(path, port, error, host, ca) { @@ -127,7 +128,7 @@ function makeReq(path, port, error, host, ca) { } if (host) { - options.headers = { host: host } + options.headers = { host: host }; } var req = https.get(options); expectResponseCount++; @@ -136,7 +137,7 @@ function makeReq(path, port, error, host, ca) { : port === port3 ? server3 : null; - if (!server) throw new Error('invalid port: '+port); + if (!server) throw new Error('invalid port: ' + port); server.expectCount++; req.on('response', function(res) { @@ -150,7 +151,7 @@ function makeReq(path, port, error, host, ca) { server3.close(); } res.resume(); - }) + }); } function allListening() { diff --git a/test/parallel/test-https-timeout-server-2.js b/test/parallel/test-https-timeout-server-2.js index d802ad4ae9b4a3..d39554fcb17124 100644 --- a/test/parallel/test-https-timeout-server-2.js +++ b/test/parallel/test-https-timeout-server-2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-timeout-server.js b/test/parallel/test-https-timeout-server.js index a24779ac7658b1..2707c30d181bf5 100644 --- a/test/parallel/test-https-timeout-server.js +++ b/test/parallel/test-https-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-timeout.js b/test/parallel/test-https-timeout.js index c03cb013d599b7..f6f1375180991c 100644 --- a/test/parallel/test-https-timeout.js +++ b/test/parallel/test-https-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-https-truncate.js b/test/parallel/test-https-truncate.js index 6a58bfe7715321..aba1be809abddd 100644 --- a/test/parallel/test-https-truncate.js +++ b/test/parallel/test-https-truncate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-internal-modules-expose.js b/test/parallel/test-internal-modules-expose.js index 4ea79dbbf73512..4ece1d0c7b6f29 100644 --- a/test/parallel/test-internal-modules-expose.js +++ b/test/parallel/test-internal-modules-expose.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose_internals var common = require('../common'); diff --git a/test/parallel/test-internal-modules.js b/test/parallel/test-internal-modules.js index ebba2500d568b2..011b6f7132e9bf 100644 --- a/test/parallel/test-internal-modules.js +++ b/test/parallel/test-internal-modules.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-intl.js b/test/parallel/test-intl.js index 390155fc26e817..8701d90f7c0acc 100644 --- a/test/parallel/test-intl.js +++ b/test/parallel/test-intl.js @@ -1,10 +1,11 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // does node think that i18n was enabled? var enablei18n = process.config.variables.v8_enable_i18n_support; if (enablei18n === undefined) { - enablei18n = false; + enablei18n = false; } // is the Intl object present? diff --git a/test/parallel/test-listen-fd-cluster.js b/test/parallel/test-listen-fd-cluster.js index 4b60a18161103c..c3ba42f315daba 100644 --- a/test/parallel/test-listen-fd-cluster.js +++ b/test/parallel/test-listen-fd-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -43,7 +44,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -58,7 +59,7 @@ function test() { assert.equal(res.statusCode, 200); console.log('ok'); }); - }) + }); } } diff --git a/test/parallel/test-listen-fd-detached-inherit.js b/test/parallel/test-listen-fd-detached-inherit.js index 329eee5f818d48..7e8f7fbaf8a018 100644 --- a/test/parallel/test-listen-fd-detached-inherit.js +++ b/test/parallel/test-listen-fd-detached-inherit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -39,7 +40,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -55,7 +56,7 @@ function test() { assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); - }) + }); } } diff --git a/test/parallel/test-listen-fd-detached.js b/test/parallel/test-listen-fd-detached.js index a014fa1ee4a5a3..fceedfd25251dc 100644 --- a/test/parallel/test-listen-fd-detached.js +++ b/test/parallel/test-listen-fd-detached.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -39,7 +40,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -55,7 +56,7 @@ function test() { assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); - }) + }); } } diff --git a/test/parallel/test-listen-fd-ebadf.js b/test/parallel/test-listen-fd-ebadf.js index 628ece68a32023..db905dfa35e966 100644 --- a/test/parallel/test-listen-fd-ebadf.js +++ b/test/parallel/test-listen-fd-ebadf.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-listen-fd-server.js b/test/parallel/test-listen-fd-server.js index 39f15014a12851..b922c25ee10683 100644 --- a/test/parallel/test-listen-fd-server.js +++ b/test/parallel/test-listen-fd-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -39,7 +40,7 @@ function test() { server: 'localhost', port: PORT, path: '/', - }).on('response', function (res) { + }).on('response', function(res) { var s = ''; res.on('data', function(c) { s += c.toString(); @@ -55,7 +56,7 @@ function test() { assert.equal(s, 'hello from child\n'); assert.equal(res.statusCode, 200); }); - }) + }); } } diff --git a/test/parallel/test-memory-usage.js b/test/parallel/test-memory-usage.js index 4c1b67c83a324f..09dc4f820a8d74 100644 --- a/test/parallel/test-memory-usage.js +++ b/test/parallel/test-memory-usage.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-microtask-queue-integration-domain.js b/test/parallel/test-microtask-queue-integration-domain.js index 7e8b9a125038b4..7a4ad77cd321e3 100644 --- a/test/parallel/test-microtask-queue-integration-domain.js +++ b/test/parallel/test-microtask-queue-integration-domain.js @@ -1,12 +1,13 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); var implementations = [ - function (fn) { + function(fn) { Promise.resolve().then(fn); }, - function (fn) { + function(fn) { var obj = {}; Object.observe(obj, fn); @@ -18,20 +19,20 @@ var implementations = [ var expected = 0; var done = 0; -process.on('exit', function () { +process.on('exit', function() { assert.equal(done, expected); }); -function test (scheduleMicrotask) { +function test(scheduleMicrotask) { var nextTickCalled = false; expected++; - scheduleMicrotask(function () { - process.nextTick(function () { + scheduleMicrotask(function() { + process.nextTick(function() { nextTickCalled = true; }); - setTimeout(function () { + setTimeout(function() { assert(nextTickCalled); done++; }, 0); @@ -42,8 +43,8 @@ function test (scheduleMicrotask) { implementations.forEach(test); // tick callback case -setTimeout(function () { - implementations.forEach(function (impl) { +setTimeout(function() { + implementations.forEach(function(impl) { process.nextTick(test.bind(null, impl)); }); }, 0); diff --git a/test/parallel/test-microtask-queue-integration.js b/test/parallel/test-microtask-queue-integration.js index 3f68d736759f9e..37de5ee33b1477 100644 --- a/test/parallel/test-microtask-queue-integration.js +++ b/test/parallel/test-microtask-queue-integration.js @@ -1,11 +1,12 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var implementations = [ - function (fn) { + function(fn) { Promise.resolve().then(fn); }, - function (fn) { + function(fn) { var obj = {}; Object.observe(obj, fn); @@ -17,20 +18,20 @@ var implementations = [ var expected = 0; var done = 0; -process.on('exit', function () { +process.on('exit', function() { assert.equal(done, expected); }); -function test (scheduleMicrotask) { +function test(scheduleMicrotask) { var nextTickCalled = false; expected++; - scheduleMicrotask(function () { - process.nextTick(function () { + scheduleMicrotask(function() { + process.nextTick(function() { nextTickCalled = true; }); - setTimeout(function () { + setTimeout(function() { assert(nextTickCalled); done++; }, 0); @@ -41,8 +42,8 @@ function test (scheduleMicrotask) { implementations.forEach(test); // tick callback case -setTimeout(function () { - implementations.forEach(function (impl) { +setTimeout(function() { + implementations.forEach(function(impl) { process.nextTick(test.bind(null, impl)); }); }, 0); diff --git a/test/parallel/test-microtask-queue-run-domain.js b/test/parallel/test-microtask-queue-run-domain.js index 8627e90eff3518..77534920ff1451 100644 --- a/test/parallel/test-microtask-queue-run-domain.js +++ b/test/parallel/test-microtask-queue-run-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); diff --git a/test/parallel/test-microtask-queue-run-immediate-domain.js b/test/parallel/test-microtask-queue-run-immediate-domain.js index aa58b7fcb14710..2dea0a76cc1bf4 100644 --- a/test/parallel/test-microtask-queue-run-immediate-domain.js +++ b/test/parallel/test-microtask-queue-run-immediate-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); diff --git a/test/parallel/test-microtask-queue-run-immediate.js b/test/parallel/test-microtask-queue-run-immediate.js index fbce91e5179406..cfd9cd3659ef00 100644 --- a/test/parallel/test-microtask-queue-run-immediate.js +++ b/test/parallel/test-microtask-queue-run-immediate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-microtask-queue-run.js b/test/parallel/test-microtask-queue-run.js index 73ba76efc49e0c..ca758546c2bcfd 100644 --- a/test/parallel/test-microtask-queue-run.js +++ b/test/parallel/test-microtask-queue-run.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-module-globalpaths-nodepath.js b/test/parallel/test-module-globalpaths-nodepath.js index d0261e81f7a802..2b991e0c28a674 100644 --- a/test/parallel/test-module-globalpaths-nodepath.js +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js index 23eac7da6fbeeb..f33605d44ee949 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-module-nodemodulepaths.js b/test/parallel/test-module-nodemodulepaths.js index e5e07dd40e3423..b1f04d41d0e092 100644 --- a/test/parallel/test-module-nodemodulepaths.js +++ b/test/parallel/test-module-nodemodulepaths.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -9,10 +10,10 @@ var file, delimiter, paths; if (isWindows) { file = 'C:\\Users\\Rocko Artischocko\\node_stuff\\foo'; - delimiter = '\\' + delimiter = '\\'; } else { file = '/usr/test/lib/node_modules/npm/foo'; - delimiter = '/' + delimiter = '/'; } paths = module._nodeModulePaths(file); diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index 99b213e0870238..223417111600a1 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-better-error-messages-listen-path.js b/test/parallel/test-net-better-error-messages-listen-path.js index fcc3062a814f68..8a7e0220b36dfa 100644 --- a/test/parallel/test-net-better-error-messages-listen-path.js +++ b/test/parallel/test-net-better-error-messages-listen-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -5,5 +6,5 @@ var fp = '/blah/fadfa'; var server = net.createServer(assert.fail); server.listen(fp, assert.fail); server.on('error', common.mustCall(function(e) { - assert.equal(e.address, fp) + assert.equal(e.address, fp); })); diff --git a/test/parallel/test-net-better-error-messages-listen.js b/test/parallel/test-net-better-error-messages-listen.js index 9c7766bd4f4e3d..7e5fad925aeb92 100644 --- a/test/parallel/test-net-better-error-messages-listen.js +++ b/test/parallel/test-net-better-error-messages-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-better-error-messages-path.js b/test/parallel/test-net-better-error-messages-path.js index dea4a10459edab..06cfecbd7c6af1 100644 --- a/test/parallel/test-net-better-error-messages-path.js +++ b/test/parallel/test-net-better-error-messages-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-better-error-messages-port-hostname.js b/test/parallel/test-net-better-error-messages-port-hostname.js index 3817dbb92ff1e2..9335f6b07a6625 100644 --- a/test/parallel/test-net-better-error-messages-port-hostname.js +++ b/test/parallel/test-net-better-error-messages-port-hostname.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-better-error-messages-port.js b/test/parallel/test-net-better-error-messages-port.js index a8c16a70385bb3..0f90089c0509fe 100644 --- a/test/parallel/test-net-better-error-messages-port.js +++ b/test/parallel/test-net-better-error-messages-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-binary.js b/test/parallel/test-net-binary.js index ae1a82ae8976bd..cf29cfe63bad71 100644 --- a/test/parallel/test-net-binary.js +++ b/test/parallel/test-net-binary.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js index ca75fb16fed9e9..ca4f554d30ca16 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-buffersize.js b/test/parallel/test-net-buffersize.js index e8618beb7ac627..fcf0331c4ed500 100644 --- a/test/parallel/test-net-buffersize.js +++ b/test/parallel/test-net-buffersize.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-bytes-stats.js b/test/parallel/test-net-bytes-stats.js index 562e9b422c69c8..4e0a2e4001a452 100644 --- a/test/parallel/test-net-bytes-stats.js +++ b/test/parallel/test-net-bytes-stats.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-can-reset-timeout.js b/test/parallel/test-net-can-reset-timeout.js index 3febac8a3034f6..9fd7da4bb498ff 100644 --- a/test/parallel/test-net-can-reset-timeout.js +++ b/test/parallel/test-net-can-reset-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var net = require('net'); var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-connect-buffer.js b/test/parallel/test-net-connect-buffer.js index 74697932b0988b..304401f56ef50d 100644 --- a/test/parallel/test-net-connect-buffer.js +++ b/test/parallel/test-net-connect-buffer.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-handle-econnrefused.js b/test/parallel/test-net-connect-handle-econnrefused.js index 77849b9b577261..0a8ce081680f76 100644 --- a/test/parallel/test-net-connect-handle-econnrefused.js +++ b/test/parallel/test-net-connect-handle-econnrefused.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-connect-immediate-finish.js b/test/parallel/test-net-connect-immediate-finish.js index 1fc908be1fba21..086cf910422372 100644 --- a/test/parallel/test-net-connect-immediate-finish.js +++ b/test/parallel/test-net-connect-immediate-finish.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-options-ipv6.js b/test/parallel/test-net-connect-options-ipv6.js index 35af5124a46cd6..0ac1367ede1cce 100644 --- a/test/parallel/test-net-connect-options-ipv6.js +++ b/test/parallel/test-net-connect-options-ipv6.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js index fba35eab1c7b68..ac8bbcefc03e4c 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-connect-paused-connection.js b/test/parallel/test-net-connect-paused-connection.js index 06e51f843fefad..60af9e44fb31f6 100644 --- a/test/parallel/test-net-connect-paused-connection.js +++ b/test/parallel/test-net-connect-paused-connection.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-net-create-connection.js b/test/parallel/test-net-create-connection.js index 9f468763c008b6..c245ddc2ae7860 100644 --- a/test/parallel/test-net-create-connection.js +++ b/test/parallel/test-net-create-connection.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -22,7 +23,7 @@ server.listen(tcpPort, 'localhost', function() { function fail(opts, errtype, msg) { assert.throws(function() { var client = net.createConnection(opts, cb); - }, function (err) { + }, function(err) { return err instanceof errtype && msg === err.message; }); } diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js index 18f6fe259b75ec..17f251cec3b6af 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js index e7c058fe144a56..18a80501185871 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index b2f139cfa0a1f8..a2fd424e0e83c0 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-eaddrinuse.js b/test/parallel/test-net-eaddrinuse.js index 209e4909c49728..c1797b7369d5ed 100644 --- a/test/parallel/test-net-eaddrinuse.js +++ b/test/parallel/test-net-eaddrinuse.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-end-without-connect.js b/test/parallel/test-net-end-without-connect.js index 6ccf2b028082d2..2911591f9f486d 100644 --- a/test/parallel/test-net-end-without-connect.js +++ b/test/parallel/test-net-end-without-connect.js @@ -1,5 +1,6 @@ +'use strict'; var common = require('../common'); var net = require('net'); -var sock = new net.Socket; +var sock = new net.Socket(); sock.end(); // Should not throw. diff --git a/test/parallel/test-net-error-twice.js b/test/parallel/test-net-error-twice.js index 1620bb8ee55fa1..af92ca93206f18 100644 --- a/test/parallel/test-net-error-twice.js +++ b/test/parallel/test-net-error-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -10,18 +11,18 @@ var errs = []; var srv = net.createServer(function onConnection(conn) { conn.write(buf); - conn.on('error', function (err) { + conn.on('error', function(err) { errs.push(err); if (errs.length > 1 && errs[0] === errs[1]) - assert(false, "We should not be emitting the same error twice"); + assert(false, 'We should not be emitting the same error twice'); }); conn.on('close', function() { srv.unref(); }); -}).listen(common.PORT, function () { +}).listen(common.PORT, function() { var client = net.connect({ port: common.PORT }); - client.on('connect', function () { + client.on('connect', function() { client.destroy(); }); }); diff --git a/test/parallel/test-net-isip.js b/test/parallel/test-net-isip.js index 1947810b82deb8..96177122b7ba21 100644 --- a/test/parallel/test-net-isip.js +++ b/test/parallel/test-net-isip.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -29,7 +30,7 @@ assert.equal(net.isIP('::'), 6); assert.equal(net.isIP('0000:0000:0000:0000:0000:0000:12345:0000'), 0); assert.equal(net.isIP('0'), 0); assert.equal(net.isIP(), 0); -assert.equal(net.isIP(""), 0); +assert.equal(net.isIP(''), 0); assert.equal(net.isIPv4('127.0.0.1'), true); assert.equal(net.isIPv4('example.com'), false); diff --git a/test/parallel/test-net-keepalive.js b/test/parallel/test-net-keepalive.js index f5299c9eb34c0e..3c339f7abaa350 100644 --- a/test/parallel/test-net-keepalive.js +++ b/test/parallel/test-net-keepalive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-large-string.js b/test/parallel/test-net-large-string.js index 318f25a1c9a1e2..387f3f4f8c1dd3 100644 --- a/test/parallel/test-net-large-string.js +++ b/test/parallel/test-net-large-string.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index f4eff779406e0f..7450cb16fc7943 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var net = require('net'); diff --git a/test/parallel/test-net-listen-close-server.js b/test/parallel/test-net-listen-close-server.js index e3a73e6ae5cb60..9c4dbcfe2e15e2 100644 --- a/test/parallel/test-net-listen-close-server.js +++ b/test/parallel/test-net-listen-close-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js index 0ed2421fdfbca9..b0d8aac8f816e3 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-fd0.js b/test/parallel/test-net-listen-fd0.js index 7cfd49dbdd3d27..bf437268c92945 100644 --- a/test/parallel/test-net-listen-fd0.js +++ b/test/parallel/test-net-listen-fd0.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -14,6 +15,6 @@ net.createServer(assert.fail).listen({fd:0}).on('error', function(e) { case 'EINVAL': case 'ENOTSOCK': gotError = e; - break + break; } }); diff --git a/test/parallel/test-net-listen-port-option.js b/test/parallel/test-net-listen-port-option.js index 1b9938f7c7f155..d1eddb6707c274 100644 --- a/test/parallel/test-net-listen-port-option.js +++ b/test/parallel/test-net-listen-port-option.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-listen-shared-ports.js b/test/parallel/test-net-listen-shared-ports.js index 3139dc7ac29365..2062dd0ce136bb 100644 --- a/test/parallel/test-net-listen-shared-ports.js +++ b/test/parallel/test-net-listen-shared-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/parallel/test-net-local-address-port.js b/test/parallel/test-net-local-address-port.js index 0bbfee80211d0c..aa28d180dae6ff 100644 --- a/test/parallel/test-net-local-address-port.js +++ b/test/parallel/test-net-local-address-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-localerror.js b/test/parallel/test-net-localerror.js index c2ef96165a6e70..45ec1fc9099955 100644 --- a/test/parallel/test-net-localerror.js +++ b/test/parallel/test-net-localerror.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-pause-resume-connecting.js b/test/parallel/test-net-pause-resume-connecting.js index b692f3508529e1..fb3b66c8cf991c 100644 --- a/test/parallel/test-net-pause-resume-connecting.js +++ b/test/parallel/test-net-pause-resume-connecting.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), net = require('net'); diff --git a/test/parallel/test-net-pingpong.js b/test/parallel/test-net-pingpong.js index 7a05591caf969b..9a0c8af5b0697d 100644 --- a/test/parallel/test-net-pingpong.js +++ b/test/parallel/test-net-pingpong.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-pipe-connect-errors.js b/test/parallel/test-net-pipe-connect-errors.js index 5150c6de819787..a831b107122c8d 100644 --- a/test/parallel/test-net-pipe-connect-errors.js +++ b/test/parallel/test-net-pipe-connect-errors.js @@ -1,3 +1,4 @@ +'use strict'; var fs = require('fs'); var net = require('net'); var path = require('path'); diff --git a/test/parallel/test-net-reconnect-error.js b/test/parallel/test-net-reconnect-error.js index 541a481fe12705..ed889829ec8abe 100644 --- a/test/parallel/test-net-reconnect-error.js +++ b/test/parallel/test-net-reconnect-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-reconnect.js b/test/parallel/test-net-reconnect.js index d65efac998102b..b2e8f6ea8b4e3f 100644 --- a/test/parallel/test-net-reconnect.js +++ b/test/parallel/test-net-reconnect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js index 2f8c673b57ef98..11d753ea460b79 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-server-close.js b/test/parallel/test-net-server-close.js index 4101baf166b555..446b835a4c67df 100644 --- a/test/parallel/test-net-server-close.js +++ b/test/parallel/test-net-server-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -23,7 +24,7 @@ var server = net.createServer(function(c) { if (sockets.length === 2) { server.close(); - sockets.forEach(function(c) { c.destroy() }); + sockets.forEach(function(c) { c.destroy(); }); } }); diff --git a/test/parallel/test-net-server-connections.js b/test/parallel/test-net-server-connections.js index 76e9c2af1cc97f..138a78defb260d 100644 --- a/test/parallel/test-net-server-connections.js +++ b/test/parallel/test-net-server-connections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-server-listen-remove-callback.js b/test/parallel/test-net-server-listen-remove-callback.js index d9a5a8bdec4934..a7d54081a6bb03 100644 --- a/test/parallel/test-net-server-listen-remove-callback.js +++ b/test/parallel/test-net-server-listen-remove-callback.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-server-max-connections.js b/test/parallel/test-net-server-max-connections.js index ea89bd9d9b04a9..3b425ba3358fb5 100644 --- a/test/parallel/test-net-server-max-connections.js +++ b/test/parallel/test-net-server-max-connections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-server-pause-on-connect.js b/test/parallel/test-net-server-pause-on-connect.js index 0f47565f0098d0..db57114302f490 100644 --- a/test/parallel/test-net-server-pause-on-connect.js +++ b/test/parallel/test-net-server-pause-on-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-server-try-ports.js b/test/parallel/test-net-server-try-ports.js index 698cbcfa23e7c6..65cd5887a1356d 100644 --- a/test/parallel/test-net-server-try-ports.js +++ b/test/parallel/test-net-server-try-ports.js @@ -1,3 +1,4 @@ +'use strict'; // This tests binds to one port, then attempts to start a server on that // port. It should be EADDRINUSE but be able to then bind to another port. var common = require('../common'); diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js index 3a5092b92e0b8f..a071b625ef26d7 100644 --- a/test/parallel/test-net-server-unref-persistent.js +++ b/test/parallel/test-net-server-unref-persistent.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-server-unref.js b/test/parallel/test-net-server-unref.js index 2365864d6b41f3..98e95d6f105a84 100644 --- a/test/parallel/test-net-server-unref.js +++ b/test/parallel/test-net-server-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-net-settimeout.js b/test/parallel/test-net-settimeout.js index 28943a1ef0c96b..61c0a90341716e 100644 --- a/test/parallel/test-net-settimeout.js +++ b/test/parallel/test-net-settimeout.js @@ -1,3 +1,4 @@ +'use strict'; // This example sets a timeout then immediately attempts to disable the timeout // https://github.com/joyent/node/pull/2245 diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js index 2782048bd521c7..f23a70abb2c9a0 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-socket-timeout-unref.js b/test/parallel/test-net-socket-timeout-unref.js index 16bdcecaf17e78..c7e651afef015f 100644 --- a/test/parallel/test-net-socket-timeout-unref.js +++ b/test/parallel/test-net-socket-timeout-unref.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); -var server = net.createServer(function (c) { +var server = net.createServer(function(c) { c.write('hello'); c.unref(); }); @@ -11,9 +12,9 @@ server.unref(); var timedout = false; -[8, 5, 3, 6, 2, 4].forEach(function (T) { +[8, 5, 3, 6, 2, 4].forEach(function(T) { var socket = net.createConnection(common.PORT, 'localhost'); - socket.setTimeout(T * 1000, function () { + socket.setTimeout(T * 1000, function() { console.log(process._getActiveHandles()); timedout = true; socket.destroy(); @@ -21,6 +22,7 @@ var timedout = false; socket.unref(); }); -process.on('exit', function () { - assert.strictEqual(timedout, false, 'Socket timeout should not hold loop open'); +process.on('exit', function() { + assert.strictEqual(timedout, false, + 'Socket timeout should not hold loop open'); }); diff --git a/test/parallel/test-net-socket-timeout.js b/test/parallel/test-net-socket-timeout.js index f4038298763e8d..5ab11909b4c306 100644 --- a/test/parallel/test-net-socket-timeout.js +++ b/test/parallel/test-net-socket-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/parallel/test-net-stream.js b/test/parallel/test-net-stream.js index 8f7efd45f6d18d..151b1b178f9adc 100644 --- a/test/parallel/test-net-stream.js +++ b/test/parallel/test-net-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -29,7 +30,7 @@ var server = net.createServer(function(socket) { socket.destroy(); }).on('close', function() { server.close(); - }) + }); for (var i = 0; i < N; ++i) { socket.write(buf, function() { }); diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js index aaec89874674f3..b9516b839263cf 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-write-connect-write.js b/test/parallel/test-net-write-connect-write.js index fbf6b51e6a1f5c..17b1b576d188be 100644 --- a/test/parallel/test-net-write-connect-write.js +++ b/test/parallel/test-net-write-connect-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 0b1cf4f5b2c9a5..4b8163984f556a 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/parallel/test-next-tick-doesnt-hang.js b/test/parallel/test-next-tick-doesnt-hang.js index 7364b2f974d128..5e63463d4d1f94 100644 --- a/test/parallel/test-next-tick-doesnt-hang.js +++ b/test/parallel/test-next-tick-doesnt-hang.js @@ -1,3 +1,4 @@ +'use strict'; /* * This test verifies that having a single nextTick statement and nothing else * does not hang the event loop. If this test times out it has failed. diff --git a/test/parallel/test-next-tick-domain.js b/test/parallel/test-next-tick-domain.js index b07d741f65264f..4d53bba6c4f5cc 100644 --- a/test/parallel/test-next-tick-domain.js +++ b/test/parallel/test-next-tick-domain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -5,4 +6,5 @@ var origNextTick = process.nextTick; require('domain'); -assert.strictEqual(origNextTick, process.nextTick, 'Requiring domain should not change nextTick'); +assert.strictEqual(origNextTick, process.nextTick, + 'Requiring domain should not change nextTick'); diff --git a/test/parallel/test-next-tick-errors.js b/test/parallel/test-next-tick-errors.js index c2e635d5c5bd5c..eccd7a43a0825f 100644 --- a/test/parallel/test-next-tick-errors.js +++ b/test/parallel/test-next-tick-errors.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-next-tick-intentional-starvation.js b/test/parallel/test-next-tick-intentional-starvation.js index 5c8b414dcfead9..d4a8a1b7481329 100644 --- a/test/parallel/test-next-tick-intentional-starvation.js +++ b/test/parallel/test-next-tick-intentional-starvation.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-next-tick-ordering.js b/test/parallel/test-next-tick-ordering.js index 4340736aefec35..c2b936a1061d52 100644 --- a/test/parallel/test-next-tick-ordering.js +++ b/test/parallel/test-next-tick-ordering.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var i; diff --git a/test/parallel/test-next-tick-ordering2.js b/test/parallel/test-next-tick-ordering2.js index 69d4897fdbf9d2..4252d623679f65 100644 --- a/test/parallel/test-next-tick-ordering2.js +++ b/test/parallel/test-next-tick-ordering2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 1081a96fa2e35d..54e7b88cf022ca 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js index ae57353435333a..2cbc851015429e 100644 --- a/test/parallel/test-os.js +++ b/test/parallel/test-os.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-path-makelong.js b/test/parallel/test-path-makelong.js index 51d6404c4d4385..b9cc116a5ed90e 100644 --- a/test/parallel/test-path-makelong.js +++ b/test/parallel/test-path-makelong.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var path = require('path'); var common = require('../common'); diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index d31dc995720030..37f37fc9b57c17 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var path = require('path'); @@ -30,18 +31,30 @@ var unixPaths = [ ]; var errors = [ - {method: 'parse', input: [null], message: /Path must be a string. Received null/}, - {method: 'parse', input: [{}], message: /Path must be a string. Received {}/}, - {method: 'parse', input: [true], message: /Path must be a string. Received true/}, - {method: 'parse', input: [1], message: /Path must be a string. Received 1/}, - {method: 'parse', input: [], message: /Path must be a string. Received undefined/}, - // {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger! - {method: 'format', input: [null], message: /Parameter 'pathObject' must be an object, not/}, - {method: 'format', input: [''], message: /Parameter 'pathObject' must be an object, not string/}, - {method: 'format', input: [true], message: /Parameter 'pathObject' must be an object, not boolean/}, - {method: 'format', input: [1], message: /Parameter 'pathObject' must be an object, not number/}, - {method: 'format', input: [{root: true}], message: /'pathObject.root' must be a string or undefined, not boolean/}, - {method: 'format', input: [{root: 12}], message: /'pathObject.root' must be a string or undefined, not number/}, + {method: 'parse', input: [null], + message: /Path must be a string. Received null/}, + {method: 'parse', input: [{}], + message: /Path must be a string. Received {}/}, + {method: 'parse', input: [true], + message: /Path must be a string. Received true/}, + {method: 'parse', input: [1], + message: /Path must be a string. Received 1/}, + {method: 'parse', input: [], + message: /Path must be a string. Received undefined/}, + // {method: 'parse', input: [''], + // message: /Invalid path/}, // omitted because it's hard to trigger! + {method: 'format', input: [null], + message: /Parameter 'pathObject' must be an object, not/}, + {method: 'format', input: [''], + message: /Parameter 'pathObject' must be an object, not string/}, + {method: 'format', input: [true], + message: /Parameter 'pathObject' must be an object, not boolean/}, + {method: 'format', input: [1], + message: /Parameter 'pathObject' must be an object, not number/}, + {method: 'format', input: [{root: true}], + message: /'pathObject.root' must be a string or undefined, not boolean/}, + {method: 'format', input: [{root: 12}], + message: /'pathObject.root' must be a string or undefined, not number/}, ]; check(path.win32, winPaths); diff --git a/test/parallel/test-path.js b/test/parallel/test-path.js index e0e9c5d5671e4e..b1209d762a53d3 100644 --- a/test/parallel/test-path.js +++ b/test/parallel/test-path.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-pipe-file-to-http.js b/test/parallel/test-pipe-file-to-http.js index 01c23cb418e426..12ce742c905bba 100644 --- a/test/parallel/test-pipe-file-to-http.js +++ b/test/parallel/test-pipe-file-to-http.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-pipe-return-val.js b/test/parallel/test-pipe-return-val.js index 6a333584f8f315..718d052cd24c27 100644 --- a/test/parallel/test-pipe-return-val.js +++ b/test/parallel/test-pipe-return-val.js @@ -1,3 +1,4 @@ +'use strict'; // This test ensures SourceStream.pipe(DestStream) returns DestStream var common = require('../common'); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index 643edfb1d970cc..08657bbfb63a5e 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), path = require('path'), @@ -12,15 +13,15 @@ var preloadOption = function(preloads) { option += '-r ' + preload + ' '; }); return option; -} +}; var fixture = function(name) { return path.join(__dirname, '../fixtures/' + name); -} +}; var fixtureA = fixture('printA.js'); var fixtureB = fixture('printB.js'); -var fixtureC = fixture('printC.js') +var fixtureC = fixture('printC.js'); var fixtureThrows = fixture('throws_error4.js'); // test preloading a single module works @@ -80,3 +81,15 @@ child_process.exec(nodeBinary + ' ' if (err) throw err; assert.ok(/worker terminated with code 43/.test(stdout)); }); + +// https://github.com/iojs/io.js/issues/1691 +var originalCwd = process.cwd(); +process.chdir(path.join(__dirname, '../fixtures/')); +child_process.exec(nodeBinary + ' ' + + '--expose_debug_as=v8debug ' + + '--require ' + fixture('cluster-preload.js') + ' ' + + 'cluster-preload-test.js', + function(err, stdout, stderr) { + if (err) throw err; + assert.ok(/worker terminated with code 43/.test(stdout)); + }); diff --git a/test/parallel/test-process-argv-0.js b/test/parallel/test-process-argv-0.js index daf8cb60ebff0d..4bdb7ac3e71971 100644 --- a/test/parallel/test-process-argv-0.js +++ b/test/parallel/test-process-argv-0.js @@ -1,3 +1,4 @@ +'use strict'; var util = require('util'); var path = require('path'); var assert = require('assert'); @@ -7,8 +8,8 @@ var common = require('../common'); console.error('argv=%j', process.argv); console.error('exec=%j', process.execPath); -if (process.argv[2] !== "child") { - var child = spawn('./iojs', [__filename, "child"], { +if (process.argv[2] !== 'child') { + var child = spawn('./iojs', [__filename, 'child'], { cwd: path.dirname(process.execPath) }); @@ -20,7 +21,7 @@ if (process.argv[2] !== "child") { child.stderr.on('data', function(chunk) { childErr += chunk; }); - child.on('exit', function () { + child.on('exit', function() { console.error('CHILD: %s', childErr.trim().split('\n').join('\nCHILD: ')); assert.equal(childArgv0, process.execPath); }); diff --git a/test/parallel/test-process-before-exit.js b/test/parallel/test-process-before-exit.js index 48639c249ddec1..eff96da98e4729 100644 --- a/test/parallel/test-process-before-exit.js +++ b/test/parallel/test-process-before-exit.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-process-binding.js b/test/parallel/test-process-binding.js index c803a8083f22b4..dad2816d40c185 100644 --- a/test/parallel/test-process-binding.js +++ b/test/parallel/test-process-binding.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); assert.throws( @@ -7,10 +8,10 @@ assert.throws( /No such module: test/ ); -assert.doesNotThrow(function () { +assert.doesNotThrow(function() { process.binding('buffer'); }, function(err) { if ( (err instanceof Error) ) { return true; } -}, "unexpected error"); +}, 'unexpected error'); diff --git a/test/parallel/test-process-config.js b/test/parallel/test-process-config.js index d9260ca94d6ff3..4fc3bcaa98afc8 100644 --- a/test/parallel/test-process-config.js +++ b/test/parallel/test-process-config.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); diff --git a/test/parallel/test-process-env.js b/test/parallel/test-process-env.js index f3e2957ba621a7..7e927d09bae668 100644 --- a/test/parallel/test-process-env.js +++ b/test/parallel/test-process-env.js @@ -1,3 +1,6 @@ +'use strict'; +/* eslint-disable max-len */ + // first things first, set the timezone; see tzset(3) process.env.TZ = 'Europe/Amsterdam'; diff --git a/test/parallel/test-process-exec-argv.js b/test/parallel/test-process-exec-argv.js index 7344000739576e..59c4264ee3c8b7 100644 --- a/test/parallel/test-process-exec-argv.js +++ b/test/parallel/test-process-exec-argv.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var spawn = require('child_process').spawn; @@ -9,11 +10,11 @@ if (process.argv[2] === 'child') { var child = spawn(process.execPath, execArgv.concat(args)); var out = ''; - child.stdout.on('data', function (chunk) { + child.stdout.on('data', function(chunk) { out += chunk; }); - child.on('exit', function () { + child.on('exit', function() { assert.deepEqual(JSON.parse(out), execArgv); }); } diff --git a/test/parallel/test-process-exit-code.js b/test/parallel/test-process-exit-code.js index 610cf662987850..fea8c2d4fcdc5d 100644 --- a/test/parallel/test-process-exit-code.js +++ b/test/parallel/test-process-exit-code.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-process-exit-from-before-exit.js b/test/parallel/test-process-exit-from-before-exit.js index e222f35245fb7d..30d358cb76da9d 100644 --- a/test/parallel/test-process-exit-from-before-exit.js +++ b/test/parallel/test-process-exit-from-before-exit.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-process-exit-recursive.js b/test/parallel/test-process-exit-recursive.js index a326ec7f630e8c..c1ee13370b26ca 100644 --- a/test/parallel/test-process-exit-recursive.js +++ b/test/parallel/test-process-exit-recursive.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); // recursively calling .exit() should not overflow the call stack diff --git a/test/parallel/test-process-exit.js b/test/parallel/test-process-exit.js index 58d7a276996c3c..999eefc1eff518 100644 --- a/test/parallel/test-process-exit.js +++ b/test/parallel/test-process-exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-process-getgroups.js b/test/parallel/test-process-getgroups.js index f7c80ca6e02003..1cb5f38c1db203 100644 --- a/test/parallel/test-process-getgroups.js +++ b/test/parallel/test-process-getgroups.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/parallel/test-process-hrtime.js b/test/parallel/test-process-hrtime.js index c845f919bb2efd..0e2c5b110e9292 100644 --- a/test/parallel/test-process-hrtime.js +++ b/test/parallel/test-process-hrtime.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -18,7 +19,7 @@ assert.throws(function() { function validateTuple(tuple) { assert(Array.isArray(tuple)); assert.equal(2, tuple.length); - tuple.forEach(function (v) { + tuple.forEach(function(v) { assert.equal('number', typeof v); assert(isFinite(v)); }); diff --git a/test/parallel/test-process-kill-null.js b/test/parallel/test-process-kill-null.js index 77e2a8bb5ee5cb..65dab752f12e6d 100644 --- a/test/parallel/test-process-kill-null.js +++ b/test/parallel/test-process-kill-null.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js index 22ec5a68145961..f193e979166da7 100644 --- a/test/parallel/test-process-kill-pid.js +++ b/test/parallel/test-process-kill-pid.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -20,8 +21,8 @@ assert.throws(function() { process.kill('SIGTERM'); }, TypeError); assert.throws(function() { process.kill(null); }, TypeError); assert.throws(function() { process.kill(undefined); }, TypeError); assert.throws(function() { process.kill(+'not a number'); }, TypeError); -assert.throws(function() { process.kill(1/0); }, TypeError); -assert.throws(function() { process.kill(-1/0); }, TypeError); +assert.throws(function() { process.kill(1 / 0); }, TypeError); +assert.throws(function() { process.kill(-1 / 0); }, TypeError); // Test kill argument processing in valid cases. // diff --git a/test/parallel/test-process-next-tick.js b/test/parallel/test-process-next-tick.js index 3b2d37ef68a3be..e7b5f8f3fe886e 100644 --- a/test/parallel/test-process-next-tick.js +++ b/test/parallel/test-process-next-tick.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var N = 2; diff --git a/test/parallel/test-process-raw-debug.js b/test/parallel/test-process-raw-debug.js index 2264e59937517b..f849457d643894 100644 --- a/test/parallel/test-process-raw-debug.js +++ b/test/parallel/test-process-raw-debug.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-process-remove-all-signal-listeners.js b/test/parallel/test-process-remove-all-signal-listeners.js index e5dd5a13a16fca..408f6596c4419e 100644 --- a/test/parallel/test-process-remove-all-signal-listeners.js +++ b/test/parallel/test-process-remove-all-signal-listeners.js @@ -1,3 +1,4 @@ +'use strict'; if (process.platform === 'win32') { // Win32 doesn't have signals, just a kindof emulation, insufficient // for this test to apply. diff --git a/test/parallel/test-process-versions.js b/test/parallel/test-process-versions.js index c3159789cefeae..637ada7fa8e349 100644 --- a/test/parallel/test-process-versions.js +++ b/test/parallel/test-process-versions.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-process-wrap.js b/test/parallel/test-process-wrap.js index f3d903adb11448..bf3dfe4e8b1651 100644 --- a/test/parallel/test-process-wrap.js +++ b/test/parallel/test-process-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Process = process.binding('process_wrap').Process; diff --git a/test/parallel/test-promises-unhandled-rejections.js b/test/parallel/test-promises-unhandled-rejections.js index 997d147a6dcc34..9a186de8dfec79 100644 --- a/test/parallel/test-promises-unhandled-rejections.js +++ b/test/parallel/test-promises-unhandled-rejections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var domain = require('domain'); @@ -105,7 +106,8 @@ function onUnhandledFail(done) { }, 10); } -asyncTest('synchronously rejected promise should trigger unhandledRejection', function(done) { +asyncTest('synchronously rejected promise should trigger' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -113,7 +115,8 @@ asyncTest('synchronously rejected promise should trigger unhandledRejection', fu Promise.reject(e); }); -asyncTest('synchronously rejected promise should trigger unhandledRejection', function(done) { +asyncTest('synchronously rejected promise should trigger' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -123,7 +126,8 @@ asyncTest('synchronously rejected promise should trigger unhandledRejection', fu }); }); -asyncTest('Promise rejected after setImmediate should trigger unhandledRejection', function(done) { +asyncTest('Promise rejected after setImmediate should trigger' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -135,7 +139,8 @@ asyncTest('Promise rejected after setImmediate should trigger unhandledRejection }); }); -asyncTest('Promise rejected after setTimeout(,1) should trigger unhandled rejection', function(done) { +asyncTest('Promise rejected after setTimeout(,1) should trigger' + + ' unhandled rejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -147,7 +152,8 @@ asyncTest('Promise rejected after setTimeout(,1) should trigger unhandled reject }); }); -asyncTest('Catching a promise rejection after setImmediate is not soon enough to stop unhandledRejection', function(done) { +asyncTest('Catching a promise rejection after setImmediate is not' + + ' soon enough to stop unhandledRejection', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -155,14 +161,15 @@ asyncTest('Catching a promise rejection after setImmediate is not soon enough to var _reject; var promise = new Promise(function(_, reject) { _reject = reject; - }) + }); _reject(e); setImmediate(function() { - promise.then(assert.fail, function(){}); + promise.then(assert.fail, function() {}); }); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown error should hit unhandledRejection', function(done) { +asyncTest('When re-throwing new errors in a promise catch, only the' + + ' re-thrown error should hit unhandledRejection', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -175,7 +182,8 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown er }); }); -asyncTest('Test params of unhandledRejection for a synchronously-rejected promise', function(done) { +asyncTest('Test params of unhandledRejection for a synchronously-rejected' + + 'promise', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -185,7 +193,9 @@ asyncTest('Test params of unhandledRejection for a synchronously-rejected promis var promise = Promise.reject(e); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown error should hit unhandledRejection: original promise rejected async with setTimeout(,1)', function(done) { +asyncTest('When re-throwing new errors in a promise catch, only the ' + + 're-thrown error should hit unhandledRejection: original promise' + + ' rejected async with setTimeout(,1)', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -202,7 +212,9 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown er }); }); -asyncTest('When re-throwing new errors in a promise catch, only the re-thrown error should hit unhandledRejection: promise catch attached a process.nextTick after rejection', function(done) { +asyncTest('When re-throwing new errors in a promise catch, only the re-thrown' + + ' error should hit unhandledRejection: promise catch attached a' + + ' process.nextTick after rejection', function(done) { var e = new Error(); var e2 = new Error(); onUnhandledSucceed(done, function(reason, promise) { @@ -223,42 +235,50 @@ asyncTest('When re-throwing new errors in a promise catch, only the re-thrown er var promise2; }); -asyncTest('unhandledRejection should not be triggered if a promise catch is attached synchronously upon the promise\'s creation', function(done) { +asyncTest('unhandledRejection should not be triggered if a promise catch is' + + ' attached synchronously upon the promise\'s creation', + function(done) { var e = new Error(); onUnhandledFail(done); - Promise.reject(e).then(assert.fail, function(){}); + Promise.reject(e).then(assert.fail, function() {}); }); -asyncTest('unhandledRejection should not be triggered if a promise catch is attached synchronously upon the promise\'s creation', function(done) { +asyncTest('unhandledRejection should not be triggered if a promise catch is' + + ' attached synchronously upon the promise\'s creation', + function(done) { var e = new Error(); onUnhandledFail(done); new Promise(function(_, reject) { reject(e); - }).then(assert.fail, function(){}); + }).then(assert.fail, function() {}); }); -asyncTest('Attaching a promise catch in a process.nextTick is soon enough to prevent unhandledRejection', function(done) { +asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + + ' prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); var promise = Promise.reject(e); process.nextTick(function() { - promise.then(assert.fail, function(){}); + promise.then(assert.fail, function() {}); }); }); -asyncTest('Attaching a promise catch in a process.nextTick is soon enough to prevent unhandledRejection', function(done) { +asyncTest('Attaching a promise catch in a process.nextTick is soon enough to' + + ' prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); var promise = new Promise(function(_, reject) { reject(e); }); process.nextTick(function() { - promise.then(assert.fail, function(){}); + promise.then(assert.fail, function() {}); }); }); // State adapation tests -asyncTest('catching a promise which is asynchronously rejected (via resolution to an asynchronously-rejected promise) prevents unhandledRejection', function(done) { +asyncTest('catching a promise which is asynchronously rejected (via' + + 'resolution to an asynchronously-rejected promise) prevents' + + ' unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { @@ -272,7 +292,8 @@ asyncTest('catching a promise which is asynchronously rejected (via resolution t }); }); -asyncTest('Catching a rejected promise derived from throwing in a fulfillment handler prevents unhandledRejection', function(done) { +asyncTest('Catching a rejected promise derived from throwing in a' + + ' fulfillment handler prevents unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { @@ -282,7 +303,9 @@ asyncTest('Catching a rejected promise derived from throwing in a fulfillment ha }); }); -asyncTest('Catching a rejected promise derived from returning a synchronously-rejected promise in a fulfillment handler prevents unhandledRejection', function(done) { +asyncTest('Catching a rejected promise derived from returning a' + + ' synchronously-rejected promise in a fulfillment handler' + + ' prevents unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.resolve().then(function() { @@ -292,7 +315,9 @@ asyncTest('Catching a rejected promise derived from returning a synchronously-re }); }); -asyncTest('A rejected promise derived from returning an asynchronously-rejected promise in a fulfillment handler does trigger unhandledRejection', function(done) { +asyncTest('A rejected promise derived from returning an' + + ' asynchronously-rejected promise in a fulfillment handler' + + ' does trigger unhandledRejection', function(done) { var e = new Error(); var _promise; onUnhandledSucceed(done, function(reason, promise) { @@ -308,7 +333,8 @@ asyncTest('A rejected promise derived from returning an asynchronously-rejected }); }); -asyncTest('A rejected promise derived from throwing in a fulfillment handler does trigger unhandledRejection', function(done) { +asyncTest('A rejected promise derived from throwing in a fulfillment handler' + + ' does trigger unhandledRejection', function(done) { var e = new Error(); var _promise; onUnhandledSucceed(done, function(reason, promise) { @@ -320,7 +346,9 @@ asyncTest('A rejected promise derived from throwing in a fulfillment handler doe }); }); -asyncTest('A rejected promise derived from returning a synchronously-rejected promise in a fulfillment handler does trigger unhandledRejection', function(done) { +asyncTest('A rejected promise derived from returning a synchronously-rejected' + + ' promise in a fulfillment handler does trigger unhandledRejection', + function(done) { var e = new Error(); var _promise; onUnhandledSucceed(done, function(reason, promise) { @@ -333,13 +361,16 @@ asyncTest('A rejected promise derived from returning a synchronously-rejected pr }); // Combinations with Promise.all -asyncTest('Catching the Promise.all() of a collection that includes a rejected promise prevents unhandledRejection', function(done) { +asyncTest('Catching the Promise.all() of a collection that includes a' + + 'rejected promise prevents unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); Promise.all([Promise.reject(e)]).then(assert.fail, function() {}); }); -asyncTest('Catching the Promise.all() of a collection that includes a nextTick-async rejected promise prevents unhandledRejection', function(done) { +asyncTest('Catching the Promise.all() of a collection that includes a ' + + 'nextTick-async rejected promise prevents unhandledRejection', + function(done) { var e = new Error(); onUnhandledFail(done); var p = new Promise(function(_, reject) { @@ -353,7 +384,9 @@ asyncTest('Catching the Promise.all() of a collection that includes a nextTick-a }); }); -asyncTest('Failing to catch the Promise.all() of a collection that includes a rejected promise triggers unhandledRejection for the returned promise, not the passed promise', function(done) { +asyncTest('Failing to catch the Promise.all() of a collection that includes' + + ' a rejected promise triggers unhandledRejection for the returned' + + ' promise, not the passed promise', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -362,7 +395,8 @@ asyncTest('Failing to catch the Promise.all() of a collection that includes a re var p = Promise.all([Promise.reject(e)]); }); -asyncTest('Waiting setTimeout(, 10) to catch a promise causes an unhandledRejection + rejectionHandled pair', function(done) { +asyncTest('Waiting setTimeout(, 10) to catch a promise causes an' + + ' unhandledRejection + rejectionHandled pair', function(done) { clean(); var unhandledPromises = []; var e = new Error(); @@ -387,7 +421,9 @@ asyncTest('Waiting setTimeout(, 10) to catch a promise causes an unhandledReject }, 10); }); -asyncTest('Waiting for some combination of process.nextTick + promise microtasks to attach a catch handler is still soon enough to prevent unhandledRejection', function(done) { +asyncTest('Waiting for some combination of process.nextTick + promise' + + ' microtasks to attach a catch handler is still soon enough to' + + ' prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); @@ -404,7 +440,9 @@ asyncTest('Waiting for some combination of process.nextTick + promise microtasks }); }); -asyncTest('Waiting for some combination of process.nextTick + promise microtasks to attach a catch handler is still soon enough to prevent unhandledRejection: inside setImmediate', function(done) { +asyncTest('Waiting for some combination of process.nextTick + promise' + + ' microtasks to attach a catch handler is still soon enough to ' + + 'prevent unhandledRejection: inside setImmediate', function(done) { var e = new Error(); onUnhandledFail(done); @@ -422,7 +460,9 @@ asyncTest('Waiting for some combination of process.nextTick + promise microtasks }); }); -asyncTest('Waiting for some combination of process.nextTick + promise microtasks to attach a catch handler is still soon enough to prevent unhandledRejection: inside setTimeout', function(done) { +asyncTest('Waiting for some combination of process.nextTick + promise ' + + 'microtasks to attach a catch handler is still soon enough to ' + + 'prevent unhandledRejection: inside setTimeout', function(done) { var e = new Error(); onUnhandledFail(done); @@ -440,7 +480,9 @@ asyncTest('Waiting for some combination of process.nextTick + promise microtasks }, 0); }); -asyncTest('Waiting for some combination of promise microtasks + process.nextTick to attach a catch handler is still soon enough to prevent unhandledRejection', function(done) { +asyncTest('Waiting for some combination of promise microtasks + ' + + 'process.nextTick to attach a catch handler is still soon enough' + + ' to prevent unhandledRejection', function(done) { var e = new Error(); onUnhandledFail(done); @@ -457,7 +499,10 @@ asyncTest('Waiting for some combination of promise microtasks + process.nextTick }); }); -asyncTest('Waiting for some combination of promise microtasks + process.nextTick to attach a catch handler is still soon enough to prevent unhandledRejection: inside setImmediate', function(done) { +asyncTest('Waiting for some combination of promise microtasks +' + + ' process.nextTick to attach a catch handler is still soon enough' + + ' to prevent unhandledRejection: inside setImmediate', + function(done) { var e = new Error(); onUnhandledFail(done); @@ -475,7 +520,9 @@ asyncTest('Waiting for some combination of promise microtasks + process.nextTick }); }); -asyncTest('Waiting for some combination of promise microtasks + process.nextTick to attach a catch handler is still soon enough to prevent unhandledRejection: inside setTimeout', function(done) { +asyncTest('Waiting for some combination of promise microtasks +' + + ' process.nextTick to attach a catch handler is still soon enough' + + ' to prevent unhandledRejection: inside setTimeout', function(done) { var e = new Error(); onUnhandledFail(done); @@ -493,7 +540,9 @@ asyncTest('Waiting for some combination of promise microtasks + process.nextTick }, 0); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch handler; unhandledRejection will be triggered in that case. (setImmediate before promise creation/rejection)', function(done) { +asyncTest('setImmediate + promise microtasks is too late to attach a catch' + + ' handler; unhandledRejection will be triggered in that case.' + + ' (setImmediate before promise creation/rejection)', function(done) { var e = new Error(); onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(e, reason); @@ -501,23 +550,25 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch handl }); var p = Promise.reject(e); setImmediate(function() { - Promise.resolve().then(function () { - p.catch(function(){}); + Promise.resolve().then(function() { + p.catch(function() {}); }); }); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch handler; unhandledRejection will be triggered in that case (setImmediate before promise creation/rejection)', function(done) { +asyncTest('setImmediate + promise microtasks is too late to attach a catch' + + ' handler; unhandledRejection will be triggered in that case' + + ' (setImmediate before promise creation/rejection)', function(done) { onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(undefined, reason); assert.strictEqual(p, promise); }); setImmediate(function() { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - p.catch(function(){}); + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + p.catch(function() {}); }); }); }); @@ -526,18 +577,20 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch handl var p = Promise.reject(); }); -asyncTest('setImmediate + promise microtasks is too late to attach a catch handler; unhandledRejection will be triggered in that case (setImmediate after promise creation/rejection)', function(done) { +asyncTest('setImmediate + promise microtasks is too late to attach a catch' + + ' handler; unhandledRejection will be triggered in that case' + + ' (setImmediate after promise creation/rejection)', function(done) { onUnhandledSucceed(done, function(reason, promise) { assert.strictEqual(undefined, reason); assert.strictEqual(p, promise); }); var p = Promise.reject(); setImmediate(function() { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - Promise.resolve().then(function () { - p.catch(function(){}); + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + Promise.resolve().then(function() { + p.catch(function() {}); }); }); }); @@ -545,7 +598,9 @@ asyncTest('setImmediate + promise microtasks is too late to attach a catch handl }); }); -asyncTest('Promise unhandledRejection handler does not interfere with domain error handlers being given exceptions thrown from nextTick.', function(done) { +asyncTest('Promise unhandledRejection handler does not interfere with domain' + + ' error handlers being given exceptions thrown from nextTick.', + function(done) { var d = domain.create(); var domainReceivedError; d.on('error', function(e) { @@ -566,7 +621,8 @@ asyncTest('Promise unhandledRejection handler does not interfere with domain err }); }); -asyncTest('nextTick is immediately scheduled when called inside an event handler', function(done) { +asyncTest('nextTick is immediately scheduled when called inside an event' + + ' handler', function(done) { clean(); var e = new Error('error'); process.on('unhandledRejection', function(reason, promise) { @@ -576,21 +632,23 @@ asyncTest('nextTick is immediately scheduled when called inside an event handler }); setTimeout(function() { order.push(2); - assert.deepEqual([1,2], order); + assert.deepEqual([1, 2], order); done(); }, 1); }); Promise.reject(e); }); -asyncTest('Throwing an error inside a rejectionHandled handler goes to unhandledException, and does not cause .catch() to throw an exception', function(done) { +asyncTest('Throwing an error inside a rejectionHandled handler goes to' + + ' unhandledException, and does not cause .catch() to throw an' + + 'exception', function(done) { clean(); var e = new Error(); var e2 = new Error(); var tearDownException = setupException(function(err) { - assert.equal(e2, err); - tearDownException(); - done(); + assert.equal(e2, err); + tearDownException(); + done(); }); process.on('rejectionHandled', function() { throw e2; @@ -598,7 +656,7 @@ asyncTest('Throwing an error inside a rejectionHandled handler goes to unhandled var p = Promise.reject(e); setTimeout(function() { try { - p.catch(function(){}); + p.catch(function() {}); } catch (e) { done(new Error('fail')); } diff --git a/test/parallel/test-punycode.js b/test/parallel/test-punycode.js index 4ac953849c0553..179bca51ec2fe0 100644 --- a/test/parallel/test-punycode.js +++ b/test/parallel/test-punycode.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var punycode = require('punycode'); var assert = require('assert'); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 17fa6df9247747..66497ac2d3b6db 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -240,7 +241,7 @@ assert.equal( // test overriding .unescape var prevUnescape = qs.unescape; -qs.unescape = function (str) { +qs.unescape = function(str) { return str.replace(/o/g, '_'); }; assert.deepEqual(qs.parse('foo=bor'), {f__: 'b_r'}); diff --git a/test/parallel/test-readdouble.js b/test/parallel/test-readdouble.js index 6dfc4015492783..c0dab8956593fe 100644 --- a/test/parallel/test-readdouble.js +++ b/test/parallel/test-readdouble.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're reading in doubles correctly */ diff --git a/test/parallel/test-readfloat.js b/test/parallel/test-readfloat.js index 9b2fc612c73324..5572bbf18e291b 100644 --- a/test/parallel/test-readfloat.js +++ b/test/parallel/test-readfloat.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're reading in floats correctly */ diff --git a/test/parallel/test-readint.js b/test/parallel/test-readint.js index 208907d03ee153..233128d792d068 100644 --- a/test/parallel/test-readint.js +++ b/test/parallel/test-readint.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're reading in signed integers correctly */ diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index 69eb4bf51992cb..6ee9ad227896b1 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var readline = require('readline'); var EventEmitter = require('events').EventEmitter; @@ -98,7 +99,7 @@ function isWarned(emitter) { assert.equal(callCount, expectedLines.length - 1); rli.close(); - // sending multiple newlines at once that does not end with a new(empty) + // sending multiple newlines at once that does not end with a new(empty) // line and a `end` event fi = new FakeInput(); rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); @@ -110,7 +111,7 @@ function isWarned(emitter) { }); rli.on('close', function() { callCount++; - }) + }); fi.emit('data', expectedLines.join('\n')); fi.emit('end'); assert.equal(callCount, expectedLines.length); @@ -191,31 +192,6 @@ function isWarned(emitter) { assert.equal(callCount, 1); rli.close(); - // keypress - [ - ['a'], - ['\x1b'], - ['\x1b[31m'], - ['\x1b[31m', '\x1b[39m'], - ['\x1b[31m', 'a', '\x1b[39m', 'a'] - ].forEach(function (keypresses) { - fi = new FakeInput(); - callCount = 0; - var remainingKeypresses = keypresses.slice(); - function keypressListener (ch, key) { - callCount++; - if (ch) assert(!key.code); - assert.equal(key.sequence, remainingKeypresses.shift()); - }; - readline.emitKeypressEvents(fi); - fi.on('keypress', keypressListener); - fi.emit('data', keypresses.join('')); - assert.equal(callCount, keypresses.length); - assert.equal(remainingKeypresses.length, 0); - fi.removeListener('keypress', keypressListener); - fi.emit('data', ''); // removes listener - }); - // calling readline without `new` fi = new FakeInput(); rli = readline.Interface({ input: fi, output: fi, terminal: terminal }); @@ -274,10 +250,14 @@ function isWarned(emitter) { assert.equal(readline.getStringWidth('A\ud83c\ude00BC'), 5); // surrogate // check if vt control chars are stripped - assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> '); - assert.equal(readline.stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > '); - assert.equal(readline.stripVTControlCharacters('\u001b[31m\u001b[39m'), ''); - assert.equal(readline.stripVTControlCharacters('> '), '> '); + assert.equal(readline + .stripVTControlCharacters('\u001b[31m> \u001b[39m'), '> '); + assert.equal(readline + .stripVTControlCharacters('\u001b[31m> \u001b[39m> '), '> > '); + assert.equal(readline + .stripVTControlCharacters('\u001b[31m\u001b[39m'), ''); + assert.equal(readline + .stripVTControlCharacters('> '), '> '); assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m'), 2); assert.equal(readline.getStringWidth('\u001b[31m> \u001b[39m> '), 4); assert.equal(readline.getStringWidth('\u001b[31m\u001b[39m'), 0); @@ -286,7 +266,7 @@ function isWarned(emitter) { assert.deepEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); // check EventEmitter memory leak - for (var i=0; i<12; i++) { + for (var i = 0; i < 12; i++) { var rl = readline.createInterface({ input: process.stdin, output: process.stdout @@ -309,7 +289,7 @@ function isWarned(emitter) { assert.ok(called); assert.doesNotThrow(function() { - rli.setPrompt("ddd> "); + rli.setPrompt('ddd> '); }); assert.doesNotThrow(function() { @@ -321,10 +301,10 @@ function isWarned(emitter) { }); assert.doesNotThrow(function() { - rli.question("What do you think of node.js? ", function(answer) { - console.log("Thank you for your valuable feedback:", answer); + rli.question('What do you think of node.js? ', function(answer) { + console.log('Thank you for your valuable feedback:', answer); rli.close(); - }) + }); }); }); diff --git a/test/parallel/test-readline-keys.js b/test/parallel/test-readline-keys.js new file mode 100644 index 00000000000000..150273f7993963 --- /dev/null +++ b/test/parallel/test-readline-keys.js @@ -0,0 +1,151 @@ +'use strict'; +var EventEmitter = require('events').EventEmitter; +var PassThrough = require('stream').PassThrough; +var assert = require('assert'); +var inherits = require('util').inherits; +var extend = require('util')._extend; +var Interface = require('readline').Interface; + + +function FakeInput() { + PassThrough.call(this); +} +inherits(FakeInput, PassThrough); + + +var fi = new FakeInput(); +var fo = new FakeInput(); +var rli = new Interface({ input: fi, output: fo, terminal: true }); + +var keys = []; +fi.on('keypress', function(s, k) { + keys.push(k); +}); + + +function addTest(sequences, expectedKeys) { + if (!Array.isArray(sequences)) { + sequences = [ sequences ]; + } + + if (!Array.isArray(expectedKeys)) { + expectedKeys = [ expectedKeys ]; + } + + expectedKeys = expectedKeys.map(function(k) { + return k ? extend({ ctrl: false, meta: false, shift: false }, k) : k; + }); + + keys = []; + + sequences.forEach(function(sequence) { + fi.write(sequence); + }); + assert.deepStrictEqual(keys, expectedKeys); +} + +// regular alphanumerics +addTest('io.JS', [ + { name: 'i', sequence: 'i' }, + { name: 'o', sequence: 'o' }, + undefined, // emitted as `emit('keypress', '.', undefined)` + { name: 'j', sequence: 'J', shift: true }, + { name: 's', sequence: 'S', shift: true }, +]); + +// named characters +addTest('\n\r\t', [ + { name: 'enter', sequence: '\n' }, + { name: 'return', sequence: '\r' }, + { name: 'tab', sequence: '\t' }, +]); + +// space and backspace +addTest('\b\x7f\x1b\b\x1b\x7f \x1b ', [ + { name: 'backspace', sequence: '\b' }, + { name: 'backspace', sequence: '\x7f' }, + { name: 'backspace', sequence: '\x1b\b', meta: true }, + { name: 'backspace', sequence: '\x1b\x7f', meta: true }, + { name: 'space', sequence: ' ' }, + { name: 'space', sequence: '\x1b ', meta: true }, +]); + +// control keys +addTest('\x01\x0b\x10', [ + { name: 'a', sequence: '\x01', ctrl: true }, + { name: 'k', sequence: '\x0b', ctrl: true }, + { name: 'p', sequence: '\x10', ctrl: true }, +]); + +// alt keys +addTest('a\x1baA\x1bA', [ + { name: 'a', sequence: 'a' }, + { name: 'a', sequence: '\x1ba', meta: true }, + { name: 'a', sequence: 'A', shift: true }, + { name: 'a', sequence: '\x1bA', meta: true, shift: true }, +]); + +// xterm/gnome +addTest('\x1bOA\x1bOB', [ + { name: 'up', sequence: '\x1bOA', code: 'OA' }, + { name: 'down', sequence: '\x1bOB', code: 'OB' }, +]); + +// old xterm shift-arrows +addTest('\x1bO2A\x1bO2B', [ + { name: 'up', sequence: '\x1bO2A', code: 'OA', shift: true }, + { name: 'down', sequence: '\x1bO2B', code: 'OB', shift: true }, +]); + +// gnome terminal +addTest('\x1b[A\x1b[B\x1b[2A\x1b[2B', [ + { name: 'up', sequence: '\x1b[A', code: '[A' }, + { name: 'down', sequence: '\x1b[B', code: '[B' }, + { name: 'up', sequence: '\x1b[2A', code: '[A', shift: true }, + { name: 'down', sequence: '\x1b[2B', code: '[B', shift: true }, +]); + +// rxvt +addTest('\x1b[20~\x1b[2$\x1b[2^', [ + { name: 'f9', sequence: '\x1b[20~', code: '[20~' }, + { name: 'insert', sequence: '\x1b[2$', code: '[2$', shift: true }, + { name: 'insert', sequence: '\x1b[2^', code: '[2^', ctrl: true }, +]); + +// xterm + modifiers +addTest('\x1b[20;5~\x1b[6;5^', [ + { name: 'f9', sequence: '\x1b[20;5~', code: '[20~', ctrl: true }, + { name: 'pagedown', sequence: '\x1b[6;5^', code: '[6^', ctrl: true }, +]); + +addTest('\x1b[H\x1b[5H\x1b[1;5H', [ + { name: 'home', sequence: '\x1b[H', code: '[H' }, + { name: 'home', sequence: '\x1b[5H', code: '[H', ctrl: true }, + { name: 'home', sequence: '\x1b[1;5H', code: '[H', ctrl: true }, +]); + +// escape sequences broken into multiple data chunks +addTest('\x1b[D\x1b[C\x1b[D\x1b[C'.split(''), [ + { name: 'left', sequence: '\x1b[D', code: '[D' }, + { name: 'right', sequence: '\x1b[C', code: '[C' }, + { name: 'left', sequence: '\x1b[D', code: '[D' }, + { name: 'right', sequence: '\x1b[C', code: '[C' }, +]); + +// escape sequences mixed with regular ones +addTest('\x1b[DD\x1b[2DD\x1b[2^D', [ + { name: 'left', sequence: '\x1b[D', code: '[D' }, + { name: 'd', sequence: 'D', shift: true }, + { name: 'left', sequence: '\x1b[2D', code: '[D', shift: true }, + { name: 'd', sequence: 'D', shift: true }, + { name: 'insert', sequence: '\x1b[2^', code: '[2^', ctrl: true }, + { name: 'd', sequence: 'D', shift: true }, +]); + +// color sequences +addTest('\x1b[31ma\x1b[39ma', [ + { name: 'undefined', sequence: '\x1b[31m', code: '[31m' }, + { name: 'a', sequence: 'a' }, + { name: 'undefined', sequence: '\x1b[39m', code: '[39m' }, + { name: 'a', sequence: 'a' }, +]); diff --git a/test/parallel/test-readline-set-raw-mode.js b/test/parallel/test-readline-set-raw-mode.js index 622d64181fbfe1..f9d5111581fa90 100644 --- a/test/parallel/test-readline-set-raw-mode.js +++ b/test/parallel/test-readline-set-raw-mode.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var readline = require('readline'); var Stream = require('stream'); diff --git a/test/parallel/test-readuint.js b/test/parallel/test-readuint.js index 293cb554ce343f..b984541bfe9eb0 100644 --- a/test/parallel/test-readuint.js +++ b/test/parallel/test-readuint.js @@ -1,3 +1,4 @@ +'use strict'; /* * A battery of tests to help us read a series of uints */ diff --git a/test/parallel/test-regress-GH-4256.js b/test/parallel/test-regress-GH-4256.js index ead32446b7b59b..f512e613162522 100644 --- a/test/parallel/test-regress-GH-4256.js +++ b/test/parallel/test-regress-GH-4256.js @@ -1,4 +1,5 @@ +'use strict'; process.domain = null; -timer = setTimeout(function() { - console.log("this console.log statement should not make node crash"); +var timer = setTimeout(function() { + console.log('this console.log statement should not make node crash'); }, 1); diff --git a/test/parallel/test-regress-GH-5927.js b/test/parallel/test-regress-GH-5927.js index dee33d854abd9c..541820c7a214c8 100644 --- a/test/parallel/test-regress-GH-5927.js +++ b/test/parallel/test-regress-GH-5927.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var readline = require('readline'); @@ -10,12 +11,12 @@ var origPause = rl.pause; rl.pause = function() { hasPaused = true; origPause.apply(this, arguments); -} +}; var origSetRawMode = rl._setRawMode; rl._setRawMode = function(mode) { assert.ok(hasPaused); origSetRawMode.apply(this, arguments); -} +}; rl.close(); diff --git a/test/parallel/test-regress-GH-6235.js b/test/parallel/test-regress-GH-6235.js index f929282b16ab75..2f2f17d9698fc9 100644 --- a/test/parallel/test-regress-GH-6235.js +++ b/test/parallel/test-regress-GH-6235.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-regress-GH-7511.js b/test/parallel/test-regress-GH-7511.js index aa7a10c0474149..0e5c4ded011a43 100644 --- a/test/parallel/test-regress-GH-7511.js +++ b/test/parallel/test-regress-GH-7511.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), vm = require('vm'); diff --git a/test/parallel/test-regress-GH-897.js b/test/parallel/test-regress-GH-897.js index fae1bd4b5d2a72..4b7ba61f9ceca9 100644 --- a/test/parallel/test-regress-GH-897.js +++ b/test/parallel/test-regress-GH-897.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-regress-GH-io-1068.js b/test/parallel/test-regress-GH-io-1068.js index e769e6b81a880d..cc91fe28df3d3e 100644 --- a/test/parallel/test-regress-GH-io-1068.js +++ b/test/parallel/test-regress-GH-io-1068.js @@ -1 +1,2 @@ +'use strict'; process.stdin.emit('end'); diff --git a/test/parallel/test-regress-GH-node-9326.js b/test/parallel/test-regress-GH-node-9326.js index 15a2abbdc55af0..5dc73e044e560b 100644 --- a/test/parallel/test-regress-GH-node-9326.js +++ b/test/parallel/test-regress-GH-node-9326.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var child_process = require('child_process'); diff --git a/test/parallel/test-regression-object-prototype.js b/test/parallel/test-regression-object-prototype.js index 17fe1727d37070..040e718948a581 100644 --- a/test/parallel/test-regression-object-prototype.js +++ b/test/parallel/test-regression-object-prototype.js @@ -1,3 +1,4 @@ +'use strict'; //console.log('puts before'); Object.prototype.xadsadsdasasdxx = function() { diff --git a/test/parallel/test-repl-.save.load.js b/test/parallel/test-repl-.save.load.js index d1c0f13e92f851..cf3224ecaf55a3 100644 --- a/test/parallel/test-repl-.save.load.js +++ b/test/parallel/test-repl-.save.load.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var util = require('util'); var join = require('path').join; @@ -13,7 +14,7 @@ function ArrayStream() { data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; @@ -28,7 +29,7 @@ var testMe = repl.start('', putIn); var testFile = [ - 'var top = function () {', + 'var top = function() {', 'var inner = {one:1};' ]; var saveFileName = join(common.tmpDir, 'test.save.js'); diff --git a/test/parallel/test-repl-autolibs.js b/test/parallel/test-repl-autolibs.js index c7727f574a6ca5..4103a19243aec5 100644 --- a/test/parallel/test-repl-autolibs.js +++ b/test/parallel/test-repl-autolibs.js @@ -1,30 +1,31 @@ +'use strict'; var assert = require('assert'); var util = require('util'); var repl = require('repl'); // A stream to push an array into a REPL function ArrayStream() { - this.run = function (data) { + this.run = function(data) { var self = this; - data.forEach(function (line) { + data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; ArrayStream.prototype.writable = true; -ArrayStream.prototype.resume = function () {}; -ArrayStream.prototype.write = function () {}; +ArrayStream.prototype.resume = function() {}; +ArrayStream.prototype.write = function() {}; -var putIn = new ArrayStream; +var putIn = new ArrayStream(); var testMe = repl.start('', putIn, null, true); test1(); -function test1(){ +function test1() { var gotWrite = false; - putIn.write = function (data) { + putIn.write = function(data) { gotWrite = true; if (data.length) { @@ -40,7 +41,7 @@ function test1(){ assert(gotWrite); } -function test2(){ +function test2() { var gotWrite = false; putIn.write = function(data) { gotWrite = true; diff --git a/test/parallel/test-repl-console.js b/test/parallel/test-repl-console.js index 45dad0f390d00d..e66fcb1621adc5 100644 --- a/test/parallel/test-repl-console.js +++ b/test/parallel/test-repl-console.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), Stream = require('stream'), @@ -5,7 +6,7 @@ var common = require('../common'), // create a dummy stream that does nothing var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; +stream.write = stream.pause = stream.resume = function() {}; stream.readable = stream.writable = true; var r = repl.start({ diff --git a/test/parallel/test-repl-domain.js b/test/parallel/test-repl-domain.js index 929cb0ffd1e80f..7528f502878f63 100644 --- a/test/parallel/test-repl-domain.js +++ b/test/parallel/test-repl-domain.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); @@ -11,7 +12,7 @@ function ArrayStream() { data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; @@ -26,15 +27,15 @@ putIn.write = function(data) { // Don't use assert for this because the domain might catch it, and // give a false negative. Don't throw, just print and exit. if (data === 'OK\n') { - console.log('ok'); + console.log('ok'); } else { - console.error(data); - process.exit(1); + console.error(data); + process.exit(1); } }; putIn.run([ - 'require("domain").create().on("error", function () { console.log("OK") })' - + '.run(function () { throw new Error("threw") })' + 'require("domain").create().on("error", function() { console.log("OK") })' + + '.run(function() { throw new Error("threw") })' ]); diff --git a/test/parallel/test-repl-end-emits-exit.js b/test/parallel/test-repl-end-emits-exit.js index bcb13a14afd021..e4bc4da78c142d 100644 --- a/test/parallel/test-repl-end-emits-exit.js +++ b/test/parallel/test-repl-end-emits-exit.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), Stream = require('stream'), @@ -7,7 +8,7 @@ var common = require('../common'), // create a dummy stream that does nothing var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; +stream.write = stream.pause = stream.resume = function() {}; stream.readable = stream.writable = true; function testTerminalMode() { diff --git a/test/parallel/test-repl-harmony.js b/test/parallel/test-repl-harmony.js index 420b3163cce252..446aebe2d51c99 100644 --- a/test/parallel/test-repl-harmony.js +++ b/test/parallel/test-repl-harmony.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-repl-options.js b/test/parallel/test-repl-options.js index e58f459393ecba..0c5f997350265f 100644 --- a/test/parallel/test-repl-options.js +++ b/test/parallel/test-repl-options.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), Stream = require('stream'), @@ -7,7 +8,7 @@ common.globalCheck = false; // create a dummy stream that does nothing var stream = new Stream(); -stream.write = stream.pause = stream.resume = function(){}; +stream.write = stream.pause = stream.resume = function() {}; stream.readable = stream.writable = true; // 1, mostly defaults @@ -64,3 +65,17 @@ assert.equal(r2.rli.input, r2.inputStream); assert.equal(r2.rli.output, r2.outputStream); assert.equal(r2.rli.terminal, false); +<<<<<<< HEAD +======= +// testing out "magic" replMode +var r3 = repl.start({ + input: stream, + output: stream, + writer: writer, + replMode: repl.REPL_MODE_MAGIC, + historySize: 50 +}); + +assert.equal(r3.replMode, repl.REPL_MODE_MAGIC); +assert.equal(r3.historySize, 50); +>>>>>>> f29762f... test: enable linting for tests diff --git a/test/parallel/test-repl-require-cache.js b/test/parallel/test-repl-require-cache.js index 3ab3b7062c2603..d9b4d71d484640 100644 --- a/test/parallel/test-repl-require-cache.js +++ b/test/parallel/test-repl-require-cache.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), repl = require('repl'); diff --git a/test/parallel/test-repl-reset-event.js b/test/parallel/test-repl-reset-event.js index eee31e24bee5a0..e6157956d43a65 100644 --- a/test/parallel/test-repl-reset-event.js +++ b/test/parallel/test-repl-reset-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); common.globalCheck = false; @@ -7,7 +8,7 @@ var Stream = require('stream'); // create a dummy stream that does nothing var dummy = new Stream(); -dummy.write = dummy.pause = dummy.resume = function(){}; +dummy.write = dummy.pause = dummy.resume = function() {}; dummy.readable = dummy.writable = true; function testReset(cb) { @@ -20,7 +21,8 @@ function testReset(cb) { r.on('reset', function(context) { assert(!!context, 'REPL did not emit a context with reset event'); assert.equal(context, r.context, 'REPL emitted incorrect context'); - assert.equal(context.foo, undefined, 'REPL emitted the previous context, and is not using global as context'); + assert.equal(context.foo, undefined, 'REPL emitted the previous context' + + ', and is not using global as context'); context.foo = 42; cb(); }); @@ -35,7 +37,8 @@ function testResetGlobal(cb) { }); r.context.foo = 42; r.on('reset', function(context) { - assert.equal(context.foo, 42, '"foo" property is missing from REPL using global as context'); + assert.equal(context.foo, 42, + '"foo" property is missing from REPL using global as context'); cb(); }); r.resetContext(); diff --git a/test/parallel/test-repl-setprompt.js b/test/parallel/test-repl-setprompt.js index 56de10023f831f..b89dd6c928ab0a 100644 --- a/test/parallel/test-repl-setprompt.js +++ b/test/parallel/test-repl-setprompt.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), spawn = require('child_process').spawn, @@ -9,14 +10,14 @@ var args = [ 'var e = new (require("repl")).REPLServer("foo.. "); e.context.e = e;', ]; -var p = "bar.. "; +var p = 'bar.. '; var child = spawn(process.execPath, args); child.stdout.setEncoding('utf8'); var data = ''; -child.stdout.on('data', function(d) { data += d }); +child.stdout.on('data', function(d) { data += d; }); child.stdin.end(util.format("e.setPrompt('%s');%s", p, os.EOL)); diff --git a/test/parallel/test-repl-syntax-error-handling.js b/test/parallel/test-repl-syntax-error-handling.js index 79489628b588c7..66e8fb6b352c56 100644 --- a/test/parallel/test-repl-syntax-error-handling.js +++ b/test/parallel/test-repl-syntax-error-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-repl-tab-complete.js b/test/parallel/test-repl-tab-complete.js index c6a07f4017bef4..659c8046a98173 100644 --- a/test/parallel/test-repl-tab-complete.js +++ b/test/parallel/test-repl-tab-complete.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -11,7 +12,7 @@ function ArrayStream() { data.forEach(function(line) { self.emit('data', line + '\n'); }); - } + }; } util.inherits(ArrayStream, require('stream').Stream); ArrayStream.prototype.readable = true; @@ -48,7 +49,7 @@ putIn.run(['.clear']); // Tab Complete will not break in an ternary operator with () putIn.run([ - 'var inner = ( true ' , + 'var inner = ( true ', '?', '{one: 1} : ' ]); @@ -60,7 +61,7 @@ putIn.run(['.clear']); // Tab Complete will return a simple local variable putIn.run([ - 'var top = function () {', + 'var top = function() {', 'var inner = {one:1};' ]); testMe.complete('inner.o', function(error, data) { @@ -78,7 +79,7 @@ putIn.run(['.clear']); // Tab Complete will return a complex local variable putIn.run([ - 'var top = function () {', + 'var top = function() {', 'var inner = {', ' one:1', '};' @@ -92,7 +93,7 @@ putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the function // has parameters putIn.run([ - 'var top = function (one, two) {', + 'var top = function(one, two) {', 'var inner = {', ' one:1', '};' @@ -106,7 +107,7 @@ putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the // scope is nested inside an immediately executed function putIn.run([ - 'var top = function () {', + 'var top = function() {', '(function test () {', 'var inner = {', ' one:1', @@ -121,7 +122,7 @@ putIn.run(['.clear']); // currently does not work, but should not break note the inner function // def has the params and { on a separate line putIn.run([ - 'var top = function () {', + 'var top = function() {', 'r = function test (', ' one, two) {', 'var inner = {', @@ -136,7 +137,7 @@ putIn.run(['.clear']); // currently does not work, but should not break, not the { putIn.run([ - 'var top = function () {', + 'var top = function() {', 'r = function test ()', '{', 'var inner = {', @@ -151,7 +152,7 @@ putIn.run(['.clear']); // currently does not work, but should not break putIn.run([ - 'var top = function () {', + 'var top = function() {', 'r = function test (', ')', '{', @@ -181,7 +182,7 @@ var spaceTimeout = setTimeout(function() { }, 1000); testMe.complete(' ', function(error, data) { - assert.deepEqual(data, [[],undefined]); + assert.deepEqual(data, [[], undefined]); clearTimeout(spaceTimeout); }); diff --git a/test/parallel/test-repl-timeout-throw.js b/test/parallel/test-repl-timeout-throw.js index eea2bea3ac9389..6c540c9e3197de 100644 --- a/test/parallel/test-repl-timeout-throw.js +++ b/test/parallel/test-repl-timeout-throw.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); @@ -14,10 +15,12 @@ child.stdout.on('data', function(c) { stdout += c; }); -child.stdin.write = function(original) { return function(c) { - process.stderr.write(c); - return original.call(child.stdin, c); -}}(child.stdin.write); +child.stdin.write = function(original) { + return function(c) { + process.stderr.write(c); + return original.call(child.stdin, c); + }; +}(child.stdin.write); child.stdout.once('data', function() { child.stdin.write('var throws = 0;'); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index e1087a2e1daf8e..1bcc13e4d23ba8 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -1,3 +1,4 @@ +/* eslint-disable max-len, strict */ var common = require('../common'); var assert = require('assert'); @@ -172,7 +173,7 @@ function error_test() { { client: client_unix, send: '1 }', expect: '{ a: 1 }' }, // Multiline anonymous function with comment - { client: client_unix, send: '(function () {', + { client: client_unix, send: '(function() {', expect: prompt_multiline }, { client: client_unix, send: '// blah', expect: prompt_multiline }, @@ -183,7 +184,7 @@ function error_test() { // npm prompt error message { client: client_unix, send: 'npm install foobar', expect: expect_npm }, - { client: client_unix, send: '(function () {\n\nreturn 1;\n})()', + { client: client_unix, send: '(function() {\n\nreturn 1;\n})()', expect: '1' }, { client: client_unix, send: '{\n\na: 1\n}', expect: '{ a: 1 }' }, diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js index a069d0a799892a..f2245345e3e4bd 100644 --- a/test/parallel/test-require-cache.js +++ b/test/parallel/test-require-cache.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-dot.js b/test/parallel/test-require-dot.js index 2551d88d2204e8..aab466e3eb6204 100644 --- a/test/parallel/test-require-dot.js +++ b/test/parallel/test-require-dot.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var module = require('module'); diff --git a/test/parallel/test-require-exceptions.js b/test/parallel/test-require-exceptions.js index 16c63a90aa41ed..e7a191b47ad6f2 100644 --- a/test/parallel/test-require-exceptions.js +++ b/test/parallel/test-require-exceptions.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-extensions-main.js b/test/parallel/test-require-extensions-main.js index 06d28ab30bddcf..6e67d3ae045bb6 100644 --- a/test/parallel/test-require-extensions-main.js +++ b/test/parallel/test-require-extensions-main.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js index cc2cd94ea6994c..1837a17bab0add 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js @@ -1,3 +1,5 @@ +/* eslint-disable max-len */ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-extensions-same-filename-as-dir.js b/test/parallel/test-require-extensions-same-filename-as-dir.js index 387620afa74cb2..41051dad45e10f 100644 --- a/test/parallel/test-require-extensions-same-filename-as-dir.js +++ b/test/parallel/test-require-extensions-same-filename-as-dir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-require-json.js b/test/parallel/test-require-json.js index dbf8c8f866d8c6..4c17fc8d025d73 100644 --- a/test/parallel/test-require-json.js +++ b/test/parallel/test-require-json.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); try { diff --git a/test/parallel/test-require-process.js b/test/parallel/test-require-process.js index 4693b4984e6dfe..fdd921a61195e5 100644 --- a/test/parallel/test-require-process.js +++ b/test/parallel/test-require-process.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var nativeProcess = require('process'); diff --git a/test/parallel/test-require-resolve.js b/test/parallel/test-require-resolve.js index c11ff65ac43307..13897c74da1752 100644 --- a/test/parallel/test-require-resolve.js +++ b/test/parallel/test-require-resolve.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var fixturesDir = common.fixturesDir; var assert = require('assert'); diff --git a/test/parallel/test-signal-handler.js b/test/parallel/test-signal-handler.js index 30cad31eef5995..f186287b0c72a7 100644 --- a/test/parallel/test-signal-handler.js +++ b/test/parallel/test-signal-handler.js @@ -1,3 +1,4 @@ +'use strict'; // SIGUSR1 and SIGHUP are not supported on Windows if (process.platform === 'win32') { process.exit(0); @@ -39,7 +40,7 @@ setInterval(function() { // has been previously registered, and `process.listeners(SIGNAL).length === 1` process.on('SIGHUP', function() {}); process.removeAllListeners('SIGHUP'); -process.on('SIGHUP', function() { sighup = true }); +process.on('SIGHUP', function() { sighup = true; }); process.kill(process.pid, 'SIGHUP'); process.on('exit', function() { diff --git a/test/parallel/test-signal-safety.js b/test/parallel/test-signal-safety.js index b037232a6b89f7..549c26662f717a 100644 --- a/test/parallel/test-signal-safety.js +++ b/test/parallel/test-signal-safety.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Signal = process.binding('signal_wrap').Signal; diff --git a/test/parallel/test-signal-unregister.js b/test/parallel/test-signal-unregister.js index c3ab108dffbf08..b65ade73db9422 100644 --- a/test/parallel/test-signal-unregister.js +++ b/test/parallel/test-signal-unregister.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-smalloc.js b/test/parallel/test-smalloc.js index ef1aa60bad6838..ce4e4f43cd08f0 100644 --- a/test/parallel/test-smalloc.js +++ b/test/parallel/test-smalloc.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); diff --git a/test/parallel/test-stdin-hang.js b/test/parallel/test-stdin-hang.js index c22a097925b456..4818a9ee952026 100644 --- a/test/parallel/test-stdin-hang.js +++ b/test/parallel/test-stdin-hang.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); // This test *only* verifies that invoking the stdin getter does not diff --git a/test/parallel/test-stdin-pause-resume-sync.js b/test/parallel/test-stdin-pause-resume-sync.js index fdb8e030b70edb..4fe4d445a2443e 100644 --- a/test/parallel/test-stdin-pause-resume-sync.js +++ b/test/parallel/test-stdin-pause-resume-sync.js @@ -1,3 +1,4 @@ +'use strict'; console.error('before opening stdin'); process.stdin.resume(); console.error('stdin opened'); diff --git a/test/parallel/test-stdin-pause-resume.js b/test/parallel/test-stdin-pause-resume.js index a9282d5aa030ed..2685deb0e9b33c 100644 --- a/test/parallel/test-stdin-pause-resume.js +++ b/test/parallel/test-stdin-pause-resume.js @@ -1,3 +1,4 @@ +'use strict'; console.error('before opening stdin'); process.stdin.resume(); console.error('stdin opened'); diff --git a/test/parallel/test-stdin-resume-pause.js b/test/parallel/test-stdin-resume-pause.js index 6290ff7999b250..963fd989f085a3 100644 --- a/test/parallel/test-stdin-resume-pause.js +++ b/test/parallel/test-stdin-resume-pause.js @@ -1,2 +1,3 @@ +'use strict'; process.stdin.resume(); process.stdin.pause(); diff --git a/test/parallel/test-stdio-closed.js b/test/parallel/test-stdio-closed.js index 2543d8b021b91d..2101f85ac061c3 100644 --- a/test/parallel/test-stdio-closed.js +++ b/test/parallel/test-stdio-closed.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/parallel/test-stdio-readable-writable.js b/test/parallel/test-stdio-readable-writable.js index 95ae679bca0389..f8a8923498cb03 100644 --- a/test/parallel/test-stdio-readable-writable.js +++ b/test/parallel/test-stdio-readable-writable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stdout-close-unref.js b/test/parallel/test-stdout-close-unref.js index 0b03e7142a8615..12a031562bf6f0 100644 --- a/test/parallel/test-stdout-close-unref.js +++ b/test/parallel/test-stdout-close-unref.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-stream-big-packet.js b/test/parallel/test-stream-big-packet.js index cfde7e47fb700a..a9f6064c7e7277 100644 --- a/test/parallel/test-stream-big-packet.js +++ b/test/parallel/test-stream-big-packet.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -5,20 +6,20 @@ var stream = require('stream'); var passed = false; -function PassThrough () { +function PassThrough() { stream.Transform.call(this); }; util.inherits(PassThrough, stream.Transform); -PassThrough.prototype._transform = function (chunk, encoding, done) { +PassThrough.prototype._transform = function(chunk, encoding, done) { this.push(chunk); done(); }; -function TestStream () { +function TestStream() { stream.Transform.call(this); }; util.inherits(TestStream, stream.Transform); -TestStream.prototype._transform = function (chunk, encoding, done) { +TestStream.prototype._transform = function(chunk, encoding, done) { if (!passed) { // Char 'a' only exists in the last write passed = chunk.toString().indexOf('a') >= 0; @@ -47,6 +48,6 @@ assert(s2.write('tiny')); setImmediate(s1.write.bind(s1), 'later'); // Assert after two IO loops when all operations have been done. -process.on('exit', function () { +process.on('exit', function() { assert(passed, 'Large buffer is not handled properly by Writable Stream'); }); diff --git a/test/parallel/test-stream-big-push.js b/test/parallel/test-stream-big-push.js index b4ed8f8a527acd..e02ff98d3c7454 100644 --- a/test/parallel/test-stream-big-push.js +++ b/test/parallel/test-stream-big-push.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); diff --git a/test/parallel/test-stream-duplex.js b/test/parallel/test-stream-duplex.js index 8efc9d4b5f4160..0e8789d6bf5555 100644 --- a/test/parallel/test-stream-duplex.js +++ b/test/parallel/test-stream-duplex.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,21 +12,21 @@ assert(stream._writableState.objectMode); var written; var read; -stream._write = function (obj, _, cb) { +stream._write = function(obj, _, cb) { written = obj; cb(); }; -stream._read = function () {}; +stream._read = function() {}; -stream.on('data', function (obj) { +stream.on('data', function(obj) { read = obj; }); stream.push({ val: 1 }); stream.end({ val: 2 }); -process.on('exit', function () { +process.on('exit', function() { assert(read.val === 1); assert(written.val === 2); }); diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js index 72825dc440df91..585d6c327fd592 100644 --- a/test/parallel/test-stream-end-paused.js +++ b/test/parallel/test-stream-end-paused.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var gotEnd = false; diff --git a/test/parallel/test-stream-ispaused.js b/test/parallel/test-stream-ispaused.js index fe895ce7c39884..8112dc733a7205 100644 --- a/test/parallel/test-stream-ispaused.js +++ b/test/parallel/test-stream-ispaused.js @@ -1,9 +1,10 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var stream = require('stream'); -var readable = new stream.Readable; +var readable = new stream.Readable(); // _read is a noop, here. readable._read = Function(); diff --git a/test/parallel/test-stream-pipe-after-end.js b/test/parallel/test-stream-pipe-after-end.js index a2fece3f7f6264..4bead73f68ce5b 100644 --- a/test/parallel/test-stream-pipe-after-end.js +++ b/test/parallel/test-stream-pipe-after-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-pipe-cleanup.js b/test/parallel/test-stream-pipe-cleanup.js index b2963c4f56c1a3..08da96f92c3a0f 100644 --- a/test/parallel/test-stream-pipe-cleanup.js +++ b/test/parallel/test-stream-pipe-cleanup.js @@ -1,3 +1,4 @@ +'use strict'; // This test asserts that Stream.prototype.pipe does not leave listeners // hanging on the source or dest. diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js index 18ce5a1edef021..031a0da7e395db 100644 --- a/test/parallel/test-stream-pipe-error-handling.js +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Stream = require('stream').Stream; @@ -41,8 +42,8 @@ var Stream = require('stream').Stream; var R = Stream.Readable; var W = Stream.Writable; - var r = new R; - var w = new W; + var r = new R(); + var w = new W(); var removed = false; var didTest = false; @@ -76,8 +77,8 @@ var Stream = require('stream').Stream; var R = Stream.Readable; var W = Stream.Writable; - var r = new R; - var w = new W; + var r = new R(); + var w = new W(); var removed = false; var didTest = false; var caught = false; diff --git a/test/parallel/test-stream-pipe-event.js b/test/parallel/test-stream-pipe-event.js index bcae20c581ebbd..0d10533b0c496a 100644 --- a/test/parallel/test-stream-pipe-event.js +++ b/test/parallel/test-stream-pipe-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var stream = require('stream'); var assert = require('assert'); diff --git a/test/parallel/test-stream-push-order.js b/test/parallel/test-stream-push-order.js index 5e403c7824beaf..d67233aff7a498 100644 --- a/test/parallel/test-stream-push-order.js +++ b/test/parallel/test-stream-push-order.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var Readable = require('stream').Readable; var assert = require('assert'); @@ -9,7 +10,7 @@ var s = new Readable({ var list = ['1', '2', '3', '4', '5', '6']; -s._read = function (n) { +s._read = function(n) { var one = list.shift(); if (!one) { s.push(null); @@ -24,8 +25,8 @@ var v = s.read(0); // ACTUALLY [1, 3, 5, 6, 4, 2] -process.on("exit", function () { +process.on('exit', function() { assert.deepEqual(s._readableState.buffer, ['1', '2', '3', '4', '5', '6']); - console.log("ok"); + console.log('ok'); }); diff --git a/test/parallel/test-stream-push-strings.js b/test/parallel/test-stream-push-strings.js index f673173de5ea57..0d9c0653c0dc66 100644 --- a/test/parallel/test-stream-push-strings.js +++ b/test/parallel/test-stream-push-strings.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-readable-constructor-set-methods.js b/test/parallel/test-stream-readable-constructor-set-methods.js index a88ffcd67a1446..928ce31a8ebe7b 100644 --- a/test/parallel/test-stream-readable-constructor-set-methods.js +++ b/test/parallel/test-stream-readable-constructor-set-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -12,7 +13,7 @@ function _read(n) { var r = new Readable({ read: _read }); r.resume(); -process.on('exit', function () { +process.on('exit', function() { assert.equal(r._read, _read); assert(_readCalled); }); diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index 2d7d1cc4f9020e..965fc82c05a1d9 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-readable-flow-recursion.js b/test/parallel/test-stream-readable-flow-recursion.js index c3dfbef53bd971..07edd579f1deea 100644 --- a/test/parallel/test-stream-readable-flow-recursion.js +++ b/test/parallel/test-stream-readable-flow-recursion.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-transform-constructor-set-methods.js b/test/parallel/test-stream-transform-constructor-set-methods.js index 55e64ed9b2e733..c24c273b6f20e1 100644 --- a/test/parallel/test-stream-transform-constructor-set-methods.js +++ b/test/parallel/test-stream-transform-constructor-set-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -23,7 +24,7 @@ var t = new Transform({ t.end(new Buffer('blerg')); t.resume(); -process.on('exit', function () { +process.on('exit', function() { assert.equal(t._transform, _transform); assert.equal(t._flush, _flush); assert(_transformCalled); diff --git a/test/parallel/test-stream-transform-objectmode-falsey-value.js b/test/parallel/test-stream-transform-objectmode-falsey-value.js index 89feabef118e59..762f0500ad3e60 100644 --- a/test/parallel/test-stream-transform-objectmode-falsey-value.js +++ b/test/parallel/test-stream-transform-objectmode-falsey-value.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-transform-split-objectmode.js b/test/parallel/test-stream-transform-split-objectmode.js index df10ed1b6553e7..24833ece051e9e 100644 --- a/test/parallel/test-stream-transform-split-objectmode.js +++ b/test/parallel/test-stream-transform-split-objectmode.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -10,19 +11,19 @@ assert(!parser._writableState.objectMode); assert(parser._readableState.highWaterMark === 16); assert(parser._writableState.highWaterMark === (16 * 1024)); -parser._transform = function (chunk, enc, callback) { +parser._transform = function(chunk, enc, callback) { callback(null, { val : chunk[0] }); }; var parsed; -parser.on('data', function (obj) { +parser.on('data', function(obj) { parsed = obj; }); parser.end(new Buffer([42])); -process.on('exit', function () { +process.on('exit', function() { assert(parsed.val === 42); }); @@ -34,18 +35,18 @@ assert(serializer._writableState.objectMode); assert(serializer._readableState.highWaterMark === (16 * 1024)); assert(serializer._writableState.highWaterMark === 16); -serializer._transform = function (obj, _, callback) { +serializer._transform = function(obj, _, callback) { callback(null, new Buffer([obj.val])); }; var serialized; -serializer.on('data', function (chunk) { +serializer.on('data', function(chunk) { serialized = chunk; }); serializer.write({ val : 42 }); -process.on('exit', function () { +process.on('exit', function() { assert(serialized[0] === 42); }); diff --git a/test/parallel/test-stream-unshift-empty-chunk.js b/test/parallel/test-stream-unshift-empty-chunk.js index c985d4bc37d279..e6c427221294a2 100644 --- a/test/parallel/test-stream-unshift-empty-chunk.js +++ b/test/parallel/test-stream-unshift-empty-chunk.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-unshift-read-race.js b/test/parallel/test-stream-unshift-read-race.js index dd7c6dfb37e10c..90f519b5b5d738 100644 --- a/test/parallel/test-stream-unshift-read-race.js +++ b/test/parallel/test-stream-unshift-read-race.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream-writable-change-default-encoding.js b/test/parallel/test-stream-writable-change-default-encoding.js index 3e2277ad980c3d..a6fcda3e62a517 100644 --- a/test/parallel/test-stream-writable-change-default-encoding.js +++ b/test/parallel/test-stream-writable-change-default-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,7 +12,7 @@ function MyWritable(fn, options) { util.inherits(MyWritable, stream.Writable); -MyWritable.prototype._write = function (chunk, encoding, callback) { +MyWritable.prototype._write = function(chunk, encoding, callback) { this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); callback(); }; diff --git a/test/parallel/test-stream-writable-constructor-set-methods.js b/test/parallel/test-stream-writable-constructor-set-methods.js index 496ce6697582d0..47fc458ce9713b 100644 --- a/test/parallel/test-stream-writable-constructor-set-methods.js +++ b/test/parallel/test-stream-writable-constructor-set-methods.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -25,7 +26,7 @@ w2.write(new Buffer('blerg')); w2.write(new Buffer('blerg')); w2.end(); -process.on('exit', function () { +process.on('exit', function() { assert.equal(w._write, _write); assert(_writeCalled); assert.equal(w2._writev, _writev); diff --git a/test/parallel/test-stream-writable-decoded-encoding.js b/test/parallel/test-stream-writable-decoded-encoding.js index fb530d0830a5d9..b637838c0c65be 100644 --- a/test/parallel/test-stream-writable-decoded-encoding.js +++ b/test/parallel/test-stream-writable-decoded-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,7 +12,7 @@ function MyWritable(fn, options) { util.inherits(MyWritable, stream.Writable); -MyWritable.prototype._write = function (chunk, encoding, callback) { +MyWritable.prototype._write = function(chunk, encoding, callback) { this.fn(Buffer.isBuffer(chunk), typeof chunk, encoding); callback(); }; diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 2a2ed3cdae3c07..f73270f2ff53ba 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -45,19 +46,24 @@ function test(decode, uncork, multi, next) { }; var expectChunks = decode ? - [{ encoding: 'buffer', - chunk: [104, 101, 108, 108, 111, 44, 32] }, - { encoding: 'buffer', chunk: [119, 111, 114, 108, 100] }, - { encoding: 'buffer', chunk: [33] }, - { encoding: 'buffer', - chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, - { encoding: 'buffer', - chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173] }] : - [{ encoding: 'ascii', chunk: 'hello, ' }, + [ + { encoding: 'buffer', + chunk: [104, 101, 108, 108, 111, 44, 32] }, + { encoding: 'buffer', + chunk: [119, 111, 114, 108, 100] }, + { encoding: 'buffer', + chunk: [33] }, + { encoding: 'buffer', + chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, + { encoding: 'buffer', + chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173]} + ] : [ + { encoding: 'ascii', chunk: 'hello, ' }, { encoding: 'utf8', chunk: 'world' }, { encoding: 'buffer', chunk: [33] }, { encoding: 'binary', chunk: '\nand then...' }, - { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' }]; + { encoding: 'hex', chunk: 'facebea7deadbeefdecafbad' } + ]; var actualChunks; w._writev = function(chunks, cb) { diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 2082c714cc69a5..37a97cd817e05b 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var W = require('_stream_writable'); @@ -27,7 +28,7 @@ dst._write = function(chunk, enc, cb) { src.on('end', function() { assert.equal(Buffer.concat(accum) + '', 'MQ=='); clearTimeout(timeout); -}) +}); src.pipe(dst); diff --git a/test/parallel/test-stream2-compatibility.js b/test/parallel/test-stream2-compatibility.js index 72b1e428505988..9eab7b713bf167 100644 --- a/test/parallel/test-stream2-compatibility.js +++ b/test/parallel/test-stream2-compatibility.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-finish-pipe.js b/test/parallel/test-stream2-finish-pipe.js index beabea0f0e5728..913bb7b0b4db09 100644 --- a/test/parallel/test-stream2-finish-pipe.js +++ b/test/parallel/test-stream2-finish-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var stream = require('stream'); var Buffer = require('buffer').Buffer; diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 55d25a9b7366df..4cd89599fee730 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index d7c532917962da..a2f554a0b8a004 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var Readable = require('_stream_readable'); var Writable = require('_stream_writable'); diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js index c7303accead89b..9eddbdd90d00c3 100644 --- a/test/parallel/test-stream2-pipe-error-handling.js +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); diff --git a/test/parallel/test-stream2-pipe-error-once-listener.js b/test/parallel/test-stream2-pipe-error-once-listener.js index 0dbe8782e92229..f2ecb87ce97a75 100644 --- a/test/parallel/test-stream2-pipe-error-once-listener.js +++ b/test/parallel/test-stream2-pipe-error-once-listener.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-push.js b/test/parallel/test-stream2-push.js index 9268f052a2381a..b58bce143585f4 100644 --- a/test/parallel/test-stream2-push.js +++ b/test/parallel/test-stream2-push.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var stream = require('stream'); var Readable = stream.Readable; @@ -15,7 +16,7 @@ var stream = new Readable({ encoding: 'utf8' }); -var source = new EE; +var source = new EE(); stream._read = function() { console.error('stream._read'); @@ -80,7 +81,7 @@ writer.on('finish', finish); // now emit some chunks. -var chunk = "asdfg"; +var chunk = 'asdfg'; var set = 0; readStart(); diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index 48b605e46a1865..e912e1039ff558 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Readable = require('stream').Readable; diff --git a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js index e71c37e36afcb0..8e4001f8022f1c 100644 --- a/test/parallel/test-stream2-readable-empty-buffer-no-eof.js +++ b/test/parallel/test-stream2-readable-empty-buffer-no-eof.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-readable-from-list.js b/test/parallel/test-stream2-readable-from-list.js index 3604ae3ec361cb..f142c49f144fbc 100644 --- a/test/parallel/test-stream2-readable-from-list.js +++ b/test/parallel/test-stream2-readable-from-list.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fromList = require('_stream_readable')._fromList; @@ -22,7 +23,7 @@ function run() { fn({ same: assert.deepEqual, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -30,7 +31,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index 7e8eb6b1ef3898..4218bace2b878f 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index d77564cacb7535..46d6f92f2b9df2 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var Readable = require('_stream_readable'); @@ -5,7 +6,7 @@ var Readable = require('_stream_readable'); var len = 0; var chunks = new Array(10); for (var i = 1; i <= 10; i++) { - chunks[i-1] = new Buffer(i); + chunks[i - 1] = new Buffer(i); len += i; } diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js index c1bc3361f23030..60417ca893300d 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -5,18 +6,18 @@ var Readable = require('_stream_readable'); var EE = require('events').EventEmitter; var oldStream = new EE(); -oldStream.pause = function(){}; -oldStream.resume = function(){}; +oldStream.pause = function() {}; +oldStream.resume = function() {}; var newStream = new Readable().wrap(oldStream); var ended = false; newStream - .on('readable', function(){}) - .on('end', function(){ ended = true; }); + .on('readable', function() {}) + .on('end', function() { ended = true; }); oldStream.emit('end'); -process.on('exit', function(){ +process.on('exit', function() { assert.ok(ended); }); diff --git a/test/parallel/test-stream2-readable-wrap.js b/test/parallel/test-stream2-readable-wrap.js index 71f8a28265bc76..8e3e04b966010f 100644 --- a/test/parallel/test-stream2-readable-wrap.js +++ b/test/parallel/test-stream2-readable-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -9,8 +10,9 @@ var testRuns = 0, completedRuns = 0; function runTest(highWaterMark, objectMode, produce) { testRuns++; - var old = new EE; - var r = new Readable({ highWaterMark: highWaterMark, objectMode: objectMode }); + var old = new EE(); + var r = new Readable({ highWaterMark: highWaterMark, + objectMode: objectMode }); assert.equal(r, r.wrap(old)); var ended = false; @@ -50,7 +52,8 @@ function runTest(highWaterMark, objectMode, produce) { } } - var w = new Writable({ highWaterMark: highWaterMark * 2, objectMode: objectMode }); + var w = new Writable({ highWaterMark: highWaterMark * 2, + objectMode: objectMode }); var written = []; w._write = function(chunk, encoding, cb) { console.log('_write', chunk); @@ -67,19 +70,19 @@ function runTest(highWaterMark, objectMode, produce) { flow(); - function performAsserts() { + function performAsserts() { assert(ended); assert(oldEnded); assert.deepEqual(written, expected); } } -runTest(100, false, function(){ return new Buffer(100); }); -runTest(10, false, function(){ return new Buffer('xxxxxxxxxx'); }); -runTest(1, true, function(){ return { foo: 'bar' }; }); +runTest(100, false, function() { return new Buffer(100); }); +runTest(10, false, function() { return new Buffer('xxxxxxxxxx'); }); +runTest(1, true, function() { return { foo: 'bar' }; }); var objectChunks = [ 5, 'a', false, 0, '', 'xyz', { x: 4 }, 7, [], 555 ]; -runTest(1, true, function(){ return objectChunks.shift() }); +runTest(1, true, function() { return objectChunks.shift(); }); process.on('exit', function() { assert.equal(testRuns, completedRuns); diff --git a/test/parallel/test-stream2-set-encoding.js b/test/parallel/test-stream2-set-encoding.js index 47f078935bd03d..ea9a315cb1a6e1 100644 --- a/test/parallel/test-stream2-set-encoding.js +++ b/test/parallel/test-stream2-set-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var R = require('_stream_readable'); @@ -23,7 +24,7 @@ function run() { fn({ same: assert.deepEqual, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -31,7 +32,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -68,7 +69,7 @@ TestReader.prototype._read = function(n) { var ret = new Buffer(n); ret.fill('a'); - console.log("this.push(ret)", ret) + console.log('this.push(ret)', ret); return this.push(ret); }.bind(this), 1); @@ -146,32 +147,32 @@ test('setEncoding hex with read(13)', function(t) { tr.setEncoding('hex'); var out = []; var expect = - [ "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "16161" ]; + [ '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '16161' ]; tr.on('readable', function flow() { - console.log("readable once") + console.log('readable once'); var chunk; while (null !== (chunk = tr.read(13))) out.push(chunk); }); tr.on('end', function() { - console.log("END") + console.log('END'); t.same(out, expect); t.end(); }); @@ -278,22 +279,22 @@ test('encoding: hex with read(13)', function(t) { var tr = new TestReader(100, { encoding: 'hex' }); var out = []; var expect = - [ "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "1616161616161", - "6161616161616", - "16161" ]; + [ '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '1616161616161', + '6161616161616', + '16161' ]; tr.on('readable', function flow() { var chunk; diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 3bdef8fbf626e4..e45c913c94f559 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var PassThrough = require('_stream_passthrough'); @@ -24,7 +25,7 @@ function run() { same: assert.deepEqual, equal: assert.equal, ok: assert, - end: function () { + end: function() { count--; run(); } @@ -32,7 +33,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -83,7 +84,7 @@ test('passthrough', function(t) { t.end(); }); -test('object passthrough', function (t) { +test('object passthrough', function(t) { var pt = new PassThrough({ objectMode: true }); pt.write(1); @@ -106,7 +107,7 @@ test('object passthrough', function (t) { }); test('simple transform', function(t) { - var pt = new Transform; + var pt = new Transform(); pt._transform = function(c, e, cb) { var ret = new Buffer(c.length); ret.fill('x'); @@ -154,7 +155,7 @@ test('simple object transform', function(t) { }); test('async passthrough', function(t) { - var pt = new Transform; + var pt = new Transform(); pt._transform = function(chunk, encoding, cb) { setTimeout(function() { pt.push(chunk); @@ -178,7 +179,7 @@ test('async passthrough', function(t) { }); test('assymetric transform (expand)', function(t) { - var pt = new Transform; + var pt = new Transform(); // emit each chunk 2 times. pt._transform = function(chunk, encoding, cb) { @@ -187,7 +188,7 @@ test('assymetric transform (expand)', function(t) { setTimeout(function() { pt.push(chunk); cb(); - }, 10) + }, 10); }, 10); }; @@ -210,7 +211,7 @@ test('assymetric transform (expand)', function(t) { }); test('assymetric transform (compress)', function(t) { - var pt = new Transform; + var pt = new Transform(); // each output is the first char of 3 consecutive chunks, // or whatever's left. @@ -348,10 +349,10 @@ test('passthrough event emission', function(t) { }); test('passthrough event emission reordered', function(t) { - var pt = new PassThrough; + var pt = new PassThrough(); var emits = 0; pt.on('readable', function() { - console.error('emit readable', emits) + console.error('emit readable', emits); emits++; }); @@ -390,7 +391,7 @@ test('passthrough event emission reordered', function(t) { test('passthrough facaded', function(t) { console.error('passthrough facaded'); - var pt = new PassThrough; + var pt = new PassThrough(); var datas = []; pt.on('data', function(chunk) { datas.push(chunk.toString()); @@ -433,8 +434,8 @@ test('object transform (json parse)', function(t) { var objects = [ { foo: 'bar' }, 100, - "string", - { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } + 'string', + { nested: { things: [ { foo: 'bar' }, 100, 'string' ] } } ]; var ended = false; @@ -455,7 +456,7 @@ test('object transform (json parse)', function(t) { process.nextTick(function() { t.ok(ended); t.end(); - }) + }); }); test('object transform (json stringify)', function(t) { @@ -475,8 +476,8 @@ test('object transform (json stringify)', function(t) { var objects = [ { foo: 'bar' }, 100, - "string", - { nested: { things: [ { foo: 'bar' }, 100, "string" ] } } + 'string', + { nested: { things: [ { foo: 'bar' }, 100, 'string' ] } } ]; var ended = false; @@ -497,5 +498,5 @@ test('object transform (json stringify)', function(t) { process.nextTick(function() { t.ok(ended); t.end(); - }) + }); }); diff --git a/test/parallel/test-stream2-unpipe-drain.js b/test/parallel/test-stream2-unpipe-drain.js index 12d1c0648d2345..a430e4a58d6514 100644 --- a/test/parallel/test-stream2-unpipe-drain.js +++ b/test/parallel/test-stream2-unpipe-drain.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); @@ -11,11 +12,11 @@ var crypto = require('crypto'); var util = require('util'); function TestWriter() { - stream.Writable.call(this); + stream.Writable.call(this); } util.inherits(TestWriter, stream.Writable); -TestWriter.prototype._write = function (buffer, encoding, callback) { +TestWriter.prototype._write = function(buffer, encoding, callback) { console.log('write called'); // super slow write stream (callback never called) }; @@ -23,12 +24,12 @@ TestWriter.prototype._write = function (buffer, encoding, callback) { var dest = new TestWriter(); function TestReader(id) { - stream.Readable.call(this); - this.reads = 0; + stream.Readable.call(this); + this.reads = 0; } util.inherits(TestReader, stream.Readable); -TestReader.prototype._read = function (size) { +TestReader.prototype._read = function(size) { this.reads += 1; this.push(crypto.randomBytes(size)); }; @@ -38,13 +39,13 @@ var src2 = new TestReader(); src1.pipe(dest); -src1.once('readable', function () { - process.nextTick(function () { +src1.once('readable', function() { + process.nextTick(function() { src2.pipe(dest); - src2.once('readable', function () { - process.nextTick(function () { + src2.once('readable', function() { + process.nextTick(function() { src1.unpipe(dest); }); @@ -53,7 +54,7 @@ src1.once('readable', function () { }); -process.on('exit', function () { +process.on('exit', function() { assert.equal(src1.reads, 2); assert.equal(src2.reads, 2); }); diff --git a/test/parallel/test-stream2-unpipe-leak.js b/test/parallel/test-stream2-unpipe-leak.js index fae2b73ac4f6cf..15b510e7f643cc 100644 --- a/test/parallel/test-stream2-unpipe-leak.js +++ b/test/parallel/test-stream2-unpipe-leak.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var stream = require('stream'); diff --git a/test/parallel/test-stream2-writable.js b/test/parallel/test-stream2-writable.js index d90a2b6f75c468..1d87d7f920c052 100644 --- a/test/parallel/test-stream2-writable.js +++ b/test/parallel/test-stream2-writable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var W = require('_stream_writable'); var D = require('_stream_duplex'); @@ -46,7 +47,7 @@ function run() { fn({ same: assert.deepEqual, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -54,7 +55,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -196,7 +197,7 @@ test('write no bufferize', function(t) { t.end(); }); -test('write callbacks', function (t) { +test('write callbacks', function(t) { var callbacks = chunks.map(function(chunk, i) { return [i, function(er) { callbacks._called[i] = chunk; @@ -225,42 +226,42 @@ test('write callbacks', function (t) { tw.end(); }); -test('end callback', function (t) { +test('end callback', function(t) { var tw = new TestWriter(); - tw.end(function () { + tw.end(function() { t.end(); }); }); -test('end callback with chunk', function (t) { +test('end callback with chunk', function(t) { var tw = new TestWriter(); - tw.end(new Buffer('hello world'), function () { + tw.end(new Buffer('hello world'), function() { t.end(); }); }); -test('end callback with chunk and encoding', function (t) { +test('end callback with chunk and encoding', function(t) { var tw = new TestWriter(); - tw.end('hello world', 'ascii', function () { + tw.end('hello world', 'ascii', function() { t.end(); }); }); -test('end callback after .write() call', function (t) { +test('end callback after .write() call', function(t) { var tw = new TestWriter(); tw.write(new Buffer('hello world')); - tw.end(function () { + tw.end(function() { t.end(); }); }); -test('end callback called after write callback', function (t) { +test('end callback called after write callback', function(t) { var tw = new TestWriter(); var writeCalledback = false; tw.write(new Buffer('hello world'), function() { writeCalledback = true; }); - tw.end(function () { + tw.end(function() { t.equal(writeCalledback, true); t.end(); }); diff --git a/test/parallel/test-stream3-pause-then-read.js b/test/parallel/test-stream3-pause-then-read.js index 737a2f30a1d136..135629a243d66c 100644 --- a/test/parallel/test-stream3-pause-then-read.js +++ b/test/parallel/test-stream3-pause-then-read.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-string-decoder-end.js b/test/parallel/test-string-decoder-end.js index 0bac7a5f28f4d7..f931c6abb9864c 100644 --- a/test/parallel/test-string-decoder-end.js +++ b/test/parallel/test-string-decoder-end.js @@ -1,3 +1,4 @@ +'use strict'; // verify that the string decoder works getting 1 byte at a time, // the whole buffer at once, and that both match the .toString(enc) // result of the entire buffer. diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index dd28ba748b389f..c540ecfacdbf07 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var StringDecoder = require('string_decoder').StringDecoder; @@ -54,11 +55,11 @@ function test(encoding, input, expected, singleSequence) { process.stdout.write('.'); if (output !== expected) { var message = - 'Expected "'+unicodeEscape(expected)+'", '+ - 'but got "'+unicodeEscape(output)+'"\n'+ - 'Write sequence: '+JSON.stringify(sequence)+'\n'+ - 'Decoder charBuffer: 0x'+decoder.charBuffer.toString('hex')+'\n'+ - 'Full Decoder State: '+JSON.stringify(decoder, null, 2); + 'Expected "' + unicodeEscape(expected) + '", ' + + 'but got "' + unicodeEscape(output) + '"\n' + + 'Write sequence: ' + JSON.stringify(sequence) + '\n' + + 'Decoder charBuffer: 0x' + decoder.charBuffer.toString('hex') + '\n' + + 'Full Decoder State: ' + JSON.stringify(decoder, null, 2); assert.fail(output, expected, message); } }); @@ -68,7 +69,7 @@ function test(encoding, input, expected, singleSequence) { function unicodeEscape(str) { var r = ''; for (var i = 0; i < str.length; i++) { - r += '\\u'+str.charCodeAt(i).toString(16); + r += '\\u' + str.charCodeAt(i).toString(16); } return r; } @@ -86,7 +87,7 @@ function unicodeEscape(str) { function writeSequences(length, start, sequence) { if (start === undefined) { start = 0; - sequence = [] + sequence = []; } else if (start === length) { return [sequence]; } diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index 5bc4c945e87705..69ca3c3fa6333b 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // minimum string size to overflow into external string space @@ -54,7 +55,7 @@ var RADIOS = 2; var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; -(function () { +(function() { for (var j = 0; j < RADIOS * 2; j += 1) { var datum = b; var slice = datum.slice(0, PRE_HALF_APEX + j); @@ -63,7 +64,7 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var pumped_string2 = slice2.toString('hex'); var decoded = new Buffer(pumped_string, 'hex'); - var metadata = "\nEXTERN_APEX=1031913 - pumped_string.length=" + var metadata = '\nEXTERN_APEX=1031913 - pumped_string.length='; metadata += pumped_string.length + '\n'; // the string are the same? @@ -80,7 +81,7 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; } })(); -(function () { +(function() { for (var j = 0; j < RADIOS * 2; j += 1) { var datum = b; var slice = datum.slice(0, PRE_3OF4_APEX + j); @@ -89,8 +90,8 @@ var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; var pumped_string2 = slice2.toString('base64'); var decoded = new Buffer(pumped_string, 'base64'); - var metadata = "\nEXTERN_APEX=1031913 - data=" + slice.length - metadata += " pumped_string.length=" + pumped_string.length + '\n'; + var metadata = '\nEXTERN_APEX=1031913 - data=" + slice.length'; + metadata += ' pumped_string.length=' + pumped_string.length + '\n'; // the string are the same? for (var k = 0; k < pumped_string.length - 3; ++k) { diff --git a/test/parallel/test-sys.js b/test/parallel/test-sys.js index 8b3ea082b6e135..a5631a5cb16930 100644 --- a/test/parallel/test-sys.js +++ b/test/parallel/test-sys.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tcp-wrap.js b/test/parallel/test-tcp-wrap.js index 6ed8fb44ca806e..93da3e5b3b41c8 100644 --- a/test/parallel/test-tcp-wrap.js +++ b/test/parallel/test-tcp-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timer-close.js b/test/parallel/test-timer-close.js index b374fe162cfed1..79f06dffa98731 100644 --- a/test/parallel/test-timer-close.js +++ b/test/parallel/test-timer-close.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var t = new (process.binding('timer_wrap').Timer); diff --git a/test/parallel/test-timers-args.js b/test/parallel/test-timers-args.js index 599037b95bc6e6..abb785ea0fc79c 100644 --- a/test/parallel/test-timers-args.js +++ b/test/parallel/test-timers-args.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-first-fire.js b/test/parallel/test-timers-first-fire.js index 385724b0b08e44..88460e1e3acb12 100644 --- a/test/parallel/test-timers-first-fire.js +++ b/test/parallel/test-timers-first-fire.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-immediate-queue.js b/test/parallel/test-timers-immediate-queue.js index 1c0b095f18c3d6..a71472d46442ab 100644 --- a/test/parallel/test-timers-immediate-queue.js +++ b/test/parallel/test-timers-immediate-queue.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-immediate.js b/test/parallel/test-timers-immediate.js index 00652d04060569..bcfc4616ac6264 100644 --- a/test/parallel/test-timers-immediate.js +++ b/test/parallel/test-timers-immediate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-linked-list.js b/test/parallel/test-timers-linked-list.js index 79a9839627c98c..00b2129d126c4a 100644 --- a/test/parallel/test-timers-linked-list.js +++ b/test/parallel/test-timers-linked-list.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var L = require('_linklist'); diff --git a/test/parallel/test-timers-non-integer-delay.js b/test/parallel/test-timers-non-integer-delay.js index 229db3892dba06..a3e5420a5e4858 100644 --- a/test/parallel/test-timers-non-integer-delay.js +++ b/test/parallel/test-timers-non-integer-delay.js @@ -1,3 +1,4 @@ +'use strict'; /* * This test makes sure that non-integer timer delays do not make the process * hang. See https://github.com/joyent/node/issues/8065 and diff --git a/test/parallel/test-timers-ordering.js b/test/parallel/test-timers-ordering.js index 9f40288ec56068..730a78a072c663 100644 --- a/test/parallel/test-timers-ordering.js +++ b/test/parallel/test-timers-ordering.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var Timer = process.binding('timer_wrap').Timer; @@ -13,13 +14,15 @@ var start = Timer.now(); var f = function(i) { if (i <= N) { // check order - assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + last_i + ' + 1'); + assert.equal(i, last_i + 1, 'order is broken: ' + i + ' != ' + + last_i + ' + 1'); last_i = i; // check that this iteration is fired at least 1ms later than the previous var now = Timer.now(); console.log(i, now); - assert(now >= last_ts + 1, 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); + assert(now >= last_ts + 1, + 'current ts ' + now + ' < prev ts ' + last_ts + ' + 1'); last_ts = now; // schedule next iteration diff --git a/test/parallel/test-timers-this.js b/test/parallel/test-timers-this.js index cacb3f247cc4b8..df710b9cb8d5c9 100644 --- a/test/parallel/test-timers-this.js +++ b/test/parallel/test-timers-this.js @@ -1,37 +1,38 @@ +'use strict'; var assert = require('assert'); var immediateThis, intervalThis, timeoutThis, immediateArgsThis, intervalArgsThis, timeoutArgsThis; -var immediateHandler = setImmediate(function () { +var immediateHandler = setImmediate(function() { immediateThis = this; }); -var immediateArgsHandler = setImmediate(function () { +var immediateArgsHandler = setImmediate(function() { immediateArgsThis = this; -}, "args ..."); +}, 'args ...'); -var intervalHandler = setInterval(function () { +var intervalHandler = setInterval(function() { clearInterval(intervalHandler); intervalThis = this; }); -var intervalArgsHandler = setInterval(function () { +var intervalArgsHandler = setInterval(function() { clearInterval(intervalArgsHandler); intervalArgsThis = this; -}, 0, "args ..."); +}, 0, 'args ...'); -var timeoutHandler = setTimeout(function () { +var timeoutHandler = setTimeout(function() { timeoutThis = this; }); -var timeoutArgsHandler = setTimeout(function () { +var timeoutArgsHandler = setTimeout(function() { timeoutArgsThis = this; -}, 0, "args ..."); +}, 0, 'args ...'); -process.once('exit', function () { +process.once('exit', function() { assert.strictEqual(immediateThis, immediateHandler); assert.strictEqual(immediateArgsThis, immediateArgsHandler); diff --git a/test/parallel/test-timers-uncaught-exception.js b/test/parallel/test-timers-uncaught-exception.js index 4e137427939654..794b3b923be1df 100644 --- a/test/parallel/test-timers-uncaught-exception.js +++ b/test/parallel/test-timers-uncaught-exception.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers-unref-call.js b/test/parallel/test-timers-unref-call.js index 4f7865b8457601..b348330d200d65 100644 --- a/test/parallel/test-timers-unref-call.js +++ b/test/parallel/test-timers-unref-call.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var Timer = process.binding('timer_wrap').Timer; diff --git a/test/parallel/test-timers-unref-leak.js b/test/parallel/test-timers-unref-leak.js index c8f958a47c40d2..55907d9bc4898d 100644 --- a/test/parallel/test-timers-unref-leak.js +++ b/test/parallel/test-timers-unref-leak.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var called = 0; diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 2f750228a4ef3f..ab2e33acd21019 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -53,9 +54,14 @@ setInterval(function() { })(); process.on('exit', function() { - assert.strictEqual(interval_fired, false, 'Interval should not fire'); - assert.strictEqual(timeout_fired, false, 'Timeout should not fire'); - assert.strictEqual(unref_timer, true, 'An unrefd timeout should still fire'); - assert.strictEqual(unref_interval, true, 'An unrefd interval should still fire'); - assert.strictEqual(unref_callbacks, 1, 'Callback should only run once'); + assert.strictEqual(interval_fired, false, + 'Interval should not fire'); + assert.strictEqual(timeout_fired, false, + 'Timeout should not fire'); + assert.strictEqual(unref_timer, true, + 'An unrefd timeout should still fire'); + assert.strictEqual(unref_interval, true, + 'An unrefd interval should still fire'); + assert.strictEqual(unref_callbacks, 1, + 'Callback should only run once'); }); diff --git a/test/parallel/test-timers-unrefd-interval-still-fires.js b/test/parallel/test-timers-unrefd-interval-still-fires.js index 3ea94454cfdb49..50a473b9c8b4b8 100644 --- a/test/parallel/test-timers-unrefd-interval-still-fires.js +++ b/test/parallel/test-timers-unrefd-interval-still-fires.js @@ -1,3 +1,4 @@ +'use strict'; /* * This test is a regression test for joyent/node#8900. */ diff --git a/test/parallel/test-timers-zero-timeout.js b/test/parallel/test-timers-zero-timeout.js index 939b8db1bb30db..1c84814363a641 100644 --- a/test/parallel/test-timers-zero-timeout.js +++ b/test/parallel/test-timers-zero-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-timers.js b/test/parallel/test-timers.js index dad1bcc69389a0..e784e262959d97 100644 --- a/test/parallel/test-timers.js +++ b/test/parallel/test-timers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-0-dns-altname.js b/test/parallel/test-tls-0-dns-altname.js index 0d01805154255a..fd10206a126359 100644 --- a/test/parallel/test-tls-0-dns-altname.js +++ b/test/parallel/test-tls-0-dns-altname.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -31,8 +32,8 @@ var server = tls.createServer({ assert.equal(cert.subjectaltname, 'DNS:google.com\0.evil.com, ' + 'DNS:just-another.com, ' + - 'IP Address:8.8.8.8, '+ - 'IP Address:8.8.4.4, '+ + 'IP Address:8.8.8.8, ' + + 'IP Address:8.8.4.4, ' + 'DNS:last.com'); c.write('ok'); }); diff --git a/test/parallel/test-tls-alert-handling.js b/test/parallel/test-tls-alert-handling.js new file mode 100644 index 00000000000000..ed8999b6b7a409 --- /dev/null +++ b/test/parallel/test-tls-alert-handling.js @@ -0,0 +1,91 @@ +'use strict'; +var common = require('../common'); +var assert = require('assert'); + +if (!common.opensslCli) { + console.error('Skipping because node compiled without OpenSSL CLI.'); + process.exit(0); +} + +if (!common.hasCrypto) { + console.log('1..0 # Skipped: missing crypto'); + process.exit(); +} + +var tls = require('tls'); +var net = require('net'); +var fs = require('fs'); + +var success = false; + +function filenamePEM(n) { + return require('path').join(common.fixturesDir, 'keys', n + '.pem'); +} + +function loadPEM(n) { + return fs.readFileSync(filenamePEM(n)); +} + +var opts = { + key: loadPEM('agent2-key'), + cert: loadPEM('agent2-cert') +}; + +var max_iter = 20; +var iter = 0; + +var server = tls.createServer(opts, function(s) { + s.pipe(s); + s.on('error', function(e) { + // ignore error + }); +}); + +server.listen(common.PORT, function() { + sendClient(); +}); + + +function sendClient() { + var client = tls.connect(common.PORT, { + rejectUnauthorized: false + }); + client.on('data', function(chunk) { + if (iter++ === 2) sendBADTLSRecord(); + if (iter < max_iter) { + client.write('a'); + return; + } + client.end(); + server.close(); + success = true; + }); + client.write('a'); + client.on('error', function(e) { + // ignore error + }); + client.on('close', function() { + server.close(); + }); +} + + +function sendBADTLSRecord() { + var BAD_RECORD = new Buffer([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + var socket = net.connect(common.PORT); + var client = tls.connect({ + socket: socket, + rejectUnauthorized: false + }, function() { + socket.write(BAD_RECORD); + socket.end(); + }); + client.on('error', function(e) { + // ignore error + }); +} + +process.on('exit', function() { + assert(iter === max_iter); + assert(success); +}); diff --git a/test/parallel/test-tls-alert.js b/test/parallel/test-tls-alert.js index a96a104f24d3d2..97087d0b3b4c03 100644 --- a/test/parallel/test-tls-alert.js +++ b/test/parallel/test-tls-alert.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -30,7 +31,8 @@ var server = tls.Server({ key: loadPEM('agent2-key'), cert:loadPEM('agent2-cert') }, null).listen(common.PORT, function() { - var args = ['s_client', '-quiet', '-tls1_1','-connect', '127.0.0.1:' + common.PORT]; + var args = ['s_client', '-quiet', '-tls1_1', + '-connect', '127.0.0.1:' + common.PORT]; var client = spawn(common.opensslCli, args); var out = ''; client.stderr.setEncoding('utf8'); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index c7b1742856aead..24bc4242749f6c 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-tls-check-server-identity.js b/test/parallel/test-tls-check-server-identity.js index 85413b62e3d591..e40cbb0f9da137 100644 --- a/test/parallel/test-tls-check-server-identity.js +++ b/test/parallel/test-tls-check-server-identity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index a2a4bba5bbd28c..25e44716c1d700 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js index 7874d3d25acd56..b64482b58dc03c 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-client-default-ciphers.js b/test/parallel/test-tls-client-default-ciphers.js index e1422bac6f3662..5da57173315a09 100644 --- a/test/parallel/test-tls-client-default-ciphers.js +++ b/test/parallel/test-tls-client-default-ciphers.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); @@ -15,7 +16,7 @@ function test1() { tls.createSecureContext = function(options) { ciphers = options.ciphers; throw new Done(); - } + }; try { var s = tls.connect(common.PORT); diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js index 08b261a7222e0c..6a1a899103d9e9 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -1,3 +1,4 @@ +'use strict'; // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. diff --git a/test/parallel/test-tls-client-reject.js b/test/parallel/test-tls-client-reject.js index 887ff283ad0a52..9e09493c6a464d 100644 --- a/test/parallel/test-tls-client-reject.js +++ b/test/parallel/test-tls-client-reject.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-client-resume.js b/test/parallel/test-tls-client-resume.js index 75d96b69335d84..8b36224a7f2a37 100644 --- a/test/parallel/test-tls-client-resume.js +++ b/test/parallel/test-tls-client-resume.js @@ -1,3 +1,4 @@ +'use strict'; // Create an ssl server. First connection, validate that not resume. // Cache session and close connection. Use session on second connection. // ASSERT resumption. diff --git a/test/parallel/test-tls-client-verify.js b/test/parallel/test-tls-client-verify.js index bdbde6f9931175..f206929f59560c 100644 --- a/test/parallel/test-tls-client-verify.js +++ b/test/parallel/test-tls-client-verify.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-close-notify.js b/test/parallel/test-tls-close-notify.js index 3960a62694042e..cfb9aab0d9789f 100644 --- a/test/parallel/test-tls-close-notify.js +++ b/test/parallel/test-tls-close-notify.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/parallel/test-tls-connect-given-socket.js b/test/parallel/test-tls-connect-given-socket.js index e309d824aba201..9e8170b13af1b7 100644 --- a/test/parallel/test-tls-connect-given-socket.js +++ b/test/parallel/test-tls-connect-given-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-connect-no-host.js b/test/parallel/test-tls-connect-no-host.js index 41aac1acabd781..30d78dfa6ed548 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.hasCrypto) { @@ -29,6 +30,6 @@ var socket = tls.connect({ // Error: Hostname/IP doesn't match certificate's altnames: // "Host: undefined. is not cert's CN: localhost" }, function() { - assert(socket.authorized); - process.exit(); + assert(socket.authorized); + process.exit(); }); diff --git a/test/parallel/test-tls-connect-pipe.js b/test/parallel/test-tls-connect-pipe.js index 70daa0d75ab047..bded532720f98b 100644 --- a/test/parallel/test-tls-connect-pipe.js +++ b/test/parallel/test-tls-connect-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-connect-simple.js b/test/parallel/test-tls-connect-simple.js index 04eb5f408a6b81..feaa7c887b1e30 100644 --- a/test/parallel/test-tls-connect-simple.js +++ b/test/parallel/test-tls-connect-simple.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-connect-stream-writes.js b/test/parallel/test-tls-connect-stream-writes.js new file mode 100644 index 00000000000000..4187c9b439e2f1 --- /dev/null +++ b/test/parallel/test-tls-connect-stream-writes.js @@ -0,0 +1,66 @@ +'use strict'; +var assert = require('assert'), + fs = require('fs'), + path = require('path'), + tls = require('tls'), + stream = require('stream'), + net = require('net'); + +var common = require('../common'); + +var server; +var cert_dir = path.resolve(__dirname, '../fixtures'), + options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), + cert: fs.readFileSync(cert_dir + '/test_cert.pem'), + ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ], + ciphers: 'AES256-GCM-SHA384' }; +var content = 'hello world'; +var recv_bufs = []; +var send_data = ''; +server = tls.createServer(options, function(s) { + s.on('data', function(c) { + recv_bufs.push(c); + }); +}); +server.listen(common.PORT, function() { + var raw = net.connect(common.PORT); + + var pending = false; + raw.on('readable', function() { + if (pending) + p._read(); + }); + + var p = new stream.Duplex({ + read: function read() { + pending = false; + + var chunk = raw.read(); + if (chunk) { + this.push(chunk); + } else { + pending = true; + } + }, + write: function write(data, enc, cb) { + raw.write(data, enc, cb); + } + }); + + var socket = tls.connect({ + socket: p, + rejectUnauthorized: false + }, function() { + for (var i = 0; i < 50; ++i) { + socket.write(content); + send_data += content; + } + socket.end(); + server.close(); + }); +}); + +process.on('exit', function() { + var recv_data = (Buffer.concat(recv_bufs)).toString(); + assert.strictEqual(send_data, recv_data); +}); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index f74dc089533c00..160d874bed3355 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-delayed-attach.js b/test/parallel/test-tls-delayed-attach.js index fba10ceffd97bd..00731592445f04 100644 --- a/test/parallel/test-tls-delayed-attach.js +++ b/test/parallel/test-tls-delayed-attach.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-dhe.js b/test/parallel/test-tls-dhe.js index eb59c84957b52d..92fff3f221b65f 100644 --- a/test/parallel/test-tls-dhe.js +++ b/test/parallel/test-tls-dhe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -61,8 +62,9 @@ function test(keylen, expectedCipher, cb) { } function test512() { - test(512, 'DHE-RSA-AES128-SHA256', test1024); - ntests++; + assert.throws(function() { + test(512, 'DHE-RSA-AES128-SHA256', null); + }, /DH parameter is less than 1024 bits/); } function test1024() { @@ -76,12 +78,13 @@ function test2048() { } function testError() { - test('error', 'ECDHE-RSA-AES128-SHA256', null); + test('error', 'ECDHE-RSA-AES128-SHA256', test512); ntests++; } -test512(); +test1024(); process.on('exit', function() { assert.equal(ntests, nsuccess); + assert.equal(ntests, 3); }); diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js index 1799ec454c0cec..1ed4ea35738d5f 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-ecdh.js b/test/parallel/test-tls-ecdh.js index 042491672ff407..cd144d79e0e073 100644 --- a/test/parallel/test-tls-ecdh.js +++ b/test/parallel/test-tls-ecdh.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-econnreset.js b/test/parallel/test-tls-econnreset.js index c339fc5be60a61..f451df68470c53 100644 --- a/test/parallel/test-tls-econnreset.js +++ b/test/parallel/test-tls-econnreset.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js index e9245aa0d5eae1..24e8bfc6886f16 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-friendly-error-message.js b/test/parallel/test-tls-friendly-error-message.js index efff0c66a3169b..b2f2de137da8fa 100644 --- a/test/parallel/test-tls-friendly-error-message.js +++ b/test/parallel/test-tls-friendly-error-message.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-getcipher.js b/test/parallel/test-tls-getcipher.js index 414010c0336e7e..12e3b8f9c64ecf 100644 --- a/test/parallel/test-tls-getcipher.js +++ b/test/parallel/test-tls-getcipher.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-handshake-nohang.js b/test/parallel/test-tls-handshake-nohang.js index 73869892fb9ff7..181d6408e05abc 100644 --- a/test/parallel/test-tls-handshake-nohang.js +++ b/test/parallel/test-tls-handshake-nohang.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-hello-parser-failure.js b/test/parallel/test-tls-hello-parser-failure.js index 463fdaa44b53e3..3ed82c536a9e7a 100644 --- a/test/parallel/test-tls-hello-parser-failure.js +++ b/test/parallel/test-tls-hello-parser-failure.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -40,7 +41,7 @@ var server = tls.createServer(options, function(c) { } }); - client.on('close', function (hadError) { + client.on('close', function(hadError) { assert.strictEqual(hadError, true, 'Client never errored'); }); }); diff --git a/test/parallel/test-tls-inception.js b/test/parallel/test-tls-inception.js index 7fd0b813d6d4c4..76e6fe077ffef9 100644 --- a/test/parallel/test-tls-inception.js +++ b/test/parallel/test-tls-inception.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -20,7 +21,7 @@ options = { }; // the "proxy" server -a = tls.createServer(options, function (socket) { +a = tls.createServer(options, function(socket) { var options = { host: '127.0.0.1', port: b.address().port, @@ -36,16 +37,16 @@ a = tls.createServer(options, function (socket) { }); // the "target" server -b = tls.createServer(options, function (socket) { +b = tls.createServer(options, function(socket) { socket.end('hello'); }); -process.on('exit', function () { +process.on('exit', function() { assert(gotHello); }); -a.listen(common.PORT, function () { - b.listen(common.PORT + 1, function () { +a.listen(common.PORT, function() { + b.listen(common.PORT + 1, function() { options = { host: '127.0.0.1', port: a.address().port, @@ -58,11 +59,11 @@ a.listen(common.PORT, function () { rejectUnauthorized: false }); ssl.setEncoding('utf8'); - ssl.once('data', function (data) { + ssl.once('data', function(data) { assert.equal('hello', data); gotHello = true; }); - ssl.on('end', function () { + ssl.on('end', function() { ssl.end(); a.close(); b.close(); diff --git a/test/parallel/test-tls-interleave.js b/test/parallel/test-tls-interleave.js index 96a7a600381d1b..e726e16998a908 100644 --- a/test/parallel/test-tls-interleave.js +++ b/test/parallel/test-tls-interleave.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index c6e94158829c35..f9607e1f4fa928 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-js-stream.js b/test/parallel/test-tls-js-stream.js index 12c3381cb4fd60..e156f446f57de9 100644 --- a/test/parallel/test-tls-js-stream.js +++ b/test/parallel/test-tls-js-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-junk-closes-server.js b/test/parallel/test-tls-junk-closes-server.js index 3fd129cbf6d470..01a83ef214e0b6 100644 --- a/test/parallel/test-tls-junk-closes-server.js +++ b/test/parallel/test-tls-junk-closes-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.hasCrypto) { diff --git a/test/parallel/test-tls-key-mismatch.js b/test/parallel/test-tls-key-mismatch.js index cd7ad605a89675..35da4687493a21 100644 --- a/test/parallel/test-tls-key-mismatch.js +++ b/test/parallel/test-tls-key-mismatch.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js index 4033b308acdb71..3e41cfa45c7d30 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-multi-key.js b/test/parallel/test-tls-multi-key.js index 85ff5e808cfe16..76aa97d1ff3daf 100644 --- a/test/parallel/test-tls-multi-key.js +++ b/test/parallel/test-tls-multi-key.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-no-cert-required.js b/test/parallel/test-tls-no-cert-required.js index 75afc110999aa6..02bbb6b664a2cf 100644 --- a/test/parallel/test-tls-no-cert-required.js +++ b/test/parallel/test-tls-no-cert-required.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.hasCrypto) { diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js index 389cd329c6fd4f..fd64438ead7f4e 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-no-sslv23.js b/test/parallel/test-tls-no-sslv23.js index 56fd89f76a3225..931bf5dba050b9 100644 --- a/test/parallel/test-tls-no-sslv23.js +++ b/test/parallel/test-tls-no-sslv23.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-no-sslv3.js b/test/parallel/test-tls-no-sslv3.js index 0fc0dcc3ae3fea..4e1975a1e00a25 100644 --- a/test/parallel/test-tls-no-sslv3.js +++ b/test/parallel/test-tls-no-sslv3.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-npn-server-client.js b/test/parallel/test-tls-npn-server-client.js index 406751b0289cb5..bebb6799b9f49c 100644 --- a/test/parallel/test-tls-npn-server-client.js +++ b/test/parallel/test-tls-npn-server-client.js @@ -1,3 +1,4 @@ +'use strict'; if (!process.features.tls_npn) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); diff --git a/test/parallel/test-tls-ocsp-callback.js b/test/parallel/test-tls-ocsp-callback.js index a9ac6ffa17d359..73f1c5772a59fb 100644 --- a/test/parallel/test-tls-ocsp-callback.js +++ b/test/parallel/test-tls-ocsp-callback.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!process.features.tls_ocsp) { diff --git a/test/parallel/test-tls-on-empty-socket.js b/test/parallel/test-tls-on-empty-socket.js index f4866701e23eb5..8d95a997200786 100644 --- a/test/parallel/test-tls-on-empty-socket.js +++ b/test/parallel/test-tls-on-empty-socket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index c851f02a575259..cf7ab78685c364 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js index f1253ee51b986f..ce68fce5f02b99 100644 --- a/test/parallel/test-tls-passphrase.js +++ b/test/parallel/test-tls-passphrase.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-pause.js b/test/parallel/test-tls-pause.js index 95f293d234e803..f9d68f1395420a 100644 --- a/test/parallel/test-tls-pause.js +++ b/test/parallel/test-tls-pause.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js index 536bfae2031934..533b9126cda573 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-peer-certificate-multi-keys.js b/test/parallel/test-tls-peer-certificate-multi-keys.js index 3488600e272091..fde55af50be2bf 100644 --- a/test/parallel/test-tls-peer-certificate-multi-keys.js +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js index a1a19d7035d3ca..8164154779f998 100644 --- a/test/parallel/test-tls-peer-certificate.js +++ b/test/parallel/test-tls-peer-certificate.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -36,13 +37,13 @@ server.listen(common.PORT, function() { common.debug(util.inspect(peerCert)); assert.equal(peerCert.subject.emailAddress, 'ry@tinyclouds.org'); - assert.equal(peerCert.serialNumber, '9A84ABCFB8A72ABE'); + assert.equal(peerCert.serialNumber, '9A84ABCFB8A72AC0'); assert.deepEqual(peerCert.infoAccess['OCSP - URI'], [ 'http://ocsp.nodejs.org/' ]); var issuer = peerCert.issuerCertificate; assert.ok(issuer.issuerCertificate === issuer); - assert.equal(issuer.serialNumber, 'B5090C899FC2FF93'); + assert.equal(issuer.serialNumber, '8DF21C01468AF393'); verified = true; server.close(); }); diff --git a/test/parallel/test-tls-request-timeout.js b/test/parallel/test-tls-request-timeout.js index 10a14696c43a71..dce27a2591289b 100644 --- a/test/parallel/test-tls-request-timeout.js +++ b/test/parallel/test-tls-request-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index 99bd4dd6f92606..7ddba939bacd30 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-server-verify.js b/test/parallel/test-tls-server-verify.js index 0204bc5d1f074e..f30134f04ac0a5 100644 --- a/test/parallel/test-tls-server-verify.js +++ b/test/parallel/test-tls-server-verify.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-tls-session-cache.js b/test/parallel/test-tls-session-cache.js index 8ba2deec2e2ebd..7ba063a3a029af 100644 --- a/test/parallel/test-tls-session-cache.js +++ b/test/parallel/test-tls-session-cache.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js index ba4341633b0895..f5284c1b58b4ac 100644 --- a/test/parallel/test-tls-set-ciphers.js +++ b/test/parallel/test-tls-set-ciphers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { diff --git a/test/parallel/test-tls-set-encoding.js b/test/parallel/test-tls-set-encoding.js index d73572c93ba0f7..fa0d72b5ad4bd7 100644 --- a/test/parallel/test-tls-set-encoding.js +++ b/test/parallel/test-tls-set-encoding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-sni-option.js b/test/parallel/test-tls-sni-option.js index 3768c7eaac8f48..68ef2caa9819d3 100644 --- a/test/parallel/test-tls-sni-option.js +++ b/test/parallel/test-tls-sni-option.js @@ -1,3 +1,4 @@ +'use strict'; if (!process.features.tls_sni) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); @@ -146,6 +147,6 @@ process.on('exit', function() { assert.deepEqual(serverResults, ['a.example.com', 'b.example.com', 'c.wrong.com', null]); assert.deepEqual(clientResults, [true, true, false, false]); - assert.deepEqual(clientErrors, [null, null, null, "socket hang up"]); - assert.deepEqual(serverErrors, [null, null, null, "Invalid SNI context"]); + assert.deepEqual(clientErrors, [null, null, null, 'socket hang up']); + assert.deepEqual(serverErrors, [null, null, null, 'Invalid SNI context']); }); diff --git a/test/parallel/test-tls-sni-server-client.js b/test/parallel/test-tls-sni-server-client.js index 7a1d09b9c2ef07..dec829face184e 100644 --- a/test/parallel/test-tls-sni-server-client.js +++ b/test/parallel/test-tls-sni-server-client.js @@ -1,3 +1,4 @@ +'use strict'; if (!process.features.tls_sni) { console.error('Skipping because node compiled without OpenSSL or ' + 'with old OpenSSL version.'); @@ -35,6 +36,11 @@ var SNIContexts = { 'asterisk.test.com': { key: loadPEM('agent3-key'), cert: loadPEM('agent3-cert') + }, + 'chain.example.com': { + key: loadPEM('agent6-key'), + // NOTE: Contains ca3 chain cert + cert: loadPEM('agent6-cert') } }; @@ -42,32 +48,29 @@ var serverPort = common.PORT; var clientsOptions = [{ port: serverPort, - key: loadPEM('agent1-key'), - cert: loadPEM('agent1-cert'), ca: [loadPEM('ca1-cert')], servername: 'a.example.com', rejectUnauthorized: false }, { port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), ca: [loadPEM('ca2-cert')], servername: 'b.test.com', rejectUnauthorized: false }, { port: serverPort, - key: loadPEM('agent2-key'), - cert: loadPEM('agent2-cert'), ca: [loadPEM('ca2-cert')], servername: 'a.b.test.com', rejectUnauthorized: false }, { port: serverPort, - key: loadPEM('agent3-key'), - cert: loadPEM('agent3-cert'), ca: [loadPEM('ca1-cert')], servername: 'c.wrong.com', rejectUnauthorized: false +}, { + port: serverPort, + ca: [loadPEM('ca1-cert')], + servername: 'chain.example.com', + rejectUnauthorized: false }]; var serverResults = [], @@ -79,6 +82,7 @@ var server = tls.createServer(serverOptions, function(c) { server.addContext('a.example.com', SNIContexts['a.example.com']); server.addContext('*.test.com', SNIContexts['asterisk.test.com']); +server.addContext('chain.example.com', SNIContexts['chain.example.com']); server.listen(serverPort, startTest); @@ -105,7 +109,9 @@ function startTest() { } process.on('exit', function() { - assert.deepEqual(serverResults, ['a.example.com', 'b.test.com', - 'a.b.test.com', 'c.wrong.com']); - assert.deepEqual(clientResults, [true, true, false, false]); + assert.deepEqual(serverResults, [ + 'a.example.com', 'b.test.com', 'a.b.test.com', 'c.wrong.com', + 'chain.example.com' + ]); + assert.deepEqual(clientResults, [true, true, false, false, true]); }); diff --git a/test/parallel/test-tls-ticket-cluster.js b/test/parallel/test-tls-ticket-cluster.js index 1b20e5ac8e90d9..a9798df0597945 100644 --- a/test/parallel/test-tls-ticket-cluster.js +++ b/test/parallel/test-tls-ticket-cluster.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-ticket.js b/test/parallel/test-tls-ticket.js index cf5cae9c8a8f7c..450f6b54a52809 100644 --- a/test/parallel/test-tls-ticket.js +++ b/test/parallel/test-tls-ticket.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -31,7 +32,9 @@ function createServer() { return server; } -var servers = [ createServer(), createServer(), createServer(), createServer(), createServer(), createServer() ]; +var servers = [ createServer(), createServer(), + createServer(), createServer(), + createServer(), createServer() ]; // Create one TCP server and balance sockets to multiple TLS server instances var shared = net.createServer(function(c) { diff --git a/test/parallel/test-tls-timeout-server-2.js b/test/parallel/test-tls-timeout-server-2.js index a16ce33167bb48..e752c004d3abbb 100644 --- a/test/parallel/test-tls-timeout-server-2.js +++ b/test/parallel/test-tls-timeout-server-2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-timeout-server.js b/test/parallel/test-tls-timeout-server.js index 47845fae39751c..4a9265079bf136 100644 --- a/test/parallel/test-tls-timeout-server.js +++ b/test/parallel/test-tls-timeout-server.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-wrap-timeout.js b/test/parallel/test-tls-wrap-timeout.js index 3013f68886597f..87534cfd2e95ef 100644 --- a/test/parallel/test-tls-wrap-timeout.js +++ b/test/parallel/test-tls-wrap-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tls-zero-clear-in.js b/test/parallel/test-tls-zero-clear-in.js index 38b21f401e21a4..6eeba92585603f 100644 --- a/test/parallel/test-tls-zero-clear-in.js +++ b/test/parallel/test-tls-zero-clear-in.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tty-stdout-end.js b/test/parallel/test-tty-stdout-end.js index a2f3ad12f4aca7..190acae42870a9 100644 --- a/test/parallel/test-tty-stdout-end.js +++ b/test/parallel/test-tty-stdout-end.js @@ -1,3 +1,4 @@ +'use strict'; // Can't test this when 'make test' doesn't assign a tty to the stdout. var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-tty-wrap.js b/test/parallel/test-tty-wrap.js index 1cd014992dcad6..370c959ea297a6 100644 --- a/test/parallel/test-tty-wrap.js +++ b/test/parallel/test-tty-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-umask.js b/test/parallel/test-umask.js index 84c34412189d25..94d3a1d06f9c6c 100644 --- a/test/parallel/test-umask.js +++ b/test/parallel/test-umask.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-url.js b/test/parallel/test-url.js index 121d6caaf612e3..e0587ae743d9b1 100644 --- a/test/parallel/test-url.js +++ b/test/parallel/test-url.js @@ -1,3 +1,5 @@ +/* eslint-disable max-len */ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -553,7 +555,6 @@ var parseTests = { 'http://bucket_name.s3.amazonaws.com/image.jpg': { protocol: 'http:', - 'slashes': true, slashes: true, host: 'bucket_name.s3.amazonaws.com', hostname: 'bucket_name.s3.amazonaws.com', @@ -857,11 +858,11 @@ var parseTests = { }; for (var u in parseTests) { - var actual = url.parse(u), - spaced = url.parse(' \t ' + u + '\n\t'); - expected = parseTests[u]; + var actual = url.parse(u); + var spaced = url.parse(' \t ' + u + '\n\t'); + var expected = parseTests[u]; - Object.keys(actual).forEach(function (i) { + Object.keys(actual).forEach(function(i) { if (expected[i] === undefined && actual[i] === null) { expected[i] = null; } @@ -1097,7 +1098,7 @@ var formatTests = { query: { foo: 'theA1' }, - hash: "#bar" + hash: '#bar' }, // `#`,`?` in path + `#` in query @@ -1107,7 +1108,7 @@ var formatTests = { query: { foo: 'the#1' }, - hash: "#bar" + hash: '#bar' }, // `?` and `#` in path and search @@ -1269,7 +1270,7 @@ var relativeTests2 = [ ['g?y#s', bases[0], 'http://a/b/c/g?y#s'], [';x', bases[0], 'http://a/b/c/;x'], ['g;x', bases[0], 'http://a/b/c/g;x'], - ['g;x?y#s' , bases[0], 'http://a/b/c/g;x?y#s'], + ['g;x?y#s', bases[0], 'http://a/b/c/g;x?y#s'], // changed with RFC 2396bis //('', bases[0], CURRENT_DOC_URI], ['', bases[0], 'http://a/b/c/d;p?q'], @@ -1280,7 +1281,7 @@ var relativeTests2 = [ ['../g', bases[0], 'http://a/b/g'], ['../..', bases[0], 'http://a/'], ['../../', bases[0], 'http://a/'], - ['../../g' , bases[0], 'http://a/g'], + ['../../g', bases[0], 'http://a/g'], ['../../../g', bases[0], ('http://a/../g', 'http://a/g')], ['../../../../g', bases[0], ('http://a/../../g', 'http://a/g')], // changed with RFC 2396bis @@ -1319,16 +1320,16 @@ var relativeTests2 = [ //('?y', bases[1], 'http://a/b/c/?y'], ['?y', bases[1], 'http://a/b/c/d;p?y'], ['g?y', bases[1], 'http://a/b/c/g?y'], - ['g?y/./x' , bases[1], 'http://a/b/c/g?y/./x'], + ['g?y/./x', bases[1], 'http://a/b/c/g?y/./x'], ['g?y/../x', bases[1], 'http://a/b/c/g?y/../x'], ['g#s', bases[1], 'http://a/b/c/g#s'], - ['g#s/./x' , bases[1], 'http://a/b/c/g#s/./x'], + ['g#s/./x', bases[1], 'http://a/b/c/g#s/./x'], ['g#s/../x', bases[1], 'http://a/b/c/g#s/../x'], ['./', bases[1], 'http://a/b/c/'], ['../', bases[1], 'http://a/b/'], ['../g', bases[1], 'http://a/b/g'], ['../../', bases[1], 'http://a/'], - ['../../g' , bases[1], 'http://a/g'], + ['../../g', bases[1], 'http://a/g'], // http://gbiv.com/protocols/uri/test/rel_examples3.html // slashes in path params @@ -1345,7 +1346,7 @@ var relativeTests2 = [ ['../', bases[2], 'http://a/b/c/'], ['../g', bases[2], 'http://a/b/c/g'], ['../../', bases[2], 'http://a/b/'], - ['../../g' , bases[2], 'http://a/b/g'], + ['../../g', bases[2], 'http://a/b/g'], // http://gbiv.com/protocols/uri/test/rel_examples4.html // double and triple slash, unknown scheme @@ -1362,7 +1363,7 @@ var relativeTests2 = [ ['../g', bases[3], 'fred:///s//a/g'], ['../../', bases[3], 'fred:///s//'], - ['../../g' , bases[3], 'fred:///s//g'], + ['../../g', bases[3], 'fred:///s//g'], ['../../../g', bases[3], 'fred:///s/g'], // may change to fred:///s//a/../../../g ['../../../../g', bases[3], 'fred:///g'], @@ -1381,7 +1382,7 @@ var relativeTests2 = [ ['../', bases[4], 'http:///s//a/'], ['../g', bases[4], 'http:///s//a/g'], ['../../', bases[4], 'http:///s//'], - ['../../g' , bases[4], 'http:///s//g'], + ['../../g', bases[4], 'http:///s//g'], // may change to http:///s//a/../../g ['../../../g', bases[4], 'http:///s/g'], // may change to http:///s//a/../../../g @@ -1569,10 +1570,10 @@ var throws = [ true, false, 0, - function () {} + function() {} ]; for (var i = 0; i < throws.length; i++) { - assert.throws(function () { url.format(throws[i]); }, TypeError); + assert.throws(function() { url.format(throws[i]); }, TypeError); }; assert(url.format('') === ''); assert(url.format({}) === ''); diff --git a/test/parallel/test-utf8-scripts.js b/test/parallel/test-utf8-scripts.js index b9bef97a5eabfe..3a891283509b9e 100644 --- a/test/parallel/test-utf8-scripts.js +++ b/test/parallel/test-utf8-scripts.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index 715509419806af..6761671e1997bd 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -57,8 +58,10 @@ assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); assert.equal(util.format(new Error('foo')), '[Error: foo]'); function CustomError(msg) { Error.call(this); - Object.defineProperty(this, 'message', { value: msg, enumerable: false }); - Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); + Object.defineProperty(this, 'message', + { value: msg, enumerable: false }); + Object.defineProperty(this, 'name', + { value: 'CustomError', enumerable: false }); } util.inherits(CustomError, Error); assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index f4aeced4d98abc..3e51e8485a9b4b 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -92,7 +93,7 @@ var w = { '\\\\': 2, '\\\\\\': 3, '\\\\\\\\': 4, -} +}; var y = ['a', 'b', 'c']; y['\\\\\\'] = 'd'; @@ -112,16 +113,16 @@ function test_color_style(style, input, implicit) { var with_color = util.inspect(input, false, 0, true); var expect = '\u001b[' + color[0] + 'm' + without_color + '\u001b[' + color[1] + 'm'; - assert.equal(with_color, expect, 'util.inspect color for style '+style); + assert.equal(with_color, expect, 'util.inspect color for style ' + style); } -test_color_style('special', function(){}); +test_color_style('special', function() {}); test_color_style('number', 123.456); test_color_style('boolean', true); test_color_style('undefined', undefined); test_color_style('null', null); test_color_style('string', 'test string'); -test_color_style('date', new Date); +test_color_style('date', new Date()); test_color_style('regexp', /regexp/); // an object with "hasOwnProperty" overwritten should not throw @@ -146,10 +147,14 @@ assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); // "customInspect" option can enable/disable calling inspect() on objects subject = { inspect: function() { return 123; } }; -assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); -assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); +assert(util.inspect(subject, + { customInspect: true }).indexOf('123') !== -1); +assert(util.inspect(subject, + { customInspect: true }).indexOf('inspect') === -1); +assert(util.inspect(subject, + { customInspect: false }).indexOf('123') === -1); +assert(util.inspect(subject, + { customInspect: false }).indexOf('inspect') !== -1); // custom inspect() functions should be able to return other Objects subject.inspect = function() { return { foo: 'bar' }; }; @@ -166,7 +171,7 @@ util.inspect(subject, { customInspectOptions: true }); function test_lines(input) { var count_lines = function(str) { return (str.match(/\n/g) || []).length; - } + }; var without_color = util.inspect(input); var with_color = util.inspect(input, {colors: true}); @@ -232,6 +237,75 @@ if (typeof Symbol !== 'undefined') { subject[Symbol('symbol')] = 42; assert.equal(util.inspect(subject), '[ 1, 2, 3 ]'); - assert.equal(util.inspect(subject, options), '[ 1, 2, 3, [length]: 3, [Symbol(symbol)]: 42 ]'); + assert.equal(util.inspect(subject, options), + '[ 1, 2, 3, [length]: 3, [Symbol(symbol)]: 42 ]'); + +} +<<<<<<< HEAD +======= + +// test Set +assert.equal(util.inspect(new Set()), 'Set {}'); +assert.equal(util.inspect(new Set([1, 2, 3])), 'Set { 1, 2, 3 }'); +var set = new Set(['foo']); +set.bar = 42; +assert.equal(util.inspect(set, true), 'Set { \'foo\', [size]: 1, bar: 42 }'); + +// test Map +assert.equal(util.inspect(new Map()), 'Map {}'); +assert.equal(util.inspect(new Map([[1, 'a'], [2, 'b'], [3, 'c']])), + 'Map { 1 => \'a\', 2 => \'b\', 3 => \'c\' }'); +var map = new Map([['foo', null]]); +map.bar = 42; +assert.equal(util.inspect(map, true), + 'Map { \'foo\' => null, [size]: 1, bar: 42 }'); + +// test Promise +assert.equal(util.inspect(Promise.resolve(3)), 'Promise { 3 }'); +assert.equal(util.inspect(Promise.reject(3)), 'Promise { 3 }'); +assert.equal(util.inspect(new Promise(function() {})), 'Promise { }'); +var promise = Promise.resolve('foo'); +promise.bar = 42; +assert.equal(util.inspect(promise), 'Promise { \'foo\', bar: 42 }'); + +// Make sure it doesn't choke on polyfills. Unlike Set/Map, there is no standard +// interface to synchronously inspect a Promise, so our techniques only work on +// a bonafide native Promise. +var oldPromise = Promise; +global.Promise = function() { this.bar = 42; }; +assert.equal(util.inspect(new Promise()), '{ bar: 42 }'); +global.Promise = oldPromise; + + +// Test alignment of items in container +// Assumes that the first numeric character is the start of an item. + +function checkAlignment(container) { + var lines = util.inspect(container).split('\n'); + var pos; + lines.forEach(function(line) { + var npos = line.search(/\d/); + if (npos !== -1) { + if (pos !== undefined) + assert.equal(pos, npos, 'container items not aligned'); + pos = npos; + } + }); +} +var big_array = []; +for (var i = 0; i < 100; i++) { + big_array.push(i); } + +checkAlignment(big_array); +checkAlignment(function() { + var obj = {}; + big_array.forEach(function(v) { + obj[v] = null; + }); + return obj; +}()); +checkAlignment(new Set(big_array)); +checkAlignment(new Map(big_array.map(function(y) { return [y, null]; }))); +>>>>>>> f29762f... test: enable linting for tests diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index f157c80bec93dc..fbe3963348adb9 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var util = require('util'); @@ -17,7 +18,7 @@ var tests = [ {input: null, output: 'null'}, {input: false, output: 'false'}, {input: 42, output: '42'}, - {input: function(){}, output: '[Function]'}, + {input: function() {}, output: '[Function]'}, {input: parseInt('not a number', 10), output: 'NaN'}, {input: {answer: 42}, output: '{ answer: 42 }'}, {input: [1,2,3], output: '[ 1, 2, 3 ]'} diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 03456d64393842..2795d3ecd68662 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -13,7 +14,7 @@ assert.equal(true, util.isArray(context('Array')())); assert.equal(false, util.isArray({})); assert.equal(false, util.isArray({ push: function() {} })); assert.equal(false, util.isArray(/regexp/)); -assert.equal(false, util.isArray(new Error)); +assert.equal(false, util.isArray(new Error())); assert.equal(false, util.isArray(Object.create(Array.prototype))); // isRegExp @@ -33,13 +34,13 @@ assert.equal(true, util.isDate(new (context('Date')))); assert.equal(false, util.isDate(Date())); assert.equal(false, util.isDate({})); assert.equal(false, util.isDate([])); -assert.equal(false, util.isDate(new Error)); +assert.equal(false, util.isDate(new Error())); assert.equal(false, util.isDate(Object.create(Date.prototype))); // isError -assert.equal(true, util.isError(new Error)); -assert.equal(true, util.isError(new TypeError)); -assert.equal(true, util.isError(new SyntaxError)); +assert.equal(true, util.isError(new Error())); +assert.equal(true, util.isError(new TypeError())); +assert.equal(true, util.isError(new SyntaxError())); assert.equal(true, util.isError(new (context('Error')))); assert.equal(true, util.isError(new (context('TypeError')))); assert.equal(true, util.isError(new (context('SyntaxError')))); @@ -53,11 +54,11 @@ assert.ok(util.isObject({}) === true); // isPrimitive assert.equal(false, util.isPrimitive({})); -assert.equal(false, util.isPrimitive(new Error)); +assert.equal(false, util.isPrimitive(new Error())); assert.equal(false, util.isPrimitive(new Date())); assert.equal(false, util.isPrimitive([])); assert.equal(false, util.isPrimitive(/regexp/)); -assert.equal(false, util.isPrimitive(function(){})); +assert.equal(false, util.isPrimitive(function() {})); assert.equal(false, util.isPrimitive(new Number(1))); assert.equal(false, util.isPrimitive(new String('bla'))); assert.equal(false, util.isPrimitive(new Boolean(true))); @@ -81,7 +82,7 @@ assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); // inherits var ctor = function() {}; -assert.throws(function() { util.inherits(ctor, {}) }, TypeError); -assert.throws(function() { util.inherits(ctor, null) }, TypeError); -assert.throws(function() { util.inherits(null, ctor) }, TypeError); -assert.doesNotThrow(function() { util.inherits(ctor, ctor) }, TypeError); +assert.throws(function() { util.inherits(ctor, {}); }, TypeError); +assert.throws(function() { util.inherits(ctor, null); }, TypeError); +assert.throws(function() { util.inherits(null, ctor); }, TypeError); +assert.doesNotThrow(function() { util.inherits(ctor, ctor); }, TypeError); diff --git a/test/parallel/test-v8-flag-type-check.js b/test/parallel/test-v8-flag-type-check.js new file mode 100644 index 00000000000000..68bf30dba3cdbc --- /dev/null +++ b/test/parallel/test-v8-flag-type-check.js @@ -0,0 +1,7 @@ +'use strict'; +var common = require('../common'); +var assert = require('assert'); +var v8 = require('v8'); + +assert.throws(function() {v8.setFlagsFromString(1);}, TypeError); +assert.throws(function() {v8.setFlagsFromString();}, TypeError); diff --git a/test/parallel/test-v8-flags.js b/test/parallel/test-v8-flags.js index 886583e4c51229..d21cbc6c2635a5 100644 --- a/test/parallel/test-v8-flags.js +++ b/test/parallel/test-v8-flags.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var v8 = require('v8'); @@ -8,5 +9,5 @@ assert(eval('%_IsSmi(42)')); assert(vm.runInThisContext('%_IsSmi(42)')); v8.setFlagsFromString('--noallow_natives_syntax'); -assert.throws(function() { eval('%_IsSmi(42)') }, SyntaxError); -assert.throws(function() { vm.runInThisContext('%_IsSmi(42)') }, SyntaxError); +assert.throws(function() { eval('%_IsSmi(42)'); }, SyntaxError); +assert.throws(function() { vm.runInThisContext('%_IsSmi(42)'); }, SyntaxError); diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js index 7acb9db1e04306..e48c1d70365073 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var v8 = require('v8'); diff --git a/test/parallel/test-vm-basic.js b/test/parallel/test-vm-basic.js index 092aa1a6363904..96c615c44af10c 100644 --- a/test/parallel/test-vm-basic.js +++ b/test/parallel/test-vm-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-context-async-script.js b/test/parallel/test-vm-context-async-script.js index 979fc24a1671b4..e146d48343aa60 100644 --- a/test/parallel/test-vm-context-async-script.js +++ b/test/parallel/test-vm-context-async-script.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -7,7 +8,7 @@ var sandbox = { setTimeout: setTimeout }; var ctx = vm.createContext(sandbox); vm.runInContext('setTimeout(function() { x = 3; }, 0);', ctx); -setTimeout(function () { +setTimeout(function() { assert.strictEqual(sandbox.x, 3); assert.strictEqual(ctx.x, 3); }, 1); diff --git a/test/parallel/test-vm-context-property-forwarding.js b/test/parallel/test-vm-context-property-forwarding.js index b1012f5dee05a5..5fcd64b8ba9094 100644 --- a/test/parallel/test-vm-context-property-forwarding.js +++ b/test/parallel/test-vm-context-property-forwarding.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-context.js b/test/parallel/test-vm-context.js index cdf76529efc08b..45e19e6638892e 100644 --- a/test/parallel/test-vm-context.js +++ b/test/parallel/test-vm-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,7 +23,7 @@ assert.equal(3, context.foo); assert.equal('lala', context.thing); // Issue GH-227: -assert.throws(function () { +assert.throws(function() { vm.runInNewContext('', null, 'some.js'); }, TypeError); diff --git a/test/parallel/test-vm-create-and-run-in-context.js b/test/parallel/test-vm-create-and-run-in-context.js index cf6a4875d5aa64..01df6ad4531e4a 100644 --- a/test/parallel/test-vm-create-and-run-in-context.js +++ b/test/parallel/test-vm-create-and-run-in-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-vm-create-context-accessors.js b/test/parallel/test-vm-create-context-accessors.js index 23fc935389def8..678cf3fbd2128e 100644 --- a/test/parallel/test-vm-create-context-accessors.js +++ b/test/parallel/test-vm-create-context-accessors.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-create-context-arg.js b/test/parallel/test-vm-create-context-arg.js index 65dcf05e2b2bf3..d44eeec18decd5 100644 --- a/test/parallel/test-vm-create-context-arg.js +++ b/test/parallel/test-vm-create-context-arg.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -12,7 +13,7 @@ assert.doesNotThrow(function() { }); assert.doesNotThrow(function() { - var sandbox = {}; - vm.createContext(sandbox); - vm.createContext(sandbox); + var sandbox = {}; + vm.createContext(sandbox); + vm.createContext(sandbox); }); diff --git a/test/parallel/test-vm-create-context-circular-reference.js b/test/parallel/test-vm-create-context-circular-reference.js index ae23eba167b9fb..cb6a90dcaef321 100644 --- a/test/parallel/test-vm-create-context-circular-reference.js +++ b/test/parallel/test-vm-create-context-circular-reference.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-cross-context.js b/test/parallel/test-vm-cross-context.js index 56c6040be7f5d6..20a3792b28578e 100644 --- a/test/parallel/test-vm-cross-context.js +++ b/test/parallel/test-vm-cross-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -5,5 +6,5 @@ var vm = require('vm'); var ctx = vm.createContext(global); assert.doesNotThrow(function() { - vm.runInContext("!function() { var x = console.log; }()", ctx); + vm.runInContext('!function() { var x = console.log; }()', ctx); }); diff --git a/test/parallel/test-vm-debug-context.js b/test/parallel/test-vm-debug-context.js index 2c6919423d230e..72851f16040d4a 100644 --- a/test/parallel/test-vm-debug-context.js +++ b/test/parallel/test-vm-debug-context.js @@ -1,3 +1,5 @@ +/* eslint-disable no-debugger */ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-function-declaration.js b/test/parallel/test-vm-function-declaration.js index c9a4fbb03eb620..5ff194e12dd8d8 100644 --- a/test/parallel/test-vm-function-declaration.js +++ b/test/parallel/test-vm-function-declaration.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -13,7 +14,7 @@ code += 'function b(){}\n'; // Grab the global b function as the completion value, to ensure that // we are getting the global function, and not some other thing -code += '(function(){return this})().b;\n' +code += '(function(){return this})().b;\n'; var res = vm.runInContext(code, o, 'test'); diff --git a/test/parallel/test-vm-global-define-property.js b/test/parallel/test-vm-global-define-property.js index ea30a4f3156745..f7f3e4f3df7d76 100644 --- a/test/parallel/test-vm-global-define-property.js +++ b/test/parallel/test-vm-global-define-property.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-vm-global-identity.js b/test/parallel/test-vm-global-identity.js index bc3d9653a7c437..647edb22b44db0 100644 --- a/test/parallel/test-vm-global-identity.js +++ b/test/parallel/test-vm-global-identity.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-harmony-proxies.js b/test/parallel/test-vm-harmony-proxies.js index 859d77cd62d73b..2f008615ebaf54 100644 --- a/test/parallel/test-vm-harmony-proxies.js +++ b/test/parallel/test-vm-harmony-proxies.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --harmony_proxies var common = require('../common'); diff --git a/test/parallel/test-vm-harmony-symbols.js b/test/parallel/test-vm-harmony-symbols.js index 127e3c4a2b291e..86fde1b978ffb2 100644 --- a/test/parallel/test-vm-harmony-symbols.js +++ b/test/parallel/test-vm-harmony-symbols.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-is-context.js b/test/parallel/test-vm-is-context.js index 7b3d6616ee4a1d..5a46a452b91634 100644 --- a/test/parallel/test-vm-is-context.js +++ b/test/parallel/test-vm-is-context.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-vm-new-script-new-context.js b/test/parallel/test-vm-new-script-new-context.js index 742f247a11c19a..4619c9345c5e5c 100644 --- a/test/parallel/test-vm-new-script-new-context.js +++ b/test/parallel/test-vm-new-script-new-context.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; @@ -23,7 +24,7 @@ assert.throws(function() { console.error('undefined reference'); var error; script = new Script('foo.bar = 5;'); -assert.throws(function () { +assert.throws(function() { script.runInNewContext(); }, /not defined/); @@ -48,7 +49,7 @@ assert.equal(2, foo); console.error('call a function by reference'); script = new Script('f()'); -function changeFoo() { foo = 100 } +function changeFoo() { foo = 100; } script.runInNewContext({ f: changeFoo }); assert.equal(foo, 100); diff --git a/test/parallel/test-vm-new-script-this-context.js b/test/parallel/test-vm-new-script-this-context.js index 99d40bea2e2237..16d8acd1ca6700 100644 --- a/test/parallel/test-vm-new-script-this-context.js +++ b/test/parallel/test-vm-new-script-this-context.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var Script = require('vm').Script; @@ -34,7 +35,7 @@ assert.equal(2, bar); assert.equal(1, foo); console.error('call a function'); -f = function() { foo = 100 }; +f = function() { foo = 100; }; script = new Script('f()'); script.runInThisContext(script); assert.equal(100, foo); diff --git a/test/parallel/test-vm-run-in-new-context.js b/test/parallel/test-vm-run-in-new-context.js index 4772c3b99d9eb5..da14a041face31 100644 --- a/test/parallel/test-vm-run-in-new-context.js +++ b/test/parallel/test-vm-run-in-new-context.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ // Flags: --expose-gc var common = require('../common'); @@ -34,7 +35,7 @@ assert.equal(2, obj.bar); assert.equal(2, foo); console.error('call a function by reference'); -function changeFoo() { foo = 100 } +function changeFoo() { foo = 100; } vm.runInNewContext('f()', { f: changeFoo }); assert.equal(foo, 100); @@ -44,7 +45,7 @@ vm.runInNewContext('f.a = 2', { f: f }); assert.equal(f.a, 2); console.error('use function in context without referencing context'); -var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }) +var fn = vm.runInNewContext('(function() { obj.p = {}; })', { obj: {} }); gc(); fn(); // Should not crash diff --git a/test/parallel/test-vm-static-this.js b/test/parallel/test-vm-static-this.js index b7b013396bef8a..fb9cb764f8422c 100644 --- a/test/parallel/test-vm-static-this.js +++ b/test/parallel/test-vm-static-this.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); var vm = require('vm'); @@ -30,6 +31,6 @@ assert.equal(2, bar); assert.equal(1, foo); console.error('call a function'); -f = function() { foo = 100 }; +f = function() { foo = 100; }; vm.runInThisContext('f()'); assert.equal(100, foo); diff --git a/test/parallel/test-vm-timeout.js b/test/parallel/test-vm-timeout.js index 9925e03ad69d30..e9511e59230a84 100644 --- a/test/parallel/test-vm-timeout.js +++ b/test/parallel/test-vm-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var vm = require('vm'); diff --git a/test/parallel/test-writedouble.js b/test/parallel/test-writedouble.js index 24ceb885f54318..2a9ab11107f147 100644 --- a/test/parallel/test-writedouble.js +++ b/test/parallel/test-writedouble.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're writing doubles correctly */ diff --git a/test/parallel/test-writefloat.js b/test/parallel/test-writefloat.js index 5d5be20354377f..948bf4910208a5 100644 --- a/test/parallel/test-writefloat.js +++ b/test/parallel/test-writefloat.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're writing floats correctly */ diff --git a/test/parallel/test-writeint.js b/test/parallel/test-writeint.js index 064716ad0ccd16..ee981a157ad761 100644 --- a/test/parallel/test-writeint.js +++ b/test/parallel/test-writeint.js @@ -1,3 +1,4 @@ +'use strict'; /* * Tests to verify we're writing signed integers correctly */ diff --git a/test/parallel/test-writeuint.js b/test/parallel/test-writeuint.js index ec2efa12fb95ef..22579ceecaef2d 100644 --- a/test/parallel/test-writeuint.js +++ b/test/parallel/test-writeuint.js @@ -1,3 +1,4 @@ +'use strict'; /* * A battery of tests to help us read a series of uints */ diff --git a/test/parallel/test-zlib-close-after-write.js b/test/parallel/test-zlib-close-after-write.js index cbb1ac1fe1f26a..c02ff33fb5eb63 100644 --- a/test/parallel/test-zlib-close-after-write.js +++ b/test/parallel/test-zlib-close-after-write.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-const.js b/test/parallel/test-zlib-const.js index df9ca3d50097ad..511eca613a5229 100644 --- a/test/parallel/test-zlib-const.js +++ b/test/parallel/test-zlib-const.js @@ -1,3 +1,4 @@ +/* eslint-disable strict */ var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-zlib-convenience-methods.js b/test/parallel/test-zlib-convenience-methods.js index a32d5d1d4c3f18..5808bdf04a8f14 100644 --- a/test/parallel/test-zlib-convenience-methods.js +++ b/test/parallel/test-zlib-convenience-methods.js @@ -1,3 +1,4 @@ +'use strict'; // test convenience methods with and without options supplied var common = require('../common'); diff --git a/test/parallel/test-zlib-dictionary-fail.js b/test/parallel/test-zlib-dictionary-fail.js index ea50bf40982d6d..ced829f8d49963 100644 --- a/test/parallel/test-zlib-dictionary-fail.js +++ b/test/parallel/test-zlib-dictionary-fail.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-dictionary.js b/test/parallel/test-zlib-dictionary.js index 3a159e6090126e..109f4273f767d0 100644 --- a/test/parallel/test-zlib-dictionary.js +++ b/test/parallel/test-zlib-dictionary.js @@ -1,3 +1,4 @@ +'use strict'; // test compression/decompression with dictionary var common = require('../common'); diff --git a/test/parallel/test-zlib-flush.js b/test/parallel/test-zlib-flush.js index cfebda7bd2e5fa..6281b8eb21feb2 100644 --- a/test/parallel/test-zlib-flush.js +++ b/test/parallel/test-zlib-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-from-gzip.js b/test/parallel/test-zlib-from-gzip.js index b218b4edfcae69..6076a6f09ba00b 100644 --- a/test/parallel/test-zlib-from-gzip.js +++ b/test/parallel/test-zlib-from-gzip.js @@ -1,3 +1,4 @@ +'use strict'; // test unzipping a file that was created with a non-node gzip lib, // piped in as fast as possible. diff --git a/test/parallel/test-zlib-from-string.js b/test/parallel/test-zlib-from-string.js index 4ce77a8b528136..49f4d139c148d9 100644 --- a/test/parallel/test-zlib-from-string.js +++ b/test/parallel/test-zlib-from-string.js @@ -1,3 +1,4 @@ +'use strict'; // test compressing and uncompressing a string with zlib var common = require('../common'); diff --git a/test/parallel/test-zlib-invalid-input.js b/test/parallel/test-zlib-invalid-input.js index 948ea2244808b2..e1e81bacc1a499 100644 --- a/test/parallel/test-zlib-invalid-input.js +++ b/test/parallel/test-zlib-invalid-input.js @@ -1,3 +1,4 @@ +'use strict'; // test uncompressing invalid input var common = require('../common'), @@ -24,15 +25,15 @@ var unzips = [ zlib.Unzip(), zlib.Inflate(), zlib.InflateRaw() ]; var hadError = []; -unzips.forEach(function (uz, i) { - console.error('Error for '+uz.constructor.name); +unzips.forEach(function(uz, i) { + console.error('Error for ' + uz.constructor.name); uz.on('error', function(er) { console.error('Error event', er); hadError[i] = true; }); uz.on('end', function(er) { - throw new Error('end event should not be emitted '+uz.constructor.name); + throw new Error('end event should not be emitted ' + uz.constructor.name); }); // this will trigger error event diff --git a/test/parallel/test-zlib-params.js b/test/parallel/test-zlib-params.js index 6f1920956159f3..f349c8dbd0afec 100644 --- a/test/parallel/test-zlib-params.js +++ b/test/parallel/test-zlib-params.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index 4044cbd211a857..fcdc81443cac91 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/parallel/test-zlib-write-after-close.js b/test/parallel/test-zlib-write-after-close.js index 54b316631f739d..a1d9adb6d9b996 100644 --- a/test/parallel/test-zlib-write-after-close.js +++ b/test/parallel/test-zlib-write-after-close.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-write-after-flush.js b/test/parallel/test-zlib-write-after-flush.js index c0dbee7774b42d..4c53ca49ebf758 100644 --- a/test/parallel/test-zlib-write-after-flush.js +++ b/test/parallel/test-zlib-write-after-flush.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js index e7c8ddc954f77a..9aa260a7f3149d 100644 --- a/test/parallel/test-zlib-zero-byte.js +++ b/test/parallel/test-zlib-zero-byte.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); -var gz = zlib.Gzip() +var gz = zlib.Gzip(); var emptyBuffer = new Buffer(0); var received = 0; gz.on('data', function(c) { diff --git a/test/parallel/test-zlib.js b/test/parallel/test-zlib.js index bb9ba53d5df2cc..aaa965c424ed98 100644 --- a/test/parallel/test-zlib.js +++ b/test/parallel/test-zlib.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); diff --git a/test/pummel/test-abort-fatal-error.js b/test/pummel/test-abort-fatal-error.js index 045ff6da7f69e0..9f012c9dfb14b8 100644 --- a/test/pummel/test-abort-fatal-error.js +++ b/test/pummel/test-abort-fatal-error.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); diff --git a/test/pummel/test-buffer-big.js b/test/pummel/test-buffer-big.js index 9caa9287663a19..b36b992214ffc5 100644 --- a/test/pummel/test-buffer-big.js +++ b/test/pummel/test-buffer-big.js @@ -1,8 +1,9 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); // The tests below should throw an error, not abort the process... -assert.throws(function() { new Buffer(0x3fffffff + 1) }, RangeError); -assert.throws(function() { new Int8Array(0x3fffffff + 1) }, RangeError); -assert.throws(function() { new ArrayBuffer(0x3fffffff + 1) }, RangeError); -assert.throws(function() { new Float64Array(0x7ffffff + 1) }, RangeError); +assert.throws(function() { new Buffer(0x3fffffff + 1); }, RangeError); +assert.throws(function() { new Int8Array(0x3fffffff + 1); }, RangeError); +assert.throws(function() { new ArrayBuffer(0x3fffffff + 1); }, RangeError); +assert.throws(function() { new Float64Array(0x7ffffff + 1); }, RangeError); diff --git a/test/pummel/test-child-process-spawn-loop.js b/test/pummel/test-child-process-spawn-loop.js index a6129dd0bb2081..defed7d5f613d2 100644 --- a/test/pummel/test-child-process-spawn-loop.js +++ b/test/pummel/test-child-process-spawn-loop.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-crypto-dh.js b/test/pummel/test-crypto-dh.js index 0f3a5407dc7ed5..5588cdb7089b5b 100644 --- a/test/pummel/test-crypto-dh.js +++ b/test/pummel/test-crypto-dh.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -19,21 +20,22 @@ assert.throws(function() { }); var hashes = { - modp1 : "b4b330a6ffeacfbd861e7fe2135b4431", - modp2 : "7c3c5cad8b9f378d88f1dd64a4b6413a", - modp5 : "b1d2acc22c542e08669a5c5ae812694d", - modp14 : "8d041538cecc1a7d915ba4b718f8ad20", - modp15 : "dc3b93def24e078c4fbf92d5e14ba69b", - modp16 : "a273487f46f699461f613b3878d9dfd9", - modp17 : "dc76e09935310348c492de9bd82014d0", - modp18 : "db08973bfd2371758a69db180871c993" -} + modp1 : 'b4b330a6ffeacfbd861e7fe2135b4431', + modp2 : '7c3c5cad8b9f378d88f1dd64a4b6413a', + modp5 : 'b1d2acc22c542e08669a5c5ae812694d', + modp14 : '8d041538cecc1a7d915ba4b718f8ad20', + modp15 : 'dc3b93def24e078c4fbf92d5e14ba69b', + modp16 : 'a273487f46f699461f613b3878d9dfd9', + modp17 : 'dc76e09935310348c492de9bd82014d0', + modp18 : 'db08973bfd2371758a69db180871c993' +}; for (var name in hashes) { var group = crypto.getDiffieHellman(name); var private_key = group.getPrime('hex'); var hash1 = hashes[name]; - var hash2 = crypto.createHash('md5').update(private_key.toUpperCase()).digest('hex'); + var hash2 = crypto.createHash('md5') + .update(private_key.toUpperCase()).digest('hex'); assert.equal(hash1, hash2); assert.equal(group.getGenerator('hex'), '02'); } diff --git a/test/pummel/test-dh-regr.js b/test/pummel/test-dh-regr.js index 5c40173b121040..a6270bd2419cb0 100644 --- a/test/pummel/test-dh-regr.js +++ b/test/pummel/test-dh-regr.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-dtrace-jsstack.js b/test/pummel/test-dtrace-jsstack.js index e86a497f6967ba..831402fc87c780 100644 --- a/test/pummel/test-dtrace-jsstack.js +++ b/test/pummel/test-dtrace-jsstack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var os = require('os'); @@ -14,18 +15,18 @@ if (os.type() != 'SunOS') { var frames = [ 'stalloogle', 'bagnoogle', 'doogle' ]; var expected; -var stalloogle = function (str) { +var stalloogle = function(str) { expected = str; os.loadavg(); }; -var bagnoogle = function (arg0, arg1) { +var bagnoogle = function(arg0, arg1) { stalloogle(arg0 + ' is ' + arg1 + ' except that it is read-only'); }; var done = false; -var doogle = function () { +var doogle = function() { if (!done) setTimeout(doogle, 10); @@ -46,15 +47,15 @@ var dtrace = spawn('dtrace', [ '-qwn', 'syscall::getloadavg:entry/pid == ' + var output = ''; -dtrace.stderr.on('data', function (data) { +dtrace.stderr.on('data', function(data) { console.log('dtrace: ' + data); }); -dtrace.stdout.on('data', function (data) { +dtrace.stdout.on('data', function(data) { output += data; }); -dtrace.on('exit', function (code) { +dtrace.on('exit', function(code) { if (code != 0) { console.error('dtrace exited with code ' + code); process.exit(code); diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index bbedc3a5729515..41d81426e63e6f 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -1,14 +1,15 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; if (process.platform !== 'win32') { // Unix. - var SLEEP3_COMMAND = "sleep 3"; + var SLEEP3_COMMAND = 'sleep 3'; } else { // Windows: `choice` is a command built into cmd.exe. Use another cmd process // to create a process tree, so we can catch bugs related to it. - var SLEEP3_COMMAND = "cmd /c choice /t 3 /c X /d X"; + var SLEEP3_COMMAND = 'cmd /c choice /t 3 /c X /d X'; } diff --git a/test/pummel/test-fs-readfile-large.js b/test/pummel/test-fs-readfile-large.js index d8c6634fb827ab..b6afbc254d317c 100644 --- a/test/pummel/test-fs-readfile-large.js +++ b/test/pummel/test-fs-readfile-large.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -26,7 +27,7 @@ function makeFile(done) { } } -makeFile(function () { +makeFile(function() { fs.readFile(filename, function(err) { assert.ok(err, 'should get RangeError'); assert.equal(err.name, 'RangeError', 'should get RangeError'); @@ -34,6 +35,6 @@ makeFile(function () { }); }); -process.on('uncaughtException', function (err) { +process.on('uncaughtException', function(err) { assert.ok(!err, 'should not throw uncaughtException'); }); diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index df8763a4e2839d..cd4b16bf310b99 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -42,13 +43,13 @@ setTimeout(createFile, TIMEOUT); function createFile() { console.log('creating file'); - fs.writeFileSync(FILENAME, "test"); + fs.writeFileSync(FILENAME, 'test'); setTimeout(touchFile, TIMEOUT); } function touchFile() { console.log('touch file'); - fs.writeFileSync(FILENAME, "test"); + fs.writeFileSync(FILENAME, 'test'); setTimeout(removeFile, TIMEOUT); } diff --git a/test/pummel/test-fs-watch-file.js b/test/pummel/test-fs-watch-file.js index 199bf5242e251b..7b57803dd4ec93 100644 --- a/test/pummel/test-fs-watch-file.js +++ b/test/pummel/test-fs-watch-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -123,7 +124,7 @@ assert.doesNotThrow( function a(curr, prev) { ++watchSeenFour; assert.equal(1, watchSeenFour); - fs.unwatchFile("." + path.sep + filenameFour, a); + fs.unwatchFile('.' + path.sep + filenameFour, a); } fs.watchFile(filenameFour, a); } diff --git a/test/pummel/test-fs-watch-non-recursive.js b/test/pummel/test-fs-watch-non-recursive.js index 60d2c6b6a84900..6adb193928e44f 100644 --- a/test/pummel/test-fs-watch-non-recursive.js +++ b/test/pummel/test-fs-watch-non-recursive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -14,7 +15,7 @@ function cleanup() { process.on('exit', cleanup); cleanup(); -try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} +try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} // Need a grace period, else the mkdirSync() above fires off an event. setTimeout(function() { diff --git a/test/pummel/test-http-client-reconnect-bug.js b/test/pummel/test-http-client-reconnect-bug.js index 00a38608125dbd..bd852e45f19410 100644 --- a/test/pummel/test-http-client-reconnect-bug.js +++ b/test/pummel/test-http-client-reconnect-bug.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-http-many-keep-alive-connections.js b/test/pummel/test-http-many-keep-alive-connections.js index fdd7a068102c3d..d90d4d97531095 100644 --- a/test/pummel/test-http-many-keep-alive-connections.js +++ b/test/pummel/test-http-many-keep-alive-connections.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/pummel/test-http-upload-timeout.js b/test/pummel/test-http-upload-timeout.js index f889c60f177b5f..08132e3c7594d1 100644 --- a/test/pummel/test-http-upload-timeout.js +++ b/test/pummel/test-http-upload-timeout.js @@ -1,3 +1,4 @@ +'use strict'; // This tests setTimeout() by having multiple clients connecting and sending // data in random intervals. Clients are also randomly disconnecting until there // are no more clients left. If no false timeout occurs, this test has passed. diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 1ca965e99ec583..fa38bea0011131 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/pummel/test-https-large-response.js b/test/pummel/test-https-large-response.js index 5ad5da480ca7a4..1aa36464a158e4 100644 --- a/test/pummel/test-https-large-response.js +++ b/test/pummel/test-https-large-response.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-https-no-reader.js b/test/pummel/test-https-no-reader.js index 798a4f70b64f81..8f407e2d7d48f8 100644 --- a/test/pummel/test-https-no-reader.js +++ b/test/pummel/test-https-no-reader.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index 58af58a25353a6..d03cb1d74f3683 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -1,3 +1,4 @@ +'use strict'; if (process.platform === 'win32') { console.log('skipping this test because there is no wrk on windows'); process.exit(0); @@ -37,7 +38,8 @@ function runAb(opts, callback) { args.push('Connection: close'); } - args.push(url.format({ hostname: '127.0.0.1', port: common.PORT, protocol: 'http'})); + args.push(url.format({ hostname: '127.0.0.1', + port: common.PORT, protocol: 'http'})); //console.log(comm, args.join(' ')); diff --git a/test/pummel/test-net-connect-econnrefused.js b/test/pummel/test-net-connect-econnrefused.js index be3db49aa4fe7a..113b04e31f3ae1 100644 --- a/test/pummel/test-net-connect-econnrefused.js +++ b/test/pummel/test-net-connect-econnrefused.js @@ -1,3 +1,4 @@ +'use strict'; // verify that connect reqs are properly cleaned up var common = require('../common'); diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index 66b7e926d8cadc..855bf1f070d7c8 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose-gc var common = require('../common'); diff --git a/test/pummel/test-net-many-clients.js b/test/pummel/test-net-many-clients.js index fce7f33e669ccb..b70efbda582571 100644 --- a/test/pummel/test-net-many-clients.js +++ b/test/pummel/test-net-many-clients.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-pause.js b/test/pummel/test-net-pause.js index 26eec2cfd092d6..6386d29835da11 100644 --- a/test/pummel/test-net-pause.js +++ b/test/pummel/test-net-pause.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-pingpong-delay.js b/test/pummel/test-net-pingpong-delay.js index 8a30e7bae7f5fd..e459c71a7185ac 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-pingpong.js b/test/pummel/test-net-pingpong.js index d38064e64a4067..a7ede0b0565ac9 100644 --- a/test/pummel/test-net-pingpong.js +++ b/test/pummel/test-net-pingpong.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/pummel/test-net-throttle.js b/test/pummel/test-net-throttle.js index 45c0a6fb6d9cc5..d556d8aaa86c43 100644 --- a/test/pummel/test-net-throttle.js +++ b/test/pummel/test-net-throttle.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -20,7 +21,8 @@ var server = net.createServer(function(connection) { connection.write(body.slice(part_N, 2 * part_N)); assert.equal(false, connection.write(body.slice(2 * part_N, N))); console.log('bufferSize: ' + connection.bufferSize, 'expecting', N); - assert.ok(0 <= connection.bufferSize && connection._writableState.length <= N); + assert.ok(0 <= connection.bufferSize && + connection._writableState.length <= N); connection.end(); }); diff --git a/test/pummel/test-net-timeout.js b/test/pummel/test-net-timeout.js index 47214fc98f528a..347e3a4344d37b 100644 --- a/test/pummel/test-net-timeout.js +++ b/test/pummel/test-net-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -12,7 +13,7 @@ var echo_server = net.createServer(function(socket) { socket.on('timeout', function() { console.log('server timeout'); - timeouttime = new Date; + timeouttime = new Date(); console.dir(timeouttime); socket.destroy(); }); @@ -53,7 +54,7 @@ echo_server.listen(common.PORT, function() { if (exchanges == 5) { console.log('wait for timeout - should come in ' + timeout + ' ms'); - starttime = new Date; + starttime = new Date(); console.dir(starttime); } } diff --git a/test/pummel/test-net-timeout2.js b/test/pummel/test-net-timeout2.js index 2eb97a6e7e2f1c..c7b445f96c4e38 100644 --- a/test/pummel/test-net-timeout2.js +++ b/test/pummel/test-net-timeout2.js @@ -1,3 +1,4 @@ +'use strict'; // socket.write was not resetting the timeout timer. See // https://github.com/joyent/node/issues/2002 diff --git a/test/pummel/test-net-write-callbacks.js b/test/pummel/test-net-write-callbacks.js index b43729d0c1ed46..21eae0f5ab72d0 100644 --- a/test/pummel/test-net-write-callbacks.js +++ b/test/pummel/test-net-write-callbacks.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/pummel/test-next-tick-infinite-calls.js b/test/pummel/test-next-tick-infinite-calls.js index 5177135a34a6e2..d4fdb3496423eb 100644 --- a/test/pummel/test-next-tick-infinite-calls.js +++ b/test/pummel/test-next-tick-infinite-calls.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-process-hrtime.js b/test/pummel/test-process-hrtime.js index faf97d8a8daed1..4fd66c03907aac 100644 --- a/test/pummel/test-process-hrtime.js +++ b/test/pummel/test-process-hrtime.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-process-uptime.js b/test/pummel/test-process-uptime.js index b105edebbd8689..a80806c2099cb1 100644 --- a/test/pummel/test-process-uptime.js +++ b/test/pummel/test-process-uptime.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-regress-GH-814.js b/test/pummel/test-regress-GH-814.js index 20183960e04af8..0059af1037a80b 100644 --- a/test/pummel/test-regress-GH-814.js +++ b/test/pummel/test-regress-GH-814.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose_gc function newBuffer(size, value) { diff --git a/test/pummel/test-regress-GH-814_2.js b/test/pummel/test-regress-GH-814_2.js index 7443e4f57eaf98..6dd2f2d32e5646 100644 --- a/test/pummel/test-regress-GH-814_2.js +++ b/test/pummel/test-regress-GH-814_2.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose_gc var common = require('../common'); diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index af314349ffd962..d84170d7648a10 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -1,3 +1,4 @@ +'use strict'; // Uploading a big file via HTTPS causes node to drop out of the event loop. // https://github.com/joyent/node/issues/892 // In this test we set up an HTTPS in this process and launch a subprocess diff --git a/test/pummel/test-smalloc-alloc-segfault.js b/test/pummel/test-smalloc-alloc-segfault.js index 3e89f726ce7f70..d41ccaee09b79d 100644 --- a/test/pummel/test-smalloc-alloc-segfault.js +++ b/test/pummel/test-smalloc-alloc-segfault.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-smalloc-dispose-segfault.js b/test/pummel/test-smalloc-dispose-segfault.js index e94d9d5ba17c76..9364cca344c136 100644 --- a/test/pummel/test-smalloc-dispose-segfault.js +++ b/test/pummel/test-smalloc-dispose-segfault.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-smalloc-sliceonto-segfault.js b/test/pummel/test-smalloc-sliceonto-segfault.js index ed43828a530ee6..e9e00979ff2814 100644 --- a/test/pummel/test-smalloc-sliceonto-segfault.js +++ b/test/pummel/test-smalloc-sliceonto-segfault.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-stream-pipe-multi.js b/test/pummel/test-stream-pipe-multi.js index 00d17f17425c0b..807e3c1415154e 100644 --- a/test/pummel/test-stream-pipe-multi.js +++ b/test/pummel/test-stream-pipe-multi.js @@ -1,3 +1,4 @@ +'use strict'; // Test that having a bunch of streams piping in parallel // doesn't break anything. diff --git a/test/pummel/test-stream2-basic.js b/test/pummel/test-stream2-basic.js index 543acd61c11d67..c83d80c5029e70 100644 --- a/test/pummel/test-stream2-basic.js +++ b/test/pummel/test-stream2-basic.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var assert = require('assert'); @@ -88,7 +89,7 @@ function run() { same: assert.deepEqual, ok: assert, equal: assert.equal, - end: function () { + end: function() { count--; run(); } @@ -96,7 +97,7 @@ function run() { } // ensure all tests have run -process.on("exit", function () { +process.on('exit', function() { assert.equal(count, 0); }); @@ -153,9 +154,9 @@ test('pipe', function(t) { 'xxxxx', 'xxxxx', 'xxxxx', - 'xxxxx' ] + 'xxxxx' ]; - var w = new TestWriter; + var w = new TestWriter(); var flush = true; w.on('end', function(received) { @@ -168,7 +169,7 @@ test('pipe', function(t) { -[1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { +[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { test('unpipe', function(t) { var r = new TestReader(5); @@ -226,7 +227,7 @@ test('pipe', function(t) { // both writers should get the same exact data. test('multipipe', function(t) { var r = new TestReader(5); - var w = [ new TestWriter, new TestWriter ]; + var w = [ new TestWriter(), new TestWriter() ]; var expect = [ 'xxxxx', 'xxxxx', @@ -254,7 +255,7 @@ test('multipipe', function(t) { }); -[1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { +[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { test('multi-unpipe', function(t) { var r = new TestReader(5); @@ -301,90 +302,90 @@ test('multipipe', function(t) { }); }); -test('back pressure respected', function (t) { +test('back pressure respected', function(t) { function noop() {} var r = new R({ objectMode: true }); r._read = noop; var counter = 0; - r.push(["one"]); - r.push(["two"]); - r.push(["three"]); - r.push(["four"]); + r.push(['one']); + r.push(['two']); + r.push(['three']); + r.push(['four']); r.push(null); var w1 = new R(); - w1.write = function (chunk) { + w1.write = function(chunk) { console.error('w1.emit("close")'); - assert.equal(chunk[0], "one"); - w1.emit("close"); - process.nextTick(function () { + assert.equal(chunk[0], 'one'); + w1.emit('close'); + process.nextTick(function() { r.pipe(w2); r.pipe(w3); - }) + }); }; w1.end = noop; r.pipe(w1); - var expected = ["two", "two", "three", "three", "four", "four"]; + var expected = ['two', 'two', 'three', 'three', 'four', 'four']; var w2 = new R(); - w2.write = function (chunk) { + w2.write = function(chunk) { console.error('w2 write', chunk, counter); assert.equal(chunk[0], expected.shift()); assert.equal(counter, 0); counter++; - if (chunk[0] === "four") { + if (chunk[0] === 'four') { return true; } - setTimeout(function () { + setTimeout(function() { counter--; - console.error("w2 drain"); - w2.emit("drain"); + console.error('w2 drain'); + w2.emit('drain'); }, 10); return false; - } + }; w2.end = noop; var w3 = new R(); - w3.write = function (chunk) { + w3.write = function(chunk) { console.error('w3 write', chunk, counter); assert.equal(chunk[0], expected.shift()); assert.equal(counter, 1); counter++; - if (chunk[0] === "four") { + if (chunk[0] === 'four') { return true; } - setTimeout(function () { + setTimeout(function() { counter--; - console.error("w3 drain"); - w3.emit("drain"); + console.error('w3 drain'); + w3.emit('drain'); }, 50); return false; }; - w3.end = function () { + w3.end = function() { assert.equal(counter, 2); assert.equal(expected.length, 0); t.end(); }; }); -test('read(0) for ended streams', function (t) { +test('read(0) for ended streams', function(t) { var r = new R(); var written = false; var ended = false; - r._read = function (n) {}; + r._read = function(n) {}; - r.push(new Buffer("foo")); + r.push(new Buffer('foo')); r.push(null); var v = r.read(0); @@ -393,38 +394,38 @@ test('read(0) for ended streams', function (t) { var w = new R(); - w.write = function (buffer) { + w.write = function(buffer) { written = true; assert.equal(ended, false); - assert.equal(buffer.toString(), "foo") + assert.equal(buffer.toString(), 'foo'); }; - w.end = function () { + w.end = function() { ended = true; assert.equal(written, true); t.end(); }; r.pipe(w); -}) +}); -test('sync _read ending', function (t) { +test('sync _read ending', function(t) { var r = new R(); var called = false; - r._read = function (n) { + r._read = function(n) { r.push(null); }; - r.once('end', function () { + r.once('end', function() { called = true; - }) + }); r.read(); - process.nextTick(function () { + process.nextTick(function() { assert.equal(called, true); t.end(); - }) + }); }); test('adding readable triggers data flow', function(t) { diff --git a/test/pummel/test-timer-wrap.js b/test/pummel/test-timer-wrap.js index fdfb855a75830d..62ba69d3fde033 100644 --- a/test/pummel/test-timer-wrap.js +++ b/test/pummel/test-timer-wrap.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-timer-wrap2.js b/test/pummel/test-timer-wrap2.js index 8a7502888b5557..b289a85644a068 100644 --- a/test/pummel/test-timer-wrap2.js +++ b/test/pummel/test-timer-wrap2.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-timers.js b/test/pummel/test-timers.js index f676b98438852e..2225da91edcf5f 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -11,9 +12,9 @@ clearTimeout(null); clearInterval(null); assert.equal(true, setTimeout instanceof Function); -var starttime = new Date; +var starttime = new Date(); setTimeout(function() { - var endtime = new Date; + var endtime = new Date(); var diff = endtime - starttime; assert.ok(diff > 0); @@ -29,7 +30,7 @@ clearTimeout(id); setInterval(function() { interval_count += 1; - var endtime = new Date; + var endtime = new Date( ); var diff = endtime - starttime; assert.ok(diff > 0); diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index 22c48699d080a7..49b9a87a7dbdc3 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/pummel/test-tls-connect-memleak.js b/test/pummel/test-tls-connect-memleak.js index 53275da60ed2a9..0345f9a6f62886 100644 --- a/test/pummel/test-tls-connect-memleak.js +++ b/test/pummel/test-tls-connect-memleak.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --expose-gc var common = require('../common'); diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index cbff5feac8fb39..7542ce62bcd154 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -1,3 +1,4 @@ +'use strict'; // var common = require('../common'); diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index c5eebb01a16fdb..e6ef89c72eb659 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/pummel/test-tls-session-timeout.js b/test/pummel/test-tls-session-timeout.js index 74a1abc99052cb..962b1206b6c956 100644 --- a/test/pummel/test-tls-session-timeout.js +++ b/test/pummel/test-tls-session-timeout.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); if (!common.opensslCli) { @@ -46,7 +47,7 @@ function doTest() { // file containing a proper serialization of a session ticket. // To avoid a source control diff, we copy the ticket to a temporary file. - var sessionFileName = (function () { + var sessionFileName = (function() { var ticketFileName = 'tls-session-ticket.txt'; var fixturesPath = join(common.fixturesDir, ticketFileName); var tmpPath = join(common.tmpDir, ticketFileName); @@ -56,7 +57,7 @@ function doTest() { // Expects a callback -- cb(connectionType : enum ['New'|'Reused']) - var Client = function (cb) { + var Client = function(cb) { var flags = [ 's_client', '-connect', 'localhost:' + common.PORT, @@ -73,7 +74,7 @@ function doTest() { }); client.on('exit', function(code) { var connectionType; - var grepConnectionType = function (line) { + var grepConnectionType = function(line) { var matches = line.match(/(New|Reused), /); if (matches) { connectionType = matches[1]; @@ -101,7 +102,7 @@ function doTest() { assert(connectionType === 'New'); Client(function(connectionType) { assert(connectionType === 'Reused'); - setTimeout(function () { + setTimeout(function() { Client(function(connectionType) { assert(connectionType === 'New'); server.close(); diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index a8a83a2a3a9001..3eb1af6da75818 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -1,3 +1,4 @@ +'use strict'; // Server sends a large string. Client counts bytes and pauses every few // seconds. Makes sure that pause and resume work properly. diff --git a/test/pummel/test-vm-memleak.js b/test/pummel/test-vm-memleak.js index 916b65d6da49a9..f93f34127f9219 100644 --- a/test/pummel/test-vm-memleak.js +++ b/test/pummel/test-vm-memleak.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --max_old_space_size=32 var assert = require('assert'); diff --git a/test/pummel/test-watch-file.js b/test/pummel/test-watch-file.js index 3e92efc26c9edb..1d0ef77d543e43 100644 --- a/test/pummel/test-watch-file.js +++ b/test/pummel/test-watch-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-chdir.js b/test/sequential/test-chdir.js index a24753de2d28e0..0fab45cb0c2803 100644 --- a/test/sequential/test-chdir.js +++ b/test/sequential/test-chdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var fs = require('fs'); @@ -20,4 +21,5 @@ fs.rmdirSync(dir); assert.throws(function() { process.chdir({}); }, TypeError, 'Bad argument.'); assert.throws(function() { process.chdir(); }, TypeError, 'Bad argument.'); -assert.throws(function() { process.chdir("x", "y"); }, TypeError, 'Bad argument.'); +assert.throws(function() { process.chdir('x', 'y'); }, + TypeError, 'Bad argument.'); diff --git a/test/sequential/test-child-process-emfile.js b/test/sequential/test-child-process-emfile.js index 66be12749c9f03..964b63a2b4513d 100644 --- a/test/sequential/test-child-process-emfile.js +++ b/test/sequential/test-child-process-emfile.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 5cd9ee433d6d35..13982e00a6756d 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var util = require('util'); @@ -58,7 +59,8 @@ assert.deepEqual(ret, msgBuf); ret = execFileSync(process.execPath, args, { encoding: 'utf8' }); -assert.strictEqual(ret, msg + '\n', 'execFileSync encoding result should match'); +assert.strictEqual(ret, msg + '\n', + 'execFileSync encoding result should match'); // Verify that the cwd option works - GH #7824 (function() { diff --git a/test/sequential/test-child-process-fork-getconnections.js b/test/sequential/test-child-process-fork-getconnections.js index 6848b2ffa0b9c6..a587713b6132f2 100644 --- a/test/sequential/test-child-process-fork-getconnections.js +++ b/test/sequential/test-child-process-fork-getconnections.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var common = require('../common'); var fork = require('child_process').fork; diff --git a/test/sequential/test-cluster-listening-port.js b/test/sequential/test-cluster-listening-port.js index 5d68b066cfd9e2..eb8a974d04bbf8 100644 --- a/test/sequential/test-cluster-listening-port.js +++ b/test/sequential/test-cluster-listening-port.js @@ -1,3 +1,4 @@ +'use strict'; var assert = require('assert'); var cluster = require('cluster'); var net = require('net'); diff --git a/test/sequential/test-debug-args.js b/test/sequential/test-debug-args.js index 7aaef76a641fd6..eb1533d4418a55 100644 --- a/test/sequential/test-debug-args.js +++ b/test/sequential/test-debug-args.js @@ -1,3 +1,4 @@ +'use strict'; // Flags: --debugger var common = require('../common'); diff --git a/test/sequential/test-deprecation-flags.js b/test/sequential/test-deprecation-flags.js index 2af60a17364999..e8565a33635744 100644 --- a/test/sequential/test-deprecation-flags.js +++ b/test/sequential/test-deprecation-flags.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var execFile = require('child_process').execFile; @@ -12,7 +13,8 @@ execFile(node, normal, function(er, stdout, stderr) { console.error('normal: show deprecation warning'); assert.equal(er, null); assert.equal(stdout, ''); - assert.equal(stderr, 'util.p: Use console.error() instead\n\'This is deprecated\'\n'); + assert.equal(stderr, + 'util.p: Use console.error() instead\n\'This is deprecated\'\n'); console.log('normal ok'); }); diff --git a/test/sequential/test-force-repl.js b/test/sequential/test-force-repl.js index c0ad1484ff25cc..5907dc2019a3a3 100644 --- a/test/sequential/test-force-repl.js +++ b/test/sequential/test-force-repl.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/sequential/test-fs-watch-recursive.js b/test/sequential/test-fs-watch-recursive.js index a789dcb3061b3d..f77b86e436985b 100644 --- a/test/sequential/test-fs-watch-recursive.js +++ b/test/sequential/test-fs-watch-recursive.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -23,7 +24,7 @@ if (process.platform === 'darwin') { try { fs.rmdirSync(testsubdir); } catch (e) { } }; - try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} + try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} assert.doesNotThrow(function() { var watcher = fs.watch(testDir, {recursive: true}); diff --git a/test/sequential/test-fs-watch.js b/test/sequential/test-fs-watch.js index d92a10cd808a10..1cfaad9b3ec975 100644 --- a/test/sequential/test-fs-watch.js +++ b/test/sequential/test-fs-watch.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -41,7 +42,7 @@ fs.writeFileSync(filepathOne, 'hello'); assert.doesNotThrow( function() { - var watcher = fs.watch(filepathOne) + var watcher = fs.watch(filepathOne); watcher.on('change', function(event, filename) { assert.equal('change', event); @@ -82,7 +83,7 @@ setTimeout(function() { }, 20); try { fs.unlinkSync(filepathThree); } catch (e) {} -try { fs.mkdirSync(testsubdir, 0700); } catch (e) {} +try { fs.mkdirSync(testsubdir, 0o700); } catch (e) {} assert.doesNotThrow( function() { @@ -123,7 +124,7 @@ assert.throws(function() { oldhandle.close(); // clean up assert.throws(function() { - var w = fs.watchFile(__filename, {persistent:false}, function(){}); + var w = fs.watchFile(__filename, {persistent:false}, function() {}); oldhandle = w._handle; w._handle = { stop: w._handle.stop }; w.stop(); diff --git a/test/sequential/test-http-pipeline-flood.js b/test/sequential/test-http-pipeline-flood.js index 6eeb785f9cbc2a..cb9fc97a865b70 100644 --- a/test/sequential/test-http-pipeline-flood.js +++ b/test/sequential/test-http-pipeline-flood.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-init.js b/test/sequential/test-init.js index abc6378a637e93..f68c001f64fffa 100644 --- a/test/sequential/test-init.js +++ b/test/sequential/test-init.js @@ -1,3 +1,4 @@ +'use strict'; (function() { var assert = require('assert'), child = require('child_process'), diff --git a/test/sequential/test-memory-usage-emfile.js b/test/sequential/test-memory-usage-emfile.js index e95fe429c37645..e4f85488f40d42 100644 --- a/test/sequential/test-memory-usage-emfile.js +++ b/test/sequential/test-memory-usage-emfile.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-mkdir-rmdir.js b/test/sequential/test-mkdir-rmdir.js index 63dc78df381e78..7bd156419e8a94 100644 --- a/test/sequential/test-mkdir-rmdir.js +++ b/test/sequential/test-mkdir-rmdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -9,12 +10,12 @@ var d = path.join(common.tmpDir, 'dir'); var mkdir_error = false; var rmdir_error = false; -fs.mkdir(d, 0666, function(err) { +fs.mkdir(d, 0o666, function(err) { if (err) { console.log('mkdir error: ' + err.message); mkdir_error = true; } else { - fs.mkdir(d, 0666, function(err) { + fs.mkdir(d, 0o666, function(err) { console.log('expect EEXIST error: ', err); assert.ok(err.message.match(/^EEXIST/), 'got EEXIST message'); assert.equal(err.code, 'EEXIST', 'got EEXIST code'); diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index c1d8df4553370c..dfca2e420263b6 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); @@ -53,7 +54,7 @@ assert.equal('D', d3.D()); assert.equal(true, common.indirectInstanceOf(d4.D, Function)); assert.equal('D', d4.D()); -assert.ok((new a.SomeClass) instanceof c.SomeClass); +assert.ok((new a.SomeClass()) instanceof c.SomeClass); common.debug('test index.js modules ids and relative loading'); var one = require('../fixtures/nested-index/one'), @@ -89,7 +90,7 @@ common.debug('test name clashes'); var my_path = require('../fixtures/path'); assert.ok(common.indirectInstanceOf(my_path.path_func, Function)); // this one does not exist and should throw -assert.throws(function() { require('./utils')}); +assert.throws(function() { require('./utils'); }); var errorThrown = false; try { @@ -187,7 +188,7 @@ assert.deepEqual(json, { // the appropriate children, and so on. var children = module.children.reduce(function red(set, child) { - var id = path.relative(path.dirname(__dirname), child.id) + var id = path.relative(path.dirname(__dirname), child.id); id = id.replace(/\\/g, '/'); set[id] = child.children.reduce(red, {}); return set; diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js index 2ee0a1d86d7af3..0478de55d62592 100644 --- a/test/sequential/test-net-GH-5504.js +++ b/test/sequential/test-net-GH-5504.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-net-listen-exclusive-random-ports.js b/test/sequential/test-net-listen-exclusive-random-ports.js index 2922a2b06e140f..c32273a59b2a50 100644 --- a/test/sequential/test-net-listen-exclusive-random-ports.js +++ b/test/sequential/test-net-listen-exclusive-random-ports.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); diff --git a/test/sequential/test-net-localport.js b/test/sequential/test-net-localport.js index 239196813ad8a3..09b6627c79ce47 100644 --- a/test/sequential/test-net-localport.js +++ b/test/sequential/test-net-localport.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -17,4 +18,4 @@ var server = net.createServer(function(socket) { }).on('connect', function() { assert.strictEqual(client.localPort, common.PORT + 1); }); -}) +}); diff --git a/test/sequential/test-net-server-address.js b/test/sequential/test-net-server-address.js index 717d46f1bbb059..1e91c348ef02ca 100644 --- a/test/sequential/test-net-server-address.js +++ b/test/sequential/test-net-server-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -60,12 +61,12 @@ server1.listen(common.PORT, function() { // Test without hostname or port var server2 = net.createServer(); -server2.on('error', function (e) { +server2.on('error', function(e) { console.log('Error on ip socket: ' + e.toString()); }); // Don't specify the port number -server2.listen(function () { +server2.listen(function() { var address = server2.address(); assert.strictEqual(address.address, anycast_ipv6); assert.strictEqual(address.family, family_ipv6); @@ -75,12 +76,12 @@ server2.listen(function () { // Test without hostname, but with a false-y port var server3 = net.createServer(); -server3.on('error', function (e) { +server3.on('error', function(e) { console.log('Error on ip socket: ' + e.toString()); }); // Specify a false-y port number -server3.listen(0, function () { +server3.listen(0, function() { var address = server3.address(); assert.strictEqual(address.address, anycast_ipv6); assert.strictEqual(address.family, family_ipv6); @@ -90,12 +91,12 @@ server3.listen(0, function () { // Test without hostname, but with port -1 var server4 = net.createServer(); -server4.on('error', function (e) { +server4.on('error', function(e) { console.log('Error on ip socket: ' + e.toString()); }); // Specify -1 as port number -server4.listen(-1, function () { +server4.listen(-1, function() { var address = server4.address(); assert.strictEqual(address.address, anycast_ipv6); assert.strictEqual(address.family, family_ipv6); diff --git a/test/sequential/test-net-server-bind.js b/test/sequential/test-net-server-bind.js index 3a7cd0e15b21db..c77341418c2c6d 100644 --- a/test/sequential/test-net-server-bind.js +++ b/test/sequential/test-net-server-bind.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-next-tick-error-spin.js b/test/sequential/test-next-tick-error-spin.js index a150ea7a589f63..7a76ab1e12df68 100644 --- a/test/sequential/test-next-tick-error-spin.js +++ b/test/sequential/test-next-tick-error-spin.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -22,24 +23,24 @@ if (process.argv[2] !== 'child') { // in the error handler, we trigger several MakeCallback events d.on('error', function(e) { - console.log('a') - console.log('b') - console.log('c') - console.log('d') - console.log('e') + console.log('a'); + console.log('b'); + console.log('c'); + console.log('d'); + console.log('e'); f(); }); function f() { process.nextTick(function() { d.run(function() { - throw(new Error('x')); + throw new Error('x'); }); }); } f(); - setTimeout(function () { + setTimeout(function() { console.error('broke in!'); //process.stdout.close(); //process.stderr.close(); diff --git a/test/sequential/test-pipe-address.js b/test/sequential/test-pipe-address.js index 6497eb7f1246c1..b9e544e97458b4 100644 --- a/test/sequential/test-pipe-address.js +++ b/test/sequential/test-pipe-address.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-pipe-head.js b/test/sequential/test-pipe-head.js index 4fa3eaa4daa59c..ac8b16515158eb 100644 --- a/test/sequential/test-pipe-head.js +++ b/test/sequential/test-pipe-head.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-pipe-stream.js b/test/sequential/test-pipe-stream.js index 5e5837b29843b6..ba4005e9e02fe0 100644 --- a/test/sequential/test-pipe-stream.js +++ b/test/sequential/test-pipe-stream.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-pipe-unref.js b/test/sequential/test-pipe-unref.js index 53853b9bdcba66..4580f2a66ee4d6 100644 --- a/test/sequential/test-pipe-unref.js +++ b/test/sequential/test-pipe-unref.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-pipe.js b/test/sequential/test-pipe.js index 11ea83b88422ba..2ef19c37ea8ca4 100644 --- a/test/sequential/test-pipe.js +++ b/test/sequential/test-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/sequential/test-pump-file2tcp-noexist.js b/test/sequential/test-pump-file2tcp-noexist.js index 8b2057e533c60e..1ffdb5d4615ce3 100644 --- a/test/sequential/test-pump-file2tcp-noexist.js +++ b/test/sequential/test-pump-file2tcp-noexist.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-pump-file2tcp.js b/test/sequential/test-pump-file2tcp.js index 50b576771f9074..86effb7c6c9a28 100644 --- a/test/sequential/test-pump-file2tcp.js +++ b/test/sequential/test-pump-file2tcp.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); diff --git a/test/sequential/test-readdir.js b/test/sequential/test-readdir.js index bba28d0d7a8bfc..4987dc1848035d 100644 --- a/test/sequential/test-readdir.js +++ b/test/sequential/test-readdir.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-regress-GH-1531.js b/test/sequential/test-regress-GH-1531.js index 9e1b8e3077870e..0d06cc3485218a 100644 --- a/test/sequential/test-regress-GH-1531.js +++ b/test/sequential/test-regress-GH-1531.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-regress-GH-1697.js b/test/sequential/test-regress-GH-1697.js index 18d1829174dd8b..ff5754f357dfc1 100644 --- a/test/sequential/test-regress-GH-1697.js +++ b/test/sequential/test-regress-GH-1697.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'), cp = require('child_process'), @@ -39,7 +40,7 @@ if (process.argv[2] === 'server') { // Block the event loop for 1 second var start = (new Date()).getTime(); - while ((new Date).getTime() < start + 1000) {} + while ((new Date()).getTime() < start + 1000) {} client.write(alittle); diff --git a/test/sequential/test-regress-GH-1726.js b/test/sequential/test-regress-GH-1726.js index 74578ab4e0fe55..859ab6cc5e4253 100644 --- a/test/sequential/test-regress-GH-1726.js +++ b/test/sequential/test-regress-GH-1726.js @@ -1,3 +1,4 @@ +'use strict'; // Open a chain of five Node processes each a child of the next. The final // process exits immediately. Each process in the chain is instructed to // exit when its child exits. @@ -26,7 +27,7 @@ assert.ok(!child.stderr); console.error('gen=%d, pid=%d', gen, process.pid); /* -var timer = setTimeout(function () { +var timer = setTimeout(function() { throw new Error('timeout! gen='+gen); }, 1000); */ diff --git a/test/sequential/test-regress-GH-1899.js b/test/sequential/test-regress-GH-1899.js index 8663eb5a4dd1ea..98396aae13b8f9 100644 --- a/test/sequential/test-regress-GH-1899.js +++ b/test/sequential/test-regress-GH-1899.js @@ -1,3 +1,4 @@ +'use strict'; var path = require('path'); var assert = require('assert'); var spawn = require('child_process').spawn; diff --git a/test/sequential/test-regress-GH-3542.js b/test/sequential/test-regress-GH-3542.js index 32b3433318855b..80f2a4c9c3e4a2 100644 --- a/test/sequential/test-regress-GH-3542.js +++ b/test/sequential/test-regress-GH-3542.js @@ -1,3 +1,4 @@ +'use strict'; // This test is only relevant on Windows. if (process.platform !== 'win32') { return process.exit(0); @@ -22,8 +23,8 @@ function test(p) { test('//localhost/c$/windows/system32'); test('//localhost/c$/windows'); -test('//localhost/c$/') -test('\\\\localhost\\c$') +test('//localhost/c$/'); +test('\\\\localhost\\c$'); test('c:\\'); test('c:'); test(process.env.windir); diff --git a/test/sequential/test-regress-GH-3739.js b/test/sequential/test-regress-GH-3739.js index d08cfce60226ba..cc16b22dc44c46 100644 --- a/test/sequential/test-regress-GH-3739.js +++ b/test/sequential/test-regress-GH-3739.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'), assert = require('assert'), fs = require('fs'), diff --git a/test/sequential/test-regress-GH-4015.js b/test/sequential/test-regress-GH-4015.js index 38a77c82086b1c..7f0e03f9ac08e1 100644 --- a/test/sequential/test-regress-GH-4015.js +++ b/test/sequential/test-regress-GH-4015.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js index de2dff180db5c0..da91be95b849a8 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-regress-GH-4948.js b/test/sequential/test-regress-GH-4948.js index e78870b704c917..c87ade9850ccf4 100644 --- a/test/sequential/test-regress-GH-4948.js +++ b/test/sequential/test-regress-GH-4948.js @@ -1,10 +1,11 @@ +'use strict'; // https://github.com/joyent/node/issues/4948 var common = require('../common'); var http = require('http'); var reqCount = 0; -var server = http.createServer(function(serverReq, serverRes){ +var server = http.createServer(function(serverReq, serverRes) { if (reqCount) { serverRes.end(); server.close(); @@ -15,9 +16,10 @@ var server = http.createServer(function(serverReq, serverRes){ // normally the use case would be to call an external site // does not require connecting locally or to itself to fail - var r = http.request({hostname: 'localhost', port: common.PORT}, function(res) { + var r = http.request({hostname: 'localhost', + port: common.PORT}, function(res) { // required, just needs to be in the client response somewhere - serverRes.end(); + serverRes.end(); // required for test to fail res.on('data', function(data) { }); diff --git a/test/sequential/test-regress-GH-746.js b/test/sequential/test-regress-GH-746.js index 93346c43f1d9e2..4b79f3c4e355d1 100644 --- a/test/sequential/test-regress-GH-746.js +++ b/test/sequential/test-regress-GH-746.js @@ -1,3 +1,4 @@ +'use strict'; // Just test that destroying stdin doesn't mess up listening on a server. // This is a regression test for GH-746. diff --git a/test/sequential/test-regress-GH-784.js b/test/sequential/test-regress-GH-784.js index a33b6f23c479bf..08f660add31048 100644 --- a/test/sequential/test-regress-GH-784.js +++ b/test/sequential/test-regress-GH-784.js @@ -1,3 +1,4 @@ +'use strict'; // Regression test for GH-784 // https://github.com/joyent/node/issues/784 // diff --git a/test/sequential/test-regress-GH-819.js b/test/sequential/test-regress-GH-819.js index 16d0f3bc54e4f3..e459587d97cba9 100644 --- a/test/sequential/test-regress-GH-819.js +++ b/test/sequential/test-regress-GH-819.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var net = require('net'); var assert = require('assert'); diff --git a/test/sequential/test-regress-GH-877.js b/test/sequential/test-regress-GH-877.js index 80c8456742d5af..69671b9dc4a143 100644 --- a/test/sequential/test-regress-GH-877.js +++ b/test/sequential/test-regress-GH-877.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var http = require('http'); var assert = require('assert'); diff --git a/test/sequential/test-require-cache-without-stat.js b/test/sequential/test-require-cache-without-stat.js index 701d47bfc91800..c602ab82b11f4d 100644 --- a/test/sequential/test-require-cache-without-stat.js +++ b/test/sequential/test-require-cache-without-stat.js @@ -1,3 +1,4 @@ +'use strict'; // We've experienced a regression where the module loader stats a bunch of // directories on require() even if it's been called before. The require() // should caching the request. diff --git a/test/sequential/test-setproctitle.js b/test/sequential/test-setproctitle.js index b7e6dd8b552a5d..a0b15e2b85d8c3 100644 --- a/test/sequential/test-setproctitle.js +++ b/test/sequential/test-setproctitle.js @@ -1,3 +1,4 @@ +'use strict'; // Original test written by Jakub Lekstan // FIXME add sunos support diff --git a/test/sequential/test-sigint-infinite-loop.js b/test/sequential/test-sigint-infinite-loop.js index c444caf419188e..8211aeb69ec5db 100644 --- a/test/sequential/test-sigint-infinite-loop.js +++ b/test/sequential/test-sigint-infinite-loop.js @@ -1,3 +1,4 @@ +'use strict'; // This test is to assert that we can SIGINT a script which loops forever. // Ref(http): // groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f diff --git a/test/sequential/test-socket-write-after-fin-error.js b/test/sequential/test-socket-write-after-fin-error.js index 5274d6e3dabe43..226440ec502670 100644 --- a/test/sequential/test-socket-write-after-fin-error.js +++ b/test/sequential/test-socket-write-after-fin-error.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); @@ -24,7 +25,7 @@ var server = net.createServer(function(sock) { serverData += c; }); sock.on('end', function() { - gotServerEnd = true + gotServerEnd = true; sock.write(serverData); sock.end(); }); diff --git a/test/sequential/test-socket-write-after-fin.js b/test/sequential/test-socket-write-after-fin.js index 44d98ba512e1ca..ea8ac27b597ec4 100644 --- a/test/sequential/test-socket-write-after-fin.js +++ b/test/sequential/test-socket-write-after-fin.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -12,7 +13,7 @@ var server = net.createServer({ allowHalfOpen: true }, function(sock) { serverData += c; }); sock.on('end', function() { - gotServerEnd = true + gotServerEnd = true; sock.end(serverData); server.close(); }); diff --git a/test/sequential/test-stdin-child-proc.js b/test/sequential/test-stdin-child-proc.js index 4d3ead73ceac6c..93bf265b8b0020 100644 --- a/test/sequential/test-stdin-child-proc.js +++ b/test/sequential/test-stdin-child-proc.js @@ -1,3 +1,4 @@ +'use strict'; // This tests that pausing and resuming stdin does not hang and timeout // when done in a child process. See test/simple/test-stdin-pause-resume.js var common = require('../common'); diff --git a/test/sequential/test-stdin-from-file.js b/test/sequential/test-stdin-from-file.js index bde2a8559c3db3..35aa5b1a89ac38 100644 --- a/test/sequential/test-stdin-from-file.js +++ b/test/sequential/test-stdin-from-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var join = require('path').join; diff --git a/test/sequential/test-stdin-pipe-resume.js b/test/sequential/test-stdin-pipe-resume.js index a326e380a73654..dbac78d78c5e12 100644 --- a/test/sequential/test-stdin-pipe-resume.js +++ b/test/sequential/test-stdin-pipe-resume.js @@ -1,3 +1,4 @@ +'use strict'; // This tests that piping stdin will cause it to resume() as well. var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdin-script-child.js b/test/sequential/test-stdin-script-child.js index dcccff1ff5d47c..8590df02d8efe9 100644 --- a/test/sequential/test-stdin-script-child.js +++ b/test/sequential/test-stdin-script-child.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js b/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js index 519dce059b2f25..c6f5aecd40e262 100644 --- a/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js +++ b/test/sequential/test-stdout-cannot-be-closed-child-process-pipe.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdout-close-catch.js b/test/sequential/test-stdout-close-catch.js index c1165350aec0ba..f0ecf9a7c4b725 100644 --- a/test/sequential/test-stdout-close-catch.js +++ b/test/sequential/test-stdout-close-catch.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-stdout-stderr-reading.js b/test/sequential/test-stdout-stderr-reading.js index 3fe0db0ce3abbd..82fd51cedda1de 100644 --- a/test/sequential/test-stdout-stderr-reading.js +++ b/test/sequential/test-stdout-stderr-reading.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-stdout-to-file.js b/test/sequential/test-stdout-to-file.js index 8a9d0476911c76..4ef473e57ada08 100644 --- a/test/sequential/test-stdout-to-file.js +++ b/test/sequential/test-stdout-to-file.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-stream2-fs.js b/test/sequential/test-stream2-fs.js index 552d686af02314..96ab97174b2478 100644 --- a/test/sequential/test-stream2-fs.js +++ b/test/sequential/test-stream2-fs.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var R = require('_stream_readable'); var assert = require('assert'); @@ -32,7 +33,7 @@ TestWriter.prototype.write = function(c) { TestWriter.prototype.end = function(c) { if (c) this.buffer.push(c.toString()); this.emit('results', this.buffer); -} +}; var r = new FSReadable(file); var w = new TestWriter(); @@ -41,7 +42,7 @@ w.on('results', function(res) { console.error(res, w.length); assert.equal(w.length, size); var l = 0; - assert.deepEqual(res.map(function (c) { + assert.deepEqual(res.map(function(c) { return c.length; }), expectLengths); console.log('ok'); diff --git a/test/sequential/test-stream2-httpclient-response-end.js b/test/sequential/test-stream2-httpclient-response-end.js index 627960888a7fac..15d7fba27f63af 100644 --- a/test/sequential/test-stream2-httpclient-response-end.js +++ b/test/sequential/test-stream2-httpclient-response-end.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var http = require('http'); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index 9b634116db7fa8..ccbdc55e4feaf9 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -1,3 +1,4 @@ +'use strict'; // Make sure that sync writes to stderr get processed before exiting. var common = require('../common'); diff --git a/test/sequential/test-sync-fileread.js b/test/sequential/test-sync-fileread.js index 3f5f6debd55fea..24a80d96c2601b 100644 --- a/test/sequential/test-sync-fileread.js +++ b/test/sequential/test-sync-fileread.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-tcp-wrap-connect.js b/test/sequential/test-tcp-wrap-connect.js index 2dc9f0cb93a185..9373906c6f612a 100644 --- a/test/sequential/test-tcp-wrap-connect.js +++ b/test/sequential/test-tcp-wrap-connect.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var TCP = process.binding('tcp_wrap').TCP; diff --git a/test/sequential/test-tcp-wrap-listen.js b/test/sequential/test-tcp-wrap-listen.js index 2c0856bd951788..a2c07a7a9ce2a2 100644 --- a/test/sequential/test-tcp-wrap-listen.js +++ b/test/sequential/test-tcp-wrap-listen.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-tls-honorcipherorder.js b/test/sequential/test-tls-honorcipherorder.js index cad1a83a30e856..c33cd9eea63465 100644 --- a/test/sequential/test-tls-honorcipherorder.js +++ b/test/sequential/test-tls-honorcipherorder.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-util-debug.js b/test/sequential/test-util-debug.js index 1af9a7705a104a..834c21ec0e50b4 100644 --- a/test/sequential/test-util-debug.js +++ b/test/sequential/test-util-debug.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); diff --git a/test/sequential/test-vm-syntax-error-stderr.js b/test/sequential/test-vm-syntax-error-stderr.js index b3f76e5e30c5e2..f7b1bef9e309dc 100644 --- a/test/sequential/test-vm-syntax-error-stderr.js +++ b/test/sequential/test-vm-syntax-error-stderr.js @@ -1,3 +1,4 @@ +'use strict'; var common = require('../common'); var assert = require('assert'); var path = require('path'); diff --git a/test/sequential/test-vm-timeout-rethrow.js b/test/sequential/test-vm-timeout-rethrow.js index 547ed2f8d6205b..4f3af900ee0ae2 100644 --- a/test/sequential/test-vm-timeout-rethrow.js +++ b/test/sequential/test-vm-timeout-rethrow.js @@ -1,10 +1,11 @@ +'use strict'; var assert = require('assert'); var vm = require('vm'); var spawn = require('child_process').spawn; if (process.argv[2] === 'child') { var code = 'var j = 0;\n' + - 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + 'for (var i = 0; i < 1000000; i++) j += add(i, i + 1);\n' + 'j;'; var ctx = vm.createContext({ diff --git a/test/sequential/test-zerolengthbufferbug.js b/test/sequential/test-zerolengthbufferbug.js index dde08c63914b38..de36444180b1ec 100644 --- a/test/sequential/test-zerolengthbufferbug.js +++ b/test/sequential/test-zerolengthbufferbug.js @@ -1,3 +1,4 @@ +'use strict'; // Serving up a zero-length buffer should work. var common = require('../common'); diff --git a/test/timers/test-timers-reliability.js b/test/timers/test-timers-reliability.js index c240a44685ac50..b4332468bc2ec3 100644 --- a/test/timers/test-timers-reliability.js +++ b/test/timers/test-timers-reliability.js @@ -1,3 +1,4 @@ +'use strict'; // FaketimeFlags: --exclude-monotonic -f '2014-07-21 09:00:00' var common = require('../common'); @@ -31,23 +32,23 @@ var intervalFired = false; */ var monoTimer = new Timer(); -monoTimer.ontimeout = function () { +monoTimer.ontimeout = function() { /* * Make sure that setTimeout's and setInterval's callbacks have * already fired, otherwise it means that they are vulnerable to * time drifting or inconsistent time changes. */ - assert(timerFired); - assert(intervalFired); + assert(timerFired); + assert(intervalFired); }; monoTimer.start(300, 0); -var timer = setTimeout(function () { - timerFired = true; +var timer = setTimeout(function() { + timerFired = true; }, 200); -var interval = setInterval(function () { - intervalFired = true; - clearInterval(interval); +var interval = setInterval(function() { + intervalFired = true; + clearInterval(interval); }, 200); diff --git a/tools/closure_linter/AUTHORS b/tools/closure_linter/AUTHORS deleted file mode 100644 index 2f72bd6b2fce9a..00000000000000 --- a/tools/closure_linter/AUTHORS +++ /dev/null @@ -1,6 +0,0 @@ -# This is a list of contributors to the Closure Linter. - -# Names should be added to this file like so: -# Name or Organization - -Google Inc. diff --git a/tools/closure_linter/LICENSE b/tools/closure_linter/LICENSE deleted file mode 100644 index d9a10c0d8e868e..00000000000000 --- a/tools/closure_linter/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS diff --git a/tools/closure_linter/README b/tools/closure_linter/README deleted file mode 100644 index 4a21b2defc39ea..00000000000000 --- a/tools/closure_linter/README +++ /dev/null @@ -1,9 +0,0 @@ -This repository contains the Closure Linter - a style checker for JavaScript. - -To install the application, run - python ./setup.py install - -After installing, you get two helper applications installed into /usr/local/bin: - - gjslint.py - runs the linter and checks for errors - fixjsstyle.py - tries to fix errors automatically diff --git a/tools/closure_linter/build/lib/closure_linter/__init__.py b/tools/closure_linter/build/lib/closure_linter/__init__.py deleted file mode 100644 index 1798c8cfff57fa..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Package indicator for gjslint.""" diff --git a/tools/closure_linter/build/lib/closure_linter/aliaspass.py b/tools/closure_linter/build/lib/closure_linter/aliaspass.py deleted file mode 100644 index bb37bfa07b2d90..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/aliaspass.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Pass that scans for goog.scope aliases and lint/usage errors.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -from closure_linter import ecmametadatapass -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter import scopeutil -from closure_linter import tokenutil -from closure_linter.common import error - - -# TODO(nnaze): Create a Pass interface and move this class, EcmaMetaDataPass, -# and related classes onto it. - - -def _GetAliasForIdentifier(identifier, alias_map): - """Returns the aliased_symbol name for an identifier. - - Example usage: - >>> alias_map = {'MyClass': 'goog.foo.MyClass'} - >>> _GetAliasForIdentifier('MyClass.prototype.action', alias_map) - 'goog.foo.MyClass.prototype.action' - - >>> _GetAliasForIdentifier('MyClass.prototype.action', {}) - None - - Args: - identifier: The identifier. - alias_map: A dictionary mapping a symbol to an alias. - - Returns: - The aliased symbol name or None if not found. - """ - ns = identifier.split('.', 1)[0] - aliased_symbol = alias_map.get(ns) - if aliased_symbol: - return aliased_symbol + identifier[len(ns):] - - -def _SetTypeAlias(js_type, alias_map): - """Updates the alias for identifiers in a type. - - Args: - js_type: A typeannotation.TypeAnnotation instance. - alias_map: A dictionary mapping a symbol to an alias. - """ - aliased_symbol = _GetAliasForIdentifier(js_type.identifier, alias_map) - if aliased_symbol: - js_type.alias = aliased_symbol - for sub_type in js_type.IterTypes(): - _SetTypeAlias(sub_type, alias_map) - - -class AliasPass(object): - """Pass to identify goog.scope() usages. - - Identifies goog.scope() usages and finds lint/usage errors. Notes any - aliases of symbols in Closurized namespaces (that is, reassignments - such as "var MyClass = goog.foo.MyClass;") and annotates identifiers - when they're using an alias (so they may be expanded to the full symbol - later -- that "MyClass.prototype.action" refers to - "goog.foo.MyClass.prototype.action" when expanded.). - """ - - def __init__(self, closurized_namespaces=None, error_handler=None): - """Creates a new pass. - - Args: - closurized_namespaces: A set of Closurized namespaces (e.g. 'goog'). - error_handler: An error handler to report lint errors to. - """ - - self._error_handler = error_handler - - # If we have namespaces, freeze the set. - if closurized_namespaces: - closurized_namespaces = frozenset(closurized_namespaces) - - self._closurized_namespaces = closurized_namespaces - - def Process(self, start_token): - """Runs the pass on a token stream. - - Args: - start_token: The first token in the stream. - """ - - if start_token is None: - return - - # TODO(nnaze): Add more goog.scope usage checks. - self._CheckGoogScopeCalls(start_token) - - # If we have closurized namespaces, identify aliased identifiers. - if self._closurized_namespaces: - context = start_token.metadata.context - root_context = context.GetRoot() - self._ProcessRootContext(root_context) - - def _CheckGoogScopeCalls(self, start_token): - """Check goog.scope calls for lint/usage errors.""" - - def IsScopeToken(token): - return (token.type is javascripttokens.JavaScriptTokenType.IDENTIFIER and - token.string == 'goog.scope') - - # Find all the goog.scope tokens in the file - scope_tokens = [t for t in start_token if IsScopeToken(t)] - - for token in scope_tokens: - scope_context = token.metadata.context - - if not (scope_context.type == ecmametadatapass.EcmaContext.STATEMENT and - scope_context.parent.type == ecmametadatapass.EcmaContext.ROOT): - self._MaybeReportError( - error.Error(errors.INVALID_USE_OF_GOOG_SCOPE, - 'goog.scope call not in global scope', token)) - - # There should be only one goog.scope reference. Register errors for - # every instance after the first. - for token in scope_tokens[1:]: - self._MaybeReportError( - error.Error(errors.EXTRA_GOOG_SCOPE_USAGE, - 'More than one goog.scope call in file.', token)) - - def _MaybeReportError(self, err): - """Report an error to the handler (if registered).""" - if self._error_handler: - self._error_handler.HandleError(err) - - @classmethod - def _YieldAllContexts(cls, context): - """Yields all contexts that are contained by the given context.""" - yield context - for child_context in context.children: - for descendent_child in cls._YieldAllContexts(child_context): - yield descendent_child - - @staticmethod - def _IsTokenInParentBlock(token, parent_block): - """Determines whether the given token is contained by the given block. - - Args: - token: A token - parent_block: An EcmaContext. - - Returns: - Whether the token is in a context that is or is a child of the given - parent_block context. - """ - context = token.metadata.context - - while context: - if context is parent_block: - return True - context = context.parent - - return False - - def _ProcessRootContext(self, root_context): - """Processes all goog.scope blocks under the root context.""" - - assert root_context.type is ecmametadatapass.EcmaContext.ROOT - - # Process aliases in statements in the root scope for goog.module-style - # aliases. - global_alias_map = {} - for context in root_context.children: - if context.type == ecmametadatapass.EcmaContext.STATEMENT: - for statement_child in context.children: - if statement_child.type == ecmametadatapass.EcmaContext.VAR: - match = scopeutil.MatchModuleAlias(statement_child) - if match: - # goog.require aliases cannot use further aliases, the symbol is - # the second part of match, directly. - symbol = match[1] - if scopeutil.IsInClosurizedNamespace(symbol, - self._closurized_namespaces): - global_alias_map[match[0]] = symbol - - # Process each block to find aliases. - for context in root_context.children: - self._ProcessBlock(context, global_alias_map) - - def _ProcessBlock(self, context, global_alias_map): - """Scans a goog.scope block to find aliases and mark alias tokens.""" - alias_map = global_alias_map.copy() - - # Iterate over every token in the context. Each token points to one - # context, but multiple tokens may point to the same context. We only want - # to check each context once, so keep track of those we've seen. - seen_contexts = set() - token = context.start_token - while token and self._IsTokenInParentBlock(token, context): - token_context = token.metadata.context if token.metadata else None - - # Check to see if this token is an alias. - if token_context and token_context not in seen_contexts: - seen_contexts.add(token_context) - - # If this is a alias statement in the goog.scope block. - if (token_context.type == ecmametadatapass.EcmaContext.VAR and - scopeutil.IsGoogScopeBlock(token_context.parent.parent)): - match = scopeutil.MatchAlias(token_context) - - # If this is an alias, remember it in the map. - if match: - alias, symbol = match - symbol = _GetAliasForIdentifier(symbol, alias_map) or symbol - if scopeutil.IsInClosurizedNamespace(symbol, - self._closurized_namespaces): - alias_map[alias] = symbol - - # If this token is an identifier that matches an alias, - # mark the token as an alias to the original symbol. - if (token.type is javascripttokens.JavaScriptTokenType.SIMPLE_LVALUE or - token.type is javascripttokens.JavaScriptTokenType.IDENTIFIER): - identifier = tokenutil.GetIdentifierForToken(token) - if identifier: - aliased_symbol = _GetAliasForIdentifier(identifier, alias_map) - if aliased_symbol: - token.metadata.aliased_symbol = aliased_symbol - - elif token.type == javascripttokens.JavaScriptTokenType.DOC_FLAG: - flag = token.attached_object - if flag and flag.HasType() and flag.jstype: - _SetTypeAlias(flag.jstype, alias_map) - - token = token.next # Get next token diff --git a/tools/closure_linter/build/lib/closure_linter/aliaspass_test.py b/tools/closure_linter/build/lib/closure_linter/aliaspass_test.py deleted file mode 100644 index 7042e5348763cb..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/aliaspass_test.py +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the aliaspass module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import unittest as googletest - -from closure_linter import aliaspass -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import testutil -from closure_linter.common import erroraccumulator - - -def _GetTokenByLineAndString(start_token, string, line_number): - for token in start_token: - if token.line_number == line_number and token.string == string: - return token - - -class AliasPassTest(googletest.TestCase): - - def testInvalidGoogScopeCall(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCOPE_SCRIPT) - - error_accumulator = erroraccumulator.ErrorAccumulator() - alias_pass = aliaspass.AliasPass( - error_handler=error_accumulator) - alias_pass.Process(start_token) - - alias_errors = error_accumulator.GetErrors() - self.assertEquals(1, len(alias_errors)) - - alias_error = alias_errors[0] - - self.assertEquals(errors.INVALID_USE_OF_GOOG_SCOPE, alias_error.code) - self.assertEquals('goog.scope', alias_error.token.string) - - def testAliasedIdentifiers(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_ALIAS_SCRIPT) - alias_pass = aliaspass.AliasPass(set(['goog', 'myproject'])) - alias_pass.Process(start_token) - - alias_token = _GetTokenByLineAndString(start_token, 'Event', 4) - self.assertTrue(alias_token.metadata.is_alias_definition) - - my_class_token = _GetTokenByLineAndString(start_token, 'myClass', 9) - self.assertIsNone(my_class_token.metadata.aliased_symbol) - - component_token = _GetTokenByLineAndString(start_token, 'Component', 17) - self.assertEquals('goog.ui.Component', - component_token.metadata.aliased_symbol) - - event_token = _GetTokenByLineAndString(start_token, 'Event.Something', 17) - self.assertEquals('goog.events.Event.Something', - event_token.metadata.aliased_symbol) - - non_closurized_token = _GetTokenByLineAndString( - start_token, 'NonClosurizedClass', 18) - self.assertIsNone(non_closurized_token.metadata.aliased_symbol) - - long_start_token = _GetTokenByLineAndString(start_token, 'Event', 24) - self.assertEquals('goog.events.Event.MultilineIdentifier.someMethod', - long_start_token.metadata.aliased_symbol) - - def testAliasedDoctypes(self): - """Tests that aliases are correctly expanded within type annotations.""" - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_ALIAS_SCRIPT) - tracker = javascriptstatetracker.JavaScriptStateTracker() - tracker.DocFlagPass(start_token, error_handler=None) - - alias_pass = aliaspass.AliasPass(set(['goog', 'myproject'])) - alias_pass.Process(start_token) - - flag_token = _GetTokenByLineAndString(start_token, '@type', 22) - self.assertEquals( - 'goog.events.Event.>', - repr(flag_token.attached_object.jstype)) - - def testModuleAlias(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(""" -goog.module('goog.test'); -var Alias = goog.require('goog.Alias'); -Alias.use(); -""") - alias_pass = aliaspass.AliasPass(set(['goog'])) - alias_pass.Process(start_token) - alias_token = _GetTokenByLineAndString(start_token, 'Alias', 3) - self.assertTrue(alias_token.metadata.is_alias_definition) - - def testMultipleGoogScopeCalls(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass( - _TEST_MULTIPLE_SCOPE_SCRIPT) - - error_accumulator = erroraccumulator.ErrorAccumulator() - - alias_pass = aliaspass.AliasPass( - set(['goog', 'myproject']), - error_handler=error_accumulator) - alias_pass.Process(start_token) - - alias_errors = error_accumulator.GetErrors() - - self.assertEquals(3, len(alias_errors)) - - error = alias_errors[0] - self.assertEquals(errors.INVALID_USE_OF_GOOG_SCOPE, error.code) - self.assertEquals(7, error.token.line_number) - - error = alias_errors[1] - self.assertEquals(errors.EXTRA_GOOG_SCOPE_USAGE, error.code) - self.assertEquals(7, error.token.line_number) - - error = alias_errors[2] - self.assertEquals(errors.EXTRA_GOOG_SCOPE_USAGE, error.code) - self.assertEquals(11, error.token.line_number) - - -_TEST_ALIAS_SCRIPT = """ -goog.scope(function() { -var events = goog.events; // scope alias -var Event = events. - Event; // nested multiline scope alias - -// This should not be registered as an aliased identifier because -// it appears before the alias. -var myClass = new MyClass(); - -var Component = goog.ui.Component; // scope alias -var MyClass = myproject.foo.MyClass; // scope alias - -// Scope alias of non-Closurized namespace. -var NonClosurizedClass = aaa.bbb.NonClosurizedClass; - -var component = new Component(Event.Something); -var nonClosurized = NonClosurizedClass(); - -/** - * A created namespace with a really long identifier. - * @type {events.Event.} - */ -Event. - MultilineIdentifier. - someMethod = function() {}; -}); -""" - -_TEST_SCOPE_SCRIPT = """ -function foo () { - // This goog.scope call is invalid. - goog.scope(function() { - - }); -} -""" - -_TEST_MULTIPLE_SCOPE_SCRIPT = """ -goog.scope(function() { - // do nothing -}); - -function foo() { - var test = goog.scope; // We should not see goog.scope mentioned. -} - -// This goog.scope invalid. There can be only one. -goog.scope(function() { - -}); -""" - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/checker.py b/tools/closure_linter/build/lib/closure_linter/checker.py deleted file mode 100644 index 1c984173b06639..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/checker.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Core methods for checking JS files for common style guide violations.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import gflags as flags - -from closure_linter import aliaspass -from closure_linter import checkerbase -from closure_linter import closurizednamespacesinfo -from closure_linter import javascriptlintrules - - -flags.DEFINE_list('closurized_namespaces', '', - 'Namespace prefixes, used for testing of' - 'goog.provide/require') -flags.DEFINE_list('ignored_extra_namespaces', '', - 'Fully qualified namespaces that should be not be reported ' - 'as extra by the linter.') - - -class JavaScriptStyleChecker(checkerbase.CheckerBase): - """Checker that applies JavaScriptLintRules.""" - - def __init__(self, state_tracker, error_handler): - """Initialize an JavaScriptStyleChecker object. - - Args: - state_tracker: State tracker. - error_handler: Error handler to pass all errors to. - """ - self._namespaces_info = None - self._alias_pass = None - if flags.FLAGS.closurized_namespaces: - self._namespaces_info = ( - closurizednamespacesinfo.ClosurizedNamespacesInfo( - flags.FLAGS.closurized_namespaces, - flags.FLAGS.ignored_extra_namespaces)) - - self._alias_pass = aliaspass.AliasPass( - flags.FLAGS.closurized_namespaces, error_handler) - - checkerbase.CheckerBase.__init__( - self, - error_handler=error_handler, - lint_rules=javascriptlintrules.JavaScriptLintRules( - self._namespaces_info), - state_tracker=state_tracker) - - def Check(self, start_token, limited_doc_checks=False, is_html=False, - stop_token=None): - """Checks a token stream for lint warnings/errors. - - Adds a separate pass for computing dependency information based on - goog.require and goog.provide statements prior to the main linting pass. - - Args: - start_token: The first token in the token stream. - limited_doc_checks: Whether to perform limited checks. - is_html: Whether this token stream is HTML. - stop_token: If given, checks should stop at this token. - """ - self._lint_rules.Initialize(self, limited_doc_checks, is_html) - - self._state_tracker.DocFlagPass(start_token, self._error_handler) - - if self._alias_pass: - self._alias_pass.Process(start_token) - - # To maximize the amount of errors that get reported before a parse error - # is displayed, don't run the dependency pass if a parse error exists. - if self._namespaces_info: - self._namespaces_info.Reset() - self._ExecutePass(start_token, self._DependencyPass, stop_token) - - self._ExecutePass(start_token, self._LintPass, stop_token) - - # If we have a stop_token, we didn't end up reading the whole file and, - # thus, don't call Finalize to do end-of-file checks. - if not stop_token: - self._lint_rules.Finalize(self._state_tracker) - - def _DependencyPass(self, token): - """Processes an individual token for dependency information. - - Used to encapsulate the logic needed to process an individual token so that - it can be passed to _ExecutePass. - - Args: - token: The token to process. - """ - self._namespaces_info.ProcessToken(token, self._state_tracker) diff --git a/tools/closure_linter/build/lib/closure_linter/checkerbase.py b/tools/closure_linter/build/lib/closure_linter/checkerbase.py deleted file mode 100644 index 6679ded05be1e1..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/checkerbase.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Base classes for writing checkers that operate on tokens.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'jacobr@google.com (Jacob Richman)') - -from closure_linter import errorrules -from closure_linter.common import error - - -class LintRulesBase(object): - """Base class for all classes defining the lint rules for a language.""" - - def __init__(self): - self.__checker = None - - def Initialize(self, checker, limited_doc_checks, is_html): - """Initializes to prepare to check a file. - - Args: - checker: Class to report errors to. - limited_doc_checks: Whether doc checking is relaxed for this file. - is_html: Whether the file is an HTML file with extracted contents. - """ - self.__checker = checker - self._limited_doc_checks = limited_doc_checks - self._is_html = is_html - - def _HandleError(self, code, message, token, position=None, - fix_data=None): - """Call the HandleError function for the checker we are associated with.""" - if errorrules.ShouldReportError(code): - self.__checker.HandleError(code, message, token, position, fix_data) - - def _SetLimitedDocChecks(self, limited_doc_checks): - """Sets whether doc checking is relaxed for this file. - - Args: - limited_doc_checks: Whether doc checking is relaxed for this file. - """ - self._limited_doc_checks = limited_doc_checks - - def CheckToken(self, token, parser_state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration. - parser_state: Object that indicates the parser state in the page. - - Raises: - TypeError: If not overridden. - """ - raise TypeError('Abstract method CheckToken not implemented') - - def Finalize(self, parser_state): - """Perform all checks that need to occur after all lines are processed. - - Args: - parser_state: State of the parser after parsing all tokens - - Raises: - TypeError: If not overridden. - """ - raise TypeError('Abstract method Finalize not implemented') - - -class CheckerBase(object): - """This class handles checking a LintRules object against a file.""" - - def __init__(self, error_handler, lint_rules, state_tracker): - """Initialize a checker object. - - Args: - error_handler: Object that handles errors. - lint_rules: LintRules object defining lint errors given a token - and state_tracker object. - state_tracker: Object that tracks the current state in the token stream. - - """ - self._error_handler = error_handler - self._lint_rules = lint_rules - self._state_tracker = state_tracker - - self._has_errors = False - - def HandleError(self, code, message, token, position=None, - fix_data=None): - """Prints out the given error message including a line number. - - Args: - code: The error code. - message: The error to print. - token: The token where the error occurred, or None if it was a file-wide - issue. - position: The position of the error, defaults to None. - fix_data: Metadata used for fixing the error. - """ - self._has_errors = True - self._error_handler.HandleError( - error.Error(code, message, token, position, fix_data)) - - def HasErrors(self): - """Returns true if the style checker has found any errors. - - Returns: - True if the style checker has found any errors. - """ - return self._has_errors - - def Check(self, start_token, limited_doc_checks=False, is_html=False, - stop_token=None): - """Checks a token stream, reporting errors to the error reporter. - - Args: - start_token: First token in token stream. - limited_doc_checks: Whether doc checking is relaxed for this file. - is_html: Whether the file being checked is an HTML file with extracted - contents. - stop_token: If given, check should stop at this token. - """ - - self._lint_rules.Initialize(self, limited_doc_checks, is_html) - self._ExecutePass(start_token, self._LintPass, stop_token=stop_token) - self._lint_rules.Finalize(self._state_tracker) - - def _LintPass(self, token): - """Checks an individual token for lint warnings/errors. - - Used to encapsulate the logic needed to check an individual token so that it - can be passed to _ExecutePass. - - Args: - token: The token to check. - """ - self._lint_rules.CheckToken(token, self._state_tracker) - - def _ExecutePass(self, token, pass_function, stop_token=None): - """Calls the given function for every token in the given token stream. - - As each token is passed to the given function, state is kept up to date and, - depending on the error_trace flag, errors are either caught and reported, or - allowed to bubble up so developers can see the full stack trace. If a parse - error is specified, the pass will proceed as normal until the token causing - the parse error is reached. - - Args: - token: The first token in the token stream. - pass_function: The function to call for each token in the token stream. - stop_token: The last token to check (if given). - - Raises: - Exception: If any error occurred while calling the given function. - """ - - self._state_tracker.Reset() - while token: - # When we are looking at a token and decided to delete the whole line, we - # will delete all of them in the "HandleToken()" below. So the current - # token and subsequent ones may already be deleted here. The way we - # delete a token does not wipe out the previous and next pointers of the - # deleted token. So we need to check the token itself to make sure it is - # not deleted. - if not token.is_deleted: - # End the pass at the stop token - if stop_token and token is stop_token: - return - - self._state_tracker.HandleToken( - token, self._state_tracker.GetLastNonSpaceToken()) - pass_function(token) - self._state_tracker.HandleAfterToken(token) - - token = token.next diff --git a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo.py b/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo.py deleted file mode 100644 index e7cbfd3318974b..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo.py +++ /dev/null @@ -1,578 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Logic for computing dependency information for closurized JavaScript files. - -Closurized JavaScript files express dependencies using goog.require and -goog.provide statements. In order for the linter to detect when a statement is -missing or unnecessary, all identifiers in the JavaScript file must first be -processed to determine if they constitute the creation or usage of a dependency. -""" - - - -import re - -from closure_linter import javascripttokens -from closure_linter import tokenutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - -DEFAULT_EXTRA_NAMESPACES = [ - 'goog.testing.asserts', - 'goog.testing.jsunit', -] - - -class UsedNamespace(object): - """A type for information about a used namespace.""" - - def __init__(self, namespace, identifier, token, alias_definition): - """Initializes the instance. - - Args: - namespace: the namespace of an identifier used in the file - identifier: the complete identifier - token: the token that uses the namespace - alias_definition: a boolean stating whether the namespace is only to used - for an alias definition and should not be required. - """ - self.namespace = namespace - self.identifier = identifier - self.token = token - self.alias_definition = alias_definition - - def GetLine(self): - return self.token.line_number - - def __repr__(self): - return 'UsedNamespace(%s)' % ', '.join( - ['%s=%s' % (k, repr(v)) for k, v in self.__dict__.iteritems()]) - - -class ClosurizedNamespacesInfo(object): - """Dependency information for closurized JavaScript files. - - Processes token streams for dependency creation or usage and provides logic - for determining if a given require or provide statement is unnecessary or if - there are missing require or provide statements. - """ - - def __init__(self, closurized_namespaces, ignored_extra_namespaces): - """Initializes an instance the ClosurizedNamespacesInfo class. - - Args: - closurized_namespaces: A list of namespace prefixes that should be - processed for dependency information. Non-matching namespaces are - ignored. - ignored_extra_namespaces: A list of namespaces that should not be reported - as extra regardless of whether they are actually used. - """ - self._closurized_namespaces = closurized_namespaces - self._ignored_extra_namespaces = (ignored_extra_namespaces + - DEFAULT_EXTRA_NAMESPACES) - self.Reset() - - def Reset(self): - """Resets the internal state to prepare for processing a new file.""" - - # A list of goog.provide tokens in the order they appeared in the file. - self._provide_tokens = [] - - # A list of goog.require tokens in the order they appeared in the file. - self._require_tokens = [] - - # Namespaces that are already goog.provided. - self._provided_namespaces = [] - - # Namespaces that are already goog.required. - self._required_namespaces = [] - - # Note that created_namespaces and used_namespaces contain both namespaces - # and identifiers because there are many existing cases where a method or - # constant is provided directly instead of its namespace. Ideally, these - # two lists would only have to contain namespaces. - - # A list of tuples where the first element is the namespace of an identifier - # created in the file, the second is the identifier itself and the third is - # the line number where it's created. - self._created_namespaces = [] - - # A list of UsedNamespace instances. - self._used_namespaces = [] - - # A list of seemingly-unnecessary namespaces that are goog.required() and - # annotated with @suppress {extraRequire}. - self._suppressed_requires = [] - - # A list of goog.provide tokens which are duplicates. - self._duplicate_provide_tokens = [] - - # A list of goog.require tokens which are duplicates. - self._duplicate_require_tokens = [] - - # Whether this file is in a goog.scope. Someday, we may add support - # for checking scopified namespaces, but for now let's just fail - # in a more reasonable way. - self._scopified_file = False - - # TODO(user): Handle the case where there are 2 different requires - # that can satisfy the same dependency, but only one is necessary. - - def GetProvidedNamespaces(self): - """Returns the namespaces which are already provided by this file. - - Returns: - A list of strings where each string is a 'namespace' corresponding to an - existing goog.provide statement in the file being checked. - """ - return set(self._provided_namespaces) - - def GetRequiredNamespaces(self): - """Returns the namespaces which are already required by this file. - - Returns: - A list of strings where each string is a 'namespace' corresponding to an - existing goog.require statement in the file being checked. - """ - return set(self._required_namespaces) - - def IsExtraProvide(self, token): - """Returns whether the given goog.provide token is unnecessary. - - Args: - token: A goog.provide token. - - Returns: - True if the given token corresponds to an unnecessary goog.provide - statement, otherwise False. - """ - namespace = tokenutil.GetStringAfterToken(token) - - if self.GetClosurizedNamespace(namespace) is None: - return False - - if token in self._duplicate_provide_tokens: - return True - - # TODO(user): There's probably a faster way to compute this. - for created_namespace, created_identifier, _ in self._created_namespaces: - if namespace == created_namespace or namespace == created_identifier: - return False - - return True - - def IsExtraRequire(self, token): - """Returns whether the given goog.require token is unnecessary. - - Args: - token: A goog.require token. - - Returns: - True if the given token corresponds to an unnecessary goog.require - statement, otherwise False. - """ - namespace = tokenutil.GetStringAfterToken(token) - - if self.GetClosurizedNamespace(namespace) is None: - return False - - if namespace in self._ignored_extra_namespaces: - return False - - if token in self._duplicate_require_tokens: - return True - - if namespace in self._suppressed_requires: - return False - - # If the namespace contains a component that is initial caps, then that - # must be the last component of the namespace. - parts = namespace.split('.') - if len(parts) > 1 and parts[-2][0].isupper(): - return True - - # TODO(user): There's probably a faster way to compute this. - for ns in self._used_namespaces: - if (not ns.alias_definition and ( - namespace == ns.namespace or namespace == ns.identifier)): - return False - - return True - - def GetMissingProvides(self): - """Returns the dict of missing provided namespaces for the current file. - - Returns: - Returns a dictionary of key as string and value as integer where each - string(key) is a namespace that should be provided by this file, but is - not and integer(value) is first line number where it's defined. - """ - missing_provides = dict() - for namespace, identifier, line_number in self._created_namespaces: - if (not self._IsPrivateIdentifier(identifier) and - namespace not in self._provided_namespaces and - identifier not in self._provided_namespaces and - namespace not in self._required_namespaces and - namespace not in missing_provides): - missing_provides[namespace] = line_number - - return missing_provides - - def GetMissingRequires(self): - """Returns the dict of missing required namespaces for the current file. - - For each non-private identifier used in the file, find either a - goog.require, goog.provide or a created identifier that satisfies it. - goog.require statements can satisfy the identifier by requiring either the - namespace of the identifier or the identifier itself. goog.provide - statements can satisfy the identifier by providing the namespace of the - identifier. A created identifier can only satisfy the used identifier if - it matches it exactly (necessary since things can be defined on a - namespace in more than one file). Note that provided namespaces should be - a subset of created namespaces, but we check both because in some cases we - can't always detect the creation of the namespace. - - Returns: - Returns a dictionary of key as string and value integer where each - string(key) is a namespace that should be required by this file, but is - not and integer(value) is first line number where it's used. - """ - external_dependencies = set(self._required_namespaces) - - # Assume goog namespace is always available. - external_dependencies.add('goog') - # goog.module is treated as a builtin, too (for goog.module.get). - external_dependencies.add('goog.module') - - created_identifiers = set() - for unused_namespace, identifier, unused_line_number in ( - self._created_namespaces): - created_identifiers.add(identifier) - - missing_requires = dict() - illegal_alias_statements = dict() - - def ShouldRequireNamespace(namespace, identifier): - """Checks if a namespace would normally be required.""" - return ( - not self._IsPrivateIdentifier(identifier) and - namespace not in external_dependencies and - namespace not in self._provided_namespaces and - identifier not in external_dependencies and - identifier not in created_identifiers and - namespace not in missing_requires) - - # First check all the used identifiers where we know that their namespace - # needs to be provided (unless they are optional). - for ns in self._used_namespaces: - namespace = ns.namespace - identifier = ns.identifier - if (not ns.alias_definition and - ShouldRequireNamespace(namespace, identifier)): - missing_requires[namespace] = ns.GetLine() - - # Now that all required namespaces are known, we can check if the alias - # definitions (that are likely being used for typeannotations that don't - # need explicit goog.require statements) are already covered. If not - # the user shouldn't use the alias. - for ns in self._used_namespaces: - if (not ns.alias_definition or - not ShouldRequireNamespace(ns.namespace, ns.identifier)): - continue - if self._FindNamespace(ns.identifier, self._provided_namespaces, - created_identifiers, external_dependencies, - missing_requires): - continue - namespace = ns.identifier.rsplit('.', 1)[0] - illegal_alias_statements[namespace] = ns.token - - return missing_requires, illegal_alias_statements - - def _FindNamespace(self, identifier, *namespaces_list): - """Finds the namespace of an identifier given a list of other namespaces. - - Args: - identifier: An identifier whose parent needs to be defined. - e.g. for goog.bar.foo we search something that provides - goog.bar. - *namespaces_list: var args of iterables of namespace identifiers - Returns: - The namespace that the given identifier is part of or None. - """ - identifier = identifier.rsplit('.', 1)[0] - identifier_prefix = identifier + '.' - for namespaces in namespaces_list: - for namespace in namespaces: - if namespace == identifier or namespace.startswith(identifier_prefix): - return namespace - return None - - def _IsPrivateIdentifier(self, identifier): - """Returns whether the given identifier is private.""" - pieces = identifier.split('.') - for piece in pieces: - if piece.endswith('_'): - return True - return False - - def IsFirstProvide(self, token): - """Returns whether token is the first provide token.""" - return self._provide_tokens and token == self._provide_tokens[0] - - def IsFirstRequire(self, token): - """Returns whether token is the first require token.""" - return self._require_tokens and token == self._require_tokens[0] - - def IsLastProvide(self, token): - """Returns whether token is the last provide token.""" - return self._provide_tokens and token == self._provide_tokens[-1] - - def IsLastRequire(self, token): - """Returns whether token is the last require token.""" - return self._require_tokens and token == self._require_tokens[-1] - - def ProcessToken(self, token, state_tracker): - """Processes the given token for dependency information. - - Args: - token: The token to process. - state_tracker: The JavaScript state tracker. - """ - - # Note that this method is in the critical path for the linter and has been - # optimized for performance in the following ways: - # - Tokens are checked by type first to minimize the number of function - # calls necessary to determine if action needs to be taken for the token. - # - The most common tokens types are checked for first. - # - The number of function calls has been minimized (thus the length of this - # function. - - if token.type == TokenType.IDENTIFIER: - # TODO(user): Consider saving the whole identifier in metadata. - whole_identifier_string = tokenutil.GetIdentifierForToken(token) - if whole_identifier_string is None: - # We only want to process the identifier one time. If the whole string - # identifier is None, that means this token was part of a multi-token - # identifier, but it was not the first token of the identifier. - return - - # In the odd case that a goog.require is encountered inside a function, - # just ignore it (e.g. dynamic loading in test runners). - if token.string == 'goog.require' and not state_tracker.InFunction(): - self._require_tokens.append(token) - namespace = tokenutil.GetStringAfterToken(token) - if namespace in self._required_namespaces: - self._duplicate_require_tokens.append(token) - else: - self._required_namespaces.append(namespace) - - # If there is a suppression for the require, add a usage for it so it - # gets treated as a regular goog.require (i.e. still gets sorted). - if self._HasSuppression(state_tracker, 'extraRequire'): - self._suppressed_requires.append(namespace) - self._AddUsedNamespace(state_tracker, namespace, token) - - elif token.string == 'goog.provide': - self._provide_tokens.append(token) - namespace = tokenutil.GetStringAfterToken(token) - if namespace in self._provided_namespaces: - self._duplicate_provide_tokens.append(token) - else: - self._provided_namespaces.append(namespace) - - # If there is a suppression for the provide, add a creation for it so it - # gets treated as a regular goog.provide (i.e. still gets sorted). - if self._HasSuppression(state_tracker, 'extraProvide'): - self._AddCreatedNamespace(state_tracker, namespace, token.line_number) - - elif token.string == 'goog.scope': - self._scopified_file = True - - elif token.string == 'goog.setTestOnly': - - # Since the message is optional, we don't want to scan to later lines. - for t in tokenutil.GetAllTokensInSameLine(token): - if t.type == TokenType.STRING_TEXT: - message = t.string - - if re.match(r'^\w+(\.\w+)+$', message): - # This looks like a namespace. If it's a Closurized namespace, - # consider it created. - base_namespace = message.split('.', 1)[0] - if base_namespace in self._closurized_namespaces: - self._AddCreatedNamespace(state_tracker, message, - token.line_number) - - break - else: - jsdoc = state_tracker.GetDocComment() - if token.metadata and token.metadata.aliased_symbol: - whole_identifier_string = token.metadata.aliased_symbol - elif (token.string == 'goog.module.get' and - not self._HasSuppression(state_tracker, 'extraRequire')): - # Cannot use _AddUsedNamespace as this is not an identifier, but - # already the entire namespace that's required. - namespace = tokenutil.GetStringAfterToken(token) - namespace = UsedNamespace(namespace, namespace, token, - alias_definition=False) - self._used_namespaces.append(namespace) - if jsdoc and jsdoc.HasFlag('typedef'): - self._AddCreatedNamespace(state_tracker, whole_identifier_string, - token.line_number, - namespace=self.GetClosurizedNamespace( - whole_identifier_string)) - else: - is_alias_definition = (token.metadata and - token.metadata.is_alias_definition) - self._AddUsedNamespace(state_tracker, whole_identifier_string, - token, is_alias_definition) - - elif token.type == TokenType.SIMPLE_LVALUE: - identifier = token.values['identifier'] - start_token = tokenutil.GetIdentifierStart(token) - if start_token and start_token != token: - # Multi-line identifier being assigned. Get the whole identifier. - identifier = tokenutil.GetIdentifierForToken(start_token) - else: - start_token = token - # If an alias is defined on the start_token, use it instead. - if (start_token and - start_token.metadata and - start_token.metadata.aliased_symbol and - not start_token.metadata.is_alias_definition): - identifier = start_token.metadata.aliased_symbol - - if identifier: - namespace = self.GetClosurizedNamespace(identifier) - if state_tracker.InFunction(): - self._AddUsedNamespace(state_tracker, identifier, token) - elif namespace and namespace != 'goog': - self._AddCreatedNamespace(state_tracker, identifier, - token.line_number, namespace=namespace) - - elif token.type == TokenType.DOC_FLAG: - flag = token.attached_object - flag_type = flag.flag_type - if flag and flag.HasType() and flag.jstype: - is_interface = state_tracker.GetDocComment().HasFlag('interface') - if flag_type == 'implements' or (flag_type == 'extends' - and is_interface): - identifier = flag.jstype.alias or flag.jstype.identifier - self._AddUsedNamespace(state_tracker, identifier, token) - # Since we process doctypes only for implements and extends, the - # type is a simple one and we don't need any iteration for subtypes. - - def _AddCreatedNamespace(self, state_tracker, identifier, line_number, - namespace=None): - """Adds the namespace of an identifier to the list of created namespaces. - - If the identifier is annotated with a 'missingProvide' suppression, it is - not added. - - Args: - state_tracker: The JavaScriptStateTracker instance. - identifier: The identifier to add. - line_number: Line number where namespace is created. - namespace: The namespace of the identifier or None if the identifier is - also the namespace. - """ - if not namespace: - namespace = identifier - - if self._HasSuppression(state_tracker, 'missingProvide'): - return - - self._created_namespaces.append([namespace, identifier, line_number]) - - def _AddUsedNamespace(self, state_tracker, identifier, token, - is_alias_definition=False): - """Adds the namespace of an identifier to the list of used namespaces. - - If the identifier is annotated with a 'missingRequire' suppression, it is - not added. - - Args: - state_tracker: The JavaScriptStateTracker instance. - identifier: An identifier which has been used. - token: The token in which the namespace is used. - is_alias_definition: If the used namespace is part of an alias_definition. - Aliased symbols need their parent namespace to be available, if it is - not yet required through another symbol, an error will be thrown. - """ - if self._HasSuppression(state_tracker, 'missingRequire'): - return - - namespace = self.GetClosurizedNamespace(identifier) - # b/5362203 If its a variable in scope then its not a required namespace. - if namespace and not state_tracker.IsVariableInScope(namespace): - namespace = UsedNamespace(namespace, identifier, token, - is_alias_definition) - self._used_namespaces.append(namespace) - - def _HasSuppression(self, state_tracker, suppression): - jsdoc = state_tracker.GetDocComment() - return jsdoc and suppression in jsdoc.suppressions - - def GetClosurizedNamespace(self, identifier): - """Given an identifier, returns the namespace that identifier is from. - - Args: - identifier: The identifier to extract a namespace from. - - Returns: - The namespace the given identifier resides in, or None if one could not - be found. - """ - if identifier.startswith('goog.global'): - # Ignore goog.global, since it is, by definition, global. - return None - - parts = identifier.split('.') - for namespace in self._closurized_namespaces: - if not identifier.startswith(namespace + '.'): - continue - - # The namespace for a class is the shortest prefix ending in a class - # name, which starts with a capital letter but is not a capitalized word. - # - # We ultimately do not want to allow requiring or providing of inner - # classes/enums. Instead, a file should provide only the top-level class - # and users should require only that. - namespace = [] - for part in parts: - if part == 'prototype' or part.isupper(): - return '.'.join(namespace) - namespace.append(part) - if part[0].isupper(): - return '.'.join(namespace) - - # At this point, we know there's no class or enum, so the namespace is - # just the identifier with the last part removed. With the exception of - # apply, inherits, and call, which should also be stripped. - if parts[-1] in ('apply', 'inherits', 'call'): - parts.pop() - parts.pop() - - # If the last part ends with an underscore, it is a private variable, - # method, or enum. The namespace is whatever is before it. - if parts and parts[-1].endswith('_'): - parts.pop() - - return '.'.join(parts) - - return None diff --git a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo_test.py b/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo_test.py deleted file mode 100644 index 7aeae21956af8d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/closurizednamespacesinfo_test.py +++ /dev/null @@ -1,873 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for ClosurizedNamespacesInfo.""" - - - -import unittest as googletest -from closure_linter import aliaspass -from closure_linter import closurizednamespacesinfo -from closure_linter import ecmametadatapass -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - - -def _ToLineDict(illegal_alias_stmts): - """Replaces tokens with the respective line number.""" - return {k: v.line_number for k, v in illegal_alias_stmts.iteritems()} - - -class ClosurizedNamespacesInfoTest(googletest.TestCase): - """Tests for ClosurizedNamespacesInfo.""" - - _test_cases = { - 'goog.global.anything': None, - 'package.CONSTANT': 'package', - 'package.methodName': 'package', - 'package.subpackage.methodName': 'package.subpackage', - 'package.subpackage.methodName.apply': 'package.subpackage', - 'package.ClassName.something': 'package.ClassName', - 'package.ClassName.Enum.VALUE.methodName': 'package.ClassName', - 'package.ClassName.CONSTANT': 'package.ClassName', - 'package.namespace.CONSTANT.methodName': 'package.namespace', - 'package.ClassName.inherits': 'package.ClassName', - 'package.ClassName.apply': 'package.ClassName', - 'package.ClassName.methodName.apply': 'package.ClassName', - 'package.ClassName.methodName.call': 'package.ClassName', - 'package.ClassName.prototype.methodName': 'package.ClassName', - 'package.ClassName.privateMethod_': 'package.ClassName', - 'package.className.privateProperty_': 'package.className', - 'package.className.privateProperty_.methodName': 'package.className', - 'package.ClassName.PrivateEnum_': 'package.ClassName', - 'package.ClassName.prototype.methodName.apply': 'package.ClassName', - 'package.ClassName.property.subProperty': 'package.ClassName', - 'package.className.prototype.something.somethingElse': 'package.className' - } - - def testGetClosurizedNamespace(self): - """Tests that the correct namespace is returned for various identifiers.""" - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=['package'], ignored_extra_namespaces=[]) - for identifier, expected_namespace in self._test_cases.items(): - actual_namespace = namespaces_info.GetClosurizedNamespace(identifier) - self.assertEqual( - expected_namespace, - actual_namespace, - 'expected namespace "' + str(expected_namespace) + - '" for identifier "' + str(identifier) + '" but was "' + - str(actual_namespace) + '"') - - def testIgnoredExtraNamespaces(self): - """Tests that ignored_extra_namespaces are ignored.""" - token = self._GetRequireTokens('package.Something') - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=['package'], - ignored_extra_namespaces=['package.Something']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should be valid since it is in ignored namespaces.') - - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - ['package'], []) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be invalid since it is not in ignored namespaces.') - - def testIsExtraProvide_created(self): - """Tests that provides for created namespaces are not extra.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is created.') - - def testIsExtraProvide_createdIdentifier(self): - """Tests that provides for created identifiers are not extra.""" - input_lines = [ - 'goog.provide(\'package.Foo.methodName\');', - 'package.Foo.methodName = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is created.') - - def testIsExtraProvide_notCreated(self): - """Tests that provides for non-created namespaces are extra.""" - input_lines = ['goog.provide(\'package.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is not created.') - - def testIsExtraProvide_notCreatedMultipartClosurizedNamespace(self): - """Tests that provides for non-created namespaces are extra.""" - input_lines = ['goog.provide(\'multi.part.namespace.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['multi.part']) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is not created.') - - def testIsExtraProvide_duplicate(self): - """Tests that providing a namespace twice makes the second one extra.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - # Advance to the second goog.provide token. - token = tokenutil.Search(token.next, TokenType.IDENTIFIER) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is already provided.') - - def testIsExtraProvide_notClosurized(self): - """Tests that provides of non-closurized namespaces are not extra.""" - input_lines = ['goog.provide(\'notclosurized.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is not closurized.') - - def testIsExtraRequire_used(self): - """Tests that requires for used namespaces are not extra.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'var x = package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is used.') - - def testIsExtraRequire_usedIdentifier(self): - """Tests that requires for used methods on classes are extra.""" - input_lines = [ - 'goog.require(\'package.Foo.methodName\');', - 'var x = package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should require the package, not the method specifically.') - - def testIsExtraRequire_notUsed(self): - """Tests that requires for unused namespaces are extra.""" - input_lines = ['goog.require(\'package.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be extra since it is not used.') - - def testIsExtraRequire_notUsedMultiPartClosurizedNamespace(self): - """Tests unused require with multi-part closurized namespaces.""" - - input_lines = ['goog.require(\'multi.part.namespace.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['multi.part']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be extra since it is not used.') - - def testIsExtraRequire_notClosurized(self): - """Tests that requires of non-closurized namespaces are not extra.""" - input_lines = ['goog.require(\'notclosurized.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is not closurized.') - - def testIsExtraRequire_objectOnClass(self): - """Tests that requiring an object on a class is extra.""" - input_lines = [ - 'goog.require(\'package.Foo.Enum\');', - 'var x = package.Foo.Enum.VALUE1;', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'The whole class, not the object, should be required.'); - - def testIsExtraRequire_constantOnClass(self): - """Tests that requiring a constant on a class is extra.""" - input_lines = [ - 'goog.require(\'package.Foo.CONSTANT\');', - 'var x = package.Foo.CONSTANT', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'The class, not the constant, should be required.'); - - def testIsExtraRequire_constantNotOnClass(self): - """Tests that requiring a constant not on a class is OK.""" - input_lines = [ - 'goog.require(\'package.subpackage.CONSTANT\');', - 'var x = package.subpackage.CONSTANT', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Constants can be required except on classes.'); - - def testIsExtraRequire_methodNotOnClass(self): - """Tests that requiring a method not on a class is OK.""" - input_lines = [ - 'goog.require(\'package.subpackage.method\');', - 'var x = package.subpackage.method()', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Methods can be required except on classes.'); - - def testIsExtraRequire_defaults(self): - """Tests that there are no warnings about extra requires for test utils""" - input_lines = ['goog.require(\'goog.testing.jsunit\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['goog']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is for testing.') - - def testGetMissingProvides_provided(self): - """Tests that provided functions don't cause a missing provide.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript( - input_lines, ['package']) - - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_providedIdentifier(self): - """Tests that provided identifiers don't cause a missing provide.""" - input_lines = [ - 'goog.provide(\'package.Foo.methodName\');', - 'package.Foo.methodName = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_providedParentIdentifier(self): - """Tests that provided identifiers on a class don't cause a missing provide - on objects attached to that class.""" - input_lines = [ - 'goog.provide(\'package.foo.ClassName\');', - 'package.foo.ClassName.methodName = function() {};', - 'package.foo.ClassName.ObjectName = 1;', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_unprovided(self): - """Tests that unprovided functions cause a missing provide.""" - input_lines = ['package.Foo = function() {};'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_provides = namespaces_info.GetMissingProvides() - self.assertEquals(1, len(missing_provides)) - missing_provide = missing_provides.popitem() - self.assertEquals('package.Foo', missing_provide[0]) - self.assertEquals(1, missing_provide[1]) - - def testGetMissingProvides_privatefunction(self): - """Tests that unprovided private functions don't cause a missing provide.""" - input_lines = ['package.Foo_ = function() {};'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_required(self): - """Tests that required namespaces don't cause a missing provide.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingRequires_required(self): - """Tests that required namespaces don't cause a missing require.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredIdentifier(self): - """Tests that required namespaces satisfy identifiers on that namespace.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredNamespace(self): - """Tests that required namespaces satisfy the namespace.""" - input_lines = [ - 'goog.require(\'package.soy.fooTemplate\');', - 'render(package.soy.fooTemplate);' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredParentClass(self): - """Tests that requiring a parent class of an object is sufficient to prevent - a missing require on that object.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName();', - 'package.Foo.methodName(package.Foo.ObjectName);' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_unrequired(self): - """Tests that unrequired namespaces cause a missing require.""" - input_lines = ['package.Foo();'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires)) - missing_req = missing_requires.popitem() - self.assertEquals('package.Foo', missing_req[0]) - self.assertEquals(1, missing_req[1]) - - def testGetMissingRequires_provided(self): - """Tests that provided namespaces satisfy identifiers on that namespace.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_created(self): - """Tests that created namespaces do not satisfy usage of an identifier.""" - input_lines = [ - 'package.Foo = function();', - 'package.Foo.methodName();', - 'package.Foo.anotherMethodName1();', - 'package.Foo.anotherMethodName2();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires)) - missing_require = missing_requires.popitem() - self.assertEquals('package.Foo', missing_require[0]) - # Make sure line number of first occurrence is reported - self.assertEquals(2, missing_require[1]) - - def testGetMissingRequires_createdIdentifier(self): - """Tests that created identifiers satisfy usage of the identifier.""" - input_lines = [ - 'package.Foo.methodName = function();', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_implements(self): - """Tests that a parametrized type requires the correct identifier.""" - input_lines = [ - '/** @constructor @implements {package.Bar} */', - 'package.Foo = function();', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertItemsEqual({'package.Bar': 1}, missing_requires) - - def testGetMissingRequires_objectOnClass(self): - """Tests that we should require a class, not the object on the class.""" - input_lines = [ - 'goog.require(\'package.Foo.Enum\');', - 'var x = package.Foo.Enum.VALUE1;', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires), - 'The whole class, not the object, should be required.') - - def testGetMissingRequires_variableWithSameName(self): - """Tests that we should not goog.require variables and parameters. - - b/5362203 Variables in scope are not missing namespaces. - """ - input_lines = [ - 'goog.provide(\'Foo\');', - 'Foo.A = function();', - 'Foo.A.prototype.method = function(ab) {', - ' if (ab) {', - ' var docs;', - ' var lvalue = new Obj();', - ' // Variable in scope hence not goog.require here.', - ' docs.foo.abc = 1;', - ' lvalue.next();', - ' }', - ' // Since js is function scope this should also not goog.require.', - ' docs.foo.func();', - ' // Its not a variable in scope hence goog.require.', - ' dummy.xyz.reset();', - ' return this.method2();', - '};', - 'Foo.A.prototype.method1 = function(docs, abcd, xyz) {', - ' // Parameter hence not goog.require.', - ' docs.nodes.length = 2;', - ' lvalue.abc.reset();', - '};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['Foo', - 'docs', - 'lvalue', - 'dummy']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(2, len(missing_requires)) - self.assertItemsEqual( - {'dummy.xyz': 14, - 'lvalue.abc': 20}, missing_requires) - - def testIsFirstProvide(self): - """Tests operation of the isFirstProvide method.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - self.assertTrue(namespaces_info.IsFirstProvide(token)) - - def testGetWholeIdentifierString(self): - """Tests that created identifiers satisfy usage of the identifier.""" - input_lines = [ - 'package.Foo.', - ' veryLong.', - ' identifier;' - ] - - token = testutil.TokenizeSource(input_lines) - - self.assertEquals('package.Foo.veryLong.identifier', - tokenutil.GetIdentifierForToken(token)) - - self.assertEquals(None, - tokenutil.GetIdentifierForToken(token.next)) - - def testScopified(self): - """Tests that a goog.scope call is noticed.""" - input_lines = [ - 'goog.scope(function() {', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertTrue(namespaces_info._scopified_file) - - def testScope_unusedAlias(self): - """Tests that an unused alias symbol is illegal.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_usedMultilevelAlias(self): - """Tests that an used alias symbol in a deep namespace is ok.""" - input_lines = [ - 'goog.require(\'goog.Events\');', - 'goog.scope(function() {', - 'var Event = goog.Events.DeepNamespace.Event;', - 'Event();', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_usedAlias(self): - """Tests that aliased symbols result in correct requires.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - 'var dom = goog.dom;', - 'Event(dom.classes.get);', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, illegal_alias_stmts) - self.assertEquals({'goog.dom.classes': 4, 'goog.events.Event': 4}, - missing_requires) - - def testModule_alias(self): - """Tests that goog.module style aliases are supported.""" - input_lines = [ - 'goog.module(\'test.module\');', - 'var Unused = goog.require(\'goog.Unused\');', - 'var AliasedClass = goog.require(\'goog.AliasedClass\');', - 'var x = new AliasedClass();', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - namespaceToken = self._GetRequireTokens('goog.AliasedClass') - self.assertFalse(namespaces_info.IsExtraRequire(namespaceToken), - 'AliasedClass should be marked as used') - unusedToken = self._GetRequireTokens('goog.Unused') - self.assertTrue(namespaces_info.IsExtraRequire(unusedToken), - 'Unused should be marked as not used') - - def testModule_aliasInScope(self): - """Tests that goog.module style aliases are supported.""" - input_lines = [ - 'goog.module(\'test.module\');', - 'var AliasedClass = goog.require(\'goog.AliasedClass\');', - 'goog.scope(function() {', - 'var x = new AliasedClass();', - '});', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - namespaceToken = self._GetRequireTokens('goog.AliasedClass') - self.assertFalse(namespaces_info.IsExtraRequire(namespaceToken), - 'AliasedClass should be marked as used') - - def testModule_getAlwaysProvided(self): - """Tests that goog.module.get is recognized as a built-in.""" - input_lines = [ - 'goog.provide(\'test.MyClass\');', - 'goog.require(\'goog.someModule\');', - 'goog.scope(function() {', - 'var someModule = goog.module.get(\'goog.someModule\');', - 'test.MyClass = function() {};', - '});', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertEquals({}, namespaces_info.GetMissingRequires()[0]) - - def testModule_requireForGet(self): - """Tests that goog.module.get needs a goog.require call.""" - input_lines = [ - 'goog.provide(\'test.MyClass\');', - 'function foo() {', - ' var someModule = goog.module.get(\'goog.someModule\');', - ' someModule.doSth();', - '}', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertEquals({'goog.someModule': 3}, - namespaces_info.GetMissingRequires()[0]) - - def testScope_usedTypeAlias(self): - """Tests aliased symbols in type annotations.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - '/** @type {Event} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_partialAlias_typeOnly(self): - """Tests a partial alias only used in type annotations. - - In this example, some goog.events namespace would need to be required - so that evaluating goog.events.bar doesn't throw an error. - """ - input_lines = [ - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Foo} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_partialAlias(self): - """Tests a partial alias in conjunction with a type annotation. - - In this example, the partial alias is already defined by another type, - therefore the doc-only type doesn't need to be required. - """ - input_lines = [ - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({'goog.events.bar.EventType': 4}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_partialAliasRequires(self): - """Tests partial aliases with correct requires.""" - input_lines = [ - 'goog.require(\'goog.events.bar.EventType\');', - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_partialAliasRequiresBoth(self): - """Tests partial aliases with correct requires.""" - input_lines = [ - 'goog.require(\'goog.events.bar.Event\');', - 'goog.require(\'goog.events.bar.EventType\');', - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - event_token = self._GetRequireTokens('goog.events.bar.Event') - self.assertTrue(namespaces_info.IsExtraRequire(event_token)) - - def testScope_partialAliasNoSubtypeRequires(self): - """Tests that partial aliases don't yield subtype requires (regression).""" - input_lines = [ - 'goog.provide(\'goog.events.Foo\');', - 'goog.scope(function() {', - 'goog.events.Foo = {};', - 'var Foo = goog.events.Foo;' - 'Foo.CssName_ = {};' - 'var CssName_ = Foo.CssName_;' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - - def testScope_aliasNamespace(self): - """Tests that an unused alias namespace is not required when available. - - In the example goog.events.Bar is not required, because the namespace - goog.events is already defined because goog.events.Foo is required. - """ - input_lines = [ - 'goog.require(\'goog.events.Foo\');', - 'goog.scope(function() {', - 'var Bar = goog.events.Bar;', - '/** @type {Bar} */;', - 'goog.events.Foo;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_aliasNamespaceIllegal(self): - """Tests that an unused alias namespace is not required when available.""" - input_lines = [ - 'goog.scope(function() {', - 'var Bar = goog.events.Bar;', - '/** @type {Bar} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_provides(self): - """Tests that aliased symbols result in correct provides.""" - input_lines = [ - 'goog.scope(function() {', - 'goog.bar = {};', - 'var bar = goog.bar;', - 'bar.Foo = {};', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_provides = namespaces_info.GetMissingProvides() - self.assertEquals({'goog.bar.Foo': 4}, missing_provides) - _, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, illegal_alias_stmts) - - def testSetTestOnlyNamespaces(self): - """Tests that a namespace in setTestOnly makes it a valid provide.""" - namespaces_info = self._GetNamespacesInfoForScript([ - 'goog.setTestOnly(\'goog.foo.barTest\');' - ], ['goog']) - - token = self._GetProvideTokens('goog.foo.barTest') - self.assertFalse(namespaces_info.IsExtraProvide(token)) - - token = self._GetProvideTokens('goog.foo.bazTest') - self.assertTrue(namespaces_info.IsExtraProvide(token)) - - def testSetTestOnlyComment(self): - """Ensure a comment in setTestOnly does not cause a created namespace.""" - namespaces_info = self._GetNamespacesInfoForScript([ - 'goog.setTestOnly(\'this is a comment\');' - ], ['goog']) - - self.assertEquals( - [], namespaces_info._created_namespaces, - 'A comment in setTestOnly should not modify created namespaces.') - - def _GetNamespacesInfoForScript(self, script, closurized_namespaces=None): - _, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - script, closurized_namespaces) - - return namespaces_info - - def _GetStartTokenAndNamespacesInfoForScript( - self, script, closurized_namespaces): - - token = testutil.TokenizeSource(script) - return token, self._GetInitializedNamespacesInfo( - token, closurized_namespaces, []) - - def _GetInitializedNamespacesInfo(self, token, closurized_namespaces, - ignored_extra_namespaces): - """Returns a namespaces info initialized with the given token stream.""" - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=closurized_namespaces, - ignored_extra_namespaces=ignored_extra_namespaces) - state_tracker = javascriptstatetracker.JavaScriptStateTracker() - - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - ecma_pass.Process(token) - - state_tracker.DocFlagPass(token, error_handler=None) - - alias_pass = aliaspass.AliasPass(closurized_namespaces) - alias_pass.Process(token) - - while token: - state_tracker.HandleToken(token, state_tracker.GetLastNonSpaceToken()) - namespaces_info.ProcessToken(token, state_tracker) - state_tracker.HandleAfterToken(token) - token = token.next - - return namespaces_info - - def _GetProvideTokens(self, namespace): - """Returns a list of tokens for a goog.require of the given namespace.""" - line_text = 'goog.require(\'' + namespace + '\');\n' - return testutil.TokenizeSource([line_text]) - - def _GetRequireTokens(self, namespace): - """Returns a list of tokens for a goog.require of the given namespace.""" - line_text = 'goog.require(\'' + namespace + '\');\n' - return testutil.TokenizeSource([line_text]) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/common/__init__.py b/tools/closure_linter/build/lib/closure_linter/common/__init__.py deleted file mode 100644 index 57930436ce4323..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Package indicator for gjslint.common.""" diff --git a/tools/closure_linter/build/lib/closure_linter/common/error.py b/tools/closure_linter/build/lib/closure_linter/common/error.py deleted file mode 100644 index 4209c235b85425..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/error.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Error object commonly used in linters.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class Error(object): - """Object representing a style error.""" - - def __init__(self, code, message, token=None, position=None, fix_data=None): - """Initialize the error object. - - Args: - code: The numeric error code. - message: The error message string. - token: The tokens.Token where the error occurred. - position: The position of the error within the token. - fix_data: Data to be used in autofixing. Codes with fix_data are: - GOOG_REQUIRES_NOT_ALPHABETIZED - List of string value tokens that are - class names in goog.requires calls. - """ - self.code = code - self.message = message - self.token = token - self.position = position - if token: - self.start_index = token.start_index - else: - self.start_index = 0 - self.fix_data = fix_data - if self.position: - self.start_index += self.position.start - - def Compare(a, b): - """Compare two error objects, by source code order. - - Args: - a: First error object. - b: Second error object. - - Returns: - A Negative/0/Positive number when a is before/the same as/after b. - """ - line_diff = a.token.line_number - b.token.line_number - if line_diff: - return line_diff - - return a.start_index - b.start_index - Compare = staticmethod(Compare) diff --git a/tools/closure_linter/build/lib/closure_linter/common/erroraccumulator.py b/tools/closure_linter/build/lib/closure_linter/common/erroraccumulator.py deleted file mode 100644 index 55844ba60356fa..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/erroraccumulator.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Linter error handler class that accumulates an array of errors.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -from closure_linter.common import errorhandler - - -class ErrorAccumulator(errorhandler.ErrorHandler): - """Error handler object that accumulates errors in a list.""" - - def __init__(self): - self._errors = [] - - def HandleError(self, error): - """Append the error to the list. - - Args: - error: The error object - """ - self._errors.append(error) - - def GetErrors(self): - """Returns the accumulated errors. - - Returns: - A sequence of errors. - """ - return self._errors diff --git a/tools/closure_linter/build/lib/closure_linter/common/errorhandler.py b/tools/closure_linter/build/lib/closure_linter/common/errorhandler.py deleted file mode 100644 index 764d54d84cb3c1..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/errorhandler.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Interface for a linter error handler. - -Error handlers aggregate a set of errors from multiple files and can optionally -perform some action based on the reported errors, for example, logging the error -or automatically fixing it. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class ErrorHandler(object): - """Error handler interface.""" - - def __init__(self): - if self.__class__ == ErrorHandler: - raise NotImplementedError('class ErrorHandler is abstract') - - def HandleFile(self, filename, first_token): - """Notifies this ErrorHandler that subsequent errors are in filename. - - Args: - filename: The file being linted. - first_token: The first token of the file. - """ - - def HandleError(self, error): - """Append the error to the list. - - Args: - error: The error object - """ - - def FinishFile(self): - """Finishes handling the current file. - - Should be called after all errors in a file have been handled. - """ - - def GetErrors(self): - """Returns the accumulated errors. - - Returns: - A sequence of errors. - """ diff --git a/tools/closure_linter/build/lib/closure_linter/common/erroroutput.py b/tools/closure_linter/build/lib/closure_linter/common/erroroutput.py deleted file mode 100644 index 149738b5d4f173..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/erroroutput.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Utility functions to format errors.""" - - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'nnaze@google.com (Nathan Naze)') - - -def GetUnixErrorOutput(filename, error, new_error=False): - """Get a output line for an error in UNIX format.""" - - line = '' - - if error.token: - line = '%d' % error.token.line_number - - error_code = '%04d' % error.code - if new_error: - error_code = 'New Error ' + error_code - return '%s:%s:(%s) %s' % (filename, line, error_code, error.message) - - -def GetErrorOutput(error, new_error=False): - """Get a output line for an error in regular format.""" - - line = '' - if error.token: - line = 'Line %d, ' % error.token.line_number - - code = 'E:%04d' % error.code - - error_message = error.message - if new_error: - error_message = 'New Error ' + error_message - - return '%s%s: %s' % (line, code, error.message) diff --git a/tools/closure_linter/build/lib/closure_linter/common/filetestcase.py b/tools/closure_linter/build/lib/closure_linter/common/filetestcase.py deleted file mode 100644 index 7cd83cd1dcf58c..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/filetestcase.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Test case that runs a checker on a file, matching errors against annotations. - -Runs the given checker on the given file, accumulating all errors. The list -of errors is then matched against those annotated in the file. Based heavily -on devtools/javascript/gpylint/full_test.py. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import re - -import gflags as flags -import unittest as googletest -from closure_linter.common import erroraccumulator - - -class AnnotatedFileTestCase(googletest.TestCase): - """Test case to run a linter against a single file.""" - - # Matches an all caps letters + underscores error identifer - _MESSAGE = {'msg': '[A-Z][A-Z_]+'} - # Matches a //, followed by an optional line number with a +/-, followed by a - # list of message IDs. Used to extract expected messages from testdata files. - # TODO(robbyw): Generalize to use different commenting patterns. - _EXPECTED_RE = re.compile(r'\s*//\s*(?:(?P[+-]?[0-9]+):)?' - r'\s*(?P%(msg)s(?:,\s*%(msg)s)*)' % _MESSAGE) - - def __init__(self, filename, lint_callable, converter): - """Create a single file lint test case. - - Args: - filename: Filename to test. - lint_callable: Callable that lints a file. This is usually runner.Run(). - converter: Function taking an error string and returning an error code. - """ - - googletest.TestCase.__init__(self, 'runTest') - self._filename = filename - self._messages = [] - self._lint_callable = lint_callable - self._converter = converter - - def setUp(self): - flags.FLAGS.dot_on_next_line = True - - def tearDown(self): - flags.FLAGS.dot_on_next_line = False - - def shortDescription(self): - """Provides a description for the test.""" - return 'Run linter on %s' % self._filename - - def runTest(self): - """Runs the test.""" - try: - filename = self._filename - stream = open(filename) - except IOError as ex: - raise IOError('Could not find testdata resource for %s: %s' % - (self._filename, ex)) - - expected = self._GetExpectedMessages(stream) - got = self._ProcessFileAndGetMessages(filename) - self.assertEqual(expected, got) - - def _GetExpectedMessages(self, stream): - """Parse a file and get a sorted list of expected messages.""" - messages = [] - for i, line in enumerate(stream): - match = self._EXPECTED_RE.search(line) - if match: - line = match.group('line') - msg_ids = match.group('msgs') - if line is None: - line = i + 1 - elif line.startswith('+') or line.startswith('-'): - line = i + 1 + int(line) - else: - line = int(line) - for msg_id in msg_ids.split(','): - # Ignore a spurious message from the license preamble. - if msg_id != 'WITHOUT': - messages.append((line, self._converter(msg_id.strip()))) - stream.seek(0) - messages.sort() - return messages - - def _ProcessFileAndGetMessages(self, filename): - """Trap gjslint's output parse it to get messages added.""" - error_accumulator = erroraccumulator.ErrorAccumulator() - self._lint_callable(filename, error_accumulator) - - errors = error_accumulator.GetErrors() - - # Convert to expected tuple format. - - error_msgs = [(error.token.line_number, error.code) for error in errors] - error_msgs.sort() - return error_msgs diff --git a/tools/closure_linter/build/lib/closure_linter/common/htmlutil.py b/tools/closure_linter/build/lib/closure_linter/common/htmlutil.py deleted file mode 100644 index 26d44c5908353d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/htmlutil.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Utilities for dealing with HTML.""" - -__author__ = ('robbyw@google.com (Robert Walker)') - -import cStringIO -import formatter -import htmllib -import HTMLParser -import re - - -class ScriptExtractor(htmllib.HTMLParser): - """Subclass of HTMLParser that extracts script contents from an HTML file. - - Also inserts appropriate blank lines so that line numbers in the extracted - code match the line numbers in the original HTML. - """ - - def __init__(self): - """Initialize a ScriptExtractor.""" - htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) - self._in_script = False - self._text = '' - - def start_script(self, attrs): - """Internal handler for the start of a script tag. - - Args: - attrs: The attributes of the script tag, as a list of tuples. - """ - for attribute in attrs: - if attribute[0].lower() == 'src': - # Skip script tags with a src specified. - return - self._in_script = True - - def end_script(self): - """Internal handler for the end of a script tag.""" - self._in_script = False - - def handle_data(self, data): - """Internal handler for character data. - - Args: - data: The character data from the HTML file. - """ - if self._in_script: - # If the last line contains whitespace only, i.e. is just there to - # properly align a tag, strip the whitespace. - if data.rstrip(' \t') != data.rstrip(' \t\n\r\f'): - data = data.rstrip(' \t') - self._text += data - else: - self._AppendNewlines(data) - - def handle_comment(self, data): - """Internal handler for HTML comments. - - Args: - data: The text of the comment. - """ - self._AppendNewlines(data) - - def _AppendNewlines(self, data): - """Count the number of newlines in the given string and append them. - - This ensures line numbers are correct for reported errors. - - Args: - data: The data to count newlines in. - """ - # We append 'x' to both sides of the string to ensure that splitlines - # gives us an accurate count. - for i in xrange(len(('x' + data + 'x').splitlines()) - 1): - self._text += '\n' - - def GetScriptLines(self): - """Return the extracted script lines. - - Returns: - The extracted script lines as a list of strings. - """ - return self._text.splitlines() - - -def GetScriptLines(f): - """Extract script tag contents from the given HTML file. - - Args: - f: The HTML file. - - Returns: - Lines in the HTML file that are from script tags. - """ - extractor = ScriptExtractor() - - # The HTML parser chokes on text like Array., so we patch - # that bug by replacing the < with < - escaping all text inside script - # tags would be better but it's a bit of a catch 22. - contents = f.read() - contents = re.sub(r'<([^\s\w/])', - lambda x: '<%s' % x.group(1), - contents) - - extractor.feed(contents) - extractor.close() - return extractor.GetScriptLines() - - -def StripTags(str): - """Returns the string with HTML tags stripped. - - Args: - str: An html string. - - Returns: - The html string with all tags stripped. If there was a parse error, returns - the text successfully parsed so far. - """ - # Brute force approach to stripping as much HTML as possible. If there is a - # parsing error, don't strip text before parse error position, and continue - # trying from there. - final_text = '' - finished = False - while not finished: - try: - strip = _HtmlStripper() - strip.feed(str) - strip.close() - str = strip.get_output() - final_text += str - finished = True - except HTMLParser.HTMLParseError, e: - final_text += str[:e.offset] - str = str[e.offset + 1:] - - return final_text - - -class _HtmlStripper(HTMLParser.HTMLParser): - """Simple class to strip tags from HTML. - - Does so by doing nothing when encountering tags, and appending character data - to a buffer when that is encountered. - """ - def __init__(self): - self.reset() - self.__output = cStringIO.StringIO() - - def handle_data(self, d): - self.__output.write(d) - - def get_output(self): - return self.__output.getvalue() diff --git a/tools/closure_linter/build/lib/closure_linter/common/lintrunner.py b/tools/closure_linter/build/lib/closure_linter/common/lintrunner.py deleted file mode 100644 index 07842c7bfeb36f..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/lintrunner.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Interface for a lint running wrapper.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class LintRunner(object): - """Interface for a lint running wrapper.""" - - def __init__(self): - if self.__class__ == LintRunner: - raise NotImplementedError('class LintRunner is abstract') - - def Run(self, filenames, error_handler): - """Run a linter on the given filenames. - - Args: - filenames: The filenames to check - error_handler: An ErrorHandler object - - Returns: - The error handler, which may have been used to collect error info. - """ diff --git a/tools/closure_linter/build/lib/closure_linter/common/matcher.py b/tools/closure_linter/build/lib/closure_linter/common/matcher.py deleted file mode 100644 index 9b4402c6718bc7..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/matcher.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Regular expression based JavaScript matcher classes.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -from closure_linter.common import position -from closure_linter.common import tokens - -# Shorthand -Token = tokens.Token -Position = position.Position - - -class Matcher(object): - """A token matcher. - - Specifies a pattern to match, the type of token it represents, what mode the - token changes to, and what mode the token applies to. - - Modes allow more advanced grammars to be incorporated, and are also necessary - to tokenize line by line. We can have different patterns apply to different - modes - i.e. looking for documentation while in comment mode. - - Attributes: - regex: The regular expression representing this matcher. - type: The type of token indicated by a successful match. - result_mode: The mode to move to after a successful match. - """ - - def __init__(self, regex, token_type, result_mode=None, line_start=False): - """Create a new matcher template. - - Args: - regex: The regular expression to match. - token_type: The type of token a successful match indicates. - result_mode: What mode to change to after a successful match. Defaults to - None, which means to not change the current mode. - line_start: Whether this matcher should only match string at the start - of a line. - """ - self.regex = regex - self.type = token_type - self.result_mode = result_mode - self.line_start = line_start diff --git a/tools/closure_linter/build/lib/closure_linter/common/position.py b/tools/closure_linter/build/lib/closure_linter/common/position.py deleted file mode 100644 index cebf17ef36277e..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/position.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Classes to represent positions within strings.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class Position(object): - """Object representing a segment of a string. - - Attributes: - start: The index in to the string where the segment starts. - length: The length of the string segment. - """ - - def __init__(self, start, length): - """Initialize the position object. - - Args: - start: The start index. - length: The number of characters to include. - """ - self.start = start - self.length = length - - def Get(self, string): - """Returns this range of the given string. - - Args: - string: The string to slice. - - Returns: - The string within the range specified by this object. - """ - return string[self.start:self.start + self.length] - - def Set(self, target, source): - """Sets this range within the target string to the source string. - - Args: - target: The target string. - source: The source string. - - Returns: - The resulting string - """ - return target[:self.start] + source + target[self.start + self.length:] - - def AtEnd(string): - """Create a Position representing the end of the given string. - - Args: - string: The string to represent the end of. - - Returns: - The created Position object. - """ - return Position(len(string), 0) - AtEnd = staticmethod(AtEnd) - - def IsAtEnd(self, string): - """Returns whether this position is at the end of the given string. - - Args: - string: The string to test for the end of. - - Returns: - Whether this position is at the end of the given string. - """ - return self.start == len(string) and self.length == 0 - - def AtBeginning(): - """Create a Position representing the beginning of any string. - - Returns: - The created Position object. - """ - return Position(0, 0) - AtBeginning = staticmethod(AtBeginning) - - def IsAtBeginning(self): - """Returns whether this position is at the beginning of any string. - - Returns: - Whether this position is at the beginning of any string. - """ - return self.start == 0 and self.length == 0 - - def All(string): - """Create a Position representing the entire string. - - Args: - string: The string to represent the entirety of. - - Returns: - The created Position object. - """ - return Position(0, len(string)) - All = staticmethod(All) - - def Index(index): - """Returns a Position object for the specified index. - - Args: - index: The index to select, inclusively. - - Returns: - The created Position object. - """ - return Position(index, 1) - Index = staticmethod(Index) diff --git a/tools/closure_linter/build/lib/closure_linter/common/simplefileflags.py b/tools/closure_linter/build/lib/closure_linter/common/simplefileflags.py deleted file mode 100644 index 3402bef3a1d36e..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/simplefileflags.py +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Determines the list of files to be checked from command line arguments.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import glob -import os -import re - -import gflags as flags - - -FLAGS = flags.FLAGS - -flags.DEFINE_multistring( - 'recurse', - None, - 'Recurse in to the subdirectories of the given path', - short_name='r') -flags.DEFINE_list( - 'exclude_directories', - ('_demos'), - 'Exclude the specified directories (only applicable along with -r or ' - '--presubmit)', - short_name='e') -flags.DEFINE_list( - 'exclude_files', - ('deps.js'), - 'Exclude the specified files', - short_name='x') - - -def MatchesSuffixes(filename, suffixes): - """Returns whether the given filename matches one of the given suffixes. - - Args: - filename: Filename to check. - suffixes: Sequence of suffixes to check. - - Returns: - Whether the given filename matches one of the given suffixes. - """ - suffix = filename[filename.rfind('.'):] - return suffix in suffixes - - -def _GetUserSpecifiedFiles(argv, suffixes): - """Returns files to be linted, specified directly on the command line. - - Can handle the '*' wildcard in filenames, but no other wildcards. - - Args: - argv: Sequence of command line arguments. The second and following arguments - are assumed to be files that should be linted. - suffixes: Expected suffixes for the file type being checked. - - Returns: - A sequence of files to be linted. - """ - files = argv[1:] or [] - all_files = [] - lint_files = [] - - # Perform any necessary globs. - for f in files: - if f.find('*') != -1: - for result in glob.glob(f): - all_files.append(result) - else: - all_files.append(f) - - for f in all_files: - if MatchesSuffixes(f, suffixes): - lint_files.append(f) - return lint_files - - -def _GetRecursiveFiles(suffixes): - """Returns files to be checked specified by the --recurse flag. - - Args: - suffixes: Expected suffixes for the file type being checked. - - Returns: - A list of files to be checked. - """ - lint_files = [] - # Perform any request recursion - if FLAGS.recurse: - for start in FLAGS.recurse: - for root, subdirs, files in os.walk(start): - for f in files: - if MatchesSuffixes(f, suffixes): - lint_files.append(os.path.join(root, f)) - return lint_files - - -def GetAllSpecifiedFiles(argv, suffixes): - """Returns all files specified by the user on the commandline. - - Args: - argv: Sequence of command line arguments. The second and following arguments - are assumed to be files that should be linted. - suffixes: Expected suffixes for the file type - - Returns: - A list of all files specified directly or indirectly (via flags) on the - command line by the user. - """ - files = _GetUserSpecifiedFiles(argv, suffixes) - - if FLAGS.recurse: - files += _GetRecursiveFiles(suffixes) - - return FilterFiles(files) - - -def FilterFiles(files): - """Filters the list of files to be linted be removing any excluded files. - - Filters out files excluded using --exclude_files and --exclude_directories. - - Args: - files: Sequence of files that needs filtering. - - Returns: - Filtered list of files to be linted. - """ - num_files = len(files) - - ignore_dirs_regexs = [] - for ignore in FLAGS.exclude_directories: - ignore_dirs_regexs.append(re.compile(r'(^|[\\/])%s[\\/]' % ignore)) - - result_files = [] - for f in files: - add_file = True - for exclude in FLAGS.exclude_files: - if f.endswith('/' + exclude) or f == exclude: - add_file = False - break - for ignore in ignore_dirs_regexs: - if ignore.search(f): - # Break out of ignore loop so we don't add to - # filtered files. - add_file = False - break - if add_file: - # Convert everything to absolute paths so we can easily remove duplicates - # using a set. - result_files.append(os.path.abspath(f)) - - skipped = num_files - len(result_files) - if skipped: - print 'Skipping %d file(s).' % skipped - - return set(result_files) - - -def GetFileList(argv, file_type, suffixes): - """Parse the flags and return the list of files to check. - - Args: - argv: Sequence of command line arguments. - suffixes: Sequence of acceptable suffixes for the file type. - - Returns: - The list of files to check. - """ - return sorted(GetAllSpecifiedFiles(argv, suffixes)) - - -def IsEmptyArgumentList(argv): - return not (len(argv[1:]) or FLAGS.recurse) diff --git a/tools/closure_linter/build/lib/closure_linter/common/tokenizer.py b/tools/closure_linter/build/lib/closure_linter/common/tokenizer.py deleted file mode 100644 index 9420ea3267a5a2..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/tokenizer.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Regular expression based lexer.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -from closure_linter.common import tokens - -# Shorthand -Type = tokens.TokenType - - -class Tokenizer(object): - """General purpose tokenizer. - - Attributes: - mode: The latest mode of the tokenizer. This allows patterns to distinguish - if they are mid-comment, mid-parameter list, etc. - matchers: Dictionary of modes to sequences of matchers that define the - patterns to check at any given time. - default_types: Dictionary of modes to types, defining what type to give - non-matched text when in the given mode. Defaults to Type.NORMAL. - """ - - def __init__(self, starting_mode, matchers, default_types): - """Initialize the tokenizer. - - Args: - starting_mode: Mode to start in. - matchers: Dictionary of modes to sequences of matchers that defines the - patterns to check at any given time. - default_types: Dictionary of modes to types, defining what type to give - non-matched text when in the given mode. Defaults to Type.NORMAL. - """ - self.__starting_mode = starting_mode - self.matchers = matchers - self.default_types = default_types - - def TokenizeFile(self, file): - """Tokenizes the given file. - - Args: - file: An iterable that yields one line of the file at a time. - - Returns: - The first token in the file - """ - # The current mode. - self.mode = self.__starting_mode - # The first token in the stream. - self.__first_token = None - # The last token added to the token stream. - self.__last_token = None - # The current line number. - self.__line_number = 0 - - for line in file: - self.__line_number += 1 - self.__TokenizeLine(line) - - return self.__first_token - - def _CreateToken(self, string, token_type, line, line_number, values=None): - """Creates a new Token object (or subclass). - - Args: - string: The string of input the token represents. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - - Returns: - The newly created Token object. - """ - return tokens.Token(string, token_type, line, line_number, values, - line_number) - - def __TokenizeLine(self, line): - """Tokenizes the given line. - - Args: - line: The contents of the line. - """ - string = line.rstrip('\n\r\f') - line_number = self.__line_number - self.__start_index = 0 - - if not string: - self.__AddToken(self._CreateToken('', Type.BLANK_LINE, line, line_number)) - return - - normal_token = '' - index = 0 - while index < len(string): - for matcher in self.matchers[self.mode]: - if matcher.line_start and index > 0: - continue - - match = matcher.regex.match(string, index) - - if match: - if normal_token: - self.__AddToken( - self.__CreateNormalToken(self.mode, normal_token, line, - line_number)) - normal_token = '' - - # Add the match. - self.__AddToken(self._CreateToken(match.group(), matcher.type, line, - line_number, match.groupdict())) - - # Change the mode to the correct one for after this match. - self.mode = matcher.result_mode or self.mode - - # Shorten the string to be matched. - index = match.end() - - break - - else: - # If the for loop finishes naturally (i.e. no matches) we just add the - # first character to the string of consecutive non match characters. - # These will constitute a NORMAL token. - if string: - normal_token += string[index:index + 1] - index += 1 - - if normal_token: - self.__AddToken( - self.__CreateNormalToken(self.mode, normal_token, line, line_number)) - - def __CreateNormalToken(self, mode, string, line, line_number): - """Creates a normal token. - - Args: - mode: The current mode. - string: The string to tokenize. - line: The line of text. - line_number: The line number within the file. - - Returns: - A Token object, of the default type for the current mode. - """ - type = Type.NORMAL - if mode in self.default_types: - type = self.default_types[mode] - return self._CreateToken(string, type, line, line_number) - - def __AddToken(self, token): - """Add the given token to the token stream. - - Args: - token: The token to add. - """ - # Store the first token, or point the previous token to this one. - if not self.__first_token: - self.__first_token = token - else: - self.__last_token.next = token - - # Establish the doubly linked list - token.previous = self.__last_token - self.__last_token = token - - # Compute the character indices - token.start_index = self.__start_index - self.__start_index += token.length diff --git a/tools/closure_linter/build/lib/closure_linter/common/tokens.py b/tools/closure_linter/build/lib/closure_linter/common/tokens.py deleted file mode 100644 index 4703998752b036..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/tokens.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Classes to represent tokens and positions within them.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class TokenType(object): - """Token types common to all languages.""" - NORMAL = 'normal' - WHITESPACE = 'whitespace' - BLANK_LINE = 'blank line' - - -class Token(object): - """Token class for intelligent text splitting. - - The token class represents a string of characters and an identifying type. - - Attributes: - type: The type of token. - string: The characters the token comprises. - length: The length of the token. - line: The text of the line the token is found in. - line_number: The number of the line the token is found in. - values: Dictionary of values returned from the tokens regex match. - previous: The token before this one. - next: The token after this one. - start_index: The character index in the line where this token starts. - attached_object: Object containing more information about this token. - metadata: Object containing metadata about this token. Must be added by - a separate metadata pass. - """ - - def __init__(self, string, token_type, line, line_number, values=None, - orig_line_number=None): - """Creates a new Token object. - - Args: - string: The string of input the token contains. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - orig_line_number: The line number of the original file this token comes - from. This should be only set during the tokenization process. For newly - created error fix tokens after that, it should be None. - """ - self.type = token_type - self.string = string - self.length = len(string) - self.line = line - self.line_number = line_number - self.orig_line_number = orig_line_number - self.values = values - self.is_deleted = False - - # These parts can only be computed when the file is fully tokenized - self.previous = None - self.next = None - self.start_index = None - - # This part is set in statetracker.py - # TODO(robbyw): Wrap this in to metadata - self.attached_object = None - - # This part is set in *metadatapass.py - self.metadata = None - - def IsFirstInLine(self): - """Tests if this token is the first token in its line. - - Returns: - Whether the token is the first token in its line. - """ - return not self.previous or self.previous.line_number != self.line_number - - def IsLastInLine(self): - """Tests if this token is the last token in its line. - - Returns: - Whether the token is the last token in its line. - """ - return not self.next or self.next.line_number != self.line_number - - def IsType(self, token_type): - """Tests if this token is of the given type. - - Args: - token_type: The type to test for. - - Returns: - True if the type of this token matches the type passed in. - """ - return self.type == token_type - - def IsAnyType(self, *token_types): - """Tests if this token is any of the given types. - - Args: - token_types: The types to check. Also accepts a single array. - - Returns: - True if the type of this token is any of the types passed in. - """ - if not isinstance(token_types[0], basestring): - return self.type in token_types[0] - else: - return self.type in token_types - - def __repr__(self): - return '' % (self.type, self.string, - self.values, self.line_number, - self.metadata) - - def __iter__(self): - """Returns a token iterator.""" - node = self - while node: - yield node - node = node.next - - def __reversed__(self): - """Returns a reverse-direction token iterator.""" - node = self - while node: - yield node - node = node.previous diff --git a/tools/closure_linter/build/lib/closure_linter/common/tokens_test.py b/tools/closure_linter/build/lib/closure_linter/common/tokens_test.py deleted file mode 100644 index 01ec89d01bc357..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/common/tokens_test.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -__author__ = 'nnaze@google.com (Nathan Naze)' - -import unittest as googletest -from closure_linter.common import tokens - - -def _CreateDummyToken(): - return tokens.Token('foo', None, 1, 1) - - -def _CreateDummyTokens(count): - dummy_tokens = [] - for _ in xrange(count): - dummy_tokens.append(_CreateDummyToken()) - return dummy_tokens - - -def _SetTokensAsNeighbors(neighbor_tokens): - for i in xrange(len(neighbor_tokens)): - prev_index = i - 1 - next_index = i + 1 - - if prev_index >= 0: - neighbor_tokens[i].previous = neighbor_tokens[prev_index] - - if next_index < len(neighbor_tokens): - neighbor_tokens[i].next = neighbor_tokens[next_index] - - -class TokensTest(googletest.TestCase): - - def testIsFirstInLine(self): - - # First token in file (has no previous). - self.assertTrue(_CreateDummyToken().IsFirstInLine()) - - a, b = _CreateDummyTokens(2) - _SetTokensAsNeighbors([a, b]) - - # Tokens on same line - a.line_number = 30 - b.line_number = 30 - - self.assertFalse(b.IsFirstInLine()) - - # Tokens on different lines - b.line_number = 31 - self.assertTrue(b.IsFirstInLine()) - - def testIsLastInLine(self): - # Last token in file (has no next). - self.assertTrue(_CreateDummyToken().IsLastInLine()) - - a, b = _CreateDummyTokens(2) - _SetTokensAsNeighbors([a, b]) - - # Tokens on same line - a.line_number = 30 - b.line_number = 30 - self.assertFalse(a.IsLastInLine()) - - b.line_number = 31 - self.assertTrue(a.IsLastInLine()) - - def testIsType(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertTrue(a.IsType('fakeType1')) - self.assertFalse(a.IsType('fakeType2')) - - def testIsAnyType(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertTrue(a.IsAnyType(['fakeType1', 'fakeType2'])) - self.assertFalse(a.IsAnyType(['fakeType3', 'fakeType4'])) - - def testRepr(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertEquals('', str(a)) - - def testIter(self): - dummy_tokens = _CreateDummyTokens(5) - _SetTokensAsNeighbors(dummy_tokens) - a, b, c, d, e = dummy_tokens - - i = iter(a) - self.assertListEqual([a, b, c, d, e], list(i)) - - def testReverseIter(self): - dummy_tokens = _CreateDummyTokens(5) - _SetTokensAsNeighbors(dummy_tokens) - a, b, c, d, e = dummy_tokens - - ri = reversed(e) - self.assertListEqual([e, d, c, b, a], list(ri)) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/ecmalintrules.py b/tools/closure_linter/build/lib/closure_linter/ecmalintrules.py deleted file mode 100644 index c07dffc86eeae3..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/ecmalintrules.py +++ /dev/null @@ -1,844 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Core methods for checking EcmaScript files for common style guide violations. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'jacobr@google.com (Jacob Richman)') - -import re - -import gflags as flags - -from closure_linter import checkerbase -from closure_linter import ecmametadatapass -from closure_linter import error_check -from closure_linter import errorrules -from closure_linter import errors -from closure_linter import indentation -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - - -FLAGS = flags.FLAGS -flags.DEFINE_list('custom_jsdoc_tags', '', 'Extra jsdoc tags to allow') -# TODO(user): When flipping this to True, remove logic from unit tests -# that overrides this flag. -flags.DEFINE_boolean('dot_on_next_line', False, 'Require dots to be' - 'placed on the next line for wrapped expressions') - -# TODO(robbyw): Check for extra parens on return statements -# TODO(robbyw): Check for 0px in strings -# TODO(robbyw): Ensure inline jsDoc is in {} -# TODO(robbyw): Check for valid JS types in parameter docs - -# Shorthand -Context = ecmametadatapass.EcmaContext -Error = error.Error -Modes = javascripttokenizer.JavaScriptModes -Position = position.Position -Rule = error_check.Rule -Type = javascripttokens.JavaScriptTokenType - - -class EcmaScriptLintRules(checkerbase.LintRulesBase): - """EmcaScript lint style checking rules. - - Can be used to find common style errors in JavaScript, ActionScript and other - Ecma like scripting languages. Style checkers for Ecma scripting languages - should inherit from this style checker. - Please do not add any state to EcmaScriptLintRules or to any subclasses. - - All state should be added to the StateTracker subclass used for a particular - language. - """ - - # It will be initialized in constructor so the flags are initialized. - max_line_length = -1 - - # Static constants. - MISSING_PARAMETER_SPACE = re.compile(r',\S') - - EXTRA_SPACE = re.compile(r'(\(\s|\s\))') - - ENDS_WITH_SPACE = re.compile(r'\s$') - - ILLEGAL_TAB = re.compile(r'\t') - - # Regex used to split up complex types to check for invalid use of ? and |. - TYPE_SPLIT = re.compile(r'[,<>()]') - - # Regex for form of author lines after the @author tag. - AUTHOR_SPEC = re.compile(r'(\s*)[^\s]+@[^(\s]+(\s*)\(.+\)') - - # Acceptable tokens to remove for line too long testing. - LONG_LINE_IGNORE = frozenset( - ['*', '//', '@see'] + - ['@%s' % tag for tag in statetracker.DocFlag.HAS_TYPE]) - - JSDOC_FLAGS_DESCRIPTION_NOT_REQUIRED = frozenset([ - '@fileoverview', '@param', '@return', '@returns']) - - def __init__(self): - """Initialize this lint rule object.""" - checkerbase.LintRulesBase.__init__(self) - if EcmaScriptLintRules.max_line_length == -1: - EcmaScriptLintRules.max_line_length = errorrules.GetMaxLineLength() - - def Initialize(self, checker, limited_doc_checks, is_html): - """Initialize this lint rule object before parsing a new file.""" - checkerbase.LintRulesBase.Initialize(self, checker, limited_doc_checks, - is_html) - self._indentation = indentation.IndentationRules() - - def HandleMissingParameterDoc(self, token, param_name): - """Handle errors associated with a parameter missing a @param tag.""" - raise TypeError('Abstract method HandleMissingParameterDoc not implemented') - - def _CheckLineLength(self, last_token, state): - """Checks whether the line is too long. - - Args: - last_token: The last token in the line. - state: parser_state object that indicates the current state in the page - """ - # Start from the last token so that we have the flag object attached to - # and DOC_FLAG tokens. - line_number = last_token.line_number - token = last_token - - # Build a representation of the string where spaces indicate potential - # line-break locations. - line = [] - while token and token.line_number == line_number: - if state.IsTypeToken(token): - line.insert(0, 'x' * len(token.string)) - elif token.type in (Type.IDENTIFIER, Type.OPERATOR): - # Dots are acceptable places to wrap (may be tokenized as identifiers). - line.insert(0, token.string.replace('.', ' ')) - else: - line.insert(0, token.string) - token = token.previous - - line = ''.join(line) - line = line.rstrip('\n\r\f') - try: - length = len(unicode(line, 'utf-8')) - except (LookupError, UnicodeDecodeError): - # Unknown encoding. The line length may be wrong, as was originally the - # case for utf-8 (see bug 1735846). For now just accept the default - # length, but as we find problems we can either add test for other - # possible encodings or return without an error to protect against - # false positives at the cost of more false negatives. - length = len(line) - - if length > EcmaScriptLintRules.max_line_length: - - # If the line matches one of the exceptions, then it's ok. - for long_line_regexp in self.GetLongLineExceptions(): - if long_line_regexp.match(last_token.line): - return - - # If the line consists of only one "word", or multiple words but all - # except one are ignoreable, then it's ok. - parts = set(line.split()) - - # We allow two "words" (type and name) when the line contains @param - max_parts = 1 - if '@param' in parts: - max_parts = 2 - - # Custom tags like @requires may have url like descriptions, so ignore - # the tag, similar to how we handle @see. - custom_tags = set(['@%s' % f for f in FLAGS.custom_jsdoc_tags]) - if (len(parts.difference(self.LONG_LINE_IGNORE | custom_tags)) - > max_parts): - self._HandleError( - errors.LINE_TOO_LONG, - 'Line too long (%d characters).' % len(line), last_token) - - def _CheckJsDocType(self, token, js_type): - """Checks the given type for style errors. - - Args: - token: The DOC_FLAG token for the flag whose type to check. - js_type: The flag's typeannotation.TypeAnnotation instance. - """ - if not js_type: return - - if js_type.type_group and len(js_type.sub_types) == 2: - identifiers = [t.identifier for t in js_type.sub_types] - if 'null' in identifiers: - # Don't warn if the identifier is a template type (e.g. {TYPE|null}. - if not identifiers[0].isupper() and not identifiers[1].isupper(): - self._HandleError( - errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL, - 'Prefer "?Type" to "Type|null": "%s"' % js_type, token) - - # TODO(user): We should report an error for wrong usage of '?' and '|' - # e.g. {?number|string|null} etc. - - for sub_type in js_type.IterTypes(): - self._CheckJsDocType(token, sub_type) - - def _CheckForMissingSpaceBeforeToken(self, token): - """Checks for a missing space at the beginning of a token. - - Reports a MISSING_SPACE error if the token does not begin with a space or - the previous token doesn't end with a space and the previous token is on the - same line as the token. - - Args: - token: The token being checked - """ - # TODO(user): Check if too many spaces? - if (len(token.string) == len(token.string.lstrip()) and - token.previous and token.line_number == token.previous.line_number and - len(token.previous.string) - len(token.previous.string.rstrip()) == 0): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space before "%s"' % token.string, - token, - position=Position.AtBeginning()) - - def _CheckOperator(self, token): - """Checks an operator for spacing and line style. - - Args: - token: The operator token. - """ - last_code = token.metadata.last_code - - if not self._ExpectSpaceBeforeOperator(token): - if (token.previous and token.previous.type == Type.WHITESPACE and - last_code and last_code.type in (Type.NORMAL, Type.IDENTIFIER) and - last_code.line_number == token.line_number): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "%s"' % token.string, - token.previous, position=Position.All(token.previous.string)) - - elif (token.previous and - not token.previous.IsComment() and - not tokenutil.IsDot(token) and - token.previous.type in Type.EXPRESSION_ENDER_TYPES): - self._HandleError(errors.MISSING_SPACE, - 'Missing space before "%s"' % token.string, token, - position=Position.AtBeginning()) - - # Check wrapping of operators. - next_code = tokenutil.GetNextCodeToken(token) - - is_dot = tokenutil.IsDot(token) - wrapped_before = last_code and last_code.line_number != token.line_number - wrapped_after = next_code and next_code.line_number != token.line_number - - if FLAGS.dot_on_next_line and is_dot and wrapped_after: - self._HandleError( - errors.LINE_ENDS_WITH_DOT, - '"." must go on the following line', - token) - if (not is_dot and wrapped_before and - not token.metadata.IsUnaryOperator()): - self._HandleError( - errors.LINE_STARTS_WITH_OPERATOR, - 'Binary operator must go on previous line "%s"' % token.string, - token) - - def _IsLabel(self, token): - # A ':' token is considered part of a label if it occurs in a case - # statement, a plain label, or an object literal, i.e. is not part of a - # ternary. - - return (token.string == ':' and - token.metadata.context.type in (Context.LITERAL_ELEMENT, - Context.CASE_BLOCK, - Context.STATEMENT)) - - def _ExpectSpaceBeforeOperator(self, token): - """Returns whether a space should appear before the given operator token. - - Args: - token: The operator token. - - Returns: - Whether there should be a space before the token. - """ - if token.string == ',' or token.metadata.IsUnaryPostOperator(): - return False - - if tokenutil.IsDot(token): - return False - - # Colons should appear in labels, object literals, the case of a switch - # statement, and ternary operator. Only want a space in the case of the - # ternary operator. - if self._IsLabel(token): - return False - - if token.metadata.IsUnaryOperator() and token.IsFirstInLine(): - return False - - return True - - def CheckToken(self, token, state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration - state: parser_state object that indicates the current state in the page - """ - # Store some convenience variables - first_in_line = token.IsFirstInLine() - last_in_line = token.IsLastInLine() - last_non_space_token = state.GetLastNonSpaceToken() - - token_type = token.type - - # Process the line change. - if not self._is_html and error_check.ShouldCheck(Rule.INDENTATION): - # TODO(robbyw): Support checking indentation in HTML files. - indentation_errors = self._indentation.CheckToken(token, state) - for indentation_error in indentation_errors: - self._HandleError(*indentation_error) - - if last_in_line: - self._CheckLineLength(token, state) - - if token_type == Type.PARAMETERS: - # Find missing spaces in parameter lists. - if self.MISSING_PARAMETER_SPACE.search(token.string): - fix_data = ', '.join([s.strip() for s in token.string.split(',')]) - self._HandleError(errors.MISSING_SPACE, 'Missing space after ","', - token, position=None, fix_data=fix_data.strip()) - - # Find extra spaces at the beginning of parameter lists. Make sure - # we aren't at the beginning of a continuing multi-line list. - if not first_in_line: - space_count = len(token.string) - len(token.string.lstrip()) - if space_count: - self._HandleError(errors.EXTRA_SPACE, 'Extra space after "("', - token, position=Position(0, space_count)) - - elif (token_type == Type.START_BLOCK and - token.metadata.context.type == Context.BLOCK): - self._CheckForMissingSpaceBeforeToken(token) - - elif token_type == Type.END_BLOCK: - last_code = token.metadata.last_code - if state.InFunction() and state.IsFunctionClose(): - if state.InTopLevelFunction(): - # A semicolons should not be included at the end of a function - # declaration. - if not state.InAssignedFunction(): - if not last_in_line and token.next.type == Type.SEMICOLON: - self._HandleError( - errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, - 'Illegal semicolon after function declaration', - token.next, position=Position.All(token.next.string)) - - # A semicolon should be included at the end of a function expression - # that is not immediately called or used by a dot operator. - if (state.InAssignedFunction() and token.next - and token.next.type != Type.SEMICOLON): - next_token = tokenutil.GetNextCodeToken(token) - is_immediately_used = (next_token.type == Type.START_PAREN or - tokenutil.IsDot(next_token)) - if not is_immediately_used: - self._HandleError( - errors.MISSING_SEMICOLON_AFTER_FUNCTION, - 'Missing semicolon after function assigned to a variable', - token, position=Position.AtEnd(token.string)) - - if state.InInterfaceMethod() and last_code.type != Type.START_BLOCK: - self._HandleError(errors.INTERFACE_METHOD_CANNOT_HAVE_CODE, - 'Interface methods cannot contain code', last_code) - - elif (state.IsBlockClose() and - token.next and token.next.type == Type.SEMICOLON): - if (last_code.metadata.context.parent.type != Context.OBJECT_LITERAL - and last_code.metadata.context.type != Context.OBJECT_LITERAL): - self._HandleError( - errors.REDUNDANT_SEMICOLON, - 'No semicolon is required to end a code block', - token.next, position=Position.All(token.next.string)) - - elif token_type == Type.SEMICOLON: - if token.previous and token.previous.type == Type.WHITESPACE: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before ";"', - token.previous, position=Position.All(token.previous.string)) - - if token.next and token.next.line_number == token.line_number: - if token.metadata.context.type != Context.FOR_GROUP_BLOCK: - # TODO(robbyw): Error about no multi-statement lines. - pass - - elif token.next.type not in ( - Type.WHITESPACE, Type.SEMICOLON, Type.END_PAREN): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space after ";" in for statement', - token.next, - position=Position.AtBeginning()) - - last_code = token.metadata.last_code - if last_code and last_code.type == Type.SEMICOLON: - # Allow a single double semi colon in for loops for cases like: - # for (;;) { }. - # NOTE(user): This is not a perfect check, and will not throw an error - # for cases like: for (var i = 0;; i < n; i++) {}, but then your code - # probably won't work either. - for_token = tokenutil.CustomSearch( - last_code, - lambda token: token.type == Type.KEYWORD and token.string == 'for', - end_func=lambda token: token.type == Type.SEMICOLON, - distance=None, - reverse=True) - - if not for_token: - self._HandleError(errors.REDUNDANT_SEMICOLON, 'Redundant semicolon', - token, position=Position.All(token.string)) - - elif token_type == Type.START_PAREN: - # Ensure that opening parentheses have a space before any keyword - # that is not being invoked like a member function. - if (token.previous and token.previous.type == Type.KEYWORD and - (not token.previous.metadata or - not token.previous.metadata.last_code or - not token.previous.metadata.last_code.string or - token.previous.metadata.last_code.string[-1:] != '.')): - self._HandleError(errors.MISSING_SPACE, 'Missing space before "("', - token, position=Position.AtBeginning()) - elif token.previous and token.previous.type == Type.WHITESPACE: - before_space = token.previous.previous - # Ensure that there is no extra space before a function invocation, - # even if the function being invoked happens to be a keyword. - if (before_space and before_space.line_number == token.line_number and - before_space.type == Type.IDENTIFIER or - (before_space.type == Type.KEYWORD and before_space.metadata and - before_space.metadata.last_code and - before_space.metadata.last_code.string and - before_space.metadata.last_code.string[-1:] == '.')): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "("', - token.previous, position=Position.All(token.previous.string)) - - elif token_type == Type.START_BRACKET: - self._HandleStartBracket(token, last_non_space_token) - elif token_type in (Type.END_PAREN, Type.END_BRACKET): - # Ensure there is no space before closing parentheses, except when - # it's in a for statement with an omitted section, or when it's at the - # beginning of a line. - if (token.previous and token.previous.type == Type.WHITESPACE and - not token.previous.IsFirstInLine() and - not (last_non_space_token and last_non_space_token.line_number == - token.line_number and - last_non_space_token.type == Type.SEMICOLON)): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "%s"' % - token.string, token.previous, - position=Position.All(token.previous.string)) - - elif token_type == Type.WHITESPACE: - if self.ILLEGAL_TAB.search(token.string): - if token.IsFirstInLine(): - if token.next: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace before "%s"' % token.next.string, - token, position=Position.All(token.string)) - else: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace', - token, position=Position.All(token.string)) - else: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace after "%s"' % token.previous.string, - token, position=Position.All(token.string)) - - # Check whitespace length if it's not the first token of the line and - # if it's not immediately before a comment. - if last_in_line: - # Check for extra whitespace at the end of a line. - self._HandleError(errors.EXTRA_SPACE, 'Extra space at end of line', - token, position=Position.All(token.string)) - elif not first_in_line and not token.next.IsComment(): - if token.length > 1: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space after "%s"' % - token.previous.string, token, - position=Position(1, len(token.string) - 1)) - - elif token_type == Type.OPERATOR: - self._CheckOperator(token) - elif token_type == Type.DOC_FLAG: - flag = token.attached_object - - if flag.flag_type == 'bug': - # TODO(robbyw): Check for exactly 1 space on the left. - string = token.next.string.lstrip() - string = string.split(' ', 1)[0] - - if not string.isdigit(): - self._HandleError(errors.NO_BUG_NUMBER_AFTER_BUG_TAG, - '@bug should be followed by a bug number', token) - - elif flag.flag_type == 'suppress': - if flag.type is None: - # A syntactically invalid suppress tag will get tokenized as a normal - # flag, indicating an error. - self._HandleError( - errors.INCORRECT_SUPPRESS_SYNTAX, - 'Invalid suppress syntax: should be @suppress {errortype}. ' - 'Spaces matter.', token) - else: - for suppress_type in flag.jstype.IterIdentifiers(): - if suppress_type not in state.GetDocFlag().SUPPRESS_TYPES: - self._HandleError( - errors.INVALID_SUPPRESS_TYPE, - 'Invalid suppression type: %s' % suppress_type, token) - - elif (error_check.ShouldCheck(Rule.WELL_FORMED_AUTHOR) and - flag.flag_type == 'author'): - # TODO(user): In non strict mode check the author tag for as much as - # it exists, though the full form checked below isn't required. - string = token.next.string - result = self.AUTHOR_SPEC.match(string) - if not result: - self._HandleError(errors.INVALID_AUTHOR_TAG_DESCRIPTION, - 'Author tag line should be of the form: ' - '@author foo@somewhere.com (Your Name)', - token.next) - else: - # Check spacing between email address and name. Do this before - # checking earlier spacing so positions are easier to calculate for - # autofixing. - num_spaces = len(result.group(2)) - if num_spaces < 1: - self._HandleError(errors.MISSING_SPACE, - 'Missing space after email address', - token.next, position=Position(result.start(2), 0)) - elif num_spaces > 1: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space after email address', - token.next, - position=Position(result.start(2) + 1, num_spaces - 1)) - - # Check for extra spaces before email address. Can't be too few, if - # not at least one we wouldn't match @author tag. - num_spaces = len(result.group(1)) - if num_spaces > 1: - self._HandleError(errors.EXTRA_SPACE, - 'Extra space before email address', - token.next, position=Position(1, num_spaces - 1)) - - elif (flag.flag_type in state.GetDocFlag().HAS_DESCRIPTION and - not self._limited_doc_checks): - if flag.flag_type == 'param': - if flag.name is None: - self._HandleError(errors.MISSING_JSDOC_PARAM_NAME, - 'Missing name in @param tag', token) - - if not flag.description or flag.description is None: - flag_name = token.type - if 'name' in token.values: - flag_name = '@' + token.values['name'] - - if flag_name not in self.JSDOC_FLAGS_DESCRIPTION_NOT_REQUIRED: - self._HandleError( - errors.MISSING_JSDOC_TAG_DESCRIPTION, - 'Missing description in %s tag' % flag_name, token) - else: - self._CheckForMissingSpaceBeforeToken(flag.description_start_token) - - if flag.HasType(): - if flag.type_start_token is not None: - self._CheckForMissingSpaceBeforeToken( - token.attached_object.type_start_token) - - if flag.jstype and not flag.jstype.IsEmpty(): - self._CheckJsDocType(token, flag.jstype) - - if error_check.ShouldCheck(Rule.BRACES_AROUND_TYPE) and ( - flag.type_start_token.type != Type.DOC_START_BRACE or - flag.type_end_token.type != Type.DOC_END_BRACE): - self._HandleError( - errors.MISSING_BRACES_AROUND_TYPE, - 'Type must always be surrounded by curly braces.', token) - - if token_type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): - if (token.values['name'] not in state.GetDocFlag().LEGAL_DOC and - token.values['name'] not in FLAGS.custom_jsdoc_tags): - self._HandleError( - errors.INVALID_JSDOC_TAG, - 'Invalid JsDoc tag: %s' % token.values['name'], token) - - if (error_check.ShouldCheck(Rule.NO_BRACES_AROUND_INHERIT_DOC) and - token.values['name'] == 'inheritDoc' and - token_type == Type.DOC_INLINE_FLAG): - self._HandleError(errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC, - 'Unnecessary braces around @inheritDoc', - token) - - elif token_type == Type.SIMPLE_LVALUE: - identifier = token.values['identifier'] - - if ((not state.InFunction() or state.InConstructor()) and - state.InTopLevel() and not state.InObjectLiteralDescendant()): - jsdoc = state.GetDocComment() - if not state.HasDocComment(identifier): - # Only test for documentation on identifiers with .s in them to - # avoid checking things like simple variables. We don't require - # documenting assignments to .prototype itself (bug 1880803). - if (not state.InConstructor() and - identifier.find('.') != -1 and not - identifier.endswith('.prototype') and not - self._limited_doc_checks): - comment = state.GetLastComment() - if not (comment and comment.lower().count('jsdoc inherited')): - self._HandleError( - errors.MISSING_MEMBER_DOCUMENTATION, - "No docs found for member '%s'" % identifier, - token) - elif jsdoc and (not state.InConstructor() or - identifier.startswith('this.')): - # We are at the top level and the function/member is documented. - if identifier.endswith('_') and not identifier.endswith('__'): - # Can have a private class which inherits documentation from a - # public superclass. - # - # @inheritDoc is deprecated in favor of using @override, and they - if (jsdoc.HasFlag('override') and not jsdoc.HasFlag('constructor') - and ('accessControls' not in jsdoc.suppressions)): - self._HandleError( - errors.INVALID_OVERRIDE_PRIVATE, - '%s should not override a private member.' % identifier, - jsdoc.GetFlag('override').flag_token) - if (jsdoc.HasFlag('inheritDoc') and not jsdoc.HasFlag('constructor') - and ('accessControls' not in jsdoc.suppressions)): - self._HandleError( - errors.INVALID_INHERIT_DOC_PRIVATE, - '%s should not inherit from a private member.' % identifier, - jsdoc.GetFlag('inheritDoc').flag_token) - if (not jsdoc.HasFlag('private') and - ('underscore' not in jsdoc.suppressions) and not - ((jsdoc.HasFlag('inheritDoc') or jsdoc.HasFlag('override')) and - ('accessControls' in jsdoc.suppressions))): - self._HandleError( - errors.MISSING_PRIVATE, - 'Member "%s" must have @private JsDoc.' % - identifier, token) - if jsdoc.HasFlag('private') and 'underscore' in jsdoc.suppressions: - self._HandleError( - errors.UNNECESSARY_SUPPRESS, - '@suppress {underscore} is not necessary with @private', - jsdoc.suppressions['underscore']) - elif (jsdoc.HasFlag('private') and - not self.InExplicitlyTypedLanguage()): - # It is convention to hide public fields in some ECMA - # implementations from documentation using the @private tag. - self._HandleError( - errors.EXTRA_PRIVATE, - 'Member "%s" must not have @private JsDoc' % - identifier, token) - - # These flags are only legal on localizable message definitions; - # such variables always begin with the prefix MSG_. - for f in ('desc', 'hidden', 'meaning'): - if (jsdoc.HasFlag(f) - and not identifier.startswith('MSG_') - and identifier.find('.MSG_') == -1): - self._HandleError( - errors.INVALID_USE_OF_DESC_TAG, - 'Member "%s" should not have @%s JsDoc' % (identifier, f), - token) - - # Check for illegaly assigning live objects as prototype property values. - index = identifier.find('.prototype.') - # Ignore anything with additional .s after the prototype. - if index != -1 and identifier.find('.', index + 11) == -1: - equal_operator = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - next_code = tokenutil.SearchExcept(equal_operator, Type.NON_CODE_TYPES) - if next_code and ( - next_code.type in (Type.START_BRACKET, Type.START_BLOCK) or - next_code.IsOperator('new')): - self._HandleError( - errors.ILLEGAL_PROTOTYPE_MEMBER_VALUE, - 'Member %s cannot have a non-primitive value' % identifier, - token) - - elif token_type == Type.END_PARAMETERS: - # Find extra space at the end of parameter lists. We check the token - # prior to the current one when it is a closing paren. - if (token.previous and token.previous.type == Type.PARAMETERS - and self.ENDS_WITH_SPACE.search(token.previous.string)): - self._HandleError(errors.EXTRA_SPACE, 'Extra space before ")"', - token.previous) - - jsdoc = state.GetDocComment() - if state.GetFunction().is_interface: - if token.previous and token.previous.type == Type.PARAMETERS: - self._HandleError( - errors.INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS, - 'Interface constructor cannot have parameters', - token.previous) - elif (state.InTopLevel() and jsdoc and not jsdoc.HasFlag('see') - and not jsdoc.InheritsDocumentation() - and not state.InObjectLiteralDescendant() and not - jsdoc.IsInvalidated()): - distance, edit = jsdoc.CompareParameters(state.GetParams()) - if distance: - params_iter = iter(state.GetParams()) - docs_iter = iter(jsdoc.ordered_params) - - for op in edit: - if op == 'I': - # Insertion. - # Parsing doc comments is the same for all languages - # but some languages care about parameters that don't have - # doc comments and some languages don't care. - # Languages that don't allow variables to by typed such as - # JavaScript care but languages such as ActionScript or Java - # that allow variables to be typed don't care. - if not self._limited_doc_checks: - self.HandleMissingParameterDoc(token, params_iter.next()) - - elif op == 'D': - # Deletion - self._HandleError(errors.EXTRA_PARAMETER_DOCUMENTATION, - 'Found docs for non-existing parameter: "%s"' % - docs_iter.next(), token) - elif op == 'S': - # Substitution - if not self._limited_doc_checks: - self._HandleError( - errors.WRONG_PARAMETER_DOCUMENTATION, - 'Parameter mismatch: got "%s", expected "%s"' % - (params_iter.next(), docs_iter.next()), token) - - else: - # Equality - just advance the iterators - params_iter.next() - docs_iter.next() - - elif token_type == Type.STRING_TEXT: - # If this is the first token after the start of the string, but it's at - # the end of a line, we know we have a multi-line string. - if token.previous.type in ( - Type.SINGLE_QUOTE_STRING_START, - Type.DOUBLE_QUOTE_STRING_START) and last_in_line: - self._HandleError(errors.MULTI_LINE_STRING, - 'Multi-line strings are not allowed', token) - - # This check is orthogonal to the ones above, and repeats some types, so - # it is a plain if and not an elif. - if token.type in Type.COMMENT_TYPES: - if self.ILLEGAL_TAB.search(token.string): - self._HandleError(errors.ILLEGAL_TAB, - 'Illegal tab in comment "%s"' % token.string, token) - - trimmed = token.string.rstrip() - if last_in_line and token.string != trimmed: - # Check for extra whitespace at the end of a line. - self._HandleError( - errors.EXTRA_SPACE, 'Extra space at end of line', token, - position=Position(len(trimmed), len(token.string) - len(trimmed))) - - # This check is also orthogonal since it is based on metadata. - if token.metadata.is_implied_semicolon: - self._HandleError(errors.MISSING_SEMICOLON, - 'Missing semicolon at end of line', token) - - def _HandleStartBracket(self, token, last_non_space_token): - """Handles a token that is an open bracket. - - Args: - token: The token to handle. - last_non_space_token: The last token that was not a space. - """ - if (not token.IsFirstInLine() and token.previous.type == Type.WHITESPACE and - last_non_space_token and - last_non_space_token.type in Type.EXPRESSION_ENDER_TYPES): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "["', - token.previous, position=Position.All(token.previous.string)) - # If the [ token is the first token in a line we shouldn't complain - # about a missing space before [. This is because some Ecma script - # languages allow syntax like: - # [Annotation] - # class MyClass {...} - # So we don't want to blindly warn about missing spaces before [. - # In the the future, when rules for computing exactly how many spaces - # lines should be indented are added, then we can return errors for - # [ tokens that are improperly indented. - # For example: - # var someVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongVariableName = - # [a,b,c]; - # should trigger a proper indentation warning message as [ is not indented - # by four spaces. - elif (not token.IsFirstInLine() and token.previous and - token.previous.type not in ( - [Type.WHITESPACE, Type.START_PAREN, Type.START_BRACKET] + - Type.EXPRESSION_ENDER_TYPES)): - self._HandleError(errors.MISSING_SPACE, 'Missing space before "["', - token, position=Position.AtBeginning()) - - def Finalize(self, state): - """Perform all checks that need to occur after all lines are processed. - - Args: - state: State of the parser after parsing all tokens - - Raises: - TypeError: If not overridden. - """ - last_non_space_token = state.GetLastNonSpaceToken() - # Check last line for ending with newline. - if state.GetLastLine() and not ( - state.GetLastLine().isspace() or - state.GetLastLine().rstrip('\n\r\f') != state.GetLastLine()): - self._HandleError( - errors.FILE_MISSING_NEWLINE, - 'File does not end with new line. (%s)' % state.GetLastLine(), - last_non_space_token) - - try: - self._indentation.Finalize() - except Exception, e: - self._HandleError( - errors.FILE_DOES_NOT_PARSE, - str(e), - last_non_space_token) - - def GetLongLineExceptions(self): - """Gets a list of regexps for lines which can be longer than the limit. - - Returns: - A list of regexps, used as matches (rather than searches). - """ - return [] - - def InExplicitlyTypedLanguage(self): - """Returns whether this ecma implementation is explicitly typed.""" - return False diff --git a/tools/closure_linter/build/lib/closure_linter/ecmametadatapass.py b/tools/closure_linter/build/lib/closure_linter/ecmametadatapass.py deleted file mode 100644 index 50621610efe08d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/ecmametadatapass.py +++ /dev/null @@ -1,574 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Metadata pass for annotating tokens in EcmaScript files.""" - -__author__ = ('robbyw@google.com (Robert Walker)') - -from closure_linter import javascripttokens -from closure_linter import tokenutil - - -TokenType = javascripttokens.JavaScriptTokenType - - -class ParseError(Exception): - """Exception indicating a parse error at the given token. - - Attributes: - token: The token where the parse error occurred. - """ - - def __init__(self, token, message=None): - """Initialize a parse error at the given token with an optional message. - - Args: - token: The token where the parse error occurred. - message: A message describing the parse error. - """ - Exception.__init__(self, message) - self.token = token - - -class EcmaContext(object): - """Context object for EcmaScript languages. - - Attributes: - type: The context type. - start_token: The token where this context starts. - end_token: The token where this context ends. - parent: The parent context. - """ - - # The root context. - ROOT = 'root' - - # A block of code. - BLOCK = 'block' - - # A pseudo-block of code for a given case or default section. - CASE_BLOCK = 'case_block' - - # Block of statements in a for loop's parentheses. - FOR_GROUP_BLOCK = 'for_block' - - # An implied block of code for 1 line if, while, and for statements - IMPLIED_BLOCK = 'implied_block' - - # An index in to an array or object. - INDEX = 'index' - - # An array literal in []. - ARRAY_LITERAL = 'array_literal' - - # An object literal in {}. - OBJECT_LITERAL = 'object_literal' - - # An individual element in an array or object literal. - LITERAL_ELEMENT = 'literal_element' - - # The portion of a ternary statement between ? and : - TERNARY_TRUE = 'ternary_true' - - # The portion of a ternary statment after : - TERNARY_FALSE = 'ternary_false' - - # The entire switch statment. This will contain a GROUP with the variable - # and a BLOCK with the code. - - # Since that BLOCK is not a normal block, it can not contain statements except - # for case and default. - SWITCH = 'switch' - - # A normal comment. - COMMENT = 'comment' - - # A JsDoc comment. - DOC = 'doc' - - # An individual statement. - STATEMENT = 'statement' - - # Code within parentheses. - GROUP = 'group' - - # Parameter names in a function declaration. - PARAMETERS = 'parameters' - - # A set of variable declarations appearing after the 'var' keyword. - VAR = 'var' - - # Context types that are blocks. - BLOCK_TYPES = frozenset([ - ROOT, BLOCK, CASE_BLOCK, FOR_GROUP_BLOCK, IMPLIED_BLOCK]) - - def __init__(self, context_type, start_token, parent=None): - """Initializes the context object. - - Args: - context_type: The context type. - start_token: The token where this context starts. - parent: The parent context. - - Attributes: - type: The context type. - start_token: The token where this context starts. - end_token: The token where this context ends. - parent: The parent context. - children: The child contexts of this context, in order. - """ - self.type = context_type - self.start_token = start_token - self.end_token = None - - self.parent = None - self.children = [] - - if parent: - parent.AddChild(self) - - def __repr__(self): - """Returns a string representation of the context object.""" - stack = [] - context = self - while context: - stack.append(context.type) - context = context.parent - return 'Context(%s)' % ' > '.join(stack) - - def AddChild(self, child): - """Adds a child to this context and sets child's parent to this context. - - Args: - child: A child EcmaContext. The child's parent will be set to this - context. - """ - - child.parent = self - - self.children.append(child) - self.children.sort(EcmaContext._CompareContexts) - - def GetRoot(self): - """Get the root context that contains this context, if any.""" - context = self - while context: - if context.type is EcmaContext.ROOT: - return context - context = context.parent - - @staticmethod - def _CompareContexts(context1, context2): - """Sorts contexts 1 and 2 by start token document position.""" - return tokenutil.Compare(context1.start_token, context2.start_token) - - -class EcmaMetaData(object): - """Token metadata for EcmaScript languages. - - Attributes: - last_code: The last code token to appear before this one. - context: The context this token appears in. - operator_type: The operator type, will be one of the *_OPERATOR constants - defined below. - aliased_symbol: The full symbol being identified, as a string (e.g. an - 'XhrIo' alias for 'goog.net.XhrIo'). Only applicable to identifier - tokens. This is set in aliaspass.py and is a best guess. - is_alias_definition: True if the symbol is part of an alias definition. - If so, these symbols won't be counted towards goog.requires/provides. - """ - - UNARY_OPERATOR = 'unary' - - UNARY_POST_OPERATOR = 'unary_post' - - BINARY_OPERATOR = 'binary' - - TERNARY_OPERATOR = 'ternary' - - def __init__(self): - """Initializes a token metadata object.""" - self.last_code = None - self.context = None - self.operator_type = None - self.is_implied_semicolon = False - self.is_implied_block = False - self.is_implied_block_close = False - self.aliased_symbol = None - self.is_alias_definition = False - - def __repr__(self): - """Returns a string representation of the context object.""" - parts = ['%r' % self.context] - if self.operator_type: - parts.append('optype: %r' % self.operator_type) - if self.is_implied_semicolon: - parts.append('implied;') - if self.aliased_symbol: - parts.append('alias for: %s' % self.aliased_symbol) - return 'MetaData(%s)' % ', '.join(parts) - - def IsUnaryOperator(self): - return self.operator_type in (EcmaMetaData.UNARY_OPERATOR, - EcmaMetaData.UNARY_POST_OPERATOR) - - def IsUnaryPostOperator(self): - return self.operator_type == EcmaMetaData.UNARY_POST_OPERATOR - - -class EcmaMetaDataPass(object): - """A pass that iterates over all tokens and builds metadata about them.""" - - def __init__(self): - """Initialize the meta data pass object.""" - self.Reset() - - def Reset(self): - """Resets the metadata pass to prepare for the next file.""" - self._token = None - self._context = None - self._AddContext(EcmaContext.ROOT) - self._last_code = None - - def _CreateContext(self, context_type): - """Overridable by subclasses to create the appropriate context type.""" - return EcmaContext(context_type, self._token, self._context) - - def _CreateMetaData(self): - """Overridable by subclasses to create the appropriate metadata type.""" - return EcmaMetaData() - - def _AddContext(self, context_type): - """Adds a context of the given type to the context stack. - - Args: - context_type: The type of context to create - """ - self._context = self._CreateContext(context_type) - - def _PopContext(self): - """Moves up one level in the context stack. - - Returns: - The former context. - - Raises: - ParseError: If the root context is popped. - """ - top_context = self._context - top_context.end_token = self._token - self._context = top_context.parent - if self._context: - return top_context - else: - raise ParseError(self._token) - - def _PopContextType(self, *stop_types): - """Pops the context stack until a context of the given type is popped. - - Args: - *stop_types: The types of context to pop to - stops at the first match. - - Returns: - The context object of the given type that was popped. - """ - last = None - while not last or last.type not in stop_types: - last = self._PopContext() - return last - - def _EndStatement(self): - """Process the end of a statement.""" - self._PopContextType(EcmaContext.STATEMENT) - if self._context.type == EcmaContext.IMPLIED_BLOCK: - self._token.metadata.is_implied_block_close = True - self._PopContext() - - def _ProcessContext(self): - """Process the context at the current token. - - Returns: - The context that should be assigned to the current token, or None if - the current context after this method should be used. - - Raises: - ParseError: When the token appears in an invalid context. - """ - token = self._token - token_type = token.type - - if self._context.type in EcmaContext.BLOCK_TYPES: - # Whenever we're in a block, we add a statement context. We make an - # exception for switch statements since they can only contain case: and - # default: and therefore don't directly contain statements. - # The block we add here may be immediately removed in some cases, but - # that causes no harm. - parent = self._context.parent - if not parent or parent.type != EcmaContext.SWITCH: - self._AddContext(EcmaContext.STATEMENT) - - elif self._context.type == EcmaContext.ARRAY_LITERAL: - self._AddContext(EcmaContext.LITERAL_ELEMENT) - - if token_type == TokenType.START_PAREN: - if self._last_code and self._last_code.IsKeyword('for'): - # for loops contain multiple statements in the group unlike while, - # switch, if, etc. - self._AddContext(EcmaContext.FOR_GROUP_BLOCK) - else: - self._AddContext(EcmaContext.GROUP) - - elif token_type == TokenType.END_PAREN: - result = self._PopContextType(EcmaContext.GROUP, - EcmaContext.FOR_GROUP_BLOCK) - keyword_token = result.start_token.metadata.last_code - # keyword_token will not exist if the open paren is the first line of the - # file, for example if all code is wrapped in an immediately executed - # annonymous function. - if keyword_token and keyword_token.string in ('if', 'for', 'while'): - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - if next_code.type != TokenType.START_BLOCK: - # Check for do-while. - is_do_while = False - pre_keyword_token = keyword_token.metadata.last_code - if (pre_keyword_token and - pre_keyword_token.type == TokenType.END_BLOCK): - start_block_token = pre_keyword_token.metadata.context.start_token - is_do_while = start_block_token.metadata.last_code.string == 'do' - - # If it's not do-while, it's an implied block. - if not is_do_while: - self._AddContext(EcmaContext.IMPLIED_BLOCK) - token.metadata.is_implied_block = True - - return result - - # else (not else if) with no open brace after it should be considered the - # start of an implied block, similar to the case with if, for, and while - # above. - elif (token_type == TokenType.KEYWORD and - token.string == 'else'): - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - if (next_code.type != TokenType.START_BLOCK and - (next_code.type != TokenType.KEYWORD or next_code.string != 'if')): - self._AddContext(EcmaContext.IMPLIED_BLOCK) - token.metadata.is_implied_block = True - - elif token_type == TokenType.START_PARAMETERS: - self._AddContext(EcmaContext.PARAMETERS) - - elif token_type == TokenType.END_PARAMETERS: - return self._PopContextType(EcmaContext.PARAMETERS) - - elif token_type == TokenType.START_BRACKET: - if (self._last_code and - self._last_code.type in TokenType.EXPRESSION_ENDER_TYPES): - self._AddContext(EcmaContext.INDEX) - else: - self._AddContext(EcmaContext.ARRAY_LITERAL) - - elif token_type == TokenType.END_BRACKET: - return self._PopContextType(EcmaContext.INDEX, EcmaContext.ARRAY_LITERAL) - - elif token_type == TokenType.START_BLOCK: - if (self._last_code.type in (TokenType.END_PAREN, - TokenType.END_PARAMETERS) or - self._last_code.IsKeyword('else') or - self._last_code.IsKeyword('do') or - self._last_code.IsKeyword('try') or - self._last_code.IsKeyword('finally') or - (self._last_code.IsOperator(':') and - self._last_code.metadata.context.type == EcmaContext.CASE_BLOCK)): - # else, do, try, and finally all might have no () before {. - # Also, handle the bizzare syntax case 10: {...}. - self._AddContext(EcmaContext.BLOCK) - else: - self._AddContext(EcmaContext.OBJECT_LITERAL) - - elif token_type == TokenType.END_BLOCK: - context = self._PopContextType(EcmaContext.BLOCK, - EcmaContext.OBJECT_LITERAL) - if self._context.type == EcmaContext.SWITCH: - # The end of the block also means the end of the switch statement it - # applies to. - return self._PopContext() - return context - - elif token.IsKeyword('switch'): - self._AddContext(EcmaContext.SWITCH) - - elif (token_type == TokenType.KEYWORD and - token.string in ('case', 'default') and - self._context.type != EcmaContext.OBJECT_LITERAL): - # Pop up to but not including the switch block. - while self._context.parent.type != EcmaContext.SWITCH: - self._PopContext() - if self._context.parent is None: - raise ParseError(token, 'Encountered case/default statement ' - 'without switch statement') - - elif token.IsOperator('?'): - self._AddContext(EcmaContext.TERNARY_TRUE) - - elif token.IsOperator(':'): - if self._context.type == EcmaContext.OBJECT_LITERAL: - self._AddContext(EcmaContext.LITERAL_ELEMENT) - - elif self._context.type == EcmaContext.TERNARY_TRUE: - self._PopContext() - self._AddContext(EcmaContext.TERNARY_FALSE) - - # Handle nested ternary statements like: - # foo = bar ? baz ? 1 : 2 : 3 - # When we encounter the second ":" the context is - # ternary_false > ternary_true > statement > root - elif (self._context.type == EcmaContext.TERNARY_FALSE and - self._context.parent.type == EcmaContext.TERNARY_TRUE): - self._PopContext() # Leave current ternary false context. - self._PopContext() # Leave current parent ternary true - self._AddContext(EcmaContext.TERNARY_FALSE) - - elif self._context.parent.type == EcmaContext.SWITCH: - self._AddContext(EcmaContext.CASE_BLOCK) - - elif token.IsKeyword('var'): - self._AddContext(EcmaContext.VAR) - - elif token.IsOperator(','): - while self._context.type not in (EcmaContext.VAR, - EcmaContext.ARRAY_LITERAL, - EcmaContext.OBJECT_LITERAL, - EcmaContext.STATEMENT, - EcmaContext.PARAMETERS, - EcmaContext.GROUP): - self._PopContext() - - elif token_type == TokenType.SEMICOLON: - self._EndStatement() - - def Process(self, first_token): - """Processes the token stream starting with the given token.""" - self._token = first_token - while self._token: - self._ProcessToken() - - if self._token.IsCode(): - self._last_code = self._token - - self._token = self._token.next - - try: - self._PopContextType(self, EcmaContext.ROOT) - except ParseError: - # Ignore the "popped to root" error. - pass - - def _ProcessToken(self): - """Process the given token.""" - token = self._token - token.metadata = self._CreateMetaData() - context = (self._ProcessContext() or self._context) - token.metadata.context = context - token.metadata.last_code = self._last_code - - # Determine the operator type of the token, if applicable. - if token.type == TokenType.OPERATOR: - token.metadata.operator_type = self._GetOperatorType(token) - - # Determine if there is an implied semicolon after the token. - if token.type != TokenType.SEMICOLON: - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - # A statement like if (x) does not need a semicolon after it - is_implied_block = self._context == EcmaContext.IMPLIED_BLOCK - is_last_code_in_line = token.IsCode() and ( - not next_code or next_code.line_number != token.line_number) - is_continued_operator = (token.type == TokenType.OPERATOR and - not token.metadata.IsUnaryPostOperator()) - is_continued_dot = token.string == '.' - next_code_is_operator = next_code and next_code.type == TokenType.OPERATOR - is_end_of_block = ( - token.type == TokenType.END_BLOCK and - token.metadata.context.type != EcmaContext.OBJECT_LITERAL) - is_multiline_string = token.type == TokenType.STRING_TEXT - is_continued_var_decl = (token.IsKeyword('var') and - next_code and - (next_code.type in [TokenType.IDENTIFIER, - TokenType.SIMPLE_LVALUE]) and - token.line_number < next_code.line_number) - next_code_is_block = next_code and next_code.type == TokenType.START_BLOCK - if (is_last_code_in_line and - self._StatementCouldEndInContext() and - not is_multiline_string and - not is_end_of_block and - not is_continued_var_decl and - not is_continued_operator and - not is_continued_dot and - not next_code_is_operator and - not is_implied_block and - not next_code_is_block): - token.metadata.is_implied_semicolon = True - self._EndStatement() - - def _StatementCouldEndInContext(self): - """Returns if the current statement (if any) may end in this context.""" - # In the basic statement or variable declaration context, statement can - # always end in this context. - if self._context.type in (EcmaContext.STATEMENT, EcmaContext.VAR): - return True - - # End of a ternary false branch inside a statement can also be the - # end of the statement, for example: - # var x = foo ? foo.bar() : null - # In this case the statement ends after the null, when the context stack - # looks like ternary_false > var > statement > root. - if (self._context.type == EcmaContext.TERNARY_FALSE and - self._context.parent.type in (EcmaContext.STATEMENT, EcmaContext.VAR)): - return True - - # In all other contexts like object and array literals, ternary true, etc. - # the statement can't yet end. - return False - - def _GetOperatorType(self, token): - """Returns the operator type of the given operator token. - - Args: - token: The token to get arity for. - - Returns: - The type of the operator. One of the *_OPERATOR constants defined in - EcmaMetaData. - """ - if token.string == '?': - return EcmaMetaData.TERNARY_OPERATOR - - if token.string in TokenType.UNARY_OPERATORS: - return EcmaMetaData.UNARY_OPERATOR - - last_code = token.metadata.last_code - if not last_code or last_code.type == TokenType.END_BLOCK: - return EcmaMetaData.UNARY_OPERATOR - - if (token.string in TokenType.UNARY_POST_OPERATORS and - last_code.type in TokenType.EXPRESSION_ENDER_TYPES): - return EcmaMetaData.UNARY_POST_OPERATOR - - if (token.string in TokenType.UNARY_OK_OPERATORS and - last_code.type not in TokenType.EXPRESSION_ENDER_TYPES and - last_code.string not in TokenType.UNARY_POST_OPERATORS): - return EcmaMetaData.UNARY_OPERATOR - - return EcmaMetaData.BINARY_OPERATOR diff --git a/tools/closure_linter/build/lib/closure_linter/error_check.py b/tools/closure_linter/build/lib/closure_linter/error_check.py deleted file mode 100644 index 8d657fe9174fff..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/error_check.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -"""Specific JSLint errors checker.""" - - - -import gflags as flags - -FLAGS = flags.FLAGS - - -class Rule(object): - """Different rules to check.""" - - # Documentations for specific rules goes in flag definition. - BLANK_LINES_AT_TOP_LEVEL = 'blank_lines_at_top_level' - INDENTATION = 'indentation' - WELL_FORMED_AUTHOR = 'well_formed_author' - NO_BRACES_AROUND_INHERIT_DOC = 'no_braces_around_inherit_doc' - BRACES_AROUND_TYPE = 'braces_around_type' - OPTIONAL_TYPE_MARKER = 'optional_type_marker' - VARIABLE_ARG_MARKER = 'variable_arg_marker' - UNUSED_PRIVATE_MEMBERS = 'unused_private_members' - UNUSED_LOCAL_VARIABLES = 'unused_local_variables' - - # Rule to raise all known errors. - ALL = 'all' - - # All rules that are to be checked when using the strict flag. E.g. the rules - # that are specific to the stricter Closure style. - CLOSURE_RULES = frozenset([BLANK_LINES_AT_TOP_LEVEL, - INDENTATION, - WELL_FORMED_AUTHOR, - NO_BRACES_AROUND_INHERIT_DOC, - BRACES_AROUND_TYPE, - OPTIONAL_TYPE_MARKER, - VARIABLE_ARG_MARKER]) - - -flags.DEFINE_boolean('strict', False, - 'Whether to validate against the stricter Closure style. ' - 'This includes ' + (', '.join(Rule.CLOSURE_RULES)) + '.') -flags.DEFINE_multistring('jslint_error', [], - 'List of specific lint errors to check. Here is a list' - ' of accepted values:\n' - ' - ' + Rule.ALL + ': enables all following errors.\n' - ' - ' + Rule.BLANK_LINES_AT_TOP_LEVEL + ': validates' - 'number of blank lines between blocks at top level.\n' - ' - ' + Rule.INDENTATION + ': checks correct ' - 'indentation of code.\n' - ' - ' + Rule.WELL_FORMED_AUTHOR + ': validates the ' - '@author JsDoc tags.\n' - ' - ' + Rule.NO_BRACES_AROUND_INHERIT_DOC + ': ' - 'forbids braces around @inheritdoc JsDoc tags.\n' - ' - ' + Rule.BRACES_AROUND_TYPE + ': enforces braces ' - 'around types in JsDoc tags.\n' - ' - ' + Rule.OPTIONAL_TYPE_MARKER + ': checks correct ' - 'use of optional marker = in param types.\n' - ' - ' + Rule.UNUSED_PRIVATE_MEMBERS + ': checks for ' - 'unused private variables.\n' - ' - ' + Rule.UNUSED_LOCAL_VARIABLES + ': checks for ' - 'unused local variables.\n') - - -def ShouldCheck(rule): - """Returns whether the optional rule should be checked. - - Computes different flags (strict, jslint_error, jslint_noerror) to find out if - this specific rule should be checked. - - Args: - rule: Name of the rule (see Rule). - - Returns: - True if the rule should be checked according to the flags, otherwise False. - """ - if rule in FLAGS.jslint_error or Rule.ALL in FLAGS.jslint_error: - return True - # Checks strict rules. - return FLAGS.strict and rule in Rule.CLOSURE_RULES diff --git a/tools/closure_linter/build/lib/closure_linter/error_fixer.py b/tools/closure_linter/build/lib/closure_linter/error_fixer.py deleted file mode 100644 index 88f9c720ab3517..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/error_fixer.py +++ /dev/null @@ -1,618 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Main class responsible for automatically fixing simple style violations.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = 'robbyw@google.com (Robert Walker)' - -import re - -import gflags as flags -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import tokenutil -from closure_linter.common import errorhandler - -# Shorthand -Token = javascripttokens.JavaScriptToken -Type = javascripttokens.JavaScriptTokenType - -END_OF_FLAG_TYPE = re.compile(r'(}?\s*)$') - -# Regex to represent common mistake inverting author name and email as -# @author User Name (user@company) -INVERTED_AUTHOR_SPEC = re.compile(r'(?P\s*)' - r'(?P[^(]+)' - r'(?P\s+)' - r'\(' - r'(?P[^\s]+@[^)\s]+)' - r'\)' - r'(?P.*)') - -FLAGS = flags.FLAGS -flags.DEFINE_boolean('disable_indentation_fixing', False, - 'Whether to disable automatic fixing of indentation.') -flags.DEFINE_list('fix_error_codes', [], 'A list of specific error codes to ' - 'fix. Defaults to all supported error codes when empty. ' - 'See errors.py for a list of error codes.') - - -class ErrorFixer(errorhandler.ErrorHandler): - """Object that fixes simple style errors.""" - - def __init__(self, external_file=None): - """Initialize the error fixer. - - Args: - external_file: If included, all output will be directed to this file - instead of overwriting the files the errors are found in. - """ - errorhandler.ErrorHandler.__init__(self) - - self._file_name = None - self._file_token = None - self._external_file = external_file - - try: - self._fix_error_codes = set([errors.ByName(error.upper()) for error in - FLAGS.fix_error_codes]) - except KeyError as ke: - raise ValueError('Unknown error code ' + ke.args[0]) - - def HandleFile(self, filename, first_token): - """Notifies this ErrorPrinter that subsequent errors are in filename. - - Args: - filename: The name of the file about to be checked. - first_token: The first token in the file. - """ - self._file_name = filename - self._file_is_html = filename.endswith('.html') or filename.endswith('.htm') - self._file_token = first_token - self._file_fix_count = 0 - self._file_changed_lines = set() - - def _AddFix(self, tokens): - """Adds the fix to the internal count. - - Args: - tokens: The token or sequence of tokens changed to fix an error. - """ - self._file_fix_count += 1 - if hasattr(tokens, 'line_number'): - self._file_changed_lines.add(tokens.line_number) - else: - for token in tokens: - self._file_changed_lines.add(token.line_number) - - def _FixJsDocPipeNull(self, js_type): - """Change number|null or null|number to ?number. - - Args: - js_type: The typeannotation.TypeAnnotation instance to fix. - """ - - # Recurse into all sub_types if the error was at a deeper level. - map(self._FixJsDocPipeNull, js_type.IterTypes()) - - if js_type.type_group and len(js_type.sub_types) == 2: - # Find and remove the null sub_type: - sub_type = None - for sub_type in js_type.sub_types: - if sub_type.identifier == 'null': - map(tokenutil.DeleteToken, sub_type.tokens) - self._AddFix(sub_type.tokens) - break - else: - return - - first_token = js_type.FirstToken() - question_mark = Token('?', Type.DOC_TYPE_MODIFIER, first_token.line, - first_token.line_number) - tokenutil.InsertTokenBefore(question_mark, first_token) - js_type.tokens.insert(0, question_mark) - js_type.tokens.remove(sub_type) - js_type.or_null = True - - # Now also remove the separator, which is in the parent's token list, - # either before or after the sub_type, there is exactly one. Scan for it. - for token in js_type.tokens: - if (token and isinstance(token, Token) and - token.type == Type.DOC_TYPE_MODIFIER and token.string == '|'): - tokenutil.DeleteToken(token) - self._AddFix(token) - break - - def HandleError(self, error): - """Attempts to fix the error. - - Args: - error: The error object - """ - code = error.code - token = error.token - - if self._fix_error_codes and code not in self._fix_error_codes: - return - - if code == errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL: - self._FixJsDocPipeNull(token.attached_object.jstype) - - elif code == errors.JSDOC_MISSING_OPTIONAL_TYPE: - iterator = token.attached_object.type_end_token - if iterator.type == Type.DOC_END_BRACE or iterator.string.isspace(): - iterator = iterator.previous - - ending_space = len(iterator.string) - len(iterator.string.rstrip()) - iterator.string = '%s=%s' % (iterator.string.rstrip(), - ' ' * ending_space) - - # Create a new flag object with updated type info. - token.attached_object = javascriptstatetracker.JsDocFlag(token) - self._AddFix(token) - - elif code == errors.JSDOC_MISSING_VAR_ARGS_TYPE: - iterator = token.attached_object.type_start_token - if iterator.type == Type.DOC_START_BRACE or iterator.string.isspace(): - iterator = iterator.next - - starting_space = len(iterator.string) - len(iterator.string.lstrip()) - iterator.string = '%s...%s' % (' ' * starting_space, - iterator.string.lstrip()) - - # Create a new flag object with updated type info. - token.attached_object = javascriptstatetracker.JsDocFlag(token) - self._AddFix(token) - - elif code in (errors.MISSING_SEMICOLON_AFTER_FUNCTION, - errors.MISSING_SEMICOLON): - semicolon_token = Token(';', Type.SEMICOLON, token.line, - token.line_number) - tokenutil.InsertTokenAfter(semicolon_token, token) - token.metadata.is_implied_semicolon = False - semicolon_token.metadata.is_implied_semicolon = False - self._AddFix(token) - - elif code in (errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, - errors.REDUNDANT_SEMICOLON, - errors.COMMA_AT_END_OF_LITERAL): - self._DeleteToken(token) - self._AddFix(token) - - elif code == errors.INVALID_JSDOC_TAG: - if token.string == '@returns': - token.string = '@return' - self._AddFix(token) - - elif code == errors.FILE_MISSING_NEWLINE: - # This error is fixed implicitly by the way we restore the file - self._AddFix(token) - - elif code == errors.MISSING_SPACE: - if error.fix_data: - token.string = error.fix_data - self._AddFix(token) - elif error.position: - if error.position.IsAtBeginning(): - tokenutil.InsertSpaceTokenAfter(token.previous) - elif error.position.IsAtEnd(token.string): - tokenutil.InsertSpaceTokenAfter(token) - else: - token.string = error.position.Set(token.string, ' ') - self._AddFix(token) - - elif code == errors.EXTRA_SPACE: - if error.position: - token.string = error.position.Set(token.string, '') - self._AddFix(token) - - elif code == errors.MISSING_LINE: - if error.position.IsAtBeginning(): - tokenutil.InsertBlankLineAfter(token.previous) - else: - tokenutil.InsertBlankLineAfter(token) - self._AddFix(token) - - elif code == errors.EXTRA_LINE: - self._DeleteToken(token) - self._AddFix(token) - - elif code == errors.WRONG_BLANK_LINE_COUNT: - if not token.previous: - # TODO(user): Add an insertBefore method to tokenutil. - return - - num_lines = error.fix_data - should_delete = False - - if num_lines < 0: - num_lines *= -1 - should_delete = True - - for unused_i in xrange(1, num_lines + 1): - if should_delete: - # TODO(user): DeleteToken should update line numbers. - self._DeleteToken(token.previous) - else: - tokenutil.InsertBlankLineAfter(token.previous) - self._AddFix(token) - - elif code == errors.UNNECESSARY_DOUBLE_QUOTED_STRING: - end_quote = tokenutil.Search(token, Type.DOUBLE_QUOTE_STRING_END) - if end_quote: - single_quote_start = Token( - "'", Type.SINGLE_QUOTE_STRING_START, token.line, token.line_number) - single_quote_end = Token( - "'", Type.SINGLE_QUOTE_STRING_START, end_quote.line, - token.line_number) - - tokenutil.InsertTokenAfter(single_quote_start, token) - tokenutil.InsertTokenAfter(single_quote_end, end_quote) - self._DeleteToken(token) - self._DeleteToken(end_quote) - self._AddFix([token, end_quote]) - - elif code == errors.MISSING_BRACES_AROUND_TYPE: - fixed_tokens = [] - start_token = token.attached_object.type_start_token - - if start_token.type != Type.DOC_START_BRACE: - leading_space = ( - len(start_token.string) - len(start_token.string.lstrip())) - if leading_space: - start_token = tokenutil.SplitToken(start_token, leading_space) - # Fix case where start and end token were the same. - if token.attached_object.type_end_token == start_token.previous: - token.attached_object.type_end_token = start_token - - new_token = Token('{', Type.DOC_START_BRACE, start_token.line, - start_token.line_number) - tokenutil.InsertTokenAfter(new_token, start_token.previous) - token.attached_object.type_start_token = new_token - fixed_tokens.append(new_token) - - end_token = token.attached_object.type_end_token - if end_token.type != Type.DOC_END_BRACE: - # If the start token was a brace, the end token will be a - # FLAG_ENDING_TYPE token, if there wasn't a starting brace then - # the end token is the last token of the actual type. - last_type = end_token - if not fixed_tokens: - last_type = end_token.previous - - while last_type.string.isspace(): - last_type = last_type.previous - - # If there was no starting brace then a lone end brace wouldn't have - # been type end token. Now that we've added any missing start brace, - # see if the last effective type token was an end brace. - if last_type.type != Type.DOC_END_BRACE: - trailing_space = (len(last_type.string) - - len(last_type.string.rstrip())) - if trailing_space: - tokenutil.SplitToken(last_type, - len(last_type.string) - trailing_space) - - new_token = Token('}', Type.DOC_END_BRACE, last_type.line, - last_type.line_number) - tokenutil.InsertTokenAfter(new_token, last_type) - token.attached_object.type_end_token = new_token - fixed_tokens.append(new_token) - - self._AddFix(fixed_tokens) - - elif code == errors.LINE_STARTS_WITH_OPERATOR: - # Remove whitespace following the operator so the line starts clean. - self._StripSpace(token, before=False) - - # Remove the operator. - tokenutil.DeleteToken(token) - self._AddFix(token) - - insertion_point = tokenutil.GetPreviousCodeToken(token) - - # Insert a space between the previous token and the new operator. - space = Token(' ', Type.WHITESPACE, insertion_point.line, - insertion_point.line_number) - tokenutil.InsertTokenAfter(space, insertion_point) - - # Insert the operator on the end of the previous line. - new_token = Token(token.string, token.type, insertion_point.line, - insertion_point.line_number) - tokenutil.InsertTokenAfter(new_token, space) - self._AddFix(new_token) - - elif code == errors.LINE_ENDS_WITH_DOT: - # Remove whitespace preceding the operator to remove trailing whitespace. - self._StripSpace(token, before=True) - - # Remove the dot. - tokenutil.DeleteToken(token) - self._AddFix(token) - - insertion_point = tokenutil.GetNextCodeToken(token) - - # Insert the dot at the beginning of the next line of code. - new_token = Token(token.string, token.type, insertion_point.line, - insertion_point.line_number) - tokenutil.InsertTokenBefore(new_token, insertion_point) - self._AddFix(new_token) - - elif code == errors.GOOG_REQUIRES_NOT_ALPHABETIZED: - require_start_token = error.fix_data - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixRequires(require_start_token) - - self._AddFix(require_start_token) - - elif code == errors.GOOG_PROVIDES_NOT_ALPHABETIZED: - provide_start_token = error.fix_data - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixProvides(provide_start_token) - - self._AddFix(provide_start_token) - - elif code == errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC: - if token.previous.string == '{' and token.next.string == '}': - self._DeleteToken(token.previous) - self._DeleteToken(token.next) - self._AddFix([token]) - - elif code == errors.INVALID_AUTHOR_TAG_DESCRIPTION: - match = INVERTED_AUTHOR_SPEC.match(token.string) - if match: - token.string = '%s%s%s(%s)%s' % (match.group('leading_whitespace'), - match.group('email'), - match.group('whitespace_after_name'), - match.group('name'), - match.group('trailing_characters')) - self._AddFix(token) - - elif (code == errors.WRONG_INDENTATION and - not FLAGS.disable_indentation_fixing): - token = tokenutil.GetFirstTokenInSameLine(token) - actual = error.position.start - expected = error.position.length - - # Cases where first token is param but with leading spaces. - if (len(token.string.lstrip()) == len(token.string) - actual and - token.string.lstrip()): - token.string = token.string.lstrip() - actual = 0 - - if token.type in (Type.WHITESPACE, Type.PARAMETERS) and actual != 0: - token.string = token.string.lstrip() + (' ' * expected) - self._AddFix([token]) - else: - # We need to add indentation. - new_token = Token(' ' * expected, Type.WHITESPACE, - token.line, token.line_number) - # Note that we'll never need to add indentation at the first line, - # since it will always not be indented. Therefore it's safe to assume - # token.previous exists. - tokenutil.InsertTokenAfter(new_token, token.previous) - self._AddFix([token]) - - elif code in [errors.MALFORMED_END_OF_SCOPE_COMMENT, - errors.MISSING_END_OF_SCOPE_COMMENT]: - # Only fix cases where }); is found with no trailing content on the line - # other than a comment. Value of 'token' is set to } for this error. - if (token.type == Type.END_BLOCK and - token.next.type == Type.END_PAREN and - token.next.next.type == Type.SEMICOLON): - current_token = token.next.next.next - removed_tokens = [] - while current_token and current_token.line_number == token.line_number: - if current_token.IsAnyType(Type.WHITESPACE, - Type.START_SINGLE_LINE_COMMENT, - Type.COMMENT): - removed_tokens.append(current_token) - current_token = current_token.next - else: - return - - if removed_tokens: - self._DeleteTokens(removed_tokens[0], len(removed_tokens)) - - whitespace_token = Token(' ', Type.WHITESPACE, token.line, - token.line_number) - start_comment_token = Token('//', Type.START_SINGLE_LINE_COMMENT, - token.line, token.line_number) - comment_token = Token(' goog.scope', Type.COMMENT, token.line, - token.line_number) - insertion_tokens = [whitespace_token, start_comment_token, - comment_token] - - tokenutil.InsertTokensAfter(insertion_tokens, token.next.next) - self._AddFix(removed_tokens + insertion_tokens) - - elif code in [errors.EXTRA_GOOG_PROVIDE, errors.EXTRA_GOOG_REQUIRE]: - tokens_in_line = tokenutil.GetAllTokensInSameLine(token) - num_delete_tokens = len(tokens_in_line) - # If line being deleted is preceded and succeed with blank lines then - # delete one blank line also. - if (tokens_in_line[0].previous and tokens_in_line[-1].next - and tokens_in_line[0].previous.type == Type.BLANK_LINE - and tokens_in_line[-1].next.type == Type.BLANK_LINE): - num_delete_tokens += 1 - self._DeleteTokens(tokens_in_line[0], num_delete_tokens) - self._AddFix(tokens_in_line) - - elif code in [errors.MISSING_GOOG_PROVIDE, errors.MISSING_GOOG_REQUIRE]: - missing_namespaces = error.fix_data[0] - need_blank_line = error.fix_data[1] or (not token.previous) - - insert_location = Token('', Type.NORMAL, '', token.line_number - 1) - dummy_first_token = insert_location - tokenutil.InsertTokenBefore(insert_location, token) - - # If inserting a blank line check blank line does not exist before - # token to avoid extra blank lines. - if (need_blank_line and insert_location.previous - and insert_location.previous.type != Type.BLANK_LINE): - tokenutil.InsertBlankLineAfter(insert_location) - insert_location = insert_location.next - - for missing_namespace in missing_namespaces: - new_tokens = self._GetNewRequireOrProvideTokens( - code == errors.MISSING_GOOG_PROVIDE, - missing_namespace, insert_location.line_number + 1) - tokenutil.InsertLineAfter(insert_location, new_tokens) - insert_location = new_tokens[-1] - self._AddFix(new_tokens) - - # If inserting a blank line check blank line does not exist after - # token to avoid extra blank lines. - if (need_blank_line and insert_location.next - and insert_location.next.type != Type.BLANK_LINE): - tokenutil.InsertBlankLineAfter(insert_location) - - tokenutil.DeleteToken(dummy_first_token) - - def _StripSpace(self, token, before): - """Strip whitespace tokens either preceding or following the given token. - - Args: - token: The token. - before: If true, strip space before the token, if false, after it. - """ - token = token.previous if before else token.next - while token and token.type == Type.WHITESPACE: - tokenutil.DeleteToken(token) - token = token.previous if before else token.next - - def _GetNewRequireOrProvideTokens(self, is_provide, namespace, line_number): - """Returns a list of tokens to create a goog.require/provide statement. - - Args: - is_provide: True if getting tokens for a provide, False for require. - namespace: The required or provided namespaces to get tokens for. - line_number: The line number the new require or provide statement will be - on. - - Returns: - Tokens to create a new goog.require or goog.provide statement. - """ - string = 'goog.require' - if is_provide: - string = 'goog.provide' - line_text = string + '(\'' + namespace + '\');\n' - return [ - Token(string, Type.IDENTIFIER, line_text, line_number), - Token('(', Type.START_PAREN, line_text, line_number), - Token('\'', Type.SINGLE_QUOTE_STRING_START, line_text, line_number), - Token(namespace, Type.STRING_TEXT, line_text, line_number), - Token('\'', Type.SINGLE_QUOTE_STRING_END, line_text, line_number), - Token(')', Type.END_PAREN, line_text, line_number), - Token(';', Type.SEMICOLON, line_text, line_number) - ] - - def _DeleteToken(self, token): - """Deletes the specified token from the linked list of tokens. - - Updates instance variables pointing to tokens such as _file_token if - they reference the deleted token. - - Args: - token: The token to delete. - """ - if token == self._file_token: - self._file_token = token.next - - tokenutil.DeleteToken(token) - - def _DeleteTokens(self, token, token_count): - """Deletes the given number of tokens starting with the given token. - - Updates instance variables pointing to tokens such as _file_token if - they reference the deleted token. - - Args: - token: The first token to delete. - token_count: The total number of tokens to delete. - """ - if token == self._file_token: - for unused_i in xrange(token_count): - self._file_token = self._file_token.next - - tokenutil.DeleteTokens(token, token_count) - - def FinishFile(self): - """Called when the current file has finished style checking. - - Used to go back and fix any errors in the file. It currently supports both - js and html files. For js files it does a simple dump of all tokens, but in - order to support html file, we need to merge the original file with the new - token set back together. This works because the tokenized html file is the - original html file with all non js lines kept but blanked out with one blank - line token per line of html. - """ - if self._file_fix_count: - # Get the original file content for html. - if self._file_is_html: - f = open(self._file_name, 'r') - original_lines = f.readlines() - f.close() - - f = self._external_file - if not f: - error_noun = 'error' if self._file_fix_count == 1 else 'errors' - print 'Fixed %d %s in %s' % ( - self._file_fix_count, error_noun, self._file_name) - f = open(self._file_name, 'w') - - token = self._file_token - # Finding the first not deleted token. - while token.is_deleted: - token = token.next - # If something got inserted before first token (e.g. due to sorting) - # then move to start. Bug 8398202. - while token.previous: - token = token.previous - char_count = 0 - line = '' - while token: - line += token.string - char_count += len(token.string) - - if token.IsLastInLine(): - # We distinguish if a blank line in html was from stripped original - # file or newly added error fix by looking at the "org_line_number" - # field on the token. It is only set in the tokenizer, so for all - # error fixes, the value should be None. - if (line or not self._file_is_html or - token.orig_line_number is None): - f.write(line) - f.write('\n') - else: - f.write(original_lines[token.orig_line_number - 1]) - line = '' - if char_count > 80 and token.line_number in self._file_changed_lines: - print 'WARNING: Line %d of %s is now longer than 80 characters.' % ( - token.line_number, self._file_name) - - char_count = 0 - - token = token.next - - if not self._external_file: - # Close the file if we created it - f.close() diff --git a/tools/closure_linter/build/lib/closure_linter/error_fixer_test.py b/tools/closure_linter/build/lib/closure_linter/error_fixer_test.py deleted file mode 100644 index 49f449de42f36f..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/error_fixer_test.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the error_fixer module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - - - -import unittest as googletest -from closure_linter import error_fixer -from closure_linter import testutil - - -class ErrorFixerTest(googletest.TestCase): - """Unit tests for error_fixer.""" - - def setUp(self): - self.error_fixer = error_fixer.ErrorFixer() - - def testDeleteToken(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCRIPT) - second_token = start_token.next - self.error_fixer.HandleFile('test_file', start_token) - - self.error_fixer._DeleteToken(start_token) - - self.assertEqual(second_token, self.error_fixer._file_token) - - def testDeleteTokens(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCRIPT) - fourth_token = start_token.next.next.next - self.error_fixer.HandleFile('test_file', start_token) - - self.error_fixer._DeleteTokens(start_token, 3) - - self.assertEqual(fourth_token, self.error_fixer._file_token) - -_TEST_SCRIPT = """\ -var x = 3; -""" - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/errorrecord.py b/tools/closure_linter/build/lib/closure_linter/errorrecord.py deleted file mode 100644 index ce9fb908c75e71..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/errorrecord.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -"""A simple, pickle-serializable class to represent a lint error.""" - -__author__ = 'nnaze@google.com (Nathan Naze)' - -import gflags as flags - -from closure_linter import errors -from closure_linter.common import erroroutput - -FLAGS = flags.FLAGS - - -class ErrorRecord(object): - """Record-keeping struct that can be serialized back from a process. - - Attributes: - path: Path to the file. - error_string: Error string for the user. - new_error: Whether this is a "new error" (see errors.NEW_ERRORS). - """ - - def __init__(self, path, error_string, new_error): - self.path = path - self.error_string = error_string - self.new_error = new_error - - -def MakeErrorRecord(path, error): - """Make an error record with correctly formatted error string. - - Errors are not able to be serialized (pickled) over processes because of - their pointers to the complex token/context graph. We use an intermediary - serializable class to pass back just the relevant information. - - Args: - path: Path of file the error was found in. - error: An error.Error instance. - - Returns: - _ErrorRecord instance. - """ - new_error = error.code in errors.NEW_ERRORS - - if FLAGS.unix_mode: - error_string = erroroutput.GetUnixErrorOutput( - path, error, new_error=new_error) - else: - error_string = erroroutput.GetErrorOutput(error, new_error=new_error) - - return ErrorRecord(path, error_string, new_error) diff --git a/tools/closure_linter/build/lib/closure_linter/errorrules.py b/tools/closure_linter/build/lib/closure_linter/errorrules.py deleted file mode 100644 index b1b72aab6dabdc..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/errorrules.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Linter error rules class for Closure Linter.""" - -__author__ = 'robbyw@google.com (Robert Walker)' - -import gflags as flags -from closure_linter import errors - - -FLAGS = flags.FLAGS -flags.DEFINE_boolean('jsdoc', True, - 'Whether to report errors for missing JsDoc.') -flags.DEFINE_list('disable', None, - 'Disable specific error. Usage Ex.: gjslint --disable 1,' - '0011 foo.js.') -flags.DEFINE_integer('max_line_length', 80, 'Maximum line length allowed ' - 'without warning.', lower_bound=1) - -disabled_error_nums = None - - -def GetMaxLineLength(): - """Returns allowed maximum length of line. - - Returns: - Length of line allowed without any warning. - """ - return FLAGS.max_line_length - - -def ShouldReportError(error): - """Whether the given error should be reported. - - Returns: - True for all errors except missing documentation errors and disabled - errors. For missing documentation, it returns the value of the - jsdoc flag. - """ - global disabled_error_nums - if disabled_error_nums is None: - disabled_error_nums = [] - if FLAGS.disable: - for error_str in FLAGS.disable: - error_num = 0 - try: - error_num = int(error_str) - except ValueError: - pass - disabled_error_nums.append(error_num) - - return ((FLAGS.jsdoc or error not in ( - errors.MISSING_PARAMETER_DOCUMENTATION, - errors.MISSING_RETURN_DOCUMENTATION, - errors.MISSING_MEMBER_DOCUMENTATION, - errors.MISSING_PRIVATE, - errors.MISSING_JSDOC_TAG_THIS)) and - (not FLAGS.disable or error not in disabled_error_nums)) diff --git a/tools/closure_linter/build/lib/closure_linter/errorrules_test.py b/tools/closure_linter/build/lib/closure_linter/errorrules_test.py deleted file mode 100644 index cb903785e60fec..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/errorrules_test.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# Copyright 2013 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Medium tests for the gjslint errorrules. - -Currently its just verifying that warnings can't be disabled. -""" - - - -import gflags as flags -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import erroraccumulator - -flags.FLAGS.strict = True -flags.FLAGS.limited_doc_files = ('dummy.js', 'externs.js') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') - - -class ErrorRulesTest(googletest.TestCase): - """Test case to for gjslint errorrules.""" - - def testNoMaxLineLengthFlagExists(self): - """Tests that --max_line_length flag does not exists.""" - self.assertTrue('max_line_length' not in flags.FLAGS.FlagDict()) - - def testGetMaxLineLength(self): - """Tests warning are reported for line greater than 80. - """ - - # One line > 100 and one line > 80 and < 100. So should produce two - # line too long error. - original = [ - 'goog.require(\'dummy.aa\');', - '', - 'function a() {', - ' dummy.aa.i = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13' - ' + 14 + 15 + 16 + 17 + 18 + 19 + 20;', - ' dummy.aa.j = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13' - ' + 14 + 15 + 16 + 17 + 18;', - '}', - '' - ] - - # Expect line too long. - expected = [errors.LINE_TOO_LONG, errors.LINE_TOO_LONG] - - self._AssertErrors(original, expected) - - def testNoDisableFlagExists(self): - """Tests that --disable flag does not exists.""" - self.assertTrue('disable' not in flags.FLAGS.FlagDict()) - - def testWarningsNotDisabled(self): - """Tests warnings are reported when nothing is disabled. - """ - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - '', - 'function a() {', - ' dummy.aa.i = 1;', - ' dummy.Cc.i = 1;', - ' dummy.Dd.i = 1;', - '}', - ] - - expected = [errors.GOOG_REQUIRES_NOT_ALPHABETIZED, - errors.FILE_MISSING_NEWLINE] - - self._AssertErrors(original, expected) - - def _AssertErrors(self, original, expected_errors, include_header=True): - """Asserts that the error fixer corrects original to expected.""" - if include_header: - original = self._GetHeader() + original - - # Trap gjslint's output parse it to get messages added. - error_accumulator = erroraccumulator.ErrorAccumulator() - runner.Run('testing.js', error_accumulator, source=original) - error_nums = [e.code for e in error_accumulator.GetErrors()] - - error_nums.sort() - expected_errors.sort() - self.assertListEqual(error_nums, expected_errors) - - def _GetHeader(self): - """Returns a fake header for a JavaScript file.""" - return [ - '// Copyright 2011 Google Inc. All Rights Reserved.', - '', - '/**', - ' * @fileoverview Fake file overview.', - ' * @author fake@google.com (Fake Person)', - ' */', - '' - ] - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/errors.py b/tools/closure_linter/build/lib/closure_linter/errors.py deleted file mode 100644 index 356ee0c5a6441d..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/errors.py +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Error codes for JavaScript style checker.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -def ByName(name): - """Get the error code for the given error name. - - Args: - name: The name of the error - - Returns: - The error code - """ - return globals()[name] - - -# "File-fatal" errors - these errors stop further parsing of a single file -FILE_NOT_FOUND = -1 -FILE_DOES_NOT_PARSE = -2 - -# Spacing -EXTRA_SPACE = 1 -MISSING_SPACE = 2 -EXTRA_LINE = 3 -MISSING_LINE = 4 -ILLEGAL_TAB = 5 -WRONG_INDENTATION = 6 -WRONG_BLANK_LINE_COUNT = 7 - -# Semicolons -MISSING_SEMICOLON = 10 -MISSING_SEMICOLON_AFTER_FUNCTION = 11 -ILLEGAL_SEMICOLON_AFTER_FUNCTION = 12 -REDUNDANT_SEMICOLON = 13 - -# Miscellaneous -ILLEGAL_PROTOTYPE_MEMBER_VALUE = 100 -LINE_TOO_LONG = 110 -LINE_STARTS_WITH_OPERATOR = 120 -COMMA_AT_END_OF_LITERAL = 121 -LINE_ENDS_WITH_DOT = 122 -MULTI_LINE_STRING = 130 -UNNECESSARY_DOUBLE_QUOTED_STRING = 131 -UNUSED_PRIVATE_MEMBER = 132 -UNUSED_LOCAL_VARIABLE = 133 - -# Requires, provides -GOOG_REQUIRES_NOT_ALPHABETIZED = 140 -GOOG_PROVIDES_NOT_ALPHABETIZED = 141 -MISSING_GOOG_REQUIRE = 142 -MISSING_GOOG_PROVIDE = 143 -EXTRA_GOOG_REQUIRE = 144 -EXTRA_GOOG_PROVIDE = 145 -ALIAS_STMT_NEEDS_GOOG_REQUIRE = 146 - -# JsDoc -INVALID_JSDOC_TAG = 200 -INVALID_USE_OF_DESC_TAG = 201 -NO_BUG_NUMBER_AFTER_BUG_TAG = 202 -MISSING_PARAMETER_DOCUMENTATION = 210 -EXTRA_PARAMETER_DOCUMENTATION = 211 -WRONG_PARAMETER_DOCUMENTATION = 212 -MISSING_JSDOC_TAG_TYPE = 213 -MISSING_JSDOC_TAG_DESCRIPTION = 214 -MISSING_JSDOC_PARAM_NAME = 215 -OUT_OF_ORDER_JSDOC_TAG_TYPE = 216 -MISSING_RETURN_DOCUMENTATION = 217 -UNNECESSARY_RETURN_DOCUMENTATION = 218 -MISSING_BRACES_AROUND_TYPE = 219 -MISSING_MEMBER_DOCUMENTATION = 220 -MISSING_PRIVATE = 221 -EXTRA_PRIVATE = 222 -INVALID_OVERRIDE_PRIVATE = 223 -INVALID_INHERIT_DOC_PRIVATE = 224 -MISSING_JSDOC_TAG_THIS = 225 -UNNECESSARY_BRACES_AROUND_INHERIT_DOC = 226 -INVALID_AUTHOR_TAG_DESCRIPTION = 227 -JSDOC_PREFER_QUESTION_TO_PIPE_NULL = 230 -JSDOC_ILLEGAL_QUESTION_WITH_PIPE = 231 -JSDOC_MISSING_OPTIONAL_TYPE = 232 -JSDOC_MISSING_OPTIONAL_PREFIX = 233 -JSDOC_MISSING_VAR_ARGS_TYPE = 234 -JSDOC_MISSING_VAR_ARGS_NAME = 235 -JSDOC_DOES_NOT_PARSE = 236 -# TODO(robbyw): Split this in to more specific syntax problems. -INCORRECT_SUPPRESS_SYNTAX = 250 -INVALID_SUPPRESS_TYPE = 251 -UNNECESSARY_SUPPRESS = 252 - -# File ending -FILE_MISSING_NEWLINE = 300 -FILE_IN_BLOCK = 301 - -# Interfaces -INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS = 400 -INTERFACE_METHOD_CANNOT_HAVE_CODE = 401 - -# Comments -MISSING_END_OF_SCOPE_COMMENT = 500 -MALFORMED_END_OF_SCOPE_COMMENT = 501 - -# goog.scope - Namespace aliasing -# TODO(nnaze) Add additional errors here and in aliaspass.py -INVALID_USE_OF_GOOG_SCOPE = 600 -EXTRA_GOOG_SCOPE_USAGE = 601 - -# ActionScript specific errors: -# TODO(user): move these errors to their own file and move all JavaScript -# specific errors to their own file as well. -# All ActionScript specific errors should have error number at least 1000. -FUNCTION_MISSING_RETURN_TYPE = 1132 -PARAMETER_MISSING_TYPE = 1133 -VAR_MISSING_TYPE = 1134 -PARAMETER_MISSING_DEFAULT_VALUE = 1135 -IMPORTS_NOT_ALPHABETIZED = 1140 -IMPORT_CONTAINS_WILDCARD = 1141 -UNUSED_IMPORT = 1142 -INVALID_TRACE_SEVERITY_LEVEL = 1250 -MISSING_TRACE_SEVERITY_LEVEL = 1251 -MISSING_TRACE_MESSAGE = 1252 -REMOVE_TRACE_BEFORE_SUBMIT = 1253 -REMOVE_COMMENT_BEFORE_SUBMIT = 1254 -# End of list of ActionScript specific errors. - -NEW_ERRORS = frozenset([ - # Errors added after 2.0.2: - WRONG_INDENTATION, - MISSING_SEMICOLON, - # Errors added after 2.3.9: - JSDOC_MISSING_VAR_ARGS_TYPE, - JSDOC_MISSING_VAR_ARGS_NAME, - # Errors added after 2.3.15: - ALIAS_STMT_NEEDS_GOOG_REQUIRE, - JSDOC_DOES_NOT_PARSE, - LINE_ENDS_WITH_DOT, - # Errors added after 2.3.17: - ]) diff --git a/tools/closure_linter/build/lib/closure_linter/fixjsstyle.py b/tools/closure_linter/build/lib/closure_linter/fixjsstyle.py deleted file mode 100644 index 2d65e0398fdcc6..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/fixjsstyle.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Automatically fix simple style guide violations.""" - -__author__ = 'robbyw@google.com (Robert Walker)' - -import StringIO -import sys - -import gflags as flags - -from closure_linter import error_fixer -from closure_linter import runner -from closure_linter.common import simplefileflags as fileflags - -FLAGS = flags.FLAGS -flags.DEFINE_list('additional_extensions', None, 'List of additional file ' - 'extensions (not js) that should be treated as ' - 'JavaScript files.') -flags.DEFINE_boolean('dry_run', False, 'Do not modify the file, only print it.') - - -def main(argv=None): - """Main function. - - Args: - argv: Sequence of command line arguments. - """ - if argv is None: - argv = flags.FLAGS(sys.argv) - - suffixes = ['.js'] - if FLAGS.additional_extensions: - suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] - - files = fileflags.GetFileList(argv, 'JavaScript', suffixes) - - output_buffer = None - if FLAGS.dry_run: - output_buffer = StringIO.StringIO() - - fixer = error_fixer.ErrorFixer(output_buffer) - - # Check the list of files. - for filename in files: - runner.Run(filename, fixer) - if FLAGS.dry_run: - print output_buffer.getvalue() - - -if __name__ == '__main__': - main() diff --git a/tools/closure_linter/build/lib/closure_linter/fixjsstyle_test.py b/tools/closure_linter/build/lib/closure_linter/fixjsstyle_test.py deleted file mode 100644 index 34de3f8488d351..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/fixjsstyle_test.py +++ /dev/null @@ -1,615 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Medium tests for the gpylint auto-fixer.""" - -__author__ = 'robbyw@google.com (Robby Walker)' - -import StringIO - -import gflags as flags -import unittest as googletest -from closure_linter import error_fixer -from closure_linter import runner - - -_RESOURCE_PREFIX = 'closure_linter/testdata' - -flags.FLAGS.strict = True -flags.FLAGS.limited_doc_files = ('dummy.js', 'externs.js') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') - - -class FixJsStyleTest(googletest.TestCase): - """Test case to for gjslint auto-fixing.""" - - def setUp(self): - flags.FLAGS.dot_on_next_line = True - - def tearDown(self): - flags.FLAGS.dot_on_next_line = False - - def testFixJsStyle(self): - test_cases = [ - ['fixjsstyle.in.js', 'fixjsstyle.out.js'], - ['indentation.js', 'fixjsstyle.indentation.out.js'], - ['fixjsstyle.html.in.html', 'fixjsstyle.html.out.html'], - ['fixjsstyle.oplineend.in.js', 'fixjsstyle.oplineend.out.js']] - for [running_input_file, running_output_file] in test_cases: - print 'Checking %s vs %s' % (running_input_file, running_output_file) - input_filename = None - golden_filename = None - current_filename = None - try: - input_filename = '%s/%s' % (_RESOURCE_PREFIX, running_input_file) - current_filename = input_filename - - golden_filename = '%s/%s' % (_RESOURCE_PREFIX, running_output_file) - current_filename = golden_filename - except IOError as ex: - raise IOError('Could not find testdata resource for %s: %s' % - (current_filename, ex)) - - if running_input_file == 'fixjsstyle.in.js': - with open(input_filename) as f: - for line in f: - # Go to last line. - pass - self.assertTrue(line == line.rstrip(), '%s file should not end ' - 'with a new line.' % (input_filename)) - - # Autofix the file, sending output to a fake file. - actual = StringIO.StringIO() - runner.Run(input_filename, error_fixer.ErrorFixer(actual)) - - # Now compare the files. - actual.seek(0) - expected = open(golden_filename, 'r') - - # Uncomment to generate new golden files and run - # open('/'.join(golden_filename.split('/')[4:]), 'w').write(actual.read()) - # actual.seek(0) - - self.assertEqual(actual.readlines(), expected.readlines()) - - def testAddProvideFirstLine(self): - """Tests handling of case where goog.provide is added.""" - original = [ - 'dummy.bb.cc = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.bb\');', - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testAddRequireFirstLine(self): - """Tests handling of case where goog.require is added.""" - original = [ - 'a = dummy.bb.cc;', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteProvideAndAddProvideFirstLine(self): - """Tests handling of case where goog.provide is deleted and added. - - Bug 14832597. - """ - original = [ - 'goog.provide(\'dummy.aa\');', - '', - 'dummy.bb.cc = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.bb\');', - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.provide(\'dummy.aa\');', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteProvideAndAddRequireFirstLine(self): - """Tests handling where goog.provide is deleted and goog.require added. - - Bug 14832597. - """ - original = [ - 'goog.provide(\'dummy.aa\');', - '', - 'a = dummy.bb.cc;', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.provide(\'dummy.aa\');', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteRequireAndAddRequireFirstLine(self): - """Tests handling of case where goog.require is deleted and added. - - Bug 14832597. - """ - original = [ - 'goog.require(\'dummy.aa\');', - '', - 'a = dummy.bb.cc;', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.require(\'dummy.aa\');', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteRequireAndAddProvideFirstLine(self): - """Tests handling where goog.require is deleted and goog.provide added. - - Bug 14832597. - """ - original = [ - 'goog.require(\'dummy.aa\');', - '', - 'dummy.bb.cc = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.bb\');', - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.require(\'dummy.aa\');', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMultipleProvideInsert(self): - original = [ - 'goog.provide(\'dummy.bb\');', - 'goog.provide(\'dummy.dd\');', - '', - 'dummy.aa.ff = 1;', - 'dummy.bb.ff = 1;', - 'dummy.cc.ff = 1;', - 'dummy.dd.ff = 1;', - 'dummy.ee.ff = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.aa\');', - 'goog.provide(\'dummy.bb\');', - 'goog.provide(\'dummy.cc\');', - 'goog.provide(\'dummy.dd\');', - 'goog.provide(\'dummy.ee\');', - '', - 'dummy.aa.ff = 1;', - 'dummy.bb.ff = 1;', - 'dummy.cc.ff = 1;', - 'dummy.dd.ff = 1;', - 'dummy.ee.ff = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMultipleRequireInsert(self): - original = [ - 'goog.require(\'dummy.bb\');', - 'goog.require(\'dummy.dd\');', - '', - 'a = dummy.aa.ff;', - 'b = dummy.bb.ff;', - 'c = dummy.cc.ff;', - 'd = dummy.dd.ff;', - 'e = dummy.ee.ff;', - ] - - expected = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.bb\');', - 'goog.require(\'dummy.cc\');', - 'goog.require(\'dummy.dd\');', - 'goog.require(\'dummy.ee\');', - '', - 'a = dummy.aa.ff;', - 'b = dummy.bb.ff;', - 'c = dummy.cc.ff;', - 'd = dummy.dd.ff;', - 'e = dummy.ee.ff;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testUnsortedRequires(self): - """Tests handling of unsorted goog.require statements without header. - - Bug 8398202. - """ - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - '', - 'function a() {', - ' dummy.aa.i = 1;', - ' dummy.Cc.i = 1;', - ' dummy.Dd.i = 1;', - '}', - ] - - expected = [ - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - 'goog.require(\'dummy.aa\');', - '', - 'function a() {', - ' dummy.aa.i = 1;', - ' dummy.Cc.i = 1;', - ' dummy.Dd.i = 1;', - '}', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMissingExtraAndUnsortedRequires(self): - """Tests handling of missing extra and unsorted goog.require statements.""" - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - '', - 'var x = new dummy.Bb();', - 'dummy.Cc.someMethod();', - 'dummy.aa.someMethod();', - ] - - expected = [ - 'goog.require(\'dummy.Bb\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.aa\');', - '', - 'var x = new dummy.Bb();', - 'dummy.Cc.someMethod();', - 'dummy.aa.someMethod();', - ] - - self._AssertFixes(original, expected) - - def testExtraRequireOnFirstLine(self): - """Tests handling of extra goog.require statement on the first line. - - There was a bug when fixjsstyle quits with an exception. It happened if - - the first line of the file is an extra goog.require() statement, - - goog.require() statements are not sorted. - """ - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.cc\');', - 'goog.require(\'dummy.bb\');', - '', - 'var x = new dummy.bb();', - 'var y = new dummy.cc();', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - 'goog.require(\'dummy.cc\');', - '', - 'var x = new dummy.bb();', - 'var y = new dummy.cc();', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testUnsortedProvides(self): - """Tests handling of unsorted goog.provide statements without header. - - Bug 8398202. - """ - original = [ - 'goog.provide(\'dummy.aa\');', - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.Dd\');', - '', - 'dummy.aa = function() {};' - 'dummy.Cc = function() {};' - 'dummy.Dd = function() {};' - ] - - expected = [ - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.Dd\');', - 'goog.provide(\'dummy.aa\');', - '', - 'dummy.aa = function() {};' - 'dummy.Cc = function() {};' - 'dummy.Dd = function() {};' - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMissingExtraAndUnsortedProvides(self): - """Tests handling of missing extra and unsorted goog.provide statements.""" - original = [ - 'goog.provide(\'dummy.aa\');', - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.Dd\');', - '', - 'dummy.Cc = function() {};', - 'dummy.Bb = function() {};', - 'dummy.aa.someMethod = function();', - ] - - expected = [ - 'goog.provide(\'dummy.Bb\');', - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.aa\');', - '', - 'dummy.Cc = function() {};', - 'dummy.Bb = function() {};', - 'dummy.aa.someMethod = function();', - ] - - self._AssertFixes(original, expected) - - def testNoRequires(self): - """Tests positioning of missing requires without existing requires.""" - original = [ - 'goog.provide(\'dummy.Something\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - expected = [ - 'goog.provide(\'dummy.Something\');', - '', - 'goog.require(\'dummy.Bb\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - self._AssertFixes(original, expected) - - def testNoProvides(self): - """Tests positioning of missing provides without existing provides.""" - original = [ - 'goog.require(\'dummy.Bb\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - expected = [ - 'goog.provide(\'dummy.Something\');', - '', - 'goog.require(\'dummy.Bb\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - self._AssertFixes(original, expected) - - def testOutputOkayWhenFirstTokenIsDeleted(self): - """Tests that autofix output is is correct when first token is deleted. - - Regression test for bug 4581567 - """ - original = ['"use strict";'] - expected = ["'use strict';"] - - self._AssertFixes(original, expected, include_header=False) - - def testGoogScopeIndentation(self): - """Tests Handling a typical end-of-scope indentation fix.""" - original = [ - 'goog.scope(function() {', - ' // TODO(brain): Take over the world.', - '}); // goog.scope', - ] - - expected = [ - 'goog.scope(function() {', - '// TODO(brain): Take over the world.', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testMissingEndOfScopeComment(self): - """Tests Handling a missing comment at end of goog.scope.""" - original = [ - 'goog.scope(function() {', - '});', - ] - - expected = [ - 'goog.scope(function() {', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testMissingEndOfScopeCommentWithOtherComment(self): - """Tests handling an irrelevant comment at end of goog.scope.""" - original = [ - 'goog.scope(function() {', - "}); // I don't belong here!", - ] - - expected = [ - 'goog.scope(function() {', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testMalformedEndOfScopeComment(self): - """Tests Handling a malformed comment at end of goog.scope.""" - original = [ - 'goog.scope(function() {', - '}); // goog.scope FTW', - ] - - expected = [ - 'goog.scope(function() {', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testEndsWithIdentifier(self): - """Tests Handling case where script ends with identifier. Bug 7643404.""" - original = [ - 'goog.provide(\'xyz\');', - '', - 'abc' - ] - - expected = [ - 'goog.provide(\'xyz\');', - '', - 'abc;' - ] - - self._AssertFixes(original, expected) - - def testFileStartsWithSemicolon(self): - """Tests handling files starting with semicolon. - - b/10062516 - """ - original = [ - ';goog.provide(\'xyz\');', - '', - 'abc;' - ] - - expected = [ - 'goog.provide(\'xyz\');', - '', - 'abc;' - ] - - self._AssertFixes(original, expected, include_header=False) - - def testCodeStartsWithSemicolon(self): - """Tests handling code in starting with semicolon after comments. - - b/10062516 - """ - original = [ - ';goog.provide(\'xyz\');', - '', - 'abc;' - ] - - expected = [ - 'goog.provide(\'xyz\');', - '', - 'abc;' - ] - - self._AssertFixes(original, expected) - - def _AssertFixes(self, original, expected, include_header=True): - """Asserts that the error fixer corrects original to expected.""" - if include_header: - original = self._GetHeader() + original - expected = self._GetHeader() + expected - - actual = StringIO.StringIO() - runner.Run('testing.js', error_fixer.ErrorFixer(actual), original) - actual.seek(0) - - expected = [x + '\n' for x in expected] - - self.assertListEqual(actual.readlines(), expected) - - def _GetHeader(self): - """Returns a fake header for a JavaScript file.""" - return [ - '// Copyright 2011 Google Inc. All Rights Reserved.', - '', - '/**', - ' * @fileoverview Fake file overview.', - ' * @author fake@google.com (Fake Person)', - ' */', - '' - ] - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/full_test.py b/tools/closure_linter/build/lib/closure_linter/full_test.py deleted file mode 100644 index d0a1557dc23dbe..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/full_test.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Full regression-type (Medium) tests for gjslint. - -Tests every error that can be thrown by gjslint. Based heavily on -devtools/javascript/gpylint/full_test.py -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import os -import sys -import unittest - -import gflags as flags -import unittest as googletest - -from closure_linter import error_check -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import filetestcase - -_RESOURCE_PREFIX = 'closure_linter/testdata' - -flags.FLAGS.strict = True -flags.FLAGS.custom_jsdoc_tags = ('customtag', 'requires') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') -flags.FLAGS.limited_doc_files = ('externs.js', 'dummy.js', - 'limited_doc_checks.js') -flags.FLAGS.jslint_error = error_check.Rule.ALL - -# List of files under testdata to test. -# We need to list files explicitly since pyglib can't list directories. -# TODO(user): Figure out how to list the directory. -_TEST_FILES = [ - 'all_js_wrapped.js', - 'blank_lines.js', - 'ends_with_block.js', - 'empty_file.js', - 'externs.js', - 'externs_jsdoc.js', - 'goog_scope.js', - 'html_parse_error.html', - 'indentation.js', - 'interface.js', - 'jsdoc.js', - 'limited_doc_checks.js', - 'minimal.js', - 'other.js', - 'provide_blank.js', - 'provide_extra.js', - 'provide_missing.js', - 'require_alias.js', - 'require_all_caps.js', - 'require_blank.js', - 'require_extra.js', - 'require_function.js', - 'require_function_missing.js', - 'require_function_through_both.js', - 'require_function_through_namespace.js', - 'require_interface.js', - 'require_interface_alias.js', - 'require_interface_base.js', - 'require_lower_case.js', - 'require_missing.js', - 'require_numeric.js', - 'require_provide_blank.js', - 'require_provide_missing.js', - 'require_provide_ok.js', - 'semicolon_missing.js', - 'simple.html', - 'spaces.js', - 'tokenizer.js', - 'unparseable.js', - 'unused_local_variables.js', - 'unused_private_members.js', - 'utf8.html', -] - - -class GJsLintTestSuite(unittest.TestSuite): - """Test suite to run a GJsLintTest for each of several files. - - If sys.argv[1:] is non-empty, it is interpreted as a list of filenames in - testdata to test. Otherwise, _TEST_FILES is used. - """ - - def __init__(self, tests=()): - unittest.TestSuite.__init__(self, tests) - - argv = sys.argv and sys.argv[1:] or [] - if argv: - test_files = argv - else: - test_files = _TEST_FILES - for test_file in test_files: - resource_path = os.path.join(_RESOURCE_PREFIX, test_file) - self.addTest( - filetestcase.AnnotatedFileTestCase( - resource_path, - runner.Run, - errors.ByName)) - -if __name__ == '__main__': - # Don't let main parse args; it happens in the TestSuite. - googletest.main(argv=sys.argv[0:1], defaultTest='GJsLintTestSuite') diff --git a/tools/closure_linter/build/lib/closure_linter/gjslint.py b/tools/closure_linter/build/lib/closure_linter/gjslint.py deleted file mode 100644 index 824e025dcb00de..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/gjslint.py +++ /dev/null @@ -1,319 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Checks JavaScript files for common style guide violations. - -gjslint.py is designed to be used as a PRESUBMIT script to check for javascript -style guide violations. As of now, it checks for the following violations: - - * Missing and extra spaces - * Lines longer than 80 characters - * Missing newline at end of file - * Missing semicolon after function declaration - * Valid JsDoc including parameter matching - -Someday it will validate to the best of its ability against the entirety of the -JavaScript style guide. - -This file is a front end that parses arguments and flags. The core of the code -is in tokenizer.py and checker.py. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'nnaze@google.com (Nathan Naze)',) - -import errno -import itertools -import os -import platform -import re -import sys -import time - -import gflags as flags - -from closure_linter import errorrecord -from closure_linter import runner -from closure_linter.common import erroraccumulator -from closure_linter.common import simplefileflags as fileflags - -# Attempt import of multiprocessing (should be available in Python 2.6 and up). -try: - # pylint: disable=g-import-not-at-top - import multiprocessing -except ImportError: - multiprocessing = None - -FLAGS = flags.FLAGS -flags.DEFINE_boolean('unix_mode', False, - 'Whether to emit warnings in standard unix format.') -flags.DEFINE_boolean('beep', True, 'Whether to beep when errors are found.') -flags.DEFINE_boolean('time', False, 'Whether to emit timing statistics.') -flags.DEFINE_boolean('quiet', False, 'Whether to minimize logged messages. ' - 'Most useful for per-file linting, such as that performed ' - 'by the presubmit linter service.') -flags.DEFINE_boolean('check_html', False, - 'Whether to check javascript in html files.') -flags.DEFINE_boolean('summary', False, - 'Whether to show an error count summary.') -flags.DEFINE_list('additional_extensions', None, 'List of additional file ' - 'extensions (not js) that should be treated as ' - 'JavaScript files.') -flags.DEFINE_boolean('multiprocess', - platform.system() is 'Linux' and bool(multiprocessing), - 'Whether to attempt parallelized linting using the ' - 'multiprocessing module. Enabled by default on Linux ' - 'if the multiprocessing module is present (Python 2.6+). ' - 'Otherwise disabled by default. ' - 'Disabling may make debugging easier.') -flags.ADOPT_module_key_flags(fileflags) -flags.ADOPT_module_key_flags(runner) - - -GJSLINT_ONLY_FLAGS = ['--unix_mode', '--beep', '--nobeep', '--time', - '--check_html', '--summary', '--quiet'] - - - -def _MultiprocessCheckPaths(paths): - """Run _CheckPath over mutltiple processes. - - Tokenization, passes, and checks are expensive operations. Running in a - single process, they can only run on one CPU/core. Instead, - shard out linting over all CPUs with multiprocessing to parallelize. - - Args: - paths: paths to check. - - Yields: - errorrecord.ErrorRecords for any found errors. - """ - - pool = multiprocessing.Pool() - - path_results = pool.imap(_CheckPath, paths) - for results in path_results: - for result in results: - yield result - - # Force destruct before returning, as this can sometimes raise spurious - # "interrupted system call" (EINTR), which we can ignore. - try: - pool.close() - pool.join() - del pool - except OSError as err: - if err.errno is not errno.EINTR: - raise err - - -def _CheckPaths(paths): - """Run _CheckPath on all paths in one thread. - - Args: - paths: paths to check. - - Yields: - errorrecord.ErrorRecords for any found errors. - """ - - for path in paths: - results = _CheckPath(path) - for record in results: - yield record - - -def _CheckPath(path): - """Check a path and return any errors. - - Args: - path: paths to check. - - Returns: - A list of errorrecord.ErrorRecords for any found errors. - """ - - error_handler = erroraccumulator.ErrorAccumulator() - runner.Run(path, error_handler) - - make_error_record = lambda err: errorrecord.MakeErrorRecord(path, err) - return map(make_error_record, error_handler.GetErrors()) - - -def _GetFilePaths(argv): - suffixes = ['.js'] - if FLAGS.additional_extensions: - suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] - if FLAGS.check_html: - suffixes += ['.html', '.htm'] - return fileflags.GetFileList(argv, 'JavaScript', suffixes) - - -# Error printing functions - - -def _PrintFileSummary(paths, records): - """Print a detailed summary of the number of errors in each file.""" - - paths = list(paths) - paths.sort() - - for path in paths: - path_errors = [e for e in records if e.path == path] - print '%s: %d' % (path, len(path_errors)) - - -def _PrintFileSeparator(path): - print '----- FILE : %s -----' % path - - -def _PrintSummary(paths, error_records): - """Print a summary of the number of errors and files.""" - - error_count = len(error_records) - all_paths = set(paths) - all_paths_count = len(all_paths) - - if error_count is 0: - print '%d files checked, no errors found.' % all_paths_count - - new_error_count = len([e for e in error_records if e.new_error]) - - error_paths = set([e.path for e in error_records]) - error_paths_count = len(error_paths) - no_error_paths_count = all_paths_count - error_paths_count - - if (error_count or new_error_count) and not FLAGS.quiet: - error_noun = 'error' if error_count == 1 else 'errors' - new_error_noun = 'error' if new_error_count == 1 else 'errors' - error_file_noun = 'file' if error_paths_count == 1 else 'files' - ok_file_noun = 'file' if no_error_paths_count == 1 else 'files' - print ('Found %d %s, including %d new %s, in %d %s (%d %s OK).' % - (error_count, - error_noun, - new_error_count, - new_error_noun, - error_paths_count, - error_file_noun, - no_error_paths_count, - ok_file_noun)) - - -def _PrintErrorRecords(error_records): - """Print error records strings in the expected format.""" - - current_path = None - for record in error_records: - - if current_path != record.path: - current_path = record.path - if not FLAGS.unix_mode: - _PrintFileSeparator(current_path) - - print record.error_string - - -def _FormatTime(t): - """Formats a duration as a human-readable string. - - Args: - t: A duration in seconds. - - Returns: - A formatted duration string. - """ - if t < 1: - return '%dms' % round(t * 1000) - else: - return '%.2fs' % t - - - - -def main(argv=None): - """Main function. - - Args: - argv: Sequence of command line arguments. - """ - if argv is None: - argv = flags.FLAGS(sys.argv) - - if FLAGS.time: - start_time = time.time() - - suffixes = ['.js'] - if FLAGS.additional_extensions: - suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] - if FLAGS.check_html: - suffixes += ['.html', '.htm'] - paths = fileflags.GetFileList(argv, 'JavaScript', suffixes) - - if FLAGS.multiprocess: - records_iter = _MultiprocessCheckPaths(paths) - else: - records_iter = _CheckPaths(paths) - - records_iter, records_iter_copy = itertools.tee(records_iter, 2) - _PrintErrorRecords(records_iter_copy) - - error_records = list(records_iter) - _PrintSummary(paths, error_records) - - exit_code = 0 - - # If there are any errors - if error_records: - exit_code += 1 - - # If there are any new errors - if [r for r in error_records if r.new_error]: - exit_code += 2 - - if exit_code: - if FLAGS.summary: - _PrintFileSummary(paths, error_records) - - if FLAGS.beep: - # Make a beep noise. - sys.stdout.write(chr(7)) - - # Write out instructions for using fixjsstyle script to fix some of the - # reported errors. - fix_args = [] - for flag in sys.argv[1:]: - for f in GJSLINT_ONLY_FLAGS: - if flag.startswith(f): - break - else: - fix_args.append(flag) - - if not FLAGS.quiet: - print """ -Some of the errors reported by GJsLint may be auto-fixable using the script -fixjsstyle. Please double check any changes it makes and report any bugs. The -script can be run by executing: - -fixjsstyle %s """ % ' '.join(fix_args) - - if FLAGS.time: - print 'Done in %s.' % _FormatTime(time.time() - start_time) - - sys.exit(exit_code) - - -if __name__ == '__main__': - main() diff --git a/tools/closure_linter/build/lib/closure_linter/indentation.py b/tools/closure_linter/build/lib/closure_linter/indentation.py deleted file mode 100644 index d48ad2b862c43a..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/indentation.py +++ /dev/null @@ -1,617 +0,0 @@ -#!/usr/bin/env python -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Methods for checking EcmaScript files for indentation issues.""" - -__author__ = ('robbyw@google.com (Robert Walker)') - -import gflags as flags - -from closure_linter import ecmametadatapass -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - - -flags.DEFINE_boolean('debug_indentation', False, - 'Whether to print debugging information for indentation.') - - -# Shorthand -Context = ecmametadatapass.EcmaContext -Error = error.Error -Position = position.Position -Type = javascripttokens.JavaScriptTokenType - - -# The general approach: -# -# 1. Build a stack of tokens that can affect indentation. -# For each token, we determine if it is a block or continuation token. -# Some tokens need to be temporarily overwritten in case they are removed -# before the end of the line. -# Much of the work here is determining which tokens to keep on the stack -# at each point. Operators, for example, should be removed once their -# expression or line is gone, while parentheses must stay until the matching -# end parentheses is found. -# -# 2. Given that stack, determine the allowable indentations. -# Due to flexible indentation rules in JavaScript, there may be many -# allowable indentations for each stack. We follows the general -# "no false positives" approach of GJsLint and build the most permissive -# set possible. - - -class TokenInfo(object): - """Stores information about a token. - - Attributes: - token: The token - is_block: Whether the token represents a block indentation. - is_transient: Whether the token should be automatically removed without - finding a matching end token. - overridden_by: TokenInfo for a token that overrides the indentation that - this token would require. - is_permanent_override: Whether the override on this token should persist - even after the overriding token is removed from the stack. For example: - x([ - 1], - 2); - needs this to be set so the last line is not required to be a continuation - indent. - line_number: The effective line number of this token. Will either be the - actual line number or the one before it in the case of a mis-wrapped - operator. - """ - - def __init__(self, token, is_block=False): - """Initializes a TokenInfo object. - - Args: - token: The token - is_block: Whether the token represents a block indentation. - """ - self.token = token - self.overridden_by = None - self.is_permanent_override = False - self.is_block = is_block - self.is_transient = not is_block and token.type not in ( - Type.START_PAREN, Type.START_PARAMETERS) - self.line_number = token.line_number - - def __repr__(self): - result = '\n %s' % self.token - if self.overridden_by: - result = '%s OVERRIDDEN [by "%s"]' % ( - result, self.overridden_by.token.string) - result += ' {is_block: %s, is_transient: %s}' % ( - self.is_block, self.is_transient) - return result - - -class IndentationRules(object): - """EmcaScript indentation rules. - - Can be used to find common indentation errors in JavaScript, ActionScript and - other Ecma like scripting languages. - """ - - def __init__(self): - """Initializes the IndentationRules checker.""" - self._stack = [] - - # Map from line number to number of characters it is off in indentation. - self._start_index_offset = {} - - def Finalize(self): - if self._stack: - old_stack = self._stack - self._stack = [] - raise Exception('INTERNAL ERROR: indentation stack is not empty: %r' % - old_stack) - - def CheckToken(self, token, state): - """Checks a token for indentation errors. - - Args: - token: The current token under consideration - state: Additional information about the current tree state - - Returns: - An error array [error code, error string, error token] if the token is - improperly indented, or None if indentation is correct. - """ - - token_type = token.type - indentation_errors = [] - stack = self._stack - is_first = self._IsFirstNonWhitespaceTokenInLine(token) - - # Add tokens that could decrease indentation before checking. - if token_type == Type.END_PAREN: - self._PopTo(Type.START_PAREN) - - elif token_type == Type.END_PARAMETERS: - self._PopTo(Type.START_PARAMETERS) - - elif token_type == Type.END_BRACKET: - self._PopTo(Type.START_BRACKET) - - elif token_type == Type.END_BLOCK: - start_token = self._PopTo(Type.START_BLOCK) - # Check for required goog.scope comment. - if start_token: - goog_scope = tokenutil.GoogScopeOrNoneFromStartBlock(start_token.token) - if goog_scope is not None: - if not token.line.endswith('; // goog.scope\n'): - if (token.line.find('//') > -1 and - token.line.find('goog.scope') > - token.line.find('//')): - indentation_errors.append([ - errors.MALFORMED_END_OF_SCOPE_COMMENT, - ('Malformed end of goog.scope comment. Please use the ' - 'exact following syntax to close the scope:\n' - '}); // goog.scope'), - token, - Position(token.start_index, token.length)]) - else: - indentation_errors.append([ - errors.MISSING_END_OF_SCOPE_COMMENT, - ('Missing comment for end of goog.scope which opened at line ' - '%d. End the scope with:\n' - '}); // goog.scope' % - (start_token.line_number)), - token, - Position(token.start_index, token.length)]) - - elif token_type == Type.KEYWORD and token.string in ('case', 'default'): - self._Add(self._PopTo(Type.START_BLOCK)) - - elif token_type == Type.SEMICOLON: - self._PopTransient() - - if (is_first and - token_type not in (Type.COMMENT, Type.DOC_PREFIX, Type.STRING_TEXT)): - if flags.FLAGS.debug_indentation: - print 'Line #%d: stack %r' % (token.line_number, stack) - - # Ignore lines that start in JsDoc since we don't check them properly yet. - # TODO(robbyw): Support checking JsDoc indentation. - # Ignore lines that start as multi-line strings since indentation is N/A. - # Ignore lines that start with operators since we report that already. - # Ignore lines with tabs since we report that already. - expected = self._GetAllowableIndentations() - actual = self._GetActualIndentation(token) - - # Special case comments describing else, case, and default. Allow them - # to outdent to the parent block. - if token_type in Type.COMMENT_TYPES: - next_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - if next_code and next_code.type == Type.END_BLOCK: - next_code = tokenutil.SearchExcept(next_code, Type.NON_CODE_TYPES) - if next_code and next_code.string in ('else', 'case', 'default'): - # TODO(robbyw): This almost certainly introduces false negatives. - expected |= self._AddToEach(expected, -2) - - if actual >= 0 and actual not in expected: - expected = sorted(expected) - indentation_errors.append([ - errors.WRONG_INDENTATION, - 'Wrong indentation: expected any of {%s} but got %d' % ( - ', '.join('%d' % x for x in expected if x < 80), actual), - token, - Position(actual, expected[0])]) - self._start_index_offset[token.line_number] = expected[0] - actual - - # Add tokens that could increase indentation. - if token_type == Type.START_BRACKET: - self._Add(TokenInfo( - token=token, - is_block=token.metadata.context.type == Context.ARRAY_LITERAL)) - - elif token_type == Type.START_BLOCK or token.metadata.is_implied_block: - self._Add(TokenInfo(token=token, is_block=True)) - - elif token_type in (Type.START_PAREN, Type.START_PARAMETERS): - self._Add(TokenInfo(token=token, is_block=False)) - - elif token_type == Type.KEYWORD and token.string == 'return': - self._Add(TokenInfo(token)) - - elif not token.IsLastInLine() and ( - token.IsAssignment() or token.IsOperator('?')): - self._Add(TokenInfo(token=token)) - - # Handle implied block closes. - if token.metadata.is_implied_block_close: - self._PopToImpliedBlock() - - # Add some tokens only if they appear at the end of the line. - is_last = self._IsLastCodeInLine(token) - if is_last: - next_code_token = tokenutil.GetNextCodeToken(token) - # Increase required indentation if this is an overlong wrapped statement - # ending in an operator. - if token_type == Type.OPERATOR: - if token.string == ':': - if stack and stack[-1].token.string == '?': - # When a ternary : is on a different line than its '?', it doesn't - # add indentation. - if token.line_number == stack[-1].token.line_number: - self._Add(TokenInfo(token)) - elif token.metadata.context.type == Context.CASE_BLOCK: - # Pop transient tokens from say, line continuations, e.g., - # case x. - # y: - # Want to pop the transient 4 space continuation indent. - self._PopTransient() - # Starting the body of the case statement, which is a type of - # block. - self._Add(TokenInfo(token=token, is_block=True)) - elif token.metadata.context.type == Context.LITERAL_ELEMENT: - # When in an object literal, acts as operator indicating line - # continuations. - self._Add(TokenInfo(token)) - else: - # ':' might also be a statement label, no effect on indentation in - # this case. - pass - - elif token.string != ',': - self._Add(TokenInfo(token)) - else: - # The token is a comma. - if token.metadata.context.type == Context.VAR: - self._Add(TokenInfo(token)) - elif token.metadata.context.type != Context.PARAMETERS: - self._PopTransient() - # Increase required indentation if this is the end of a statement that's - # continued with an operator on the next line (e.g. the '.'). - elif (next_code_token and next_code_token.type == Type.OPERATOR and - not next_code_token.metadata.IsUnaryOperator()): - self._Add(TokenInfo(token)) - elif token_type == Type.PARAMETERS and token.string.endswith(','): - # Parameter lists. - self._Add(TokenInfo(token)) - elif token.IsKeyword('var'): - self._Add(TokenInfo(token)) - elif token.metadata.is_implied_semicolon: - self._PopTransient() - elif token.IsAssignment(): - self._Add(TokenInfo(token)) - - return indentation_errors - - def _AddToEach(self, original, amount): - """Returns a new set with the given amount added to each element. - - Args: - original: The original set of numbers - amount: The amount to add to each element - - Returns: - A new set containing each element of the original set added to the amount. - """ - return set([x + amount for x in original]) - - _HARD_STOP_TYPES = (Type.START_PAREN, Type.START_PARAMETERS, - Type.START_BRACKET) - - _HARD_STOP_STRINGS = ('return', '?') - - def _IsHardStop(self, token): - """Determines if the given token can have a hard stop after it. - - Args: - token: token to examine - - Returns: - Whether the token can have a hard stop after it. - - Hard stops are indentations defined by the position of another token as in - indentation lined up with return, (, [, and ?. - """ - return (token.type in self._HARD_STOP_TYPES or - token.string in self._HARD_STOP_STRINGS or - token.IsAssignment()) - - def _GetAllowableIndentations(self): - """Computes the set of allowable indentations. - - Returns: - The set of allowable indentations, given the current stack. - """ - expected = set([0]) - hard_stops = set([]) - - # Whether the tokens are still in the same continuation, meaning additional - # indentation is optional. As an example: - # x = 5 + - # 6 + - # 7; - # The second '+' does not add any required indentation. - in_same_continuation = False - - for token_info in self._stack: - token = token_info.token - - # Handle normal additive indentation tokens. - if not token_info.overridden_by and token.string != 'return': - if token_info.is_block: - expected = self._AddToEach(expected, 2) - hard_stops = self._AddToEach(hard_stops, 2) - in_same_continuation = False - elif in_same_continuation: - expected |= self._AddToEach(expected, 4) - hard_stops |= self._AddToEach(hard_stops, 4) - else: - expected = self._AddToEach(expected, 4) - hard_stops |= self._AddToEach(hard_stops, 4) - in_same_continuation = True - - # Handle hard stops after (, [, return, =, and ? - if self._IsHardStop(token): - override_is_hard_stop = (token_info.overridden_by and - self._IsHardStop( - token_info.overridden_by.token)) - if token.type == Type.START_PAREN and token.previous: - # For someFunction(...) we allow to indent at the beginning of the - # identifier +4 - prev = token.previous - if (prev.type == Type.IDENTIFIER and - prev.line_number == token.line_number): - hard_stops.add(prev.start_index + 4) - if not override_is_hard_stop: - start_index = token.start_index - if token.line_number in self._start_index_offset: - start_index += self._start_index_offset[token.line_number] - if (token.type in (Type.START_PAREN, Type.START_PARAMETERS) and - not token_info.overridden_by): - hard_stops.add(start_index + 1) - - elif token.string == 'return' and not token_info.overridden_by: - hard_stops.add(start_index + 7) - - elif token.type == Type.START_BRACKET: - hard_stops.add(start_index + 1) - - elif token.IsAssignment(): - hard_stops.add(start_index + len(token.string) + 1) - - elif token.IsOperator('?') and not token_info.overridden_by: - hard_stops.add(start_index + 2) - - return (expected | hard_stops) or set([0]) - - def _GetActualIndentation(self, token): - """Gets the actual indentation of the line containing the given token. - - Args: - token: Any token on the line. - - Returns: - The actual indentation of the line containing the given token. Returns - -1 if this line should be ignored due to the presence of tabs. - """ - # Move to the first token in the line - token = tokenutil.GetFirstTokenInSameLine(token) - - # If it is whitespace, it is the indentation. - if token.type == Type.WHITESPACE: - if token.string.find('\t') >= 0: - return -1 - else: - return len(token.string) - elif token.type == Type.PARAMETERS: - return len(token.string) - len(token.string.lstrip()) - else: - return 0 - - def _IsFirstNonWhitespaceTokenInLine(self, token): - """Determines if the given token is the first non-space token on its line. - - Args: - token: The token. - - Returns: - True if the token is the first non-whitespace token on its line. - """ - if token.type in (Type.WHITESPACE, Type.BLANK_LINE): - return False - if token.IsFirstInLine(): - return True - return (token.previous and token.previous.IsFirstInLine() and - token.previous.type == Type.WHITESPACE) - - def _IsLastCodeInLine(self, token): - """Determines if the given token is the last code token on its line. - - Args: - token: The token. - - Returns: - True if the token is the last code token on its line. - """ - if token.type in Type.NON_CODE_TYPES: - return False - start_token = token - while True: - token = token.next - if not token or token.line_number != start_token.line_number: - return True - if token.type not in Type.NON_CODE_TYPES: - return False - - def _AllFunctionPropertyAssignTokens(self, start_token, end_token): - """Checks if tokens are (likely) a valid function property assignment. - - Args: - start_token: Start of the token range. - end_token: End of the token range. - - Returns: - True if all tokens between start_token and end_token are legal tokens - within a function declaration and assignment into a property. - """ - for token in tokenutil.GetTokenRange(start_token, end_token): - fn_decl_tokens = (Type.FUNCTION_DECLARATION, - Type.PARAMETERS, - Type.START_PARAMETERS, - Type.END_PARAMETERS, - Type.END_PAREN) - if (token.type not in fn_decl_tokens and - token.IsCode() and - not tokenutil.IsIdentifierOrDot(token) and - not token.IsAssignment() and - not (token.type == Type.OPERATOR and token.string == ',')): - return False - return True - - def _Add(self, token_info): - """Adds the given token info to the stack. - - Args: - token_info: The token information to add. - """ - if self._stack and self._stack[-1].token == token_info.token: - # Don't add the same token twice. - return - - if token_info.is_block or token_info.token.type == Type.START_PAREN: - scope_token = tokenutil.GoogScopeOrNoneFromStartBlock(token_info.token) - token_info.overridden_by = TokenInfo(scope_token) if scope_token else None - - if (token_info.token.type == Type.START_BLOCK and - token_info.token.metadata.context.type == Context.BLOCK): - # Handle function() {} assignments: their block contents get special - # treatment and are allowed to just indent by two whitespace. - # For example - # long.long.name = function( - # a) { - # In this case the { and the = are on different lines. But the - # override should still apply for all previous stack tokens that are - # part of an assignment of a block. - - has_assignment = any(x for x in self._stack if x.token.IsAssignment()) - if has_assignment: - last_token = token_info.token.previous - for stack_info in reversed(self._stack): - if (last_token and - not self._AllFunctionPropertyAssignTokens(stack_info.token, - last_token)): - break - stack_info.overridden_by = token_info - stack_info.is_permanent_override = True - last_token = stack_info.token - - index = len(self._stack) - 1 - while index >= 0: - stack_info = self._stack[index] - stack_token = stack_info.token - - if stack_info.line_number == token_info.line_number: - # In general, tokens only override each other when they are on - # the same line. - stack_info.overridden_by = token_info - if (token_info.token.type == Type.START_BLOCK and - (stack_token.IsAssignment() or - stack_token.type in (Type.IDENTIFIER, Type.START_PAREN))): - # Multi-line blocks have lasting overrides, as in: - # callFn({ - # a: 10 - # }, - # 30); - # b/11450054. If a string is not closed properly then close_block - # could be null. - close_block = token_info.token.metadata.context.end_token - stack_info.is_permanent_override = close_block and ( - close_block.line_number != token_info.token.line_number) - else: - break - index -= 1 - - self._stack.append(token_info) - - def _Pop(self): - """Pops the top token from the stack. - - Returns: - The popped token info. - """ - token_info = self._stack.pop() - if token_info.token.type not in (Type.START_BLOCK, Type.START_BRACKET): - # Remove any temporary overrides. - self._RemoveOverrides(token_info) - else: - # For braces and brackets, which can be object and array literals, remove - # overrides when the literal is closed on the same line. - token_check = token_info.token - same_type = token_check.type - goal_type = None - if token_info.token.type == Type.START_BRACKET: - goal_type = Type.END_BRACKET - else: - goal_type = Type.END_BLOCK - line_number = token_info.token.line_number - count = 0 - while token_check and token_check.line_number == line_number: - if token_check.type == goal_type: - count -= 1 - if not count: - self._RemoveOverrides(token_info) - break - if token_check.type == same_type: - count += 1 - token_check = token_check.next - return token_info - - def _PopToImpliedBlock(self): - """Pops the stack until an implied block token is found.""" - while not self._Pop().token.metadata.is_implied_block: - pass - - def _PopTo(self, stop_type): - """Pops the stack until a token of the given type is popped. - - Args: - stop_type: The type of token to pop to. - - Returns: - The token info of the given type that was popped. - """ - last = None - while True: - last = self._Pop() - if last.token.type == stop_type: - break - return last - - def _RemoveOverrides(self, token_info): - """Marks any token that was overridden by this token as active again. - - Args: - token_info: The token that is being removed from the stack. - """ - for stack_token in self._stack: - if (stack_token.overridden_by == token_info and - not stack_token.is_permanent_override): - stack_token.overridden_by = None - - def _PopTransient(self): - """Pops all transient tokens - i.e. not blocks, literals, or parens.""" - while self._stack and self._stack[-1].is_transient: - self._Pop() diff --git a/tools/closure_linter/build/lib/closure_linter/javascriptlintrules.py b/tools/closure_linter/build/lib/closure_linter/javascriptlintrules.py deleted file mode 100644 index 9578009daacb5a..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/javascriptlintrules.py +++ /dev/null @@ -1,754 +0,0 @@ -#!/usr/bin/env python -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Methods for checking JS files for common style guide violations. - -These style guide violations should only apply to JavaScript and not an Ecma -scripting languages. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'jacobr@google.com (Jacob Richman)') - -import re - -from closure_linter import ecmalintrules -from closure_linter import error_check -from closure_linter import errors -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - -# Shorthand -Error = error.Error -Position = position.Position -Rule = error_check.Rule -Type = javascripttokens.JavaScriptTokenType - - -class JavaScriptLintRules(ecmalintrules.EcmaScriptLintRules): - """JavaScript lint rules that catch JavaScript specific style errors.""" - - def __init__(self, namespaces_info): - """Initializes a JavaScriptLintRules instance.""" - ecmalintrules.EcmaScriptLintRules.__init__(self) - self._namespaces_info = namespaces_info - self._declared_private_member_tokens = {} - self._declared_private_members = set() - self._used_private_members = set() - # A stack of dictionaries, one for each function scope entered. Each - # dictionary is keyed by an identifier that defines a local variable and has - # a token as its value. - self._unused_local_variables_by_scope = [] - - def HandleMissingParameterDoc(self, token, param_name): - """Handle errors associated with a parameter missing a param tag.""" - self._HandleError(errors.MISSING_PARAMETER_DOCUMENTATION, - 'Missing docs for parameter: "%s"' % param_name, token) - - # pylint: disable=too-many-statements - def CheckToken(self, token, state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration - state: parser_state object that indicates the current state in the page - """ - - # Call the base class's CheckToken function. - super(JavaScriptLintRules, self).CheckToken(token, state) - - # Store some convenience variables - namespaces_info = self._namespaces_info - - if error_check.ShouldCheck(Rule.UNUSED_LOCAL_VARIABLES): - self._CheckUnusedLocalVariables(token, state) - - if error_check.ShouldCheck(Rule.UNUSED_PRIVATE_MEMBERS): - # Find all assignments to private members. - if token.type == Type.SIMPLE_LVALUE: - identifier = token.string - if identifier.endswith('_') and not identifier.endswith('__'): - doc_comment = state.GetDocComment() - suppressed = doc_comment and ( - 'underscore' in doc_comment.suppressions or - 'unusedPrivateMembers' in doc_comment.suppressions) - if not suppressed: - # Look for static members defined on a provided namespace. - if namespaces_info: - namespace = namespaces_info.GetClosurizedNamespace(identifier) - provided_namespaces = namespaces_info.GetProvidedNamespaces() - else: - namespace = None - provided_namespaces = set() - - # Skip cases of this.something_.somethingElse_. - regex = re.compile(r'^this\.[a-zA-Z_]+$') - if namespace in provided_namespaces or regex.match(identifier): - variable = identifier.split('.')[-1] - self._declared_private_member_tokens[variable] = token - self._declared_private_members.add(variable) - elif not identifier.endswith('__'): - # Consider setting public members of private members to be a usage. - for piece in identifier.split('.'): - if piece.endswith('_'): - self._used_private_members.add(piece) - - # Find all usages of private members. - if token.type == Type.IDENTIFIER: - for piece in token.string.split('.'): - if piece.endswith('_'): - self._used_private_members.add(piece) - - if token.type == Type.DOC_FLAG: - flag = token.attached_object - - if flag.flag_type == 'param' and flag.name_token is not None: - self._CheckForMissingSpaceBeforeToken( - token.attached_object.name_token) - - if flag.type is not None and flag.name is not None: - if error_check.ShouldCheck(Rule.VARIABLE_ARG_MARKER): - # Check for variable arguments marker in type. - if flag.jstype.IsVarArgsType() and flag.name != 'var_args': - self._HandleError(errors.JSDOC_MISSING_VAR_ARGS_NAME, - 'Variable length argument %s must be renamed ' - 'to var_args.' % flag.name, - token) - elif not flag.jstype.IsVarArgsType() and flag.name == 'var_args': - self._HandleError(errors.JSDOC_MISSING_VAR_ARGS_TYPE, - 'Variable length argument %s type must start ' - 'with \'...\'.' % flag.name, - token) - - if error_check.ShouldCheck(Rule.OPTIONAL_TYPE_MARKER): - # Check for optional marker in type. - if (flag.jstype.opt_arg and - not flag.name.startswith('opt_')): - self._HandleError(errors.JSDOC_MISSING_OPTIONAL_PREFIX, - 'Optional parameter name %s must be prefixed ' - 'with opt_.' % flag.name, - token) - elif (not flag.jstype.opt_arg and - flag.name.startswith('opt_')): - self._HandleError(errors.JSDOC_MISSING_OPTIONAL_TYPE, - 'Optional parameter %s type must end with =.' % - flag.name, - token) - - if flag.flag_type in state.GetDocFlag().HAS_TYPE: - # Check for both missing type token and empty type braces '{}' - # Missing suppress types are reported separately and we allow enums, - # const, private, public and protected without types. - if (flag.flag_type not in state.GetDocFlag().CAN_OMIT_TYPE - and (not flag.jstype or flag.jstype.IsEmpty())): - self._HandleError(errors.MISSING_JSDOC_TAG_TYPE, - 'Missing type in %s tag' % token.string, token) - - elif flag.name_token and flag.type_end_token and tokenutil.Compare( - flag.type_end_token, flag.name_token) > 0: - self._HandleError( - errors.OUT_OF_ORDER_JSDOC_TAG_TYPE, - 'Type should be immediately after %s tag' % token.string, - token) - - elif token.type == Type.DOUBLE_QUOTE_STRING_START: - next_token = token.next - while next_token.type == Type.STRING_TEXT: - if javascripttokenizer.JavaScriptTokenizer.SINGLE_QUOTE.search( - next_token.string): - break - next_token = next_token.next - else: - self._HandleError( - errors.UNNECESSARY_DOUBLE_QUOTED_STRING, - 'Single-quoted string preferred over double-quoted string.', - token, - position=Position.All(token.string)) - - elif token.type == Type.END_DOC_COMMENT: - doc_comment = state.GetDocComment() - - # When @externs appears in a @fileoverview comment, it should trigger - # the same limited doc checks as a special filename like externs.js. - if doc_comment.HasFlag('fileoverview') and doc_comment.HasFlag('externs'): - self._SetLimitedDocChecks(True) - - if (error_check.ShouldCheck(Rule.BLANK_LINES_AT_TOP_LEVEL) and - not self._is_html and - state.InTopLevel() and - not state.InNonScopeBlock()): - - # Check if we're in a fileoverview or constructor JsDoc. - is_constructor = ( - doc_comment.HasFlag('constructor') or - doc_comment.HasFlag('interface')) - # @fileoverview is an optional tag so if the dosctring is the first - # token in the file treat it as a file level docstring. - is_file_level_comment = ( - doc_comment.HasFlag('fileoverview') or - not doc_comment.start_token.previous) - - # If the comment is not a file overview, and it does not immediately - # precede some code, skip it. - # NOTE: The tokenutil methods are not used here because of their - # behavior at the top of a file. - next_token = token.next - if (not next_token or - (not is_file_level_comment and - next_token.type in Type.NON_CODE_TYPES)): - return - - # Don't require extra blank lines around suppression of extra - # goog.require errors. - if (doc_comment.SuppressionOnly() and - next_token.type == Type.IDENTIFIER and - next_token.string in ['goog.provide', 'goog.require']): - return - - # Find the start of this block (include comments above the block, unless - # this is a file overview). - block_start = doc_comment.start_token - if not is_file_level_comment: - token = block_start.previous - while token and token.type in Type.COMMENT_TYPES: - block_start = token - token = token.previous - - # Count the number of blank lines before this block. - blank_lines = 0 - token = block_start.previous - while token and token.type in [Type.WHITESPACE, Type.BLANK_LINE]: - if token.type == Type.BLANK_LINE: - # A blank line. - blank_lines += 1 - elif token.type == Type.WHITESPACE and not token.line.strip(): - # A line with only whitespace on it. - blank_lines += 1 - token = token.previous - - # Log errors. - error_message = False - expected_blank_lines = 0 - - # Only need blank line before file overview if it is not the beginning - # of the file, e.g. copyright is first. - if is_file_level_comment and blank_lines == 0 and block_start.previous: - error_message = 'Should have a blank line before a file overview.' - expected_blank_lines = 1 - elif is_constructor and blank_lines != 3: - error_message = ( - 'Should have 3 blank lines before a constructor/interface.') - expected_blank_lines = 3 - elif (not is_file_level_comment and not is_constructor and - blank_lines != 2): - error_message = 'Should have 2 blank lines between top-level blocks.' - expected_blank_lines = 2 - - if error_message: - self._HandleError( - errors.WRONG_BLANK_LINE_COUNT, error_message, - block_start, position=Position.AtBeginning(), - fix_data=expected_blank_lines - blank_lines) - - elif token.type == Type.END_BLOCK: - if state.InFunction() and state.IsFunctionClose(): - is_immediately_called = (token.next and - token.next.type == Type.START_PAREN) - - function = state.GetFunction() - if not self._limited_doc_checks: - if (function.has_return and function.doc and - not is_immediately_called and - not function.doc.HasFlag('return') and - not function.doc.InheritsDocumentation() and - not function.doc.HasFlag('constructor')): - # Check for proper documentation of return value. - self._HandleError( - errors.MISSING_RETURN_DOCUMENTATION, - 'Missing @return JsDoc in function with non-trivial return', - function.doc.end_token, position=Position.AtBeginning()) - elif (not function.has_return and - not function.has_throw and - function.doc and - function.doc.HasFlag('return') and - not state.InInterfaceMethod()): - flag = function.doc.GetFlag('return') - valid_no_return_names = ['undefined', 'void', '*'] - invalid_return = flag.jstype is None or not any( - sub_type.identifier in valid_no_return_names - for sub_type in flag.jstype.IterTypeGroup()) - - if invalid_return: - self._HandleError( - errors.UNNECESSARY_RETURN_DOCUMENTATION, - 'Found @return JsDoc on function that returns nothing', - flag.flag_token, position=Position.AtBeginning()) - - # b/4073735. Method in object literal definition of prototype can - # safely reference 'this'. - prototype_object_literal = False - block_start = None - previous_code = None - previous_previous_code = None - - # Search for cases where prototype is defined as object literal. - # previous_previous_code - # | previous_code - # | | block_start - # | | | - # a.b.prototype = { - # c : function() { - # this.d = 1; - # } - # } - - # If in object literal, find first token of block so to find previous - # tokens to check above condition. - if state.InObjectLiteral(): - block_start = state.GetCurrentBlockStart() - - # If an object literal then get previous token (code type). For above - # case it should be '='. - if block_start: - previous_code = tokenutil.SearchExcept(block_start, - Type.NON_CODE_TYPES, - reverse=True) - - # If previous token to block is '=' then get its previous token. - if previous_code and previous_code.IsOperator('='): - previous_previous_code = tokenutil.SearchExcept(previous_code, - Type.NON_CODE_TYPES, - reverse=True) - - # If variable/token before '=' ends with '.prototype' then its above - # case of prototype defined with object literal. - prototype_object_literal = (previous_previous_code and - previous_previous_code.string.endswith( - '.prototype')) - - if (function.has_this and function.doc and - not function.doc.HasFlag('this') and - not function.is_constructor and - not function.is_interface and - '.prototype.' not in function.name and - not prototype_object_literal): - self._HandleError( - errors.MISSING_JSDOC_TAG_THIS, - 'Missing @this JsDoc in function referencing "this". (' - 'this usually means you are trying to reference "this" in ' - 'a static function, or you have forgotten to mark a ' - 'constructor with @constructor)', - function.doc.end_token, position=Position.AtBeginning()) - - elif token.type == Type.IDENTIFIER: - if token.string == 'goog.inherits' and not state.InFunction(): - if state.GetLastNonSpaceToken().line_number == token.line_number: - self._HandleError( - errors.MISSING_LINE, - 'Missing newline between constructor and goog.inherits', - token, - position=Position.AtBeginning()) - - extra_space = state.GetLastNonSpaceToken().next - while extra_space != token: - if extra_space.type == Type.BLANK_LINE: - self._HandleError( - errors.EXTRA_LINE, - 'Extra line between constructor and goog.inherits', - extra_space) - extra_space = extra_space.next - - # TODO(robbyw): Test the last function was a constructor. - # TODO(robbyw): Test correct @extends and @implements documentation. - - elif (token.string == 'goog.provide' and - not state.InFunction() and - namespaces_info is not None): - namespace = tokenutil.GetStringAfterToken(token) - - # Report extra goog.provide statement. - if not namespace or namespaces_info.IsExtraProvide(token): - if not namespace: - msg = 'Empty namespace in goog.provide' - else: - msg = 'Unnecessary goog.provide: ' + namespace - - # Hint to user if this is a Test namespace. - if namespace.endswith('Test'): - msg += (' *Test namespaces must be mentioned in the ' - 'goog.setTestOnly() call') - - self._HandleError( - errors.EXTRA_GOOG_PROVIDE, - msg, - token, position=Position.AtBeginning()) - - if namespaces_info.IsLastProvide(token): - # Report missing provide statements after the last existing provide. - missing_provides = namespaces_info.GetMissingProvides() - if missing_provides: - self._ReportMissingProvides( - missing_provides, - tokenutil.GetLastTokenInSameLine(token).next, - False) - - # If there are no require statements, missing requires should be - # reported after the last provide. - if not namespaces_info.GetRequiredNamespaces(): - missing_requires, illegal_alias_statements = ( - namespaces_info.GetMissingRequires()) - if missing_requires: - self._ReportMissingRequires( - missing_requires, - tokenutil.GetLastTokenInSameLine(token).next, - True) - if illegal_alias_statements: - self._ReportIllegalAliasStatement(illegal_alias_statements) - - elif (token.string == 'goog.require' and - not state.InFunction() and - namespaces_info is not None): - namespace = tokenutil.GetStringAfterToken(token) - - # If there are no provide statements, missing provides should be - # reported before the first require. - if (namespaces_info.IsFirstRequire(token) and - not namespaces_info.GetProvidedNamespaces()): - missing_provides = namespaces_info.GetMissingProvides() - if missing_provides: - self._ReportMissingProvides( - missing_provides, - tokenutil.GetFirstTokenInSameLine(token), - True) - - # Report extra goog.require statement. - if not namespace or namespaces_info.IsExtraRequire(token): - if not namespace: - msg = 'Empty namespace in goog.require' - else: - msg = 'Unnecessary goog.require: ' + namespace - - self._HandleError( - errors.EXTRA_GOOG_REQUIRE, - msg, - token, position=Position.AtBeginning()) - - # Report missing goog.require statements. - if namespaces_info.IsLastRequire(token): - missing_requires, illegal_alias_statements = ( - namespaces_info.GetMissingRequires()) - if missing_requires: - self._ReportMissingRequires( - missing_requires, - tokenutil.GetLastTokenInSameLine(token).next, - False) - if illegal_alias_statements: - self._ReportIllegalAliasStatement(illegal_alias_statements) - - elif token.type == Type.OPERATOR: - last_in_line = token.IsLastInLine() - # If the token is unary and appears to be used in a unary context - # it's ok. Otherwise, if it's at the end of the line or immediately - # before a comment, it's ok. - # Don't report an error before a start bracket - it will be reported - # by that token's space checks. - if (not token.metadata.IsUnaryOperator() and not last_in_line - and not token.next.IsComment() - and not token.next.IsOperator(',') - and not tokenutil.IsDot(token) - and token.next.type not in (Type.WHITESPACE, Type.END_PAREN, - Type.END_BRACKET, Type.SEMICOLON, - Type.START_BRACKET)): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space after "%s"' % token.string, - token, - position=Position.AtEnd(token.string)) - elif token.type == Type.WHITESPACE: - first_in_line = token.IsFirstInLine() - last_in_line = token.IsLastInLine() - # Check whitespace length if it's not the first token of the line and - # if it's not immediately before a comment. - if not last_in_line and not first_in_line and not token.next.IsComment(): - # Ensure there is no space after opening parentheses. - if (token.previous.type in (Type.START_PAREN, Type.START_BRACKET, - Type.FUNCTION_NAME) - or token.next.type == Type.START_PARAMETERS): - self._HandleError( - errors.EXTRA_SPACE, - 'Extra space after "%s"' % token.previous.string, - token, - position=Position.All(token.string)) - elif token.type == Type.SEMICOLON: - previous_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, - reverse=True) - if not previous_token: - self._HandleError( - errors.REDUNDANT_SEMICOLON, - 'Semicolon without any statement', - token, - position=Position.AtEnd(token.string)) - elif (previous_token.type == Type.KEYWORD and - previous_token.string not in ['break', 'continue', 'return']): - self._HandleError( - errors.REDUNDANT_SEMICOLON, - ('Semicolon after \'%s\' without any statement.' - ' Looks like an error.' % previous_token.string), - token, - position=Position.AtEnd(token.string)) - - def _CheckUnusedLocalVariables(self, token, state): - """Checks for unused local variables in function blocks. - - Args: - token: The token to check. - state: The state tracker. - """ - # We don't use state.InFunction because that disregards scope functions. - in_function = state.FunctionDepth() > 0 - if token.type == Type.SIMPLE_LVALUE or token.type == Type.IDENTIFIER: - if in_function: - identifier = token.string - # Check whether the previous token was var. - previous_code_token = tokenutil.CustomSearch( - token, - lambda t: t.type not in Type.NON_CODE_TYPES, - reverse=True) - if previous_code_token and previous_code_token.IsKeyword('var'): - # Add local variable declaration to the top of the unused locals - # stack. - self._unused_local_variables_by_scope[-1][identifier] = token - elif token.type == Type.IDENTIFIER: - # This covers most cases where the variable is used as an identifier. - self._MarkLocalVariableUsed(token.string) - elif token.type == Type.SIMPLE_LVALUE and '.' in identifier: - # This covers cases where a value is assigned to a property of the - # variable. - self._MarkLocalVariableUsed(token.string) - elif token.type == Type.START_BLOCK: - if in_function and state.IsFunctionOpen(): - # Push a new map onto the stack - self._unused_local_variables_by_scope.append({}) - elif token.type == Type.END_BLOCK: - if state.IsFunctionClose(): - # Pop the stack and report any remaining locals as unused. - unused_local_variables = self._unused_local_variables_by_scope.pop() - for unused_token in unused_local_variables.values(): - self._HandleError( - errors.UNUSED_LOCAL_VARIABLE, - 'Unused local variable: %s.' % unused_token.string, - unused_token) - elif token.type == Type.DOC_FLAG: - # Flags that use aliased symbols should be counted. - flag = token.attached_object - js_type = flag and flag.jstype - if flag and flag.flag_type in state.GetDocFlag().HAS_TYPE and js_type: - self._MarkAliasUsed(js_type) - - def _MarkAliasUsed(self, js_type): - """Marks aliases in a type as used. - - Recursively iterates over all subtypes in a jsdoc type annotation and - tracks usage of aliased symbols (which may be local variables). - Marks the local variable as used in the scope nearest to the current - scope that matches the given token. - - Args: - js_type: The jsdoc type, a typeannotation.TypeAnnotation object. - """ - if js_type.alias: - self._MarkLocalVariableUsed(js_type.identifier) - for sub_type in js_type.IterTypes(): - self._MarkAliasUsed(sub_type) - - def _MarkLocalVariableUsed(self, identifier): - """Marks the local variable as used in the relevant scope. - - Marks the local variable in the scope nearest to the current scope that - matches the given identifier as used. - - Args: - identifier: The identifier representing the potential usage of a local - variable. - """ - identifier = identifier.split('.', 1)[0] - # Find the first instance of the identifier in the stack of function scopes - # and mark it used. - for unused_local_variables in reversed( - self._unused_local_variables_by_scope): - if identifier in unused_local_variables: - del unused_local_variables[identifier] - break - - def _ReportMissingProvides(self, missing_provides, token, need_blank_line): - """Reports missing provide statements to the error handler. - - Args: - missing_provides: A dictionary of string(key) and integer(value) where - each string(key) is a namespace that should be provided, but is not - and integer(value) is first line number where it's required. - token: The token where the error was detected (also where the new provides - will be inserted. - need_blank_line: Whether a blank line needs to be inserted after the new - provides are inserted. May be True, False, or None, where None - indicates that the insert location is unknown. - """ - - missing_provides_msg = 'Missing the following goog.provide statements:\n' - missing_provides_msg += '\n'.join(['goog.provide(\'%s\');' % x for x in - sorted(missing_provides)]) - missing_provides_msg += '\n' - - missing_provides_msg += '\nFirst line where provided: \n' - missing_provides_msg += '\n'.join( - [' %s : line %d' % (x, missing_provides[x]) for x in - sorted(missing_provides)]) - missing_provides_msg += '\n' - - self._HandleError( - errors.MISSING_GOOG_PROVIDE, - missing_provides_msg, - token, position=Position.AtBeginning(), - fix_data=(missing_provides.keys(), need_blank_line)) - - def _ReportMissingRequires(self, missing_requires, token, need_blank_line): - """Reports missing require statements to the error handler. - - Args: - missing_requires: A dictionary of string(key) and integer(value) where - each string(key) is a namespace that should be required, but is not - and integer(value) is first line number where it's required. - token: The token where the error was detected (also where the new requires - will be inserted. - need_blank_line: Whether a blank line needs to be inserted before the new - requires are inserted. May be True, False, or None, where None - indicates that the insert location is unknown. - """ - - missing_requires_msg = 'Missing the following goog.require statements:\n' - missing_requires_msg += '\n'.join(['goog.require(\'%s\');' % x for x in - sorted(missing_requires)]) - missing_requires_msg += '\n' - - missing_requires_msg += '\nFirst line where required: \n' - missing_requires_msg += '\n'.join( - [' %s : line %d' % (x, missing_requires[x]) for x in - sorted(missing_requires)]) - missing_requires_msg += '\n' - - self._HandleError( - errors.MISSING_GOOG_REQUIRE, - missing_requires_msg, - token, position=Position.AtBeginning(), - fix_data=(missing_requires.keys(), need_blank_line)) - - def _ReportIllegalAliasStatement(self, illegal_alias_statements): - """Reports alias statements that would need a goog.require.""" - for namespace, token in illegal_alias_statements.iteritems(): - self._HandleError( - errors.ALIAS_STMT_NEEDS_GOOG_REQUIRE, - 'The alias definition would need the namespace \'%s\' which is not ' - 'required through any other symbol.' % namespace, - token, position=Position.AtBeginning()) - - def Finalize(self, state): - """Perform all checks that need to occur after all lines are processed.""" - # Call the base class's Finalize function. - super(JavaScriptLintRules, self).Finalize(state) - - if error_check.ShouldCheck(Rule.UNUSED_PRIVATE_MEMBERS): - # Report an error for any declared private member that was never used. - unused_private_members = (self._declared_private_members - - self._used_private_members) - - for variable in unused_private_members: - token = self._declared_private_member_tokens[variable] - self._HandleError(errors.UNUSED_PRIVATE_MEMBER, - 'Unused private member: %s.' % token.string, - token) - - # Clear state to prepare for the next file. - self._declared_private_member_tokens = {} - self._declared_private_members = set() - self._used_private_members = set() - - namespaces_info = self._namespaces_info - if namespaces_info is not None: - # If there are no provide or require statements, missing provides and - # requires should be reported on line 1. - if (not namespaces_info.GetProvidedNamespaces() and - not namespaces_info.GetRequiredNamespaces()): - missing_provides = namespaces_info.GetMissingProvides() - if missing_provides: - self._ReportMissingProvides( - missing_provides, state.GetFirstToken(), None) - - missing_requires, illegal_alias = namespaces_info.GetMissingRequires() - if missing_requires: - self._ReportMissingRequires( - missing_requires, state.GetFirstToken(), None) - if illegal_alias: - self._ReportIllegalAliasStatement(illegal_alias) - - self._CheckSortedRequiresProvides(state.GetFirstToken()) - - def _CheckSortedRequiresProvides(self, token): - """Checks that all goog.require and goog.provide statements are sorted. - - Note that this method needs to be run after missing statements are added to - preserve alphabetical order. - - Args: - token: The first token in the token stream. - """ - sorter = requireprovidesorter.RequireProvideSorter() - first_provide_token = sorter.CheckProvides(token) - if first_provide_token: - new_order = sorter.GetFixedProvideString(first_provide_token) - self._HandleError( - errors.GOOG_PROVIDES_NOT_ALPHABETIZED, - 'goog.provide classes must be alphabetized. The correct code is:\n' + - new_order, - first_provide_token, - position=Position.AtBeginning(), - fix_data=first_provide_token) - - first_require_token = sorter.CheckRequires(token) - if first_require_token: - new_order = sorter.GetFixedRequireString(first_require_token) - self._HandleError( - errors.GOOG_REQUIRES_NOT_ALPHABETIZED, - 'goog.require classes must be alphabetized. The correct code is:\n' + - new_order, - first_require_token, - position=Position.AtBeginning(), - fix_data=first_require_token) - - def GetLongLineExceptions(self): - """Gets a list of regexps for lines which can be longer than the limit. - - Returns: - A list of regexps, used as matches (rather than searches). - """ - return [ - re.compile(r'(var .+\s*=\s*)?goog\.require\(.+\);?\s*$'), - re.compile(r'goog\.(provide|module|setTestOnly)\(.+\);?\s*$'), - re.compile(r'[\s/*]*@visibility\s*{.*}[\s*/]*$'), - ] diff --git a/tools/closure_linter/build/lib/closure_linter/javascriptstatetracker.py b/tools/closure_linter/build/lib/closure_linter/javascriptstatetracker.py deleted file mode 100644 index e0a42f66a84aae..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/javascriptstatetracker.py +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Parser for JavaScript files.""" - - - -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import tokenutil - -# Shorthand -Type = javascripttokens.JavaScriptTokenType - - -class JsDocFlag(statetracker.DocFlag): - """Javascript doc flag object. - - Attribute: - flag_type: param, return, define, type, etc. - flag_token: The flag token. - type_start_token: The first token specifying the flag JS type, - including braces. - type_end_token: The last token specifying the flag JS type, - including braces. - type: The type spec string. - jstype: The type spec, a TypeAnnotation instance. - name_token: The token specifying the flag name. - name: The flag name - description_start_token: The first token in the description. - description_end_token: The end token in the description. - description: The description. - """ - - # Please keep these lists alphabetized. - - # Some projects use the following extensions to JsDoc. - # TODO(robbyw): determine which of these, if any, should be illegal. - EXTENDED_DOC = frozenset([ - 'class', 'code', 'desc', 'final', 'hidden', 'inheritDoc', 'link', - 'meaning', 'provideGoog', 'throws']) - - LEGAL_DOC = EXTENDED_DOC | statetracker.DocFlag.LEGAL_DOC - - -class JavaScriptStateTracker(statetracker.StateTracker): - """JavaScript state tracker. - - Inherits from the core EcmaScript StateTracker adding extra state tracking - functionality needed for JavaScript. - """ - - def __init__(self): - """Initializes a JavaScript token stream state tracker.""" - statetracker.StateTracker.__init__(self, JsDocFlag) - - def Reset(self): - self._scope_depth = 0 - self._block_stack = [] - super(JavaScriptStateTracker, self).Reset() - - def InTopLevel(self): - """Compute whether we are at the top level in the class. - - This function call is language specific. In some languages like - JavaScript, a function is top level if it is not inside any parenthesis. - In languages such as ActionScript, a function is top level if it is directly - within a class. - - Returns: - Whether we are at the top level in the class. - """ - return self._scope_depth == self.ParenthesesDepth() - - def InFunction(self): - """Returns true if the current token is within a function. - - This js-specific override ignores goog.scope functions. - - Returns: - True if the current token is within a function. - """ - return self._scope_depth != self.FunctionDepth() - - def InNonScopeBlock(self): - """Compute whether we are nested within a non-goog.scope block. - - Returns: - True if the token is not enclosed in a block that does not originate from - a goog.scope statement. False otherwise. - """ - return self._scope_depth != self.BlockDepth() - - def GetBlockType(self, token): - """Determine the block type given a START_BLOCK token. - - Code blocks come after parameters, keywords like else, and closing parens. - - Args: - token: The current token. Can be assumed to be type START_BLOCK - Returns: - Code block type for current token. - """ - last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, reverse=True) - if last_code.type in (Type.END_PARAMETERS, Type.END_PAREN, - Type.KEYWORD) and not last_code.IsKeyword('return'): - return self.CODE - else: - return self.OBJECT_LITERAL - - def GetCurrentBlockStart(self): - """Gets the start token of current block. - - Returns: - Starting token of current block. None if not in block. - """ - if self._block_stack: - return self._block_stack[-1] - else: - return None - - def HandleToken(self, token, last_non_space_token): - """Handles the given token and updates state. - - Args: - token: The token to handle. - last_non_space_token: The last non space token encountered - """ - if token.type == Type.START_BLOCK: - self._block_stack.append(token) - if token.type == Type.IDENTIFIER and token.string == 'goog.scope': - self._scope_depth += 1 - if token.type == Type.END_BLOCK: - start_token = self._block_stack.pop() - if tokenutil.GoogScopeOrNoneFromStartBlock(start_token): - self._scope_depth -= 1 - super(JavaScriptStateTracker, self).HandleToken(token, - last_non_space_token) diff --git a/tools/closure_linter/build/lib/closure_linter/javascriptstatetracker_test.py b/tools/closure_linter/build/lib/closure_linter/javascriptstatetracker_test.py deleted file mode 100644 index 76dabd2c70d58a..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/javascriptstatetracker_test.py +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the javascriptstatetracker module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - - -import unittest as googletest - -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - - -_FUNCTION_SCRIPT = """\ -var a = 3; - -function foo(aaa, bbb, ccc) { - var b = 4; -} - - -/** - * JSDoc comment. - */ -var bar = function(ddd, eee, fff) { - -}; - - -/** - * Verify that nested functions get their proper parameters recorded. - */ -var baz = function(ggg, hhh, iii) { - var qux = function(jjj, kkk, lll) { - }; - // make sure that entering a new block does not change baz' parameters. - {}; -}; - -""" - - -class FunctionTest(googletest.TestCase): - - def testFunctionParse(self): - functions, _ = testutil.ParseFunctionsAndComments(_FUNCTION_SCRIPT) - self.assertEquals(4, len(functions)) - - # First function - function = functions[0] - self.assertEquals(['aaa', 'bbb', 'ccc'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(3, start_token.line_number) - self.assertEquals(0, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(5, end_token.line_number) - self.assertEquals(0, end_token.start_index) - - self.assertEquals('foo', function.name) - - self.assertIsNone(function.doc) - - # Second function - function = functions[1] - self.assertEquals(['ddd', 'eee', 'fff'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(11, start_token.line_number) - self.assertEquals(10, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(13, end_token.line_number) - self.assertEquals(0, end_token.start_index) - - self.assertEquals('bar', function.name) - - self.assertIsNotNone(function.doc) - - # Check function JSDoc - doc = function.doc - doc_tokens = tokenutil.GetTokenRange(doc.start_token, doc.end_token) - - comment_type = javascripttokens.JavaScriptTokenType.COMMENT - comment_tokens = filter(lambda t: t.type is comment_type, doc_tokens) - - self.assertEquals('JSDoc comment.', - tokenutil.TokensToString(comment_tokens).strip()) - - # Third function - function = functions[2] - self.assertEquals(['ggg', 'hhh', 'iii'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(19, start_token.line_number) - self.assertEquals(10, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(24, end_token.line_number) - self.assertEquals(0, end_token.start_index) - - self.assertEquals('baz', function.name) - self.assertIsNotNone(function.doc) - - # Fourth function (inside third function) - function = functions[3] - self.assertEquals(['jjj', 'kkk', 'lll'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(20, start_token.line_number) - self.assertEquals(12, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(21, end_token.line_number) - self.assertEquals(2, end_token.start_index) - - self.assertEquals('qux', function.name) - self.assertIsNone(function.doc) - - - -class CommentTest(googletest.TestCase): - - def testGetDescription(self): - comment = self._ParseComment(""" - /** - * Comment targeting goog.foo. - * - * This is the second line. - * @param {number} foo The count of foo. - */ - target;""") - - self.assertEqual( - 'Comment targeting goog.foo.\n\nThis is the second line.', - comment.description) - - def testCommentGetTarget(self): - self.assertCommentTarget('goog.foo', """ - /** - * Comment targeting goog.foo. - */ - goog.foo = 6; - """) - - self.assertCommentTarget('bar', """ - /** - * Comment targeting bar. - */ - var bar = "Karate!"; - """) - - self.assertCommentTarget('doThing', """ - /** - * Comment targeting doThing. - */ - function doThing() {}; - """) - - self.assertCommentTarget('this.targetProperty', """ - goog.bar.Baz = function() { - /** - * Comment targeting targetProperty. - */ - this.targetProperty = 3; - }; - """) - - self.assertCommentTarget('goog.bar.prop', """ - /** - * Comment targeting goog.bar.prop. - */ - goog.bar.prop; - """) - - self.assertCommentTarget('goog.aaa.bbb', """ - /** - * Comment targeting goog.aaa.bbb. - */ - (goog.aaa.bbb) - """) - - self.assertCommentTarget('theTarget', """ - /** - * Comment targeting symbol preceded by newlines, whitespace, - * and parens -- things we ignore. - */ - (theTarget) - """) - - self.assertCommentTarget(None, """ - /** - * @fileoverview File overview. - */ - (notATarget) - """) - - self.assertCommentTarget(None, """ - /** - * Comment that doesn't find a target. - */ - """) - - self.assertCommentTarget('theTarget.is.split.across.lines', """ - /** - * Comment that addresses a symbol split across lines. - */ - (theTarget.is.split - .across.lines) - """) - - self.assertCommentTarget('theTarget.is.split.across.lines', """ - /** - * Comment that addresses a symbol split across lines. - */ - (theTarget.is.split. - across.lines) - """) - - def _ParseComment(self, script): - """Parse a script that contains one comment and return it.""" - _, comments = testutil.ParseFunctionsAndComments(script) - self.assertEquals(1, len(comments)) - return comments[0] - - def assertCommentTarget(self, target, script): - comment = self._ParseComment(script) - self.assertEquals(target, comment.GetTargetIdentifier()) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/javascripttokenizer.py b/tools/closure_linter/build/lib/closure_linter/javascripttokenizer.py deleted file mode 100644 index 2ee5b81ee13c65..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/javascripttokenizer.py +++ /dev/null @@ -1,463 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Regular expression based JavaScript parsing classes.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import copy -import re - -from closure_linter import javascripttokens -from closure_linter.common import matcher -from closure_linter.common import tokenizer - -# Shorthand -Type = javascripttokens.JavaScriptTokenType -Matcher = matcher.Matcher - - -class JavaScriptModes(object): - """Enumeration of the different matcher modes used for JavaScript.""" - TEXT_MODE = 'text' - SINGLE_QUOTE_STRING_MODE = 'single_quote_string' - DOUBLE_QUOTE_STRING_MODE = 'double_quote_string' - BLOCK_COMMENT_MODE = 'block_comment' - DOC_COMMENT_MODE = 'doc_comment' - DOC_COMMENT_LEX_SPACES_MODE = 'doc_comment_spaces' - LINE_COMMENT_MODE = 'line_comment' - PARAMETER_MODE = 'parameter' - FUNCTION_MODE = 'function' - - -class JavaScriptTokenizer(tokenizer.Tokenizer): - """JavaScript tokenizer. - - Convert JavaScript code in to an array of tokens. - """ - - # Useful patterns for JavaScript parsing. - IDENTIFIER_CHAR = r'A-Za-z0-9_$' - - # Number patterns based on: - # http://www.mozilla.org/js/language/js20-2000-07/formal/lexer-grammar.html - MANTISSA = r""" - (\d+(?!\.)) | # Matches '10' - (\d+\.(?!\d)) | # Matches '10.' - (\d*\.\d+) # Matches '.5' or '10.5' - """ - DECIMAL_LITERAL = r'(%s)([eE][-+]?\d+)?' % MANTISSA - HEX_LITERAL = r'0[xX][0-9a-fA-F]+' - NUMBER = re.compile(r""" - ((%s)|(%s)) - """ % (HEX_LITERAL, DECIMAL_LITERAL), re.VERBOSE) - - # Strings come in three parts - first we match the start of the string, then - # the contents, then the end. The contents consist of any character except a - # backslash or end of string, or a backslash followed by any character, or a - # backslash followed by end of line to support correct parsing of multi-line - # strings. - SINGLE_QUOTE = re.compile(r"'") - SINGLE_QUOTE_TEXT = re.compile(r"([^'\\]|\\(.|$))+") - DOUBLE_QUOTE = re.compile(r'"') - DOUBLE_QUOTE_TEXT = re.compile(r'([^"\\]|\\(.|$))+') - - START_SINGLE_LINE_COMMENT = re.compile(r'//') - END_OF_LINE_SINGLE_LINE_COMMENT = re.compile(r'//$') - - START_DOC_COMMENT = re.compile(r'/\*\*') - START_BLOCK_COMMENT = re.compile(r'/\*') - END_BLOCK_COMMENT = re.compile(r'\*/') - BLOCK_COMMENT_TEXT = re.compile(r'([^*]|\*(?!/))+') - - # Comment text is anything that we are not going to parse into another special - # token like (inline) flags or end comments. Complicated regex to match - # most normal characters, and '*', '{', '}', and '@' when we are sure that - # it is safe. Expression [^*{\s]@ must come first, or the other options will - # match everything before @, and we won't match @'s that aren't part of flags - # like in email addresses in the @author tag. - DOC_COMMENT_TEXT = re.compile(r'([^*{}\s]@|[^*{}@]|\*(?!/))+') - DOC_COMMENT_NO_SPACES_TEXT = re.compile(r'([^*{}\s]@|[^*{}@\s]|\*(?!/))+') - # Match anything that is allowed in a type definition, except for tokens - # needed to parse it (and the lookahead assertion for "*/"). - DOC_COMMENT_TYPE_TEXT = re.compile(r'([^*|!?=<>(){}:,\s]|\*(?!/))+') - - # Match the prefix ' * ' that starts every line of jsdoc. Want to include - # spaces after the '*', but nothing else that occurs after a '*', and don't - # want to match the '*' in '*/'. - DOC_PREFIX = re.compile(r'\s*\*(\s+|(?!/))') - - START_BLOCK = re.compile('{') - END_BLOCK = re.compile('}') - - REGEX_CHARACTER_CLASS = r""" - \[ # Opening bracket - ([^\]\\]|\\.)* # Anything but a ] or \, - # or a backslash followed by anything - \] # Closing bracket - """ - # We ensure the regex is followed by one of the above tokens to avoid - # incorrectly parsing something like x / y / z as x REGEX(/ y /) z - POST_REGEX_LIST = [ - ';', ',', r'\.', r'\)', r'\]', '$', r'\/\/', r'\/\*', ':', '}'] - - REGEX = re.compile(r""" - / # opening slash - (?!\*) # not the start of a comment - (\\.|[^\[\/\\]|(%s))* # a backslash followed by anything, - # or anything but a / or [ or \, - # or a character class - / # closing slash - [gimsx]* # optional modifiers - (?=\s*(%s)) - """ % (REGEX_CHARACTER_CLASS, '|'.join(POST_REGEX_LIST)), - re.VERBOSE) - - ANYTHING = re.compile(r'.*') - PARAMETERS = re.compile(r'[^\)]+') - CLOSING_PAREN_WITH_SPACE = re.compile(r'\)\s*') - - FUNCTION_DECLARATION = re.compile(r'\bfunction\b') - - OPENING_PAREN = re.compile(r'\(') - CLOSING_PAREN = re.compile(r'\)') - - OPENING_BRACKET = re.compile(r'\[') - CLOSING_BRACKET = re.compile(r'\]') - - # We omit these JS keywords from the list: - # function - covered by FUNCTION_DECLARATION. - # delete, in, instanceof, new, typeof - included as operators. - # this - included in identifiers. - # null, undefined - not included, should go in some "special constant" list. - KEYWORD_LIST = [ - 'break', - 'case', - 'catch', - 'continue', - 'default', - 'do', - 'else', - 'finally', - 'for', - 'if', - 'return', - 'switch', - 'throw', - 'try', - 'var', - 'while', - 'with', - ] - - # List of regular expressions to match as operators. Some notes: for our - # purposes, the comma behaves similarly enough to a normal operator that we - # include it here. r'\bin\b' actually matches 'in' surrounded by boundary - # characters - this may not match some very esoteric uses of the in operator. - # Operators that are subsets of larger operators must come later in this list - # for proper matching, e.g., '>>' must come AFTER '>>>'. - OPERATOR_LIST = [ - ',', - r'\+\+', - '===', - '!==', - '>>>=', - '>>>', - '==', - '>=', - '<=', - '!=', - '<<=', - '>>=', - '<<', - '>>', - '=>', - '>', - '<', - r'\+=', - r'\+', - '--', - r'\^=', - '-=', - '-', - '/=', - '/', - r'\*=', - r'\*', - '%=', - '%', - '&&', - r'\|\|', - '&=', - '&', - r'\|=', - r'\|', - '=', - '!', - ':', - r'\?', - r'\^', - r'\bdelete\b', - r'\bin\b', - r'\binstanceof\b', - r'\bnew\b', - r'\btypeof\b', - r'\bvoid\b', - r'\.', - ] - OPERATOR = re.compile('|'.join(OPERATOR_LIST)) - - WHITESPACE = re.compile(r'\s+') - SEMICOLON = re.compile(r';') - # Technically JavaScript identifiers can't contain '.', but we treat a set of - # nested identifiers as a single identifier, except for trailing dots. - NESTED_IDENTIFIER = r'[a-zA-Z_$]([%s]|\.[a-zA-Z_$])*' % IDENTIFIER_CHAR - IDENTIFIER = re.compile(NESTED_IDENTIFIER) - - SIMPLE_LVALUE = re.compile(r""" - (?P%s) # a valid identifier - (?=\s* # optional whitespace - \= # look ahead to equal sign - (?!=)) # not follwed by equal - """ % NESTED_IDENTIFIER, re.VERBOSE) - - # A doc flag is a @ sign followed by non-space characters that appears at the - # beginning of the line, after whitespace, or after a '{'. The look-behind - # check is necessary to not match someone@google.com as a flag. - DOC_FLAG = re.compile(r'(^|(?<=\s))@(?P[a-zA-Z]+)') - # To properly parse parameter names and complex doctypes containing - # whitespace, we need to tokenize whitespace into a token after certain - # doctags. All statetracker.HAS_TYPE that are not listed here must not contain - # any whitespace in their types. - DOC_FLAG_LEX_SPACES = re.compile( - r'(^|(?<=\s))@(?P%s)\b' % - '|'.join([ - 'const', - 'enum', - 'extends', - 'final', - 'implements', - 'param', - 'private', - 'protected', - 'public', - 'return', - 'type', - 'typedef' - ])) - - DOC_INLINE_FLAG = re.compile(r'(?<={)@(?P[a-zA-Z]+)') - - DOC_TYPE_BLOCK_START = re.compile(r'[<(]') - DOC_TYPE_BLOCK_END = re.compile(r'[>)]') - DOC_TYPE_MODIFIERS = re.compile(r'[!?|,:=]') - - # Star followed by non-slash, i.e a star that does not end a comment. - # This is used for TYPE_GROUP below. - SAFE_STAR = r'(\*(?!/))' - - COMMON_DOC_MATCHERS = [ - # Find the end of the comment. - Matcher(END_BLOCK_COMMENT, Type.END_DOC_COMMENT, - JavaScriptModes.TEXT_MODE), - - # Tokenize documented flags like @private. - Matcher(DOC_INLINE_FLAG, Type.DOC_INLINE_FLAG), - Matcher(DOC_FLAG_LEX_SPACES, Type.DOC_FLAG, - JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE), - - # Encountering a doc flag should leave lex spaces mode. - Matcher(DOC_FLAG, Type.DOC_FLAG, JavaScriptModes.DOC_COMMENT_MODE), - - # Tokenize braces so we can find types. - Matcher(START_BLOCK, Type.DOC_START_BRACE), - Matcher(END_BLOCK, Type.DOC_END_BRACE), - - # And some more to parse types. - Matcher(DOC_TYPE_BLOCK_START, Type.DOC_TYPE_START_BLOCK), - Matcher(DOC_TYPE_BLOCK_END, Type.DOC_TYPE_END_BLOCK), - - Matcher(DOC_TYPE_MODIFIERS, Type.DOC_TYPE_MODIFIER), - Matcher(DOC_COMMENT_TYPE_TEXT, Type.COMMENT), - - Matcher(DOC_PREFIX, Type.DOC_PREFIX, None, True)] - - # When text is not matched, it is given this default type based on mode. - # If unspecified in this map, the default default is Type.NORMAL. - JAVASCRIPT_DEFAULT_TYPES = { - JavaScriptModes.DOC_COMMENT_MODE: Type.COMMENT, - JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: Type.COMMENT - } - - @classmethod - def BuildMatchers(cls): - """Builds the token matcher group. - - The token matcher groups work as follows: it is a list of Matcher objects. - The matchers will be tried in this order, and the first to match will be - returned. Hence the order is important because the matchers that come first - overrule the matchers that come later. - - Returns: - The completed token matcher group. - """ - # Match a keyword string followed by a non-identifier character in order to - # not match something like doSomething as do + Something. - keyword = re.compile('(%s)((?=[^%s])|$)' % ( - '|'.join(cls.KEYWORD_LIST), cls.IDENTIFIER_CHAR)) - return { - - # Matchers for basic text mode. - JavaScriptModes.TEXT_MODE: [ - # Check a big group - strings, starting comments, and regexes - all - # of which could be intertwined. 'string with /regex/', - # /regex with 'string'/, /* comment with /regex/ and string */ (and - # so on) - Matcher(cls.START_DOC_COMMENT, Type.START_DOC_COMMENT, - JavaScriptModes.DOC_COMMENT_MODE), - Matcher(cls.START_BLOCK_COMMENT, Type.START_BLOCK_COMMENT, - JavaScriptModes.BLOCK_COMMENT_MODE), - Matcher(cls.END_OF_LINE_SINGLE_LINE_COMMENT, - Type.START_SINGLE_LINE_COMMENT), - Matcher(cls.START_SINGLE_LINE_COMMENT, - Type.START_SINGLE_LINE_COMMENT, - JavaScriptModes.LINE_COMMENT_MODE), - Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_START, - JavaScriptModes.SINGLE_QUOTE_STRING_MODE), - Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_START, - JavaScriptModes.DOUBLE_QUOTE_STRING_MODE), - Matcher(cls.REGEX, Type.REGEX), - - # Next we check for start blocks appearing outside any of the items - # above. - Matcher(cls.START_BLOCK, Type.START_BLOCK), - Matcher(cls.END_BLOCK, Type.END_BLOCK), - - # Then we search for function declarations. - Matcher(cls.FUNCTION_DECLARATION, Type.FUNCTION_DECLARATION, - JavaScriptModes.FUNCTION_MODE), - - # Next, we convert non-function related parens to tokens. - Matcher(cls.OPENING_PAREN, Type.START_PAREN), - Matcher(cls.CLOSING_PAREN, Type.END_PAREN), - - # Next, we convert brackets to tokens. - Matcher(cls.OPENING_BRACKET, Type.START_BRACKET), - Matcher(cls.CLOSING_BRACKET, Type.END_BRACKET), - - # Find numbers. This has to happen before operators because - # scientific notation numbers can have + and - in them. - Matcher(cls.NUMBER, Type.NUMBER), - - # Find operators and simple assignments - Matcher(cls.SIMPLE_LVALUE, Type.SIMPLE_LVALUE), - Matcher(cls.OPERATOR, Type.OPERATOR), - - # Find key words and whitespace. - Matcher(keyword, Type.KEYWORD), - Matcher(cls.WHITESPACE, Type.WHITESPACE), - - # Find identifiers. - Matcher(cls.IDENTIFIER, Type.IDENTIFIER), - - # Finally, we convert semicolons to tokens. - Matcher(cls.SEMICOLON, Type.SEMICOLON)], - - # Matchers for single quote strings. - JavaScriptModes.SINGLE_QUOTE_STRING_MODE: [ - Matcher(cls.SINGLE_QUOTE_TEXT, Type.STRING_TEXT), - Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_END, - JavaScriptModes.TEXT_MODE)], - - # Matchers for double quote strings. - JavaScriptModes.DOUBLE_QUOTE_STRING_MODE: [ - Matcher(cls.DOUBLE_QUOTE_TEXT, Type.STRING_TEXT), - Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_END, - JavaScriptModes.TEXT_MODE)], - - # Matchers for block comments. - JavaScriptModes.BLOCK_COMMENT_MODE: [ - # First we check for exiting a block comment. - Matcher(cls.END_BLOCK_COMMENT, Type.END_BLOCK_COMMENT, - JavaScriptModes.TEXT_MODE), - - # Match non-comment-ending text.. - Matcher(cls.BLOCK_COMMENT_TEXT, Type.COMMENT)], - - # Matchers for doc comments. - JavaScriptModes.DOC_COMMENT_MODE: cls.COMMON_DOC_MATCHERS + [ - Matcher(cls.DOC_COMMENT_TEXT, Type.COMMENT)], - - JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: cls.COMMON_DOC_MATCHERS + [ - Matcher(cls.WHITESPACE, Type.COMMENT), - Matcher(cls.DOC_COMMENT_NO_SPACES_TEXT, Type.COMMENT)], - - # Matchers for single line comments. - JavaScriptModes.LINE_COMMENT_MODE: [ - # We greedy match until the end of the line in line comment mode. - Matcher(cls.ANYTHING, Type.COMMENT, JavaScriptModes.TEXT_MODE)], - - # Matchers for code after the function keyword. - JavaScriptModes.FUNCTION_MODE: [ - # Must match open paren before anything else and move into parameter - # mode, otherwise everything inside the parameter list is parsed - # incorrectly. - Matcher(cls.OPENING_PAREN, Type.START_PARAMETERS, - JavaScriptModes.PARAMETER_MODE), - Matcher(cls.WHITESPACE, Type.WHITESPACE), - Matcher(cls.IDENTIFIER, Type.FUNCTION_NAME)], - - # Matchers for function parameters - JavaScriptModes.PARAMETER_MODE: [ - # When in function parameter mode, a closing paren is treated - # specially. Everything else is treated as lines of parameters. - Matcher(cls.CLOSING_PAREN_WITH_SPACE, Type.END_PARAMETERS, - JavaScriptModes.TEXT_MODE), - Matcher(cls.PARAMETERS, Type.PARAMETERS, - JavaScriptModes.PARAMETER_MODE)]} - - def __init__(self, parse_js_doc=True): - """Create a tokenizer object. - - Args: - parse_js_doc: Whether to do detailed parsing of javascript doc comments, - or simply treat them as normal comments. Defaults to parsing JsDoc. - """ - matchers = self.BuildMatchers() - if not parse_js_doc: - # Make a copy so the original doesn't get modified. - matchers = copy.deepcopy(matchers) - matchers[JavaScriptModes.DOC_COMMENT_MODE] = matchers[ - JavaScriptModes.BLOCK_COMMENT_MODE] - - tokenizer.Tokenizer.__init__(self, JavaScriptModes.TEXT_MODE, matchers, - self.JAVASCRIPT_DEFAULT_TYPES) - - def _CreateToken(self, string, token_type, line, line_number, values=None): - """Creates a new JavaScriptToken object. - - Args: - string: The string of input the token contains. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - """ - return javascripttokens.JavaScriptToken(string, token_type, line, - line_number, values, line_number) diff --git a/tools/closure_linter/build/lib/closure_linter/javascripttokens.py b/tools/closure_linter/build/lib/closure_linter/javascripttokens.py deleted file mode 100644 index f5815d2bf86119..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/javascripttokens.py +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Classes to represent JavaScript tokens.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -from closure_linter.common import tokens - -class JavaScriptTokenType(tokens.TokenType): - """Enumeration of JavaScript token types, and useful sets of token types.""" - NUMBER = 'number' - START_SINGLE_LINE_COMMENT = '//' - START_BLOCK_COMMENT = '/*' - START_DOC_COMMENT = '/**' - END_BLOCK_COMMENT = '*/' - END_DOC_COMMENT = 'doc */' - COMMENT = 'comment' - SINGLE_QUOTE_STRING_START = "'string" - SINGLE_QUOTE_STRING_END = "string'" - DOUBLE_QUOTE_STRING_START = '"string' - DOUBLE_QUOTE_STRING_END = 'string"' - STRING_TEXT = 'string' - START_BLOCK = '{' - END_BLOCK = '}' - START_PAREN = '(' - END_PAREN = ')' - START_BRACKET = '[' - END_BRACKET = ']' - REGEX = '/regex/' - FUNCTION_DECLARATION = 'function(...)' - FUNCTION_NAME = 'function functionName(...)' - START_PARAMETERS = 'startparams(' - PARAMETERS = 'pa,ra,ms' - END_PARAMETERS = ')endparams' - SEMICOLON = ';' - DOC_FLAG = '@flag' - DOC_INLINE_FLAG = '{@flag ...}' - DOC_START_BRACE = 'doc {' - DOC_END_BRACE = 'doc }' - DOC_PREFIX = 'comment prefix: * ' - DOC_TYPE_START_BLOCK = 'Type <' - DOC_TYPE_END_BLOCK = 'Type >' - DOC_TYPE_MODIFIER = 'modifier' - SIMPLE_LVALUE = 'lvalue=' - KEYWORD = 'keyword' - OPERATOR = 'operator' - IDENTIFIER = 'identifier' - - STRING_TYPES = frozenset([ - SINGLE_QUOTE_STRING_START, SINGLE_QUOTE_STRING_END, - DOUBLE_QUOTE_STRING_START, DOUBLE_QUOTE_STRING_END, STRING_TEXT]) - - COMMENT_TYPES = frozenset([ - START_SINGLE_LINE_COMMENT, COMMENT, - START_BLOCK_COMMENT, START_DOC_COMMENT, - END_BLOCK_COMMENT, END_DOC_COMMENT, - DOC_START_BRACE, DOC_END_BRACE, - DOC_FLAG, DOC_INLINE_FLAG, DOC_PREFIX, - DOC_TYPE_START_BLOCK, DOC_TYPE_END_BLOCK, DOC_TYPE_MODIFIER]) - - FLAG_DESCRIPTION_TYPES = frozenset([ - DOC_INLINE_FLAG, COMMENT, DOC_START_BRACE, DOC_END_BRACE, - DOC_TYPE_START_BLOCK, DOC_TYPE_END_BLOCK, DOC_TYPE_MODIFIER]) - - FLAG_ENDING_TYPES = frozenset([DOC_FLAG, END_DOC_COMMENT]) - - NON_CODE_TYPES = COMMENT_TYPES | frozenset([ - tokens.TokenType.WHITESPACE, tokens.TokenType.BLANK_LINE]) - - UNARY_OPERATORS = ['!', 'new', 'delete', 'typeof', 'void'] - - UNARY_OK_OPERATORS = ['--', '++', '-', '+'] + UNARY_OPERATORS - - UNARY_POST_OPERATORS = ['--', '++'] - - # An expression ender is any token that can end an object - i.e. we could have - # x.y or [1, 2], or (10 + 9) or {a: 10}. - EXPRESSION_ENDER_TYPES = [tokens.TokenType.NORMAL, IDENTIFIER, NUMBER, - SIMPLE_LVALUE, END_BRACKET, END_PAREN, END_BLOCK, - SINGLE_QUOTE_STRING_END, DOUBLE_QUOTE_STRING_END] - - -class JavaScriptToken(tokens.Token): - """JavaScript token subclass of Token, provides extra instance checks. - - The following token types have data in attached_object: - - All JsDoc flags: a parser.JsDocFlag object. - """ - - def IsKeyword(self, keyword): - """Tests if this token is the given keyword. - - Args: - keyword: The keyword to compare to. - - Returns: - True if this token is a keyword token with the given name. - """ - return self.type == JavaScriptTokenType.KEYWORD and self.string == keyword - - def IsOperator(self, operator): - """Tests if this token is the given operator. - - Args: - operator: The operator to compare to. - - Returns: - True if this token is a operator token with the given name. - """ - return self.type == JavaScriptTokenType.OPERATOR and self.string == operator - - def IsAssignment(self): - """Tests if this token is an assignment operator. - - Returns: - True if this token is an assignment operator. - """ - return (self.type == JavaScriptTokenType.OPERATOR and - self.string.endswith('=') and - self.string not in ('==', '!=', '>=', '<=', '===', '!==')) - - def IsComment(self): - """Tests if this token is any part of a comment. - - Returns: - True if this token is any part of a comment. - """ - return self.type in JavaScriptTokenType.COMMENT_TYPES - - def IsCode(self): - """Tests if this token is code, as opposed to a comment or whitespace.""" - return self.type not in JavaScriptTokenType.NON_CODE_TYPES - - def __repr__(self): - return '' % (self.line_number, - self.type, self.string, - self.values, - self.metadata) diff --git a/tools/closure_linter/build/lib/closure_linter/not_strict_test.py b/tools/closure_linter/build/lib/closure_linter/not_strict_test.py deleted file mode 100644 index c92c13ee031e1b..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/not_strict_test.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for gjslint --nostrict. - -Tests errors that can be thrown by gjslint when not in strict mode. -""" - - - -import os -import sys -import unittest - -import gflags as flags -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import filetestcase - -_RESOURCE_PREFIX = 'closure_linter/testdata' - -flags.FLAGS.strict = False -flags.FLAGS.custom_jsdoc_tags = ('customtag', 'requires') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') -flags.FLAGS.limited_doc_files = ('externs.js', 'dummy.js', - 'limited_doc_checks.js') - - -# List of files under testdata to test. -# We need to list files explicitly since pyglib can't list directories. -_TEST_FILES = [ - 'not_strict.js' - ] - - -class GJsLintTestSuite(unittest.TestSuite): - """Test suite to run a GJsLintTest for each of several files. - - If sys.argv[1:] is non-empty, it is interpreted as a list of filenames in - testdata to test. Otherwise, _TEST_FILES is used. - """ - - def __init__(self, tests=()): - unittest.TestSuite.__init__(self, tests) - - argv = sys.argv and sys.argv[1:] or [] - if argv: - test_files = argv - else: - test_files = _TEST_FILES - for test_file in test_files: - resource_path = os.path.join(_RESOURCE_PREFIX, test_file) - self.addTest(filetestcase.AnnotatedFileTestCase(resource_path, - runner.Run, - errors.ByName)) - -if __name__ == '__main__': - # Don't let main parse args; it happens in the TestSuite. - googletest.main(argv=sys.argv[0:1], defaultTest='GJsLintTestSuite') diff --git a/tools/closure_linter/build/lib/closure_linter/requireprovidesorter.py b/tools/closure_linter/build/lib/closure_linter/requireprovidesorter.py deleted file mode 100644 index e7e08a13c2946f..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/requireprovidesorter.py +++ /dev/null @@ -1,329 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Contains logic for sorting goog.provide and goog.require statements. - -Closurized JavaScript files use goog.provide and goog.require statements at the -top of the file to manage dependencies. These statements should be sorted -alphabetically, however, it is common for them to be accompanied by inline -comments or suppression annotations. In order to sort these statements without -disrupting their comments and annotations, the association between statements -and comments/annotations must be maintained while sorting. - - RequireProvideSorter: Handles checking/fixing of provide/require statements. -""" - - - -from closure_linter import javascripttokens -from closure_linter import tokenutil - -# Shorthand -Type = javascripttokens.JavaScriptTokenType - - -class RequireProvideSorter(object): - """Checks for and fixes alphabetization of provide and require statements. - - When alphabetizing, comments on the same line or comments directly above a - goog.provide or goog.require statement are associated with that statement and - stay with the statement as it gets sorted. - """ - - def CheckProvides(self, token): - """Checks alphabetization of goog.provide statements. - - Iterates over tokens in given token stream, identifies goog.provide tokens, - and checks that they occur in alphabetical order by the object being - provided. - - Args: - token: A token in the token stream before any goog.provide tokens. - - Returns: - The first provide token in the token stream. - - None is returned if all goog.provide statements are already sorted. - """ - provide_tokens = self._GetRequireOrProvideTokens(token, 'goog.provide') - provide_strings = self._GetRequireOrProvideTokenStrings(provide_tokens) - sorted_provide_strings = sorted(provide_strings) - if provide_strings != sorted_provide_strings: - return provide_tokens[0] - return None - - def CheckRequires(self, token): - """Checks alphabetization of goog.require statements. - - Iterates over tokens in given token stream, identifies goog.require tokens, - and checks that they occur in alphabetical order by the dependency being - required. - - Args: - token: A token in the token stream before any goog.require tokens. - - Returns: - The first require token in the token stream. - - None is returned if all goog.require statements are already sorted. - """ - require_tokens = self._GetRequireOrProvideTokens(token, 'goog.require') - require_strings = self._GetRequireOrProvideTokenStrings(require_tokens) - sorted_require_strings = sorted(require_strings) - if require_strings != sorted_require_strings: - return require_tokens[0] - return None - - def FixProvides(self, token): - """Sorts goog.provide statements in the given token stream alphabetically. - - Args: - token: The first token in the token stream. - """ - self._FixProvidesOrRequires( - self._GetRequireOrProvideTokens(token, 'goog.provide')) - - def FixRequires(self, token): - """Sorts goog.require statements in the given token stream alphabetically. - - Args: - token: The first token in the token stream. - """ - self._FixProvidesOrRequires( - self._GetRequireOrProvideTokens(token, 'goog.require')) - - def _FixProvidesOrRequires(self, tokens): - """Sorts goog.provide or goog.require statements. - - Args: - tokens: A list of goog.provide or goog.require tokens in the order they - appear in the token stream. i.e. the first token in this list must - be the first goog.provide or goog.require token. - """ - strings = self._GetRequireOrProvideTokenStrings(tokens) - sorted_strings = sorted(strings) - - # Make a separate pass to remove any blank lines between goog.require/ - # goog.provide tokens. - first_token = tokens[0] - last_token = tokens[-1] - i = last_token - while i != first_token and i is not None: - if i.type is Type.BLANK_LINE: - tokenutil.DeleteToken(i) - i = i.previous - - # A map from required/provided object name to tokens that make up the line - # it was on, including any comments immediately before it or after it on the - # same line. - tokens_map = self._GetTokensMap(tokens) - - # Iterate over the map removing all tokens. - for name in tokens_map: - tokens_to_delete = tokens_map[name] - for i in tokens_to_delete: - tokenutil.DeleteToken(i) - - # Save token to rest of file. Sorted token will be inserted before this. - rest_of_file = tokens_map[strings[-1]][-1].next - - # Re-add all tokens in the map in alphabetical order. - insert_after = tokens[0].previous - for string in sorted_strings: - for i in tokens_map[string]: - if rest_of_file: - tokenutil.InsertTokenBefore(i, rest_of_file) - else: - tokenutil.InsertTokenAfter(i, insert_after) - insert_after = i - - def _GetRequireOrProvideTokens(self, token, token_string): - """Gets all goog.provide or goog.require tokens in the given token stream. - - Args: - token: The first token in the token stream. - token_string: One of 'goog.provide' or 'goog.require' to indicate which - tokens to find. - - Returns: - A list of goog.provide or goog.require tokens in the order they appear in - the token stream. - """ - tokens = [] - while token: - if token.type == Type.IDENTIFIER: - if token.string == token_string: - tokens.append(token) - elif token.string not in [ - 'goog.provide', 'goog.require', 'goog.setTestOnly']: - # These 3 identifiers are at the top of the file. So if any other - # identifier is encountered, return. - # TODO(user): Once it's decided what ordering goog.require - # should use, add 'goog.module' to the list above and implement the - # decision. - break - token = token.next - - return tokens - - def _GetRequireOrProvideTokenStrings(self, tokens): - """Gets a list of strings corresponding to the given list of tokens. - - The string will be the next string in the token stream after each token in - tokens. This is used to find the object being provided/required by a given - goog.provide or goog.require token. - - Args: - tokens: A list of goog.provide or goog.require tokens. - - Returns: - A list of object names that are being provided or required by the given - list of tokens. For example: - - ['object.a', 'object.c', 'object.b'] - """ - token_strings = [] - for token in tokens: - if not token.is_deleted: - name = tokenutil.GetStringAfterToken(token) - token_strings.append(name) - return token_strings - - def _GetTokensMap(self, tokens): - """Gets a map from object name to tokens associated with that object. - - Starting from the goog.provide/goog.require token, searches backwards in the - token stream for any lines that start with a comment. These lines are - associated with the goog.provide/goog.require token. Also associates any - tokens on the same line as the goog.provide/goog.require token with that - token. - - Args: - tokens: A list of goog.provide or goog.require tokens. - - Returns: - A dictionary that maps object names to the tokens associated with the - goog.provide or goog.require of that object name. For example: - - { - 'object.a': [JavaScriptToken, JavaScriptToken, ...], - 'object.b': [...] - } - - The list of tokens includes any comment lines above the goog.provide or - goog.require statement and everything after the statement on the same - line. For example, all of the following would be associated with - 'object.a': - - /** @suppress {extraRequire} */ - goog.require('object.a'); // Some comment. - """ - tokens_map = {} - for token in tokens: - object_name = tokenutil.GetStringAfterToken(token) - # If the previous line starts with a comment, presume that the comment - # relates to the goog.require or goog.provide and keep them together when - # sorting. - first_token = token - previous_first_token = tokenutil.GetFirstTokenInPreviousLine(first_token) - while (previous_first_token and - previous_first_token.IsAnyType(Type.COMMENT_TYPES)): - first_token = previous_first_token - previous_first_token = tokenutil.GetFirstTokenInPreviousLine( - first_token) - - # Find the last token on the line. - last_token = tokenutil.GetLastTokenInSameLine(token) - - all_tokens = self._GetTokenList(first_token, last_token) - tokens_map[object_name] = all_tokens - return tokens_map - - def _GetTokenList(self, first_token, last_token): - """Gets a list of all tokens from first_token to last_token, inclusive. - - Args: - first_token: The first token to get. - last_token: The last token to get. - - Returns: - A list of all tokens between first_token and last_token, including both - first_token and last_token. - - Raises: - Exception: If the token stream ends before last_token is reached. - """ - token_list = [] - token = first_token - while token != last_token: - if not token: - raise Exception('ran out of tokens') - token_list.append(token) - token = token.next - token_list.append(last_token) - - return token_list - - def GetFixedRequireString(self, token): - """Get fixed/sorted order of goog.require statements. - - Args: - token: The first token in the token stream. - - Returns: - A string for correct sorted order of goog.require. - """ - return self._GetFixedRequireOrProvideString( - self._GetRequireOrProvideTokens(token, 'goog.require')) - - def GetFixedProvideString(self, token): - """Get fixed/sorted order of goog.provide statements. - - Args: - token: The first token in the token stream. - - Returns: - A string for correct sorted order of goog.provide. - """ - return self._GetFixedRequireOrProvideString( - self._GetRequireOrProvideTokens(token, 'goog.provide')) - - def _GetFixedRequireOrProvideString(self, tokens): - """Sorts goog.provide or goog.require statements. - - Args: - tokens: A list of goog.provide or goog.require tokens in the order they - appear in the token stream. i.e. the first token in this list must - be the first goog.provide or goog.require token. - - Returns: - A string for sorted goog.require or goog.provide statements - """ - - # A map from required/provided object name to tokens that make up the line - # it was on, including any comments immediately before it or after it on the - # same line. - tokens_map = self._GetTokensMap(tokens) - sorted_strings = sorted(tokens_map.keys()) - - new_order = '' - for string in sorted_strings: - for i in tokens_map[string]: - new_order += i.string - if i.IsLastInLine(): - new_order += '\n' - - return new_order diff --git a/tools/closure_linter/build/lib/closure_linter/requireprovidesorter_test.py b/tools/closure_linter/build/lib/closure_linter/requireprovidesorter_test.py deleted file mode 100644 index fecb6d04dad9ce..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/requireprovidesorter_test.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for RequireProvideSorter.""" - - - -import unittest as googletest -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import testutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - - -class RequireProvideSorterTest(googletest.TestCase): - """Tests for RequireProvideSorter.""" - - def testGetFixedProvideString(self): - """Tests that fixed string constains proper comments also.""" - input_lines = [ - 'goog.provide(\'package.xyz\');', - '/** @suppress {extraprovide} **/', - 'goog.provide(\'package.abcd\');' - ] - - expected_lines = [ - '/** @suppress {extraprovide} **/', - 'goog.provide(\'package.abcd\');', - 'goog.provide(\'package.xyz\');' - ] - - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - fixed_provide_string = sorter.GetFixedProvideString(token) - - self.assertEquals(expected_lines, fixed_provide_string.splitlines()) - - def testGetFixedRequireString(self): - """Tests that fixed string constains proper comments also.""" - input_lines = [ - 'goog.require(\'package.xyz\');', - '/** This is needed for scope. **/', - 'goog.require(\'package.abcd\');' - ] - - expected_lines = [ - '/** This is needed for scope. **/', - 'goog.require(\'package.abcd\');', - 'goog.require(\'package.xyz\');' - ] - - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - fixed_require_string = sorter.GetFixedRequireString(token) - - self.assertEquals(expected_lines, fixed_require_string.splitlines()) - - def testFixRequires_removeBlankLines(self): - """Tests that blank lines are omitted in sorted goog.require statements.""" - input_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassB\');', - '', - 'goog.require(\'package.subpackage.ClassA\');' - ] - expected_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassA\');', - 'goog.require(\'package.subpackage.ClassB\');' - ] - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixRequires(token) - - self.assertEquals(expected_lines, self._GetLines(token)) - - def fixRequiresTest_withTestOnly(self, position): - """Regression-tests sorting even with a goog.setTestOnly statement. - - Args: - position: The position in the list where to insert the goog.setTestOnly - statement. Will be used to test all possible combinations for - this test. - """ - input_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassB\');', - 'goog.require(\'package.subpackage.ClassA\');' - ] - expected_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassA\');', - 'goog.require(\'package.subpackage.ClassB\');' - ] - input_lines.insert(position, 'goog.setTestOnly();') - expected_lines.insert(position, 'goog.setTestOnly();') - - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixRequires(token) - - self.assertEquals(expected_lines, self._GetLines(token)) - - def testFixRequires_withTestOnly(self): - """Regression-tests sorting even after a goog.setTestOnly statement.""" - - # goog.setTestOnly at first line. - self.fixRequiresTest_withTestOnly(position=0) - - # goog.setTestOnly after goog.provide. - self.fixRequiresTest_withTestOnly(position=1) - - # goog.setTestOnly before goog.require. - self.fixRequiresTest_withTestOnly(position=2) - - # goog.setTestOnly after goog.require. - self.fixRequiresTest_withTestOnly(position=4) - - def _GetLines(self, token): - """Returns an array of lines based on the specified token stream.""" - lines = [] - line = '' - while token: - line += token.string - if token.IsLastInLine(): - lines.append(line) - line = '' - token = token.next - return lines - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/runner.py b/tools/closure_linter/build/lib/closure_linter/runner.py deleted file mode 100644 index 04e7fa4ac87a1c..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/runner.py +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Main lint function. Tokenizes file, runs passes, and feeds to checker.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = 'nnaze@google.com (Nathan Naze)' - -import traceback - -import gflags as flags - -from closure_linter import checker -from closure_linter import ecmalintrules -from closure_linter import ecmametadatapass -from closure_linter import error_check -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokenizer - -from closure_linter.common import error -from closure_linter.common import htmlutil -from closure_linter.common import tokens - -flags.DEFINE_list('limited_doc_files', ['dummy.js', 'externs.js'], - 'List of files with relaxed documentation checks. Will not ' - 'report errors for missing documentation, some missing ' - 'descriptions, or methods whose @return tags don\'t have a ' - 'matching return statement.') -flags.DEFINE_boolean('error_trace', False, - 'Whether to show error exceptions.') -flags.ADOPT_module_key_flags(checker) -flags.ADOPT_module_key_flags(ecmalintrules) -flags.ADOPT_module_key_flags(error_check) - - -def _GetLastNonWhiteSpaceToken(start_token): - """Get the last non-whitespace token in a token stream.""" - ret_token = None - - whitespace_tokens = frozenset([ - tokens.TokenType.WHITESPACE, tokens.TokenType.BLANK_LINE]) - for t in start_token: - if t.type not in whitespace_tokens: - ret_token = t - - return ret_token - - -def _IsHtml(filename): - return filename.endswith('.html') or filename.endswith('.htm') - - -def _Tokenize(fileobj): - """Tokenize a file. - - Args: - fileobj: file-like object (or iterable lines) with the source. - - Returns: - The first token in the token stream and the ending mode of the tokenizer. - """ - tokenizer = javascripttokenizer.JavaScriptTokenizer() - start_token = tokenizer.TokenizeFile(fileobj) - return start_token, tokenizer.mode - - -def _IsLimitedDocCheck(filename, limited_doc_files): - """Whether this this a limited-doc file. - - Args: - filename: The filename. - limited_doc_files: Iterable of strings. Suffixes of filenames that should - be limited doc check. - - Returns: - Whether the file should be limited check. - """ - for limited_doc_filename in limited_doc_files: - if filename.endswith(limited_doc_filename): - return True - return False - - -def Run(filename, error_handler, source=None): - """Tokenize, run passes, and check the given file. - - Args: - filename: The path of the file to check - error_handler: The error handler to report errors to. - source: A file-like object with the file source. If omitted, the file will - be read from the filename path. - """ - if not source: - try: - source = open(filename) - except IOError: - error_handler.HandleFile(filename, None) - error_handler.HandleError( - error.Error(errors.FILE_NOT_FOUND, 'File not found')) - error_handler.FinishFile() - return - - if _IsHtml(filename): - source_file = htmlutil.GetScriptLines(source) - else: - source_file = source - - token, tokenizer_mode = _Tokenize(source_file) - - error_handler.HandleFile(filename, token) - - # If we did not end in the basic mode, this a failed parse. - if tokenizer_mode is not javascripttokenizer.JavaScriptModes.TEXT_MODE: - error_handler.HandleError( - error.Error(errors.FILE_IN_BLOCK, - 'File ended in mode "%s".' % tokenizer_mode, - _GetLastNonWhiteSpaceToken(token))) - - # Run the ECMA pass - error_token = None - - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - error_token = RunMetaDataPass(token, ecma_pass, error_handler, filename) - - is_limited_doc_check = ( - _IsLimitedDocCheck(filename, flags.FLAGS.limited_doc_files)) - - _RunChecker(token, error_handler, - is_limited_doc_check, - is_html=_IsHtml(filename), - stop_token=error_token) - - error_handler.FinishFile() - - -def RunMetaDataPass(start_token, metadata_pass, error_handler, filename=''): - """Run a metadata pass over a token stream. - - Args: - start_token: The first token in a token stream. - metadata_pass: Metadata pass to run. - error_handler: The error handler to report errors to. - filename: Filename of the source. - - Returns: - The token where the error occurred (if any). - """ - - try: - metadata_pass.Process(start_token) - except ecmametadatapass.ParseError, parse_err: - if flags.FLAGS.error_trace: - traceback.print_exc() - error_token = parse_err.token - error_msg = str(parse_err) - error_handler.HandleError( - error.Error(errors.FILE_DOES_NOT_PARSE, - ('Error parsing file at token "%s". Unable to ' - 'check the rest of file.' - '\nError "%s"' % (error_token, error_msg)), error_token)) - return error_token - except Exception: # pylint: disable=broad-except - traceback.print_exc() - error_handler.HandleError( - error.Error( - errors.FILE_DOES_NOT_PARSE, - 'Internal error in %s' % filename)) - - -def _RunChecker(start_token, error_handler, - limited_doc_checks, is_html, - stop_token=None): - - state_tracker = javascriptstatetracker.JavaScriptStateTracker() - - style_checker = checker.JavaScriptStyleChecker( - state_tracker=state_tracker, - error_handler=error_handler) - - style_checker.Check(start_token, - is_html=is_html, - limited_doc_checks=limited_doc_checks, - stop_token=stop_token) diff --git a/tools/closure_linter/build/lib/closure_linter/runner_test.py b/tools/closure_linter/build/lib/closure_linter/runner_test.py deleted file mode 100644 index da5857d30950f6..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/runner_test.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the runner module.""" - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import StringIO - - -import mox - - -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import error -from closure_linter.common import errorhandler -from closure_linter.common import tokens - - -class LimitedDocTest(googletest.TestCase): - - def testIsLimitedDocCheck(self): - self.assertTrue(runner._IsLimitedDocCheck('foo_test.js', ['_test.js'])) - self.assertFalse(runner._IsLimitedDocCheck('foo_bar.js', ['_test.js'])) - - self.assertTrue(runner._IsLimitedDocCheck( - 'foo_moo.js', ['moo.js', 'quack.js'])) - self.assertFalse(runner._IsLimitedDocCheck( - 'foo_moo.js', ['woof.js', 'quack.js'])) - - -class RunnerTest(googletest.TestCase): - - def setUp(self): - self.mox = mox.Mox() - - def testRunOnMissingFile(self): - mock_error_handler = self.mox.CreateMock(errorhandler.ErrorHandler) - - def ValidateError(err): - return (isinstance(err, error.Error) and - err.code is errors.FILE_NOT_FOUND and - err.token is None) - - mock_error_handler.HandleFile('does_not_exist.js', None) - mock_error_handler.HandleError(mox.Func(ValidateError)) - mock_error_handler.FinishFile() - - self.mox.ReplayAll() - - runner.Run('does_not_exist.js', mock_error_handler) - - self.mox.VerifyAll() - - def testBadTokenization(self): - mock_error_handler = self.mox.CreateMock(errorhandler.ErrorHandler) - - def ValidateError(err): - return (isinstance(err, error.Error) and - err.code is errors.FILE_IN_BLOCK and - err.token.string == '}') - - mock_error_handler.HandleFile('foo.js', mox.IsA(tokens.Token)) - mock_error_handler.HandleError(mox.Func(ValidateError)) - mock_error_handler.HandleError(mox.IsA(error.Error)) - mock_error_handler.FinishFile() - - self.mox.ReplayAll() - - source = StringIO.StringIO(_BAD_TOKENIZATION_SCRIPT) - runner.Run('foo.js', mock_error_handler, source) - - self.mox.VerifyAll() - - -_BAD_TOKENIZATION_SCRIPT = """ -function foo () { - var a = 3; - var b = 2; - return b + a; /* Comment not closed -} -""" - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/scopeutil.py b/tools/closure_linter/build/lib/closure_linter/scopeutil.py deleted file mode 100644 index a7ca9b630a470c..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/scopeutil.py +++ /dev/null @@ -1,206 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tools to match goog.scope alias statements.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import itertools - -from closure_linter import ecmametadatapass -from closure_linter import tokenutil -from closure_linter.javascripttokens import JavaScriptTokenType - - - -def IsGoogScopeBlock(context): - """Whether the given context is a goog.scope block. - - This function only checks that the block is a function block inside - a goog.scope() call. - - TODO(nnaze): Implement goog.scope checks that verify the call is - in the root context and contains only a single function literal. - - Args: - context: An EcmaContext of type block. - - Returns: - Whether the context is a goog.scope block. - """ - - if context.type != ecmametadatapass.EcmaContext.BLOCK: - return False - - if not _IsFunctionLiteralBlock(context): - return False - - # Check that this function is contained by a group - # of form "goog.scope(...)". - parent = context.parent - if parent and parent.type is ecmametadatapass.EcmaContext.GROUP: - - last_code_token = parent.start_token.metadata.last_code - - if (last_code_token and - last_code_token.type is JavaScriptTokenType.IDENTIFIER and - last_code_token.string == 'goog.scope'): - return True - - return False - - -def _IsFunctionLiteralBlock(block_context): - """Check if a context is a function literal block (without parameters). - - Example function literal block: 'function() {}' - - Args: - block_context: An EcmaContext of type block. - - Returns: - Whether this context is a function literal block. - """ - - previous_code_tokens_iter = itertools.ifilter( - lambda token: token not in JavaScriptTokenType.NON_CODE_TYPES, - reversed(block_context.start_token)) - - # Ignore the current token - next(previous_code_tokens_iter, None) - - # Grab the previous three tokens and put them in correct order. - previous_code_tokens = list(itertools.islice(previous_code_tokens_iter, 3)) - previous_code_tokens.reverse() - - # There aren't three previous tokens. - if len(previous_code_tokens) is not 3: - return False - - # Check that the previous three code tokens are "function ()" - previous_code_token_types = [token.type for token in previous_code_tokens] - if (previous_code_token_types == [ - JavaScriptTokenType.FUNCTION_DECLARATION, - JavaScriptTokenType.START_PARAMETERS, - JavaScriptTokenType.END_PARAMETERS]): - return True - - return False - - -def IsInClosurizedNamespace(symbol, closurized_namespaces): - """Match a goog.scope alias. - - Args: - symbol: An identifier like 'goog.events.Event'. - closurized_namespaces: Iterable of valid Closurized namespaces (strings). - - Returns: - True if symbol is an identifier in a Closurized namespace, otherwise False. - """ - for ns in closurized_namespaces: - if symbol.startswith(ns + '.'): - return True - - return False - - -def _GetVarAssignmentTokens(context): - """Returns the tokens from context if it is a var assignment. - - Args: - context: An EcmaContext. - - Returns: - If a var assignment, the tokens contained within it w/o the trailing - semicolon. - """ - if context.type != ecmametadatapass.EcmaContext.VAR: - return - - # Get the tokens in this statement. - if context.start_token and context.end_token: - statement_tokens = tokenutil.GetTokenRange(context.start_token, - context.end_token) - else: - return - - # And now just those tokens that are actually code. - is_non_code_type = lambda t: t.type not in JavaScriptTokenType.NON_CODE_TYPES - code_tokens = filter(is_non_code_type, statement_tokens) - - # Pop off the semicolon if present. - if code_tokens and code_tokens[-1].IsType(JavaScriptTokenType.SEMICOLON): - code_tokens.pop() - - if len(code_tokens) < 4: - return - - if (code_tokens[0].IsKeyword('var') and - code_tokens[1].IsType(JavaScriptTokenType.SIMPLE_LVALUE) and - code_tokens[2].IsOperator('=')): - return code_tokens - - -def MatchAlias(context): - """Match an alias statement (some identifier assigned to a variable). - - Example alias: var MyClass = proj.longNamespace.MyClass. - - Args: - context: An EcmaContext of type EcmaContext.VAR. - - Returns: - If a valid alias, returns a tuple of alias and symbol, otherwise None. - """ - code_tokens = _GetVarAssignmentTokens(context) - if code_tokens is None: - return - - if all(tokenutil.IsIdentifierOrDot(t) for t in code_tokens[3:]): - # var Foo = bar.Foo; - alias, symbol = code_tokens[1], code_tokens[3] - # Mark both tokens as an alias definition to not count them as usages. - alias.metadata.is_alias_definition = True - symbol.metadata.is_alias_definition = True - return alias.string, tokenutil.GetIdentifierForToken(symbol) - - -def MatchModuleAlias(context): - """Match an alias statement in a goog.module style import. - - Example alias: var MyClass = goog.require('proj.longNamespace.MyClass'). - - Args: - context: An EcmaContext. - - Returns: - If a valid alias, returns a tuple of alias and symbol, otherwise None. - """ - code_tokens = _GetVarAssignmentTokens(context) - if code_tokens is None: - return - - if(code_tokens[3].IsType(JavaScriptTokenType.IDENTIFIER) and - code_tokens[3].string == 'goog.require'): - # var Foo = goog.require('bar.Foo'); - alias = code_tokens[1] - symbol = tokenutil.GetStringAfterToken(code_tokens[3]) - if symbol: - alias.metadata.is_alias_definition = True - return alias.string, symbol diff --git a/tools/closure_linter/build/lib/closure_linter/scopeutil_test.py b/tools/closure_linter/build/lib/closure_linter/scopeutil_test.py deleted file mode 100644 index 722a95390022de..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/scopeutil_test.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the scopeutil module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - - -import unittest as googletest - -from closure_linter import ecmametadatapass -from closure_linter import scopeutil -from closure_linter import testutil - - -def _FindContexts(start_token): - """Depth first search of all contexts referenced by a token stream. - - Includes contexts' parents, which might not be directly referenced - by any token in the stream. - - Args: - start_token: First token in the token stream. - - Yields: - All contexts referenced by this token stream. - """ - - seen_contexts = set() - - # For each token, yield the context if we haven't seen it before. - for token in start_token: - - token_context = token.metadata.context - contexts = [token_context] - - # Also grab all the context's ancestors. - parent = token_context.parent - while parent: - contexts.append(parent) - parent = parent.parent - - # Yield each of these contexts if we've not seen them. - for context in contexts: - if context not in seen_contexts: - yield context - - seen_contexts.add(context) - - -def _FindFirstContextOfType(token, context_type): - """Returns the first statement context.""" - for context in _FindContexts(token): - if context.type == context_type: - return context - - -def _ParseAssignment(script): - start_token = testutil.TokenizeSourceAndRunEcmaPass(script) - statement = _FindFirstContextOfType( - start_token, ecmametadatapass.EcmaContext.VAR) - return statement - - -class StatementTest(googletest.TestCase): - - def assertAlias(self, expected_match, script): - statement = _ParseAssignment(script) - match = scopeutil.MatchAlias(statement) - self.assertEquals(expected_match, match) - - def assertModuleAlias(self, expected_match, script): - statement = _ParseAssignment(script) - match = scopeutil.MatchModuleAlias(statement) - self.assertEquals(expected_match, match) - - def testSimpleAliases(self): - self.assertAlias( - ('foo', 'goog.foo'), - 'var foo = goog.foo;') - - self.assertAlias( - ('foo', 'goog.foo'), - 'var foo = goog.foo') # No semicolon - - def testAliasWithComment(self): - self.assertAlias( - ('Component', 'goog.ui.Component'), - 'var Component = /* comment */ goog.ui.Component;') - - def testMultilineAlias(self): - self.assertAlias( - ('Component', 'goog.ui.Component'), - 'var Component = \n goog.ui.\n Component;') - - def testNonSymbolAliasVarStatements(self): - self.assertAlias(None, 'var foo = 3;') - self.assertAlias(None, 'var foo = function() {};') - self.assertAlias(None, 'var foo = bar ? baz : qux;') - - def testModuleAlias(self): - self.assertModuleAlias( - ('foo', 'goog.foo'), - 'var foo = goog.require("goog.foo");') - self.assertModuleAlias( - None, - 'var foo = goog.require(notastring);') - - -class ScopeBlockTest(googletest.TestCase): - - @staticmethod - def _GetBlocks(source): - start_token = testutil.TokenizeSourceAndRunEcmaPass(source) - for context in _FindContexts(start_token): - if context.type is ecmametadatapass.EcmaContext.BLOCK: - yield context - - def assertNoBlocks(self, script): - blocks = list(self._GetBlocks(script)) - self.assertEquals([], blocks) - - def testNotBlocks(self): - # Ensure these are not considered blocks. - self.assertNoBlocks('goog.scope(if{});') - self.assertNoBlocks('goog.scope(for{});') - self.assertNoBlocks('goog.scope(switch{});') - self.assertNoBlocks('goog.scope(function foo{});') - - def testNonScopeBlocks(self): - - blocks = list(self._GetBlocks('goog.scope(try{});')) - self.assertEquals(1, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - blocks = list(self._GetBlocks('goog.scope(function(a,b){});')) - self.assertEquals(1, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - blocks = list(self._GetBlocks('goog.scope(try{} catch(){});')) - # Two blocks: try and catch. - self.assertEquals(2, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - blocks = list(self._GetBlocks('goog.scope(try{} catch(){} finally {});')) - self.assertEquals(3, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - -class AliasTest(googletest.TestCase): - - def setUp(self): - self.start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCRIPT) - - def testMatchAliasStatement(self): - matches = set() - for context in _FindContexts(self.start_token): - match = scopeutil.MatchAlias(context) - if match: - matches.add(match) - - self.assertEquals( - set([('bar', 'baz'), - ('foo', 'this.foo_'), - ('Component', 'goog.ui.Component'), - ('MyClass', 'myproject.foo.MyClass'), - ('NonClosurizedClass', 'aaa.bbb.NonClosurizedClass')]), - matches) - - def testMatchAliasStatement_withClosurizedNamespaces(self): - - closurized_namepaces = frozenset(['goog', 'myproject']) - - matches = set() - for context in _FindContexts(self.start_token): - match = scopeutil.MatchAlias(context) - if match: - unused_alias, symbol = match - if scopeutil.IsInClosurizedNamespace(symbol, closurized_namepaces): - matches.add(match) - - self.assertEquals( - set([('MyClass', 'myproject.foo.MyClass'), - ('Component', 'goog.ui.Component')]), - matches) - -_TEST_SCRIPT = """ -goog.scope(function() { - var Component = goog.ui.Component; // scope alias - var MyClass = myproject.foo.MyClass; // scope alias - - // Scope alias of non-Closurized namespace. - var NonClosurizedClass = aaa.bbb.NonClosurizedClass; - - var foo = this.foo_; // non-scope object property alias - var bar = baz; // variable alias - - var component = new Component(); -}); - -""" - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/statetracker.py b/tools/closure_linter/build/lib/closure_linter/statetracker.py deleted file mode 100644 index 52e363972f200a..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/statetracker.py +++ /dev/null @@ -1,1294 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Light weight EcmaScript state tracker that reads tokens and tracks state.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import re - -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import tokenutil -from closure_linter import typeannotation - -# Shorthand -Type = javascripttokens.JavaScriptTokenType - - -class DocFlag(object): - """Generic doc flag object. - - Attribute: - flag_type: param, return, define, type, etc. - flag_token: The flag token. - type_start_token: The first token specifying the flag type, - including braces. - type_end_token: The last token specifying the flag type, - including braces. - type: The type spec string. - jstype: The type spec, a TypeAnnotation instance. - name_token: The token specifying the flag name. - name: The flag name - description_start_token: The first token in the description. - description_end_token: The end token in the description. - description: The description. - """ - - # Please keep these lists alphabetized. - - # The list of standard jsdoc tags is from - STANDARD_DOC = frozenset([ - 'author', - 'bug', - 'classTemplate', - 'consistentIdGenerator', - 'const', - 'constructor', - 'define', - 'deprecated', - 'dict', - 'enum', - 'export', - 'expose', - 'extends', - 'externs', - 'fileoverview', - 'idGenerator', - 'implements', - 'implicitCast', - 'interface', - 'lends', - 'license', - 'ngInject', # This annotation is specific to AngularJS. - 'noalias', - 'nocompile', - 'nosideeffects', - 'override', - 'owner', - 'package', - 'param', - 'preserve', - 'private', - 'protected', - 'public', - 'return', - 'see', - 'stableIdGenerator', - 'struct', - 'supported', - 'template', - 'this', - 'type', - 'typedef', - 'unrestricted', - ]) - - ANNOTATION = frozenset(['preserveTry', 'suppress']) - - LEGAL_DOC = STANDARD_DOC | ANNOTATION - - # Includes all Closure Compiler @suppress types. - # Not all of these annotations are interpreted by Closure Linter. - # - # Specific cases: - # - accessControls is supported by the compiler at the expression - # and method level to suppress warnings about private/protected - # access (method level applies to all references in the method). - # The linter mimics the compiler behavior. - SUPPRESS_TYPES = frozenset([ - 'accessControls', - 'ambiguousFunctionDecl', - 'checkDebuggerStatement', - 'checkRegExp', - 'checkStructDictInheritance', - 'checkTypes', - 'checkVars', - 'const', - 'constantProperty', - 'deprecated', - 'duplicate', - 'es5Strict', - 'externsValidation', - 'extraProvide', - 'extraRequire', - 'fileoverviewTags', - 'globalThis', - 'internetExplorerChecks', - 'invalidCasts', - 'missingProperties', - 'missingProvide', - 'missingRequire', - 'missingReturn', - 'nonStandardJsDocs', - 'strictModuleDepCheck', - 'suspiciousCode', - 'tweakValidation', - 'typeInvalidation', - 'undefinedNames', - 'undefinedVars', - 'underscore', - 'unknownDefines', - 'unnecessaryCasts', - 'unusedPrivateMembers', - 'uselessCode', - 'visibility', - 'with', - ]) - - HAS_DESCRIPTION = frozenset([ - 'define', - 'deprecated', - 'desc', - 'fileoverview', - 'license', - 'param', - 'preserve', - 'return', - 'supported', - ]) - - # Docflags whose argument should be parsed using the typeannotation parser. - HAS_TYPE = frozenset([ - 'const', - 'define', - 'enum', - 'extends', - 'final', - 'implements', - 'mods', - 'package', - 'param', - 'private', - 'protected', - 'public', - 'return', - 'suppress', - 'type', - 'typedef', - ]) - - # Docflags for which it's ok to omit the type (flag without an argument). - CAN_OMIT_TYPE = frozenset([ - 'const', - 'enum', - 'final', - 'package', - 'private', - 'protected', - 'public', - 'suppress', # We'll raise a separate INCORRECT_SUPPRESS_SYNTAX instead. - ]) - - # Docflags that only take a type as an argument and should not parse a - # following description. - TYPE_ONLY = frozenset([ - 'const', - 'enum', - 'extends', - 'implements', - 'package', - 'suppress', - 'type', - ]) - - HAS_NAME = frozenset(['param']) - - EMPTY_COMMENT_LINE = re.compile(r'^\s*\*?\s*$') - EMPTY_STRING = re.compile(r'^\s*$') - - def __init__(self, flag_token, error_handler=None): - """Creates the DocFlag object and attaches it to the given start token. - - Args: - flag_token: The starting token of the flag. - error_handler: An optional error handler for errors occurring while - parsing the doctype. - """ - self.flag_token = flag_token - self.flag_type = flag_token.string.strip().lstrip('@') - - # Extract type, if applicable. - self.type = None - self.jstype = None - self.type_start_token = None - self.type_end_token = None - if self.flag_type in self.HAS_TYPE: - brace = tokenutil.SearchUntil(flag_token, [Type.DOC_START_BRACE], - Type.FLAG_ENDING_TYPES) - if brace: - end_token, contents = _GetMatchingEndBraceAndContents(brace) - self.type = contents - self.jstype = typeannotation.Parse(brace, end_token, - error_handler) - self.type_start_token = brace - self.type_end_token = end_token - elif (self.flag_type in self.TYPE_ONLY and - flag_token.next.type not in Type.FLAG_ENDING_TYPES and - flag_token.line_number == flag_token.next.line_number): - # b/10407058. If the flag is expected to be followed by a type then - # search for type in same line only. If no token after flag in same - # line then conclude that no type is specified. - self.type_start_token = flag_token.next - self.type_end_token, self.type = _GetEndTokenAndContents( - self.type_start_token) - if self.type is not None: - self.type = self.type.strip() - self.jstype = typeannotation.Parse(flag_token, self.type_end_token, - error_handler) - - # Extract name, if applicable. - self.name_token = None - self.name = None - if self.flag_type in self.HAS_NAME: - # Handle bad case, name could be immediately after flag token. - self.name_token = _GetNextPartialIdentifierToken(flag_token) - - # Handle good case, if found token is after type start, look for - # a identifier (substring to cover cases like [cnt] b/4197272) after - # type end, since types contain identifiers. - if (self.type and self.name_token and - tokenutil.Compare(self.name_token, self.type_start_token) > 0): - self.name_token = _GetNextPartialIdentifierToken(self.type_end_token) - - if self.name_token: - self.name = self.name_token.string - - # Extract description, if applicable. - self.description_start_token = None - self.description_end_token = None - self.description = None - if self.flag_type in self.HAS_DESCRIPTION: - search_start_token = flag_token - if self.name_token and self.type_end_token: - if tokenutil.Compare(self.type_end_token, self.name_token) > 0: - search_start_token = self.type_end_token - else: - search_start_token = self.name_token - elif self.name_token: - search_start_token = self.name_token - elif self.type: - search_start_token = self.type_end_token - - interesting_token = tokenutil.Search(search_start_token, - Type.FLAG_DESCRIPTION_TYPES | Type.FLAG_ENDING_TYPES) - if interesting_token.type in Type.FLAG_DESCRIPTION_TYPES: - self.description_start_token = interesting_token - self.description_end_token, self.description = ( - _GetEndTokenAndContents(interesting_token)) - - def HasType(self): - """Returns whether this flag should have a type annotation.""" - return self.flag_type in self.HAS_TYPE - - def __repr__(self): - return '' % (self.flag_type, repr(self.jstype)) - - -class DocComment(object): - """JavaScript doc comment object. - - Attributes: - ordered_params: Ordered list of parameters documented. - start_token: The token that starts the doc comment. - end_token: The token that ends the doc comment. - suppressions: Map of suppression type to the token that added it. - """ - def __init__(self, start_token): - """Create the doc comment object. - - Args: - start_token: The first token in the doc comment. - """ - self.__flags = [] - self.start_token = start_token - self.end_token = None - self.suppressions = {} - self.invalidated = False - - @property - def ordered_params(self): - """Gives the list of parameter names as a list of strings.""" - params = [] - for flag in self.__flags: - if flag.flag_type == 'param' and flag.name: - params.append(flag.name) - return params - - def Invalidate(self): - """Indicate that the JSDoc is well-formed but we had problems parsing it. - - This is a short-circuiting mechanism so that we don't emit false - positives about well-formed doc comments just because we don't support - hot new syntaxes. - """ - self.invalidated = True - - def IsInvalidated(self): - """Test whether Invalidate() has been called.""" - return self.invalidated - - def AddSuppression(self, token): - """Add a new error suppression flag. - - Args: - token: The suppression flag token. - """ - flag = token and token.attached_object - if flag and flag.jstype: - for suppression in flag.jstype.IterIdentifiers(): - self.suppressions[suppression] = token - - def SuppressionOnly(self): - """Returns whether this comment contains only suppression flags.""" - if not self.__flags: - return False - - for flag in self.__flags: - if flag.flag_type != 'suppress': - return False - - return True - - def AddFlag(self, flag): - """Add a new document flag. - - Args: - flag: DocFlag object. - """ - self.__flags.append(flag) - - def InheritsDocumentation(self): - """Test if the jsdoc implies documentation inheritance. - - Returns: - True if documentation may be pulled off the superclass. - """ - return self.HasFlag('inheritDoc') or self.HasFlag('override') - - def HasFlag(self, flag_type): - """Test if the given flag has been set. - - Args: - flag_type: The type of the flag to check. - - Returns: - True if the flag is set. - """ - for flag in self.__flags: - if flag.flag_type == flag_type: - return True - return False - - def GetFlag(self, flag_type): - """Gets the last flag of the given type. - - Args: - flag_type: The type of the flag to get. - - Returns: - The last instance of the given flag type in this doc comment. - """ - for flag in reversed(self.__flags): - if flag.flag_type == flag_type: - return flag - - def GetDocFlags(self): - """Return the doc flags for this comment.""" - return list(self.__flags) - - def _YieldDescriptionTokens(self): - for token in self.start_token: - - if (token is self.end_token or - token.type is javascripttokens.JavaScriptTokenType.DOC_FLAG or - token.type not in javascripttokens.JavaScriptTokenType.COMMENT_TYPES): - return - - if token.type not in [ - javascripttokens.JavaScriptTokenType.START_DOC_COMMENT, - javascripttokens.JavaScriptTokenType.END_DOC_COMMENT, - javascripttokens.JavaScriptTokenType.DOC_PREFIX]: - yield token - - @property - def description(self): - return tokenutil.TokensToString( - self._YieldDescriptionTokens()) - - def GetTargetIdentifier(self): - """Returns the identifier (as a string) that this is a comment for. - - Note that this uses method uses GetIdentifierForToken to get the full - identifier, even if broken up by whitespace, newlines, or comments, - and thus could be longer than GetTargetToken().string. - - Returns: - The identifier for the token this comment is for. - """ - token = self.GetTargetToken() - if token: - return tokenutil.GetIdentifierForToken(token) - - def GetTargetToken(self): - """Get this comment's target token. - - Returns: - The token that is the target of this comment, or None if there isn't one. - """ - - # File overviews describe the file, not a token. - if self.HasFlag('fileoverview'): - return - - skip_types = frozenset([ - Type.WHITESPACE, - Type.BLANK_LINE, - Type.START_PAREN]) - - target_types = frozenset([ - Type.FUNCTION_NAME, - Type.IDENTIFIER, - Type.SIMPLE_LVALUE]) - - token = self.end_token.next - while token: - if token.type in target_types: - return token - - # Handles the case of a comment on "var foo = ...' - if token.IsKeyword('var'): - next_code_token = tokenutil.CustomSearch( - token, - lambda t: t.type not in Type.NON_CODE_TYPES) - - if (next_code_token and - next_code_token.IsType(Type.SIMPLE_LVALUE)): - return next_code_token - - return - - # Handles the case of a comment on "function foo () {}" - if token.type is Type.FUNCTION_DECLARATION: - next_code_token = tokenutil.CustomSearch( - token, - lambda t: t.type not in Type.NON_CODE_TYPES) - - if next_code_token.IsType(Type.FUNCTION_NAME): - return next_code_token - - return - - # Skip types will end the search. - if token.type not in skip_types: - return - - token = token.next - - def CompareParameters(self, params): - """Computes the edit distance and list from the function params to the docs. - - Uses the Levenshtein edit distance algorithm, with code modified from - http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python - - Args: - params: The parameter list for the function declaration. - - Returns: - The edit distance, the edit list. - """ - source_len, target_len = len(self.ordered_params), len(params) - edit_lists = [[]] - distance = [[]] - for i in range(target_len+1): - edit_lists[0].append(['I'] * i) - distance[0].append(i) - - for j in range(1, source_len+1): - edit_lists.append([['D'] * j]) - distance.append([j]) - - for i in range(source_len): - for j in range(target_len): - cost = 1 - if self.ordered_params[i] == params[j]: - cost = 0 - - deletion = distance[i][j+1] + 1 - insertion = distance[i+1][j] + 1 - substitution = distance[i][j] + cost - - edit_list = None - best = None - if deletion <= insertion and deletion <= substitution: - # Deletion is best. - best = deletion - edit_list = list(edit_lists[i][j+1]) - edit_list.append('D') - - elif insertion <= substitution: - # Insertion is best. - best = insertion - edit_list = list(edit_lists[i+1][j]) - edit_list.append('I') - edit_lists[i+1].append(edit_list) - - else: - # Substitution is best. - best = substitution - edit_list = list(edit_lists[i][j]) - if cost: - edit_list.append('S') - else: - edit_list.append('=') - - edit_lists[i+1].append(edit_list) - distance[i+1].append(best) - - return distance[source_len][target_len], edit_lists[source_len][target_len] - - def __repr__(self): - """Returns a string representation of this object. - - Returns: - A string representation of this object. - """ - return '' % ( - str(self.ordered_params), str(self.__flags)) - - -# -# Helper methods used by DocFlag and DocComment to parse out flag information. -# - - -def _GetMatchingEndBraceAndContents(start_brace): - """Returns the matching end brace and contents between the two braces. - - If any FLAG_ENDING_TYPE token is encountered before a matching end brace, then - that token is used as the matching ending token. Contents will have all - comment prefixes stripped out of them, and all comment prefixes in between the - start and end tokens will be split out into separate DOC_PREFIX tokens. - - Args: - start_brace: The DOC_START_BRACE token immediately before desired contents. - - Returns: - The matching ending token (DOC_END_BRACE or FLAG_ENDING_TYPE) and a string - of the contents between the matching tokens, minus any comment prefixes. - """ - open_count = 1 - close_count = 0 - contents = [] - - # We don't consider the start brace part of the type string. - token = start_brace.next - while open_count != close_count: - if token.type == Type.DOC_START_BRACE: - open_count += 1 - elif token.type == Type.DOC_END_BRACE: - close_count += 1 - - if token.type != Type.DOC_PREFIX: - contents.append(token.string) - - if token.type in Type.FLAG_ENDING_TYPES: - break - token = token.next - - #Don't include the end token (end brace, end doc comment, etc.) in type. - token = token.previous - contents = contents[:-1] - - return token, ''.join(contents) - - -def _GetNextPartialIdentifierToken(start_token): - """Returns the first token having identifier as substring after a token. - - Searches each token after the start to see if it contains an identifier. - If found, token is returned. If no identifier is found returns None. - Search is abandoned when a FLAG_ENDING_TYPE token is found. - - Args: - start_token: The token to start searching after. - - Returns: - The token found containing identifier, None otherwise. - """ - token = start_token.next - - while token and token.type not in Type.FLAG_ENDING_TYPES: - match = javascripttokenizer.JavaScriptTokenizer.IDENTIFIER.search( - token.string) - if match is not None and token.type == Type.COMMENT: - return token - - token = token.next - - return None - - -def _GetEndTokenAndContents(start_token): - """Returns last content token and all contents before FLAG_ENDING_TYPE token. - - Comment prefixes are split into DOC_PREFIX tokens and stripped from the - returned contents. - - Args: - start_token: The token immediately before the first content token. - - Returns: - The last content token and a string of all contents including start and - end tokens, with comment prefixes stripped. - """ - iterator = start_token - last_line = iterator.line_number - last_token = None - contents = '' - doc_depth = 0 - while not iterator.type in Type.FLAG_ENDING_TYPES or doc_depth > 0: - if (iterator.IsFirstInLine() and - DocFlag.EMPTY_COMMENT_LINE.match(iterator.line)): - # If we have a blank comment line, consider that an implicit - # ending of the description. This handles a case like: - # - # * @return {boolean} True - # * - # * Note: This is a sentence. - # - # The note is not part of the @return description, but there was - # no definitive ending token. Rather there was a line containing - # only a doc comment prefix or whitespace. - break - - # b/2983692 - # don't prematurely match against a @flag if inside a doc flag - # need to think about what is the correct behavior for unterminated - # inline doc flags - if (iterator.type == Type.DOC_START_BRACE and - iterator.next.type == Type.DOC_INLINE_FLAG): - doc_depth += 1 - elif (iterator.type == Type.DOC_END_BRACE and - doc_depth > 0): - doc_depth -= 1 - - if iterator.type in Type.FLAG_DESCRIPTION_TYPES: - contents += iterator.string - last_token = iterator - - iterator = iterator.next - if iterator.line_number != last_line: - contents += '\n' - last_line = iterator.line_number - - end_token = last_token - if DocFlag.EMPTY_STRING.match(contents): - contents = None - else: - # Strip trailing newline. - contents = contents[:-1] - - return end_token, contents - - -class Function(object): - """Data about a JavaScript function. - - Attributes: - block_depth: Block depth the function began at. - doc: The DocComment associated with the function. - has_return: If the function has a return value. - has_this: If the function references the 'this' object. - is_assigned: If the function is part of an assignment. - is_constructor: If the function is a constructor. - name: The name of the function, whether given in the function keyword or - as the lvalue the function is assigned to. - start_token: First token of the function (the function' keyword token). - end_token: Last token of the function (the closing '}' token). - parameters: List of parameter names. - """ - - def __init__(self, block_depth, is_assigned, doc, name): - self.block_depth = block_depth - self.is_assigned = is_assigned - self.is_constructor = doc and doc.HasFlag('constructor') - self.is_interface = doc and doc.HasFlag('interface') - self.has_return = False - self.has_throw = False - self.has_this = False - self.name = name - self.doc = doc - self.start_token = None - self.end_token = None - self.parameters = None - - -class StateTracker(object): - """EcmaScript state tracker. - - Tracks block depth, function names, etc. within an EcmaScript token stream. - """ - - OBJECT_LITERAL = 'o' - CODE = 'c' - - def __init__(self, doc_flag=DocFlag): - """Initializes a JavaScript token stream state tracker. - - Args: - doc_flag: An optional custom DocFlag used for validating - documentation flags. - """ - self._doc_flag = doc_flag - self.Reset() - - def Reset(self): - """Resets the state tracker to prepare for processing a new page.""" - self._block_depth = 0 - self._is_block_close = False - self._paren_depth = 0 - self._function_stack = [] - self._functions_by_name = {} - self._last_comment = None - self._doc_comment = None - self._cumulative_params = None - self._block_types = [] - self._last_non_space_token = None - self._last_line = None - self._first_token = None - self._documented_identifiers = set() - self._variables_in_scope = [] - - def DocFlagPass(self, start_token, error_handler): - """Parses doc flags. - - This pass needs to be executed before the aliaspass and we don't want to do - a full-blown statetracker dry run for these. - - Args: - start_token: The token at which to start iterating - error_handler: An error handler for error reporting. - """ - if not start_token: - return - doc_flag_types = (Type.DOC_FLAG, Type.DOC_INLINE_FLAG) - for token in start_token: - if token.type in doc_flag_types: - token.attached_object = self._doc_flag(token, error_handler) - - def InFunction(self): - """Returns true if the current token is within a function. - - Returns: - True if the current token is within a function. - """ - return bool(self._function_stack) - - def InConstructor(self): - """Returns true if the current token is within a constructor. - - Returns: - True if the current token is within a constructor. - """ - return self.InFunction() and self._function_stack[-1].is_constructor - - def InInterfaceMethod(self): - """Returns true if the current token is within an interface method. - - Returns: - True if the current token is within an interface method. - """ - if self.InFunction(): - if self._function_stack[-1].is_interface: - return True - else: - name = self._function_stack[-1].name - prototype_index = name.find('.prototype.') - if prototype_index != -1: - class_function_name = name[0:prototype_index] - if (class_function_name in self._functions_by_name and - self._functions_by_name[class_function_name].is_interface): - return True - - return False - - def InTopLevelFunction(self): - """Returns true if the current token is within a top level function. - - Returns: - True if the current token is within a top level function. - """ - return len(self._function_stack) == 1 and self.InTopLevel() - - def InAssignedFunction(self): - """Returns true if the current token is within a function variable. - - Returns: - True if if the current token is within a function variable - """ - return self.InFunction() and self._function_stack[-1].is_assigned - - def IsFunctionOpen(self): - """Returns true if the current token is a function block open. - - Returns: - True if the current token is a function block open. - """ - return (self._function_stack and - self._function_stack[-1].block_depth == self._block_depth - 1) - - def IsFunctionClose(self): - """Returns true if the current token is a function block close. - - Returns: - True if the current token is a function block close. - """ - return (self._function_stack and - self._function_stack[-1].block_depth == self._block_depth) - - def InBlock(self): - """Returns true if the current token is within a block. - - Returns: - True if the current token is within a block. - """ - return bool(self._block_depth) - - def IsBlockClose(self): - """Returns true if the current token is a block close. - - Returns: - True if the current token is a block close. - """ - return self._is_block_close - - def InObjectLiteral(self): - """Returns true if the current token is within an object literal. - - Returns: - True if the current token is within an object literal. - """ - return self._block_depth and self._block_types[-1] == self.OBJECT_LITERAL - - def InObjectLiteralDescendant(self): - """Returns true if the current token has an object literal ancestor. - - Returns: - True if the current token has an object literal ancestor. - """ - return self.OBJECT_LITERAL in self._block_types - - def InParentheses(self): - """Returns true if the current token is within parentheses. - - Returns: - True if the current token is within parentheses. - """ - return bool(self._paren_depth) - - def ParenthesesDepth(self): - """Returns the number of parens surrounding the token. - - Returns: - The number of parenthesis surrounding the token. - """ - return self._paren_depth - - def BlockDepth(self): - """Returns the number of blocks in which the token is nested. - - Returns: - The number of blocks in which the token is nested. - """ - return self._block_depth - - def FunctionDepth(self): - """Returns the number of functions in which the token is nested. - - Returns: - The number of functions in which the token is nested. - """ - return len(self._function_stack) - - def InTopLevel(self): - """Whether we are at the top level in the class. - - This function call is language specific. In some languages like - JavaScript, a function is top level if it is not inside any parenthesis. - In languages such as ActionScript, a function is top level if it is directly - within a class. - """ - raise TypeError('Abstract method InTopLevel not implemented') - - def GetBlockType(self, token): - """Determine the block type given a START_BLOCK token. - - Code blocks come after parameters, keywords like else, and closing parens. - - Args: - token: The current token. Can be assumed to be type START_BLOCK. - Returns: - Code block type for current token. - """ - raise TypeError('Abstract method GetBlockType not implemented') - - def GetParams(self): - """Returns the accumulated input params as an array. - - In some EcmasSript languages, input params are specified like - (param:Type, param2:Type2, ...) - in other they are specified just as - (param, param2) - We handle both formats for specifying parameters here and leave - it to the compilers for each language to detect compile errors. - This allows more code to be reused between lint checkers for various - EcmaScript languages. - - Returns: - The accumulated input params as an array. - """ - params = [] - if self._cumulative_params: - params = re.compile(r'\s+').sub('', self._cumulative_params).split(',') - # Strip out the type from parameters of the form name:Type. - params = map(lambda param: param.split(':')[0], params) - - return params - - def GetLastComment(self): - """Return the last plain comment that could be used as documentation. - - Returns: - The last plain comment that could be used as documentation. - """ - return self._last_comment - - def GetDocComment(self): - """Return the most recent applicable documentation comment. - - Returns: - The last applicable documentation comment. - """ - return self._doc_comment - - def HasDocComment(self, identifier): - """Returns whether the identifier has been documented yet. - - Args: - identifier: The identifier. - - Returns: - Whether the identifier has been documented yet. - """ - return identifier in self._documented_identifiers - - def InDocComment(self): - """Returns whether the current token is in a doc comment. - - Returns: - Whether the current token is in a doc comment. - """ - return self._doc_comment and self._doc_comment.end_token is None - - def GetDocFlag(self): - """Returns the current documentation flags. - - Returns: - The current documentation flags. - """ - return self._doc_flag - - def IsTypeToken(self, t): - if self.InDocComment() and t.type not in (Type.START_DOC_COMMENT, - Type.DOC_FLAG, Type.DOC_INLINE_FLAG, Type.DOC_PREFIX): - f = tokenutil.SearchUntil(t, [Type.DOC_FLAG], [Type.START_DOC_COMMENT], - None, True) - if (f and f.attached_object.type_start_token is not None and - f.attached_object.type_end_token is not None): - return (tokenutil.Compare(t, f.attached_object.type_start_token) > 0 and - tokenutil.Compare(t, f.attached_object.type_end_token) < 0) - return False - - def GetFunction(self): - """Return the function the current code block is a part of. - - Returns: - The current Function object. - """ - if self._function_stack: - return self._function_stack[-1] - - def GetBlockDepth(self): - """Return the block depth. - - Returns: - The current block depth. - """ - return self._block_depth - - def GetLastNonSpaceToken(self): - """Return the last non whitespace token.""" - return self._last_non_space_token - - def GetLastLine(self): - """Return the last line.""" - return self._last_line - - def GetFirstToken(self): - """Return the very first token in the file.""" - return self._first_token - - def IsVariableInScope(self, token_string): - """Checks if string is variable in current scope. - - For given string it checks whether the string is a defined variable - (including function param) in current state. - - E.g. if variables defined (variables in current scope) is docs - then docs, docs.length etc will be considered as variable in current - scope. This will help in avoding extra goog.require for variables. - - Args: - token_string: String to check if its is a variable in current scope. - - Returns: - true if given string is a variable in current scope. - """ - for variable in self._variables_in_scope: - if (token_string == variable - or token_string.startswith(variable + '.')): - return True - - return False - - def HandleToken(self, token, last_non_space_token): - """Handles the given token and updates state. - - Args: - token: The token to handle. - last_non_space_token: - """ - self._is_block_close = False - - if not self._first_token: - self._first_token = token - - # Track block depth. - type = token.type - if type == Type.START_BLOCK: - self._block_depth += 1 - - # Subclasses need to handle block start very differently because - # whether a block is a CODE or OBJECT_LITERAL block varies significantly - # by language. - self._block_types.append(self.GetBlockType(token)) - - # When entering a function body, record its parameters. - if self.InFunction(): - function = self._function_stack[-1] - if self._block_depth == function.block_depth + 1: - function.parameters = self.GetParams() - - # Track block depth. - elif type == Type.END_BLOCK: - self._is_block_close = not self.InObjectLiteral() - self._block_depth -= 1 - self._block_types.pop() - - # Track parentheses depth. - elif type == Type.START_PAREN: - self._paren_depth += 1 - - # Track parentheses depth. - elif type == Type.END_PAREN: - self._paren_depth -= 1 - - elif type == Type.COMMENT: - self._last_comment = token.string - - elif type == Type.START_DOC_COMMENT: - self._last_comment = None - self._doc_comment = DocComment(token) - - elif type == Type.END_DOC_COMMENT: - self._doc_comment.end_token = token - - elif type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): - # Don't overwrite flags if they were already parsed in a previous pass. - if token.attached_object is None: - flag = self._doc_flag(token) - token.attached_object = flag - else: - flag = token.attached_object - self._doc_comment.AddFlag(flag) - - if flag.flag_type == 'suppress': - self._doc_comment.AddSuppression(token) - - elif type == Type.FUNCTION_DECLARATION: - last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, None, - True) - doc = None - # Only top-level functions are eligible for documentation. - if self.InTopLevel(): - doc = self._doc_comment - - name = '' - is_assigned = last_code and (last_code.IsOperator('=') or - last_code.IsOperator('||') or last_code.IsOperator('&&') or - (last_code.IsOperator(':') and not self.InObjectLiteral())) - if is_assigned: - # TODO(robbyw): This breaks for x[2] = ... - # Must use loop to find full function name in the case of line-wrapped - # declarations (bug 1220601) like: - # my.function.foo. - # bar = function() ... - identifier = tokenutil.Search(last_code, Type.SIMPLE_LVALUE, None, True) - while identifier and tokenutil.IsIdentifierOrDot(identifier): - name = identifier.string + name - # Traverse behind us, skipping whitespace and comments. - while True: - identifier = identifier.previous - if not identifier or not identifier.type in Type.NON_CODE_TYPES: - break - - else: - next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - while next_token and next_token.IsType(Type.FUNCTION_NAME): - name += next_token.string - next_token = tokenutil.Search(next_token, Type.FUNCTION_NAME, 2) - - function = Function(self._block_depth, is_assigned, doc, name) - function.start_token = token - - self._function_stack.append(function) - self._functions_by_name[name] = function - - # Add a delimiter in stack for scope variables to define start of - # function. This helps in popping variables of this function when - # function declaration ends. - self._variables_in_scope.append('') - - elif type == Type.START_PARAMETERS: - self._cumulative_params = '' - - elif type == Type.PARAMETERS: - self._cumulative_params += token.string - self._variables_in_scope.extend(self.GetParams()) - - elif type == Type.KEYWORD and token.string == 'return': - next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - if not next_token.IsType(Type.SEMICOLON): - function = self.GetFunction() - if function: - function.has_return = True - - elif type == Type.KEYWORD and token.string == 'throw': - function = self.GetFunction() - if function: - function.has_throw = True - - elif type == Type.KEYWORD and token.string == 'var': - function = self.GetFunction() - next_token = tokenutil.Search(token, [Type.IDENTIFIER, - Type.SIMPLE_LVALUE]) - - if next_token: - if next_token.type == Type.SIMPLE_LVALUE: - self._variables_in_scope.append(next_token.values['identifier']) - else: - self._variables_in_scope.append(next_token.string) - - elif type == Type.SIMPLE_LVALUE: - identifier = token.values['identifier'] - jsdoc = self.GetDocComment() - if jsdoc: - self._documented_identifiers.add(identifier) - - self._HandleIdentifier(identifier, True) - - elif type == Type.IDENTIFIER: - self._HandleIdentifier(token.string, False) - - # Detect documented non-assignments. - next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - if next_token and next_token.IsType(Type.SEMICOLON): - if (self._last_non_space_token and - self._last_non_space_token.IsType(Type.END_DOC_COMMENT)): - self._documented_identifiers.add(token.string) - - def _HandleIdentifier(self, identifier, is_assignment): - """Process the given identifier. - - Currently checks if it references 'this' and annotates the function - accordingly. - - Args: - identifier: The identifer to process. - is_assignment: Whether the identifer is being written to. - """ - if identifier == 'this' or identifier.startswith('this.'): - function = self.GetFunction() - if function: - function.has_this = True - - def HandleAfterToken(self, token): - """Handle updating state after a token has been checked. - - This function should be used for destructive state changes such as - deleting a tracked object. - - Args: - token: The token to handle. - """ - type = token.type - if type == Type.SEMICOLON or type == Type.END_PAREN or ( - type == Type.END_BRACKET and - self._last_non_space_token.type not in ( - Type.SINGLE_QUOTE_STRING_END, Type.DOUBLE_QUOTE_STRING_END)): - # We end on any numeric array index, but keep going for string based - # array indices so that we pick up manually exported identifiers. - self._doc_comment = None - self._last_comment = None - - elif type == Type.END_BLOCK: - self._doc_comment = None - self._last_comment = None - - if self.InFunction() and self.IsFunctionClose(): - # TODO(robbyw): Detect the function's name for better errors. - function = self._function_stack.pop() - function.end_token = token - - # Pop all variables till delimiter ('') those were defined in the - # function being closed so make them out of scope. - while self._variables_in_scope and self._variables_in_scope[-1]: - self._variables_in_scope.pop() - - # Pop delimiter - if self._variables_in_scope: - self._variables_in_scope.pop() - - elif type == Type.END_PARAMETERS and self._doc_comment: - self._doc_comment = None - self._last_comment = None - - if not token.IsAnyType(Type.WHITESPACE, Type.BLANK_LINE): - self._last_non_space_token = token - - self._last_line = token.line diff --git a/tools/closure_linter/build/lib/closure_linter/statetracker_test.py b/tools/closure_linter/build/lib/closure_linter/statetracker_test.py deleted file mode 100644 index 494dc642fc5bde..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/statetracker_test.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the statetracker module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - - - -import unittest as googletest - -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import testutil - - -class _FakeDocFlag(object): - - def __repr__(self): - return '@%s %s' % (self.flag_type, self.name) - - -class IdentifierTest(googletest.TestCase): - - def testJustIdentifier(self): - a = javascripttokens.JavaScriptToken( - 'abc', javascripttokens.JavaScriptTokenType.IDENTIFIER, 'abc', 1) - - st = statetracker.StateTracker() - st.HandleToken(a, None) - - -class DocCommentTest(googletest.TestCase): - - @staticmethod - def _MakeDocFlagFake(flag_type, name=None): - flag = _FakeDocFlag() - flag.flag_type = flag_type - flag.name = name - return flag - - def testDocFlags(self): - comment = statetracker.DocComment(None) - - a = self._MakeDocFlagFake('param', 'foo') - comment.AddFlag(a) - - b = self._MakeDocFlagFake('param', '') - comment.AddFlag(b) - - c = self._MakeDocFlagFake('param', 'bar') - comment.AddFlag(c) - - self.assertEquals( - ['foo', 'bar'], - comment.ordered_params) - - self.assertEquals( - [a, b, c], - comment.GetDocFlags()) - - def testInvalidate(self): - comment = statetracker.DocComment(None) - - self.assertFalse(comment.invalidated) - self.assertFalse(comment.IsInvalidated()) - - comment.Invalidate() - - self.assertTrue(comment.invalidated) - self.assertTrue(comment.IsInvalidated()) - - def testSuppressionOnly(self): - comment = statetracker.DocComment(None) - - self.assertFalse(comment.SuppressionOnly()) - comment.AddFlag(self._MakeDocFlagFake('suppress')) - self.assertTrue(comment.SuppressionOnly()) - comment.AddFlag(self._MakeDocFlagFake('foo')) - self.assertFalse(comment.SuppressionOnly()) - - def testRepr(self): - comment = statetracker.DocComment(None) - comment.AddFlag(self._MakeDocFlagFake('param', 'foo')) - comment.AddFlag(self._MakeDocFlagFake('param', 'bar')) - - self.assertEquals( - '', - repr(comment)) - - def testDocFlagParam(self): - comment = self._ParseComment(""" - /** - * @param {string} [name] Name of customer. - */""") - flag = comment.GetFlag('param') - self.assertEquals('string', flag.type) - self.assertEquals('string', flag.jstype.ToString()) - self.assertEquals('[name]', flag.name) - - def _ParseComment(self, script): - """Parse a script that contains one comment and return it.""" - _, comments = testutil.ParseFunctionsAndComments(script) - self.assertEquals(1, len(comments)) - return comments[0] - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/strict_test.py b/tools/closure_linter/build/lib/closure_linter/strict_test.py deleted file mode 100644 index 2634456874f1d2..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/strict_test.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# Copyright 2013 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for gjslint --strict. - -Tests errors that can be thrown by gjslint when in strict mode. -""" - - - -import unittest - -import gflags as flags -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import erroraccumulator - -flags.FLAGS.strict = True - - -class StrictTest(unittest.TestCase): - """Tests scenarios where strict generates warnings.""" - - def testUnclosedString(self): - """Tests warnings are reported when nothing is disabled. - - b/11450054. - """ - original = [ - 'bug = function() {', - ' (\'foo\'\');', - '};', - '', - ] - - expected = [errors.FILE_DOES_NOT_PARSE, errors.MULTI_LINE_STRING, - errors.FILE_IN_BLOCK] - self._AssertErrors(original, expected) - - def _AssertErrors(self, original, expected_errors): - """Asserts that the error fixer corrects original to expected.""" - - # Trap gjslint's output parse it to get messages added. - error_accumulator = erroraccumulator.ErrorAccumulator() - runner.Run('testing.js', error_accumulator, source=original) - error_nums = [e.code for e in error_accumulator.GetErrors()] - - error_nums.sort() - expected_errors.sort() - self.assertListEqual(error_nums, expected_errors) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/testutil.py b/tools/closure_linter/build/lib/closure_linter/testutil.py deleted file mode 100644 index f7084ee37b0683..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/testutil.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Utility functions for testing gjslint components.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import StringIO - -from closure_linter import ecmametadatapass -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokenizer - - -def TokenizeSource(source): - """Convert a source into a string of tokens. - - Args: - source: A source file as a string or file-like object (iterates lines). - - Returns: - The first token of the resulting token stream. - """ - - if isinstance(source, basestring): - source = StringIO.StringIO(source) - - tokenizer = javascripttokenizer.JavaScriptTokenizer() - return tokenizer.TokenizeFile(source) - - -def TokenizeSourceAndRunEcmaPass(source): - """Tokenize a source and run the EcmaMetaDataPass on it. - - Args: - source: A source file as a string or file-like object (iterates lines). - - Returns: - The first token of the resulting token stream. - """ - start_token = TokenizeSource(source) - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - ecma_pass.Process(start_token) - return start_token - - -def ParseFunctionsAndComments(source, error_handler=None): - """Run the tokenizer and tracker and return comments and functions found. - - Args: - source: A source file as a string or file-like object (iterates lines). - error_handler: An error handler. - - Returns: - The functions and comments as a tuple. - """ - start_token = TokenizeSourceAndRunEcmaPass(source) - - tracker = javascriptstatetracker.JavaScriptStateTracker() - if error_handler is not None: - tracker.DocFlagPass(start_token, error_handler) - - functions = [] - comments = [] - for token in start_token: - tracker.HandleToken(token, tracker.GetLastNonSpaceToken()) - - function = tracker.GetFunction() - if function and function not in functions: - functions.append(function) - - comment = tracker.GetDocComment() - if comment and comment not in comments: - comments.append(comment) - - tracker.HandleAfterToken(token) - - return functions, comments diff --git a/tools/closure_linter/build/lib/closure_linter/tokenutil.py b/tools/closure_linter/build/lib/closure_linter/tokenutil.py deleted file mode 100644 index 11e3ccc68bbe06..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/tokenutil.py +++ /dev/null @@ -1,697 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Token utility functions.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import copy -import StringIO - -from closure_linter.common import tokens -from closure_linter.javascripttokens import JavaScriptToken -from closure_linter.javascripttokens import JavaScriptTokenType - -# Shorthand -Type = tokens.TokenType - - -def GetFirstTokenInSameLine(token): - """Returns the first token in the same line as token. - - Args: - token: Any token in the line. - - Returns: - The first token in the same line as token. - """ - while not token.IsFirstInLine(): - token = token.previous - return token - - -def GetFirstTokenInPreviousLine(token): - """Returns the first token in the previous line as token. - - Args: - token: Any token in the line. - - Returns: - The first token in the previous line as token, or None if token is on the - first line. - """ - first_in_line = GetFirstTokenInSameLine(token) - if first_in_line.previous: - return GetFirstTokenInSameLine(first_in_line.previous) - - return None - - -def GetLastTokenInSameLine(token): - """Returns the last token in the same line as token. - - Args: - token: Any token in the line. - - Returns: - The last token in the same line as token. - """ - while not token.IsLastInLine(): - token = token.next - return token - - -def GetAllTokensInSameLine(token): - """Returns all tokens in the same line as the given token. - - Args: - token: Any token in the line. - - Returns: - All tokens on the same line as the given token. - """ - first_token = GetFirstTokenInSameLine(token) - last_token = GetLastTokenInSameLine(token) - - tokens_in_line = [] - while first_token != last_token: - tokens_in_line.append(first_token) - first_token = first_token.next - tokens_in_line.append(last_token) - - return tokens_in_line - - -def CustomSearch(start_token, func, end_func=None, distance=None, - reverse=False): - """Returns the first token where func is True within distance of this token. - - Args: - start_token: The token to start searching from - func: The function to call to test a token for applicability - end_func: The function to call to test a token to determine whether to abort - the search. - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token matching func within distance of this token, or None if no - such token is found. - """ - token = start_token - if reverse: - while token and (distance is None or distance > 0): - previous = token.previous - if previous: - if func(previous): - return previous - if end_func and end_func(previous): - return None - - token = previous - if distance is not None: - distance -= 1 - - else: - while token and (distance is None or distance > 0): - next_token = token.next - if next_token: - if func(next_token): - return next_token - if end_func and end_func(next_token): - return None - - token = next_token - if distance is not None: - distance -= 1 - - return None - - -def Search(start_token, token_types, distance=None, reverse=False): - """Returns the first token of type in token_types within distance. - - Args: - start_token: The token to start searching from - token_types: The allowable types of the token being searched for - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token of any type in token_types within distance of this token, or - None if no such token is found. - """ - return CustomSearch(start_token, lambda token: token.IsAnyType(token_types), - None, distance, reverse) - - -def SearchExcept(start_token, token_types, distance=None, reverse=False): - """Returns the first token not of any type in token_types within distance. - - Args: - start_token: The token to start searching from - token_types: The unallowable types of the token being searched for - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token of any type in token_types within distance of this token, or - None if no such token is found. - """ - return CustomSearch(start_token, - lambda token: not token.IsAnyType(token_types), - None, distance, reverse) - - -def SearchUntil(start_token, token_types, end_types, distance=None, - reverse=False): - """Returns the first token of type in token_types before a token of end_type. - - Args: - start_token: The token to start searching from. - token_types: The allowable types of the token being searched for. - end_types: Types of tokens to abort search if we find. - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token of any type in token_types within distance of this token - before any tokens of type in end_type, or None if no such token is found. - """ - return CustomSearch(start_token, lambda token: token.IsAnyType(token_types), - lambda token: token.IsAnyType(end_types), - distance, reverse) - - -def DeleteToken(token): - """Deletes the given token from the linked list. - - Args: - token: The token to delete - """ - # When deleting a token, we do not update the deleted token itself to make - # sure the previous and next pointers are still pointing to tokens which are - # not deleted. Also it is very hard to keep track of all previously deleted - # tokens to update them when their pointers become invalid. So we add this - # flag that any token linked list iteration logic can skip deleted node safely - # when its current token is deleted. - token.is_deleted = True - if token.previous: - token.previous.next = token.next - - if token.next: - token.next.previous = token.previous - - following_token = token.next - while following_token and following_token.metadata.last_code == token: - following_token.metadata.last_code = token.metadata.last_code - following_token = following_token.next - - -def DeleteTokens(token, token_count): - """Deletes the given number of tokens starting with the given token. - - Args: - token: The token to start deleting at. - token_count: The total number of tokens to delete. - """ - for i in xrange(1, token_count): - DeleteToken(token.next) - DeleteToken(token) - - -def InsertTokenBefore(new_token, token): - """Insert new_token before token. - - Args: - new_token: A token to be added to the stream - token: A token already in the stream - """ - new_token.next = token - new_token.previous = token.previous - - new_token.metadata = copy.copy(token.metadata) - - if new_token.IsCode(): - old_last_code = token.metadata.last_code - following_token = token - while (following_token and - following_token.metadata.last_code == old_last_code): - following_token.metadata.last_code = new_token - following_token = following_token.next - - token.previous = new_token - if new_token.previous: - new_token.previous.next = new_token - - if new_token.start_index is None: - if new_token.line_number == token.line_number: - new_token.start_index = token.start_index - else: - previous_token = new_token.previous - if previous_token: - new_token.start_index = (previous_token.start_index + - len(previous_token.string)) - else: - new_token.start_index = 0 - - iterator = new_token.next - while iterator and iterator.line_number == new_token.line_number: - iterator.start_index += len(new_token.string) - iterator = iterator.next - - -def InsertTokenAfter(new_token, token): - """Insert new_token after token. - - Args: - new_token: A token to be added to the stream - token: A token already in the stream - """ - new_token.previous = token - new_token.next = token.next - - new_token.metadata = copy.copy(token.metadata) - - if token.IsCode(): - new_token.metadata.last_code = token - - if new_token.IsCode(): - following_token = token.next - while following_token and following_token.metadata.last_code == token: - following_token.metadata.last_code = new_token - following_token = following_token.next - - token.next = new_token - if new_token.next: - new_token.next.previous = new_token - - if new_token.start_index is None: - if new_token.line_number == token.line_number: - new_token.start_index = token.start_index + len(token.string) - else: - new_token.start_index = 0 - - iterator = new_token.next - while iterator and iterator.line_number == new_token.line_number: - iterator.start_index += len(new_token.string) - iterator = iterator.next - - -def InsertTokensAfter(new_tokens, token): - """Insert multiple tokens after token. - - Args: - new_tokens: An array of tokens to be added to the stream - token: A token already in the stream - """ - # TODO(user): It would be nicer to have InsertTokenAfter defer to here - # instead of vice-versa. - current_token = token - for new_token in new_tokens: - InsertTokenAfter(new_token, current_token) - current_token = new_token - - -def InsertSpaceTokenAfter(token): - """Inserts a space token after the given token. - - Args: - token: The token to insert a space token after - - Returns: - A single space token - """ - space_token = JavaScriptToken(' ', Type.WHITESPACE, token.line, - token.line_number) - InsertTokenAfter(space_token, token) - - -def InsertBlankLineAfter(token): - """Inserts a blank line after the given token. - - Args: - token: The token to insert a blank line after - - Returns: - A single space token - """ - blank_token = JavaScriptToken('', Type.BLANK_LINE, '', - token.line_number + 1) - InsertLineAfter(token, [blank_token]) - - -def InsertLineAfter(token, new_tokens): - """Inserts a new line consisting of new_tokens after the given token. - - Args: - token: The token to insert after. - new_tokens: The tokens that will make up the new line. - """ - insert_location = token - for new_token in new_tokens: - InsertTokenAfter(new_token, insert_location) - insert_location = new_token - - # Update all subsequent line numbers. - next_token = new_tokens[-1].next - while next_token: - next_token.line_number += 1 - next_token = next_token.next - - -def SplitToken(token, position): - """Splits the token into two tokens at position. - - Args: - token: The token to split - position: The position to split at. Will be the beginning of second token. - - Returns: - The new second token. - """ - new_string = token.string[position:] - token.string = token.string[:position] - - new_token = JavaScriptToken(new_string, token.type, token.line, - token.line_number) - InsertTokenAfter(new_token, token) - - return new_token - - -def Compare(token1, token2): - """Compares two tokens and determines their relative order. - - Args: - token1: The first token to compare. - token2: The second token to compare. - - Returns: - A negative integer, zero, or a positive integer as the first token is - before, equal, or after the second in the token stream. - """ - if token2.line_number != token1.line_number: - return token1.line_number - token2.line_number - else: - return token1.start_index - token2.start_index - - -def GoogScopeOrNoneFromStartBlock(token): - """Determines if the given START_BLOCK is part of a goog.scope statement. - - Args: - token: A token of type START_BLOCK. - - Returns: - The goog.scope function call token, or None if such call doesn't exist. - """ - if token.type != JavaScriptTokenType.START_BLOCK: - return None - - # Search for a goog.scope statement, which will be 5 tokens before the - # block. Illustration of the tokens found prior to the start block: - # goog.scope(function() { - # 5 4 3 21 ^ - - maybe_goog_scope = token - for unused_i in xrange(5): - maybe_goog_scope = (maybe_goog_scope.previous if maybe_goog_scope and - maybe_goog_scope.previous else None) - if maybe_goog_scope and maybe_goog_scope.string == 'goog.scope': - return maybe_goog_scope - - -def GetTokenRange(start_token, end_token): - """Returns a list of tokens between the two given, inclusive. - - Args: - start_token: Start token in the range. - end_token: End token in the range. - - Returns: - A list of tokens, in order, from start_token to end_token (including start - and end). Returns none if the tokens do not describe a valid range. - """ - - token_range = [] - token = start_token - - while token: - token_range.append(token) - - if token == end_token: - return token_range - - token = token.next - - -def TokensToString(token_iterable): - """Convert a number of tokens into a string. - - Newlines will be inserted whenever the line_number of two neighboring - strings differ. - - Args: - token_iterable: The tokens to turn to a string. - - Returns: - A string representation of the given tokens. - """ - - buf = StringIO.StringIO() - token_list = list(token_iterable) - if not token_list: - return '' - - line_number = token_list[0].line_number - - for token in token_list: - - while line_number < token.line_number: - line_number += 1 - buf.write('\n') - - if line_number > token.line_number: - line_number = token.line_number - buf.write('\n') - - buf.write(token.string) - - return buf.getvalue() - - -def GetPreviousCodeToken(token): - """Returns the code token before the specified token. - - Args: - token: A token. - - Returns: - The code token before the specified token or None if no such token - exists. - """ - - return CustomSearch( - token, - lambda t: t and t.type not in JavaScriptTokenType.NON_CODE_TYPES, - reverse=True) - - -def GetNextCodeToken(token): - """Returns the next code token after the specified token. - - Args: - token: A token. - - Returns: - The next code token after the specified token or None if no such token - exists. - """ - - return CustomSearch( - token, - lambda t: t and t.type not in JavaScriptTokenType.NON_CODE_TYPES, - reverse=False) - - -def GetIdentifierStart(token): - """Returns the first token in an identifier. - - Given a token which is part of an identifier, returns the token at the start - of the identifier. - - Args: - token: A token which is part of an identifier. - - Returns: - The token at the start of the identifier or None if the identifier was not - of the form 'a.b.c' (e.g. "['a']['b'].c"). - """ - - start_token = token - previous_code_token = GetPreviousCodeToken(token) - - while (previous_code_token and ( - previous_code_token.IsType(JavaScriptTokenType.IDENTIFIER) or - IsDot(previous_code_token))): - start_token = previous_code_token - previous_code_token = GetPreviousCodeToken(previous_code_token) - - if IsDot(start_token): - return None - - return start_token - - -def GetIdentifierForToken(token): - """Get the symbol specified by a token. - - Given a token, this function additionally concatenates any parts of an - identifying symbol being identified that are split by whitespace or a - newline. - - The function will return None if the token is not the first token of an - identifier. - - Args: - token: The first token of a symbol. - - Returns: - The whole symbol, as a string. - """ - - # Search backward to determine if this token is the first token of the - # identifier. If it is not the first token, return None to signal that this - # token should be ignored. - prev_token = token.previous - while prev_token: - if (prev_token.IsType(JavaScriptTokenType.IDENTIFIER) or - IsDot(prev_token)): - return None - - if (prev_token.IsType(tokens.TokenType.WHITESPACE) or - prev_token.IsAnyType(JavaScriptTokenType.COMMENT_TYPES)): - prev_token = prev_token.previous - else: - break - - # A "function foo()" declaration. - if token.type is JavaScriptTokenType.FUNCTION_NAME: - return token.string - - # A "var foo" declaration (if the previous token is 'var') - previous_code_token = GetPreviousCodeToken(token) - - if previous_code_token and previous_code_token.IsKeyword('var'): - return token.string - - # Otherwise, this is potentially a namespaced (goog.foo.bar) identifier that - # could span multiple lines or be broken up by whitespace. We need - # to concatenate. - identifier_types = set([ - JavaScriptTokenType.IDENTIFIER, - JavaScriptTokenType.SIMPLE_LVALUE - ]) - - assert token.type in identifier_types - - # Start with the first token - symbol_tokens = [token] - - if token.next: - for t in token.next: - last_symbol_token = symbol_tokens[-1] - - # A dot is part of the previous symbol. - if IsDot(t): - symbol_tokens.append(t) - continue - - # An identifier is part of the previous symbol if the previous one was a - # dot. - if t.type in identifier_types: - if IsDot(last_symbol_token): - symbol_tokens.append(t) - continue - else: - break - - # Skip any whitespace - if t.type in JavaScriptTokenType.NON_CODE_TYPES: - continue - - # This is the end of the identifier. Stop iterating. - break - - if symbol_tokens: - return ''.join([t.string for t in symbol_tokens]) - - -def GetStringAfterToken(token): - """Get string after token. - - Args: - token: Search will be done after this token. - - Returns: - String if found after token else None (empty string will also - return None). - - Search until end of string as in case of empty string Type.STRING_TEXT is not - present/found and don't want to return next string. - E.g. - a = ''; - b = 'test'; - When searching for string after 'a' if search is not limited by end of string - then it will return 'test' which is not desirable as there is a empty string - before that. - - This will return None for cases where string is empty or no string found - as in both cases there is no Type.STRING_TEXT. - """ - string_token = SearchUntil(token, JavaScriptTokenType.STRING_TEXT, - [JavaScriptTokenType.SINGLE_QUOTE_STRING_END, - JavaScriptTokenType.DOUBLE_QUOTE_STRING_END]) - if string_token: - return string_token.string - else: - return None - - -def IsDot(token): - """Whether the token represents a "dot" operator (foo.bar).""" - return token.type is JavaScriptTokenType.OPERATOR and token.string == '.' - - -def IsIdentifierOrDot(token): - """Whether the token is either an identifier or a '.'.""" - return (token.type in [JavaScriptTokenType.IDENTIFIER, - JavaScriptTokenType.SIMPLE_LVALUE] or - IsDot(token)) diff --git a/tools/closure_linter/build/lib/closure_linter/tokenutil_test.py b/tools/closure_linter/build/lib/closure_linter/tokenutil_test.py deleted file mode 100644 index c7d3854776bd48..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/tokenutil_test.py +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the scopeutil module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import unittest as googletest - -from closure_linter import ecmametadatapass -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - - -class FakeToken(object): - pass - - -class TokenUtilTest(googletest.TestCase): - - def testGetTokenRange(self): - - a = FakeToken() - b = FakeToken() - c = FakeToken() - d = FakeToken() - e = FakeToken() - - a.next = b - b.next = c - c.next = d - - self.assertEquals([a, b, c, d], tokenutil.GetTokenRange(a, d)) - - # This is an error as e does not come after a in the token chain. - self.assertRaises(Exception, lambda: tokenutil.GetTokenRange(a, e)) - - def testTokensToString(self): - - a = FakeToken() - b = FakeToken() - c = FakeToken() - d = FakeToken() - e = FakeToken() - - a.string = 'aaa' - b.string = 'bbb' - c.string = 'ccc' - d.string = 'ddd' - e.string = 'eee' - - a.line_number = 5 - b.line_number = 6 - c.line_number = 6 - d.line_number = 10 - e.line_number = 11 - - self.assertEquals( - 'aaa\nbbbccc\n\n\n\nddd\neee', - tokenutil.TokensToString([a, b, c, d, e])) - - self.assertEquals( - 'ddd\neee\naaa\nbbbccc', - tokenutil.TokensToString([d, e, a, b, c]), - 'Neighboring tokens not in line_number order should have a newline ' - 'between them.') - - def testGetPreviousCodeToken(self): - - tokens = testutil.TokenizeSource(""" -start1. // comment - /* another comment */ - end1 -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - None, - tokenutil.GetPreviousCodeToken(_GetTokenStartingWith('start1'))) - - self.assertEquals( - '.', - tokenutil.GetPreviousCodeToken(_GetTokenStartingWith('end1')).string) - - self.assertEquals( - 'start1', - tokenutil.GetPreviousCodeToken(_GetTokenStartingWith('.')).string) - - def testGetNextCodeToken(self): - - tokens = testutil.TokenizeSource(""" -start1. // comment - /* another comment */ - end1 -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - '.', - tokenutil.GetNextCodeToken(_GetTokenStartingWith('start1')).string) - - self.assertEquals( - 'end1', - tokenutil.GetNextCodeToken(_GetTokenStartingWith('.')).string) - - self.assertEquals( - None, - tokenutil.GetNextCodeToken(_GetTokenStartingWith('end1'))) - - def testGetIdentifierStart(self): - - tokens = testutil.TokenizeSource(""" -start1 . // comment - prototype. /* another comment */ - end1 - -['edge'][case].prototype. - end2 = function() {} -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - 'start1', - tokenutil.GetIdentifierStart(_GetTokenStartingWith('end1')).string) - - self.assertEquals( - 'start1', - tokenutil.GetIdentifierStart(_GetTokenStartingWith('start1')).string) - - self.assertEquals( - None, - tokenutil.GetIdentifierStart(_GetTokenStartingWith('end2'))) - - def testInsertTokenBefore(self): - - self.AssertInsertTokenAfterBefore(False) - - def testInsertTokenAfter(self): - - self.AssertInsertTokenAfterBefore(True) - - def AssertInsertTokenAfterBefore(self, after): - - new_token = javascripttokens.JavaScriptToken( - 'a', javascripttokens.JavaScriptTokenType.IDENTIFIER, 1, 1) - - existing_token1 = javascripttokens.JavaScriptToken( - 'var', javascripttokens.JavaScriptTokenType.KEYWORD, 1, 1) - existing_token1.start_index = 0 - existing_token1.metadata = ecmametadatapass.EcmaMetaData() - - existing_token2 = javascripttokens.JavaScriptToken( - ' ', javascripttokens.JavaScriptTokenType.WHITESPACE, 1, 1) - existing_token2.start_index = 3 - existing_token2.metadata = ecmametadatapass.EcmaMetaData() - existing_token2.metadata.last_code = existing_token1 - - existing_token1.next = existing_token2 - existing_token2.previous = existing_token1 - - if after: - tokenutil.InsertTokenAfter(new_token, existing_token1) - else: - tokenutil.InsertTokenBefore(new_token, existing_token2) - - self.assertEquals(existing_token1, new_token.previous) - self.assertEquals(existing_token2, new_token.next) - - self.assertEquals(new_token, existing_token1.next) - self.assertEquals(new_token, existing_token2.previous) - - self.assertEquals(existing_token1, new_token.metadata.last_code) - self.assertEquals(new_token, existing_token2.metadata.last_code) - - self.assertEquals(0, existing_token1.start_index) - self.assertEquals(3, new_token.start_index) - self.assertEquals(4, existing_token2.start_index) - - def testGetIdentifierForToken(self): - - tokens = testutil.TokenizeSource(""" -start1.abc.def.prototype. - onContinuedLine - -(start2.abc.def - .hij.klm - .nop) - -start3.abc.def - .hij = function() {}; - -// An absurd multi-liner. -start4.abc.def. - hij. - klm = function() {}; - -start5 . aaa . bbb . ccc - shouldntBePartOfThePreviousSymbol - -start6.abc.def ghi.shouldntBePartOfThePreviousSymbol - -var start7 = 42; - -function start8() { - -} - -start9.abc. // why is there a comment here? - def /* another comment */ - shouldntBePart - -start10.abc // why is there a comment here? - .def /* another comment */ - shouldntBePart - -start11.abc. middle1.shouldNotBeIdentifier -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - 'start1.abc.def.prototype.onContinuedLine', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start1'))) - - self.assertEquals( - 'start2.abc.def.hij.klm.nop', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start2'))) - - self.assertEquals( - 'start3.abc.def.hij', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start3'))) - - self.assertEquals( - 'start4.abc.def.hij.klm', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start4'))) - - self.assertEquals( - 'start5.aaa.bbb.ccc', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start5'))) - - self.assertEquals( - 'start6.abc.def', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start6'))) - - self.assertEquals( - 'start7', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start7'))) - - self.assertEquals( - 'start8', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start8'))) - - self.assertEquals( - 'start9.abc.def', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start9'))) - - self.assertEquals( - 'start10.abc.def', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start10'))) - - self.assertIsNone( - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('middle1'))) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/build/lib/closure_linter/typeannotation.py b/tools/closure_linter/build/lib/closure_linter/typeannotation.py deleted file mode 100644 index 00604c13a7b31b..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/typeannotation.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -#*-* coding: utf-8 -"""Closure typeannotation parsing and utilities.""" - - - -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter.common import error - -# Shorthand -TYPE = javascripttokens.JavaScriptTokenType - - -class TypeAnnotation(object): - """Represents a structured view of a closure type annotation. - - Attribute: - identifier: The name of the type. - key_type: The name part before a colon. - sub_types: The list of sub_types used e.g. for Array.<…> - or_null: The '?' annotation - not_null: The '!' annotation - type_group: If this a a grouping (a|b), but does not include function(a). - return_type: The return type of a function definition. - alias: The actual type set by closurizednamespaceinfo if the identifier uses - an alias to shorten the name. - tokens: An ordered list of tokens used for this type. May contain - TypeAnnotation instances for sub_types, key_type or return_type. - """ - - IMPLICIT_TYPE_GROUP = 2 - - NULLABILITY_UNKNOWN = 2 - - # Frequently used known non-nullable types. - NON_NULLABLE = frozenset([ - 'boolean', 'function', 'number', 'string', 'undefined']) - # Frequently used known nullable types. - NULLABLE_TYPE_WHITELIST = frozenset([ - 'Array', 'Document', 'Element', 'Function', 'Node', 'NodeList', - 'Object']) - - def __init__(self): - self.identifier = '' - self.sub_types = [] - self.or_null = False - self.not_null = False - self.type_group = False - self.alias = None - self.key_type = None - self.record_type = False - self.opt_arg = False - self.return_type = None - self.tokens = [] - - def IsFunction(self): - """Determines whether this is a function definition.""" - return self.identifier == 'function' - - def IsConstructor(self): - """Determines whether this is a function definition for a constructor.""" - key_type = self.sub_types and self.sub_types[0].key_type - return self.IsFunction() and key_type.identifier == 'new' - - def IsRecordType(self): - """Returns True if this type is a record type.""" - return (self.record_type or - bool([t for t in self.sub_types if t.IsRecordType()])) - - def IsVarArgsType(self): - """Determines if the type is a var_args type, i.e. starts with '...'.""" - return self.identifier.startswith('...') or ( - self.type_group == TypeAnnotation.IMPLICIT_TYPE_GROUP and - self.sub_types[0].identifier.startswith('...')) - - def IsEmpty(self): - """Returns True if the type is empty.""" - return not self.tokens - - def IsUnknownType(self): - """Returns True if this is the unknown type {?}.""" - return (self.or_null - and not self.identifier - and not self.sub_types - and not self.return_type) - - def Append(self, item): - """Adds a sub_type to this type and finalizes it. - - Args: - item: The TypeAnnotation item to append. - """ - # item is a TypeAnnotation instance, so pylint: disable=protected-access - self.sub_types.append(item._Finalize(self)) - - def __repr__(self): - """Reconstructs the type definition.""" - append = '' - if self.sub_types: - separator = (',' if not self.type_group else '|') - if self.identifier == 'function': - surround = '(%s)' - else: - surround = {False: '{%s}' if self.record_type else '<%s>', - True: '(%s)', - self.IMPLICIT_TYPE_GROUP: '%s'}[self.type_group] - append = surround % separator.join([repr(t) for t in self.sub_types]) - if self.return_type: - append += ':%s' % repr(self.return_type) - append += '=' if self.opt_arg else '' - prefix = '' + ('?' if self.or_null else '') + ('!' if self.not_null else '') - keyword = '%s:' % repr(self.key_type) if self.key_type else '' - return keyword + prefix + '%s' % (self.alias or self.identifier) + append - - def ToString(self): - """Concats the type's tokens to form a string again.""" - ret = [] - for token in self.tokens: - if not isinstance(token, TypeAnnotation): - ret.append(token.string) - else: - ret.append(token.ToString()) - return ''.join(ret) - - def Dump(self, indent=''): - """Dumps this type's structure for debugging purposes.""" - result = [] - for t in self.tokens: - if isinstance(t, TypeAnnotation): - result.append(indent + str(t) + ' =>\n' + t.Dump(indent + ' ')) - else: - result.append(indent + str(t)) - return '\n'.join(result) - - def IterIdentifiers(self): - """Iterates over all identifiers in this type and its subtypes.""" - if self.identifier: - yield self.identifier - for subtype in self.IterTypes(): - for identifier in subtype.IterIdentifiers(): - yield identifier - - def IterTypeGroup(self): - """Iterates over all types in the type group including self. - - Yields: - If this is a implicit or manual type-group: all sub_types. - Otherwise: self - E.g. for @type {Foo.} this will yield only Foo., - for @type {Foo|(Bar|Sample)} this will yield Foo, Bar and Sample. - - """ - if self.type_group: - for sub_type in self.sub_types: - for sub_type in sub_type.IterTypeGroup(): - yield sub_type - else: - yield self - - def IterTypes(self): - """Iterates over each subtype as well as return and key types.""" - if self.return_type: - yield self.return_type - - if self.key_type: - yield self.key_type - - for sub_type in self.sub_types: - yield sub_type - - def GetNullability(self, modifiers=True): - """Computes whether the type may be null. - - Args: - modifiers: Whether the modifiers ? and ! should be considered in the - evaluation. - Returns: - True if the type allows null, False if the type is strictly non nullable - and NULLABILITY_UNKNOWN if the nullability cannot be determined. - """ - - # Explicitly marked nullable types or 'null' are nullable. - if (modifiers and self.or_null) or self.identifier == 'null': - return True - - # Explicitly marked non-nullable types or non-nullable base types: - if ((modifiers and self.not_null) or self.record_type - or self.identifier in self.NON_NULLABLE): - return False - - # A type group is nullable if any of its elements are nullable. - if self.type_group: - maybe_nullable = False - for sub_type in self.sub_types: - nullability = sub_type.GetNullability() - if nullability == self.NULLABILITY_UNKNOWN: - maybe_nullable = nullability - elif nullability: - return True - return maybe_nullable - - # Whitelisted types are nullable. - if self.identifier.rstrip('.') in self.NULLABLE_TYPE_WHITELIST: - return True - - # All other types are unknown (most should be nullable, but - # enums are not and typedefs might not be). - return self.NULLABILITY_UNKNOWN - - def WillAlwaysBeNullable(self): - """Computes whether the ! flag is illegal for this type. - - This is the case if this type or any of the subtypes is marked as - explicitly nullable. - - Returns: - True if the ! flag would be illegal. - """ - if self.or_null or self.identifier == 'null': - return True - - if self.type_group: - return bool([t for t in self.sub_types if t.WillAlwaysBeNullable()]) - - return False - - def _Finalize(self, parent): - """Fixes some parsing issues once the TypeAnnotation is complete.""" - - # Normalize functions whose definition ended up in the key type because - # they defined a return type after a colon. - if self.key_type and self.key_type.identifier == 'function': - current = self.key_type - current.return_type = self - self.key_type = None - # opt_arg never refers to the return type but to the function itself. - current.opt_arg = self.opt_arg - self.opt_arg = False - return current - - # If a typedef just specified the key, it will not end up in the key type. - if parent.record_type and not self.key_type: - current = TypeAnnotation() - current.key_type = self - current.tokens.append(self) - return current - return self - - def FirstToken(self): - """Returns the first token used in this type or any of its subtypes.""" - first = self.tokens[0] - return first.FirstToken() if isinstance(first, TypeAnnotation) else first - - -def Parse(token, token_end, error_handler): - """Parses a type annotation and returns a TypeAnnotation object.""" - return TypeAnnotationParser(error_handler).Parse(token.next, token_end) - - -class TypeAnnotationParser(object): - """A parser for type annotations constructing the TypeAnnotation object.""" - - def __init__(self, error_handler): - self._stack = [] - self._error_handler = error_handler - self._closing_error = False - - def Parse(self, token, token_end): - """Parses a type annotation and returns a TypeAnnotation object.""" - root = TypeAnnotation() - self._stack.append(root) - current = TypeAnnotation() - root.tokens.append(current) - - while token and token != token_end: - if token.type in (TYPE.DOC_TYPE_START_BLOCK, TYPE.DOC_START_BRACE): - if token.string == '(': - if (current.identifier and - current.identifier not in ['function', '...']): - self.Error(token, - 'Invalid identifier for (): "%s"' % current.identifier) - current.type_group = current.identifier != 'function' - elif token.string == '{': - current.record_type = True - current.tokens.append(token) - self._stack.append(current) - current = TypeAnnotation() - self._stack[-1].tokens.append(current) - - elif token.type in (TYPE.DOC_TYPE_END_BLOCK, TYPE.DOC_END_BRACE): - prev = self._stack.pop() - prev.Append(current) - current = prev - - # If an implicit type group was created, close it as well. - if prev.type_group == TypeAnnotation.IMPLICIT_TYPE_GROUP: - prev = self._stack.pop() - prev.Append(current) - current = prev - current.tokens.append(token) - - elif token.type == TYPE.DOC_TYPE_MODIFIER: - if token.string == '!': - current.tokens.append(token) - current.not_null = True - elif token.string == '?': - current.tokens.append(token) - current.or_null = True - elif token.string == ':': - current.tokens.append(token) - prev = current - current = TypeAnnotation() - prev.tokens.append(current) - current.key_type = prev - elif token.string == '=': - # For implicit type groups the '=' refers to the parent. - try: - if self._stack[-1].type_group == TypeAnnotation.IMPLICIT_TYPE_GROUP: - self._stack[-1].tokens.append(token) - self._stack[-1].opt_arg = True - else: - current.tokens.append(token) - current.opt_arg = True - except IndexError: - self.ClosingError(token) - elif token.string == '|': - # If a type group has explicitly been opened do a normal append. - # Otherwise we have to open the type group and move the current - # type into it, before appending - if not self._stack[-1].type_group: - type_group = TypeAnnotation() - if current.key_type and current.key_type.identifier != 'function': - type_group.key_type = current.key_type - current.key_type = None - type_group.type_group = TypeAnnotation.IMPLICIT_TYPE_GROUP - # Fix the token order - prev = self._stack[-1].tokens.pop() - self._stack[-1].tokens.append(type_group) - type_group.tokens.append(prev) - self._stack.append(type_group) - self._stack[-1].tokens.append(token) - self.Append(current, error_token=token) - current = TypeAnnotation() - self._stack[-1].tokens.append(current) - elif token.string == ',': - self.Append(current, error_token=token) - current = TypeAnnotation() - self._stack[-1].tokens.append(token) - self._stack[-1].tokens.append(current) - else: - current.tokens.append(token) - self.Error(token, 'Invalid token') - - elif token.type == TYPE.COMMENT: - current.tokens.append(token) - current.identifier += token.string.strip() - - elif token.type in [TYPE.DOC_PREFIX, TYPE.WHITESPACE]: - current.tokens.append(token) - - else: - current.tokens.append(token) - self.Error(token, 'Unexpected token') - - token = token.next - - self.Append(current, error_token=token) - try: - ret = self._stack.pop() - except IndexError: - self.ClosingError(token) - # The type is screwed up, but let's return something. - return current - - if self._stack and (len(self._stack) != 1 or - ret.type_group != TypeAnnotation.IMPLICIT_TYPE_GROUP): - self.Error(token, 'Too many opening items.') - - return ret if len(ret.sub_types) > 1 else ret.sub_types[0] - - def Append(self, type_obj, error_token): - """Appends a new TypeAnnotation object to the current parent.""" - if self._stack: - self._stack[-1].Append(type_obj) - else: - self.ClosingError(error_token) - - def ClosingError(self, token): - """Reports an error about too many closing items, but only once.""" - if not self._closing_error: - self._closing_error = True - self.Error(token, 'Too many closing items.') - - def Error(self, token, message): - """Calls the error_handler to post an error message.""" - if self._error_handler: - self._error_handler.HandleError(error.Error( - errors.JSDOC_DOES_NOT_PARSE, - 'Error parsing jsdoc type at token "%s" (column: %d): %s' % - (token.string, token.start_index, message), token)) diff --git a/tools/closure_linter/build/lib/closure_linter/typeannotation_test.py b/tools/closure_linter/build/lib/closure_linter/typeannotation_test.py deleted file mode 100644 index da9dfa369f0bc8..00000000000000 --- a/tools/closure_linter/build/lib/closure_linter/typeannotation_test.py +++ /dev/null @@ -1,232 +0,0 @@ -#!/usr/bin/env python -"""Unit tests for the typeannotation module.""" - - - - -import unittest as googletest - -from closure_linter import testutil -from closure_linter.common import erroraccumulator - -CRAZY_TYPE = ('Array.))>') - - -class TypeErrorException(Exception): - """Exception for TypeErrors.""" - - def __init__(self, errors): - super(TypeErrorException, self).__init__() - self.errors = errors - - -class TypeParserTest(googletest.TestCase): - """Tests for typeannotation parsing.""" - - def _ParseComment(self, script): - """Parse a script that contains one comment and return it.""" - accumulator = erroraccumulator.ErrorAccumulator() - _, comments = testutil.ParseFunctionsAndComments(script, accumulator) - if accumulator.GetErrors(): - raise TypeErrorException(accumulator.GetErrors()) - self.assertEquals(1, len(comments)) - return comments[0] - - def _ParseType(self, type_str): - """Creates a comment to parse and returns the parsed type.""" - comment = self._ParseComment('/** @type {%s} **/' % type_str) - return comment.GetDocFlags()[0].jstype - - def assertProperReconstruction(self, type_str, matching_str=None): - """Parses the type and asserts the its repr matches the type. - - If matching_str is specified, it will assert that the repr matches this - string instead. - - Args: - type_str: The type string to parse. - matching_str: A string the __repr__ of the parsed type should match. - Returns: - The parsed js_type. - """ - parsed_type = self._ParseType(type_str) - # Use listEqual assertion to more easily identify the difference - self.assertListEqual(list(matching_str or type_str), - list(repr(parsed_type))) - self.assertEquals(matching_str or type_str, repr(parsed_type)) - - # Newlines will be inserted by the file writer. - self.assertEquals(type_str.replace('\n', ''), parsed_type.ToString()) - return parsed_type - - def assertNullable(self, type_str, nullable=True): - parsed_type = self.assertProperReconstruction(type_str) - self.assertEquals(nullable, parsed_type.GetNullability(), - '"%s" should %sbe nullable' % - (type_str, 'not ' if nullable else '')) - - def assertNotNullable(self, type_str): - return self.assertNullable(type_str, nullable=False) - - def testReconstruction(self): - self.assertProperReconstruction('*') - self.assertProperReconstruction('number') - self.assertProperReconstruction('(((number)))') - self.assertProperReconstruction('!number') - self.assertProperReconstruction('?!number') - self.assertProperReconstruction('number=') - self.assertProperReconstruction('number=!?', '?!number=') - self.assertProperReconstruction('number|?string') - self.assertProperReconstruction('(number|string)') - self.assertProperReconstruction('?(number|string)') - self.assertProperReconstruction('Object.') - self.assertProperReconstruction('function(new:Object)') - self.assertProperReconstruction('function(new:Object):number') - self.assertProperReconstruction('function(new:Object,Element):number') - self.assertProperReconstruction('function(this:T,...)') - self.assertProperReconstruction('{a:?number}') - self.assertProperReconstruction('{a:?number,b:(number|string)}') - self.assertProperReconstruction('{c:{nested_element:*}|undefined}') - self.assertProperReconstruction('{handleEvent:function(?):?}') - self.assertProperReconstruction('function():?|null') - self.assertProperReconstruction('null|function():?|bar') - - def testOptargs(self): - self.assertProperReconstruction('number=') - self.assertProperReconstruction('number|string=') - self.assertProperReconstruction('(number|string)=') - self.assertProperReconstruction('(number|string=)') - self.assertProperReconstruction('(number=|string)') - self.assertProperReconstruction('function(...):number=') - - def testIndepth(self): - # Do an deeper check of the crazy identifier - crazy = self.assertProperReconstruction(CRAZY_TYPE) - self.assertEquals('Array.', crazy.identifier) - self.assertEquals(1, len(crazy.sub_types)) - func1 = crazy.sub_types[0] - func2 = func1.return_type - self.assertEquals('function', func1.identifier) - self.assertEquals('function', func2.identifier) - self.assertEquals(3, len(func1.sub_types)) - self.assertEquals(1, len(func2.sub_types)) - self.assertEquals('Object.', func2.sub_types[0].sub_types[0].identifier) - - def testIterIdentifiers(self): - nested_identifiers = self._ParseType('(a|{b:(c|function(new:d):e)})') - for identifier in ('a', 'b', 'c', 'd', 'e'): - self.assertIn(identifier, nested_identifiers.IterIdentifiers()) - - def testIsEmpty(self): - self.assertTrue(self._ParseType('').IsEmpty()) - self.assertFalse(self._ParseType('?').IsEmpty()) - self.assertFalse(self._ParseType('!').IsEmpty()) - self.assertFalse(self._ParseType('').IsEmpty()) - - def testIsConstructor(self): - self.assertFalse(self._ParseType('').IsConstructor()) - self.assertFalse(self._ParseType('Array.').IsConstructor()) - self.assertTrue(self._ParseType('function(new:T)').IsConstructor()) - - def testIsVarArgsType(self): - self.assertTrue(self._ParseType('...number').IsVarArgsType()) - self.assertTrue(self._ParseType('...Object|Array').IsVarArgsType()) - self.assertTrue(self._ParseType('...(Object|Array)').IsVarArgsType()) - self.assertFalse(self._ParseType('Object|...Array').IsVarArgsType()) - self.assertFalse(self._ParseType('(...Object|Array)').IsVarArgsType()) - - def testIsUnknownType(self): - self.assertTrue(self._ParseType('?').IsUnknownType()) - self.assertTrue(self._ParseType('Foo.').sub_types[0].IsUnknownType()) - self.assertFalse(self._ParseType('?|!').IsUnknownType()) - self.assertTrue(self._ParseType('?|!').sub_types[0].IsUnknownType()) - self.assertFalse(self._ParseType('!').IsUnknownType()) - - long_type = 'function():?|{handleEvent:function(?=):?,sample:?}|?=' - record = self._ParseType(long_type) - # First check that there's not just one type with 3 return types, but three - # top-level types. - self.assertEquals(3, len(record.sub_types)) - - # Now extract all unknown type instances and verify that they really are. - handle_event, sample = record.sub_types[1].sub_types - for i, sub_type in enumerate([ - record.sub_types[0].return_type, - handle_event.return_type, - handle_event.sub_types[0], - sample, - record.sub_types[2]]): - self.assertTrue(sub_type.IsUnknownType(), - 'Type %d should be the unknown type: %s\n%s' % ( - i, sub_type.tokens, record.Dump())) - - def testTypedefNames(self): - easy = self._ParseType('{a}') - self.assertTrue(easy.record_type) - - easy = self.assertProperReconstruction('{a}', '{a:}').sub_types[0] - self.assertEquals('a', easy.key_type.identifier) - self.assertEquals('', easy.identifier) - - easy = self.assertProperReconstruction('{a:b}').sub_types[0] - self.assertEquals('a', easy.key_type.identifier) - self.assertEquals('b', easy.identifier) - - def assertTypeError(self, type_str): - """Asserts that parsing the given type raises a linter error.""" - self.assertRaises(TypeErrorException, self._ParseType, type_str) - - def testParseBadTypes(self): - """Tests that several errors in types don't break the parser.""" - self.assertTypeError('<') - self.assertTypeError('>') - self.assertTypeError('Foo.=') - self.assertTypeError('Foo.>=') - self.assertTypeError('(') - self.assertTypeError(')') - self.assertTypeError('Foo.') - self._ParseType(':') - self._ParseType(':foo') - self.assertTypeError(':)foo') - self.assertTypeError('(a|{b:(c|function(new:d):e') - - def testNullable(self): - self.assertNullable('null') - self.assertNullable('Object') - self.assertNullable('?string') - self.assertNullable('?number') - - self.assertNotNullable('string') - self.assertNotNullable('number') - self.assertNotNullable('boolean') - self.assertNotNullable('function(Object)') - self.assertNotNullable('function(Object):Object') - self.assertNotNullable('function(?Object):?Object') - self.assertNotNullable('!Object') - - self.assertNotNullable('boolean|string') - self.assertNotNullable('(boolean|string)') - - self.assertNullable('(boolean|string|null)') - self.assertNullable('(?boolean)') - self.assertNullable('?(boolean)') - - self.assertNullable('(boolean|Object)') - self.assertNotNullable('(boolean|(string|{a:}))') - - def testSpaces(self): - """Tests that spaces don't change the outcome.""" - type_str = (' A < b | ( c | ? ! d e f ) > | ' - 'function ( x : . . . ) : { y : z = } ') - two_spaces = type_str.replace(' ', ' ') - no_spaces = type_str.replace(' ', '') - newlines = type_str.replace(' ', '\n * ') - self.assertProperReconstruction(no_spaces) - self.assertProperReconstruction(type_str, no_spaces) - self.assertProperReconstruction(two_spaces, no_spaces) - self.assertProperReconstruction(newlines, no_spaces) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter.egg-info/PKG-INFO b/tools/closure_linter/closure_linter.egg-info/PKG-INFO deleted file mode 100644 index 8055c15c21f1ee..00000000000000 --- a/tools/closure_linter/closure_linter.egg-info/PKG-INFO +++ /dev/null @@ -1,10 +0,0 @@ -Metadata-Version: 1.0 -Name: closure-linter -Version: 2.3.17 -Summary: Closure Linter -Home-page: http://code.google.com/p/closure-linter -Author: The Closure Linter Authors -Author-email: opensource@google.com -License: Apache -Description: UNKNOWN -Platform: UNKNOWN diff --git a/tools/closure_linter/closure_linter.egg-info/SOURCES.txt b/tools/closure_linter/closure_linter.egg-info/SOURCES.txt deleted file mode 100644 index a193cdfeb9442d..00000000000000 --- a/tools/closure_linter/closure_linter.egg-info/SOURCES.txt +++ /dev/null @@ -1,63 +0,0 @@ -README -setup.py -closure_linter/__init__.py -closure_linter/aliaspass.py -closure_linter/aliaspass_test.py -closure_linter/checker.py -closure_linter/checkerbase.py -closure_linter/closurizednamespacesinfo.py -closure_linter/closurizednamespacesinfo_test.py -closure_linter/ecmalintrules.py -closure_linter/ecmametadatapass.py -closure_linter/error_check.py -closure_linter/error_fixer.py -closure_linter/error_fixer_test.py -closure_linter/errorrecord.py -closure_linter/errorrules.py -closure_linter/errorrules_test.py -closure_linter/errors.py -closure_linter/fixjsstyle.py -closure_linter/fixjsstyle_test.py -closure_linter/full_test.py -closure_linter/gjslint.py -closure_linter/indentation.py -closure_linter/javascriptlintrules.py -closure_linter/javascriptstatetracker.py -closure_linter/javascriptstatetracker_test.py -closure_linter/javascripttokenizer.py -closure_linter/javascripttokens.py -closure_linter/not_strict_test.py -closure_linter/requireprovidesorter.py -closure_linter/requireprovidesorter_test.py -closure_linter/runner.py -closure_linter/runner_test.py -closure_linter/scopeutil.py -closure_linter/scopeutil_test.py -closure_linter/statetracker.py -closure_linter/statetracker_test.py -closure_linter/strict_test.py -closure_linter/testutil.py -closure_linter/tokenutil.py -closure_linter/tokenutil_test.py -closure_linter/typeannotation.py -closure_linter/typeannotation_test.py -closure_linter.egg-info/PKG-INFO -closure_linter.egg-info/SOURCES.txt -closure_linter.egg-info/dependency_links.txt -closure_linter.egg-info/entry_points.txt -closure_linter.egg-info/requires.txt -closure_linter.egg-info/top_level.txt -closure_linter/common/__init__.py -closure_linter/common/error.py -closure_linter/common/erroraccumulator.py -closure_linter/common/errorhandler.py -closure_linter/common/erroroutput.py -closure_linter/common/filetestcase.py -closure_linter/common/htmlutil.py -closure_linter/common/lintrunner.py -closure_linter/common/matcher.py -closure_linter/common/position.py -closure_linter/common/simplefileflags.py -closure_linter/common/tokenizer.py -closure_linter/common/tokens.py -closure_linter/common/tokens_test.py \ No newline at end of file diff --git a/tools/closure_linter/closure_linter.egg-info/dependency_links.txt b/tools/closure_linter/closure_linter.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791fe9..00000000000000 --- a/tools/closure_linter/closure_linter.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/closure_linter/closure_linter.egg-info/entry_points.txt b/tools/closure_linter/closure_linter.egg-info/entry_points.txt deleted file mode 100644 index 459b9d08b80562..00000000000000 --- a/tools/closure_linter/closure_linter.egg-info/entry_points.txt +++ /dev/null @@ -1,4 +0,0 @@ -[console_scripts] -fixjsstyle = closure_linter.fixjsstyle:main -gjslint = closure_linter.gjslint:main - diff --git a/tools/closure_linter/closure_linter.egg-info/requires.txt b/tools/closure_linter/closure_linter.egg-info/requires.txt deleted file mode 100644 index 71b67f110ca21b..00000000000000 --- a/tools/closure_linter/closure_linter.egg-info/requires.txt +++ /dev/null @@ -1 +0,0 @@ -python-gflags \ No newline at end of file diff --git a/tools/closure_linter/closure_linter.egg-info/top_level.txt b/tools/closure_linter/closure_linter.egg-info/top_level.txt deleted file mode 100644 index 7ece71f1c9118f..00000000000000 --- a/tools/closure_linter/closure_linter.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -closure_linter diff --git a/tools/closure_linter/closure_linter/__init__.py b/tools/closure_linter/closure_linter/__init__.py deleted file mode 100755 index 1798c8cfff57fa..00000000000000 --- a/tools/closure_linter/closure_linter/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Package indicator for gjslint.""" diff --git a/tools/closure_linter/closure_linter/aliaspass.py b/tools/closure_linter/closure_linter/aliaspass.py deleted file mode 100644 index bb37bfa07b2d90..00000000000000 --- a/tools/closure_linter/closure_linter/aliaspass.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Pass that scans for goog.scope aliases and lint/usage errors.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -from closure_linter import ecmametadatapass -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter import scopeutil -from closure_linter import tokenutil -from closure_linter.common import error - - -# TODO(nnaze): Create a Pass interface and move this class, EcmaMetaDataPass, -# and related classes onto it. - - -def _GetAliasForIdentifier(identifier, alias_map): - """Returns the aliased_symbol name for an identifier. - - Example usage: - >>> alias_map = {'MyClass': 'goog.foo.MyClass'} - >>> _GetAliasForIdentifier('MyClass.prototype.action', alias_map) - 'goog.foo.MyClass.prototype.action' - - >>> _GetAliasForIdentifier('MyClass.prototype.action', {}) - None - - Args: - identifier: The identifier. - alias_map: A dictionary mapping a symbol to an alias. - - Returns: - The aliased symbol name or None if not found. - """ - ns = identifier.split('.', 1)[0] - aliased_symbol = alias_map.get(ns) - if aliased_symbol: - return aliased_symbol + identifier[len(ns):] - - -def _SetTypeAlias(js_type, alias_map): - """Updates the alias for identifiers in a type. - - Args: - js_type: A typeannotation.TypeAnnotation instance. - alias_map: A dictionary mapping a symbol to an alias. - """ - aliased_symbol = _GetAliasForIdentifier(js_type.identifier, alias_map) - if aliased_symbol: - js_type.alias = aliased_symbol - for sub_type in js_type.IterTypes(): - _SetTypeAlias(sub_type, alias_map) - - -class AliasPass(object): - """Pass to identify goog.scope() usages. - - Identifies goog.scope() usages and finds lint/usage errors. Notes any - aliases of symbols in Closurized namespaces (that is, reassignments - such as "var MyClass = goog.foo.MyClass;") and annotates identifiers - when they're using an alias (so they may be expanded to the full symbol - later -- that "MyClass.prototype.action" refers to - "goog.foo.MyClass.prototype.action" when expanded.). - """ - - def __init__(self, closurized_namespaces=None, error_handler=None): - """Creates a new pass. - - Args: - closurized_namespaces: A set of Closurized namespaces (e.g. 'goog'). - error_handler: An error handler to report lint errors to. - """ - - self._error_handler = error_handler - - # If we have namespaces, freeze the set. - if closurized_namespaces: - closurized_namespaces = frozenset(closurized_namespaces) - - self._closurized_namespaces = closurized_namespaces - - def Process(self, start_token): - """Runs the pass on a token stream. - - Args: - start_token: The first token in the stream. - """ - - if start_token is None: - return - - # TODO(nnaze): Add more goog.scope usage checks. - self._CheckGoogScopeCalls(start_token) - - # If we have closurized namespaces, identify aliased identifiers. - if self._closurized_namespaces: - context = start_token.metadata.context - root_context = context.GetRoot() - self._ProcessRootContext(root_context) - - def _CheckGoogScopeCalls(self, start_token): - """Check goog.scope calls for lint/usage errors.""" - - def IsScopeToken(token): - return (token.type is javascripttokens.JavaScriptTokenType.IDENTIFIER and - token.string == 'goog.scope') - - # Find all the goog.scope tokens in the file - scope_tokens = [t for t in start_token if IsScopeToken(t)] - - for token in scope_tokens: - scope_context = token.metadata.context - - if not (scope_context.type == ecmametadatapass.EcmaContext.STATEMENT and - scope_context.parent.type == ecmametadatapass.EcmaContext.ROOT): - self._MaybeReportError( - error.Error(errors.INVALID_USE_OF_GOOG_SCOPE, - 'goog.scope call not in global scope', token)) - - # There should be only one goog.scope reference. Register errors for - # every instance after the first. - for token in scope_tokens[1:]: - self._MaybeReportError( - error.Error(errors.EXTRA_GOOG_SCOPE_USAGE, - 'More than one goog.scope call in file.', token)) - - def _MaybeReportError(self, err): - """Report an error to the handler (if registered).""" - if self._error_handler: - self._error_handler.HandleError(err) - - @classmethod - def _YieldAllContexts(cls, context): - """Yields all contexts that are contained by the given context.""" - yield context - for child_context in context.children: - for descendent_child in cls._YieldAllContexts(child_context): - yield descendent_child - - @staticmethod - def _IsTokenInParentBlock(token, parent_block): - """Determines whether the given token is contained by the given block. - - Args: - token: A token - parent_block: An EcmaContext. - - Returns: - Whether the token is in a context that is or is a child of the given - parent_block context. - """ - context = token.metadata.context - - while context: - if context is parent_block: - return True - context = context.parent - - return False - - def _ProcessRootContext(self, root_context): - """Processes all goog.scope blocks under the root context.""" - - assert root_context.type is ecmametadatapass.EcmaContext.ROOT - - # Process aliases in statements in the root scope for goog.module-style - # aliases. - global_alias_map = {} - for context in root_context.children: - if context.type == ecmametadatapass.EcmaContext.STATEMENT: - for statement_child in context.children: - if statement_child.type == ecmametadatapass.EcmaContext.VAR: - match = scopeutil.MatchModuleAlias(statement_child) - if match: - # goog.require aliases cannot use further aliases, the symbol is - # the second part of match, directly. - symbol = match[1] - if scopeutil.IsInClosurizedNamespace(symbol, - self._closurized_namespaces): - global_alias_map[match[0]] = symbol - - # Process each block to find aliases. - for context in root_context.children: - self._ProcessBlock(context, global_alias_map) - - def _ProcessBlock(self, context, global_alias_map): - """Scans a goog.scope block to find aliases and mark alias tokens.""" - alias_map = global_alias_map.copy() - - # Iterate over every token in the context. Each token points to one - # context, but multiple tokens may point to the same context. We only want - # to check each context once, so keep track of those we've seen. - seen_contexts = set() - token = context.start_token - while token and self._IsTokenInParentBlock(token, context): - token_context = token.metadata.context if token.metadata else None - - # Check to see if this token is an alias. - if token_context and token_context not in seen_contexts: - seen_contexts.add(token_context) - - # If this is a alias statement in the goog.scope block. - if (token_context.type == ecmametadatapass.EcmaContext.VAR and - scopeutil.IsGoogScopeBlock(token_context.parent.parent)): - match = scopeutil.MatchAlias(token_context) - - # If this is an alias, remember it in the map. - if match: - alias, symbol = match - symbol = _GetAliasForIdentifier(symbol, alias_map) or symbol - if scopeutil.IsInClosurizedNamespace(symbol, - self._closurized_namespaces): - alias_map[alias] = symbol - - # If this token is an identifier that matches an alias, - # mark the token as an alias to the original symbol. - if (token.type is javascripttokens.JavaScriptTokenType.SIMPLE_LVALUE or - token.type is javascripttokens.JavaScriptTokenType.IDENTIFIER): - identifier = tokenutil.GetIdentifierForToken(token) - if identifier: - aliased_symbol = _GetAliasForIdentifier(identifier, alias_map) - if aliased_symbol: - token.metadata.aliased_symbol = aliased_symbol - - elif token.type == javascripttokens.JavaScriptTokenType.DOC_FLAG: - flag = token.attached_object - if flag and flag.HasType() and flag.jstype: - _SetTypeAlias(flag.jstype, alias_map) - - token = token.next # Get next token diff --git a/tools/closure_linter/closure_linter/aliaspass_test.py b/tools/closure_linter/closure_linter/aliaspass_test.py deleted file mode 100755 index 7042e5348763cb..00000000000000 --- a/tools/closure_linter/closure_linter/aliaspass_test.py +++ /dev/null @@ -1,191 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the aliaspass module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import unittest as googletest - -from closure_linter import aliaspass -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import testutil -from closure_linter.common import erroraccumulator - - -def _GetTokenByLineAndString(start_token, string, line_number): - for token in start_token: - if token.line_number == line_number and token.string == string: - return token - - -class AliasPassTest(googletest.TestCase): - - def testInvalidGoogScopeCall(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCOPE_SCRIPT) - - error_accumulator = erroraccumulator.ErrorAccumulator() - alias_pass = aliaspass.AliasPass( - error_handler=error_accumulator) - alias_pass.Process(start_token) - - alias_errors = error_accumulator.GetErrors() - self.assertEquals(1, len(alias_errors)) - - alias_error = alias_errors[0] - - self.assertEquals(errors.INVALID_USE_OF_GOOG_SCOPE, alias_error.code) - self.assertEquals('goog.scope', alias_error.token.string) - - def testAliasedIdentifiers(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_ALIAS_SCRIPT) - alias_pass = aliaspass.AliasPass(set(['goog', 'myproject'])) - alias_pass.Process(start_token) - - alias_token = _GetTokenByLineAndString(start_token, 'Event', 4) - self.assertTrue(alias_token.metadata.is_alias_definition) - - my_class_token = _GetTokenByLineAndString(start_token, 'myClass', 9) - self.assertIsNone(my_class_token.metadata.aliased_symbol) - - component_token = _GetTokenByLineAndString(start_token, 'Component', 17) - self.assertEquals('goog.ui.Component', - component_token.metadata.aliased_symbol) - - event_token = _GetTokenByLineAndString(start_token, 'Event.Something', 17) - self.assertEquals('goog.events.Event.Something', - event_token.metadata.aliased_symbol) - - non_closurized_token = _GetTokenByLineAndString( - start_token, 'NonClosurizedClass', 18) - self.assertIsNone(non_closurized_token.metadata.aliased_symbol) - - long_start_token = _GetTokenByLineAndString(start_token, 'Event', 24) - self.assertEquals('goog.events.Event.MultilineIdentifier.someMethod', - long_start_token.metadata.aliased_symbol) - - def testAliasedDoctypes(self): - """Tests that aliases are correctly expanded within type annotations.""" - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_ALIAS_SCRIPT) - tracker = javascriptstatetracker.JavaScriptStateTracker() - tracker.DocFlagPass(start_token, error_handler=None) - - alias_pass = aliaspass.AliasPass(set(['goog', 'myproject'])) - alias_pass.Process(start_token) - - flag_token = _GetTokenByLineAndString(start_token, '@type', 22) - self.assertEquals( - 'goog.events.Event.>', - repr(flag_token.attached_object.jstype)) - - def testModuleAlias(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(""" -goog.module('goog.test'); -var Alias = goog.require('goog.Alias'); -Alias.use(); -""") - alias_pass = aliaspass.AliasPass(set(['goog'])) - alias_pass.Process(start_token) - alias_token = _GetTokenByLineAndString(start_token, 'Alias', 3) - self.assertTrue(alias_token.metadata.is_alias_definition) - - def testMultipleGoogScopeCalls(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass( - _TEST_MULTIPLE_SCOPE_SCRIPT) - - error_accumulator = erroraccumulator.ErrorAccumulator() - - alias_pass = aliaspass.AliasPass( - set(['goog', 'myproject']), - error_handler=error_accumulator) - alias_pass.Process(start_token) - - alias_errors = error_accumulator.GetErrors() - - self.assertEquals(3, len(alias_errors)) - - error = alias_errors[0] - self.assertEquals(errors.INVALID_USE_OF_GOOG_SCOPE, error.code) - self.assertEquals(7, error.token.line_number) - - error = alias_errors[1] - self.assertEquals(errors.EXTRA_GOOG_SCOPE_USAGE, error.code) - self.assertEquals(7, error.token.line_number) - - error = alias_errors[2] - self.assertEquals(errors.EXTRA_GOOG_SCOPE_USAGE, error.code) - self.assertEquals(11, error.token.line_number) - - -_TEST_ALIAS_SCRIPT = """ -goog.scope(function() { -var events = goog.events; // scope alias -var Event = events. - Event; // nested multiline scope alias - -// This should not be registered as an aliased identifier because -// it appears before the alias. -var myClass = new MyClass(); - -var Component = goog.ui.Component; // scope alias -var MyClass = myproject.foo.MyClass; // scope alias - -// Scope alias of non-Closurized namespace. -var NonClosurizedClass = aaa.bbb.NonClosurizedClass; - -var component = new Component(Event.Something); -var nonClosurized = NonClosurizedClass(); - -/** - * A created namespace with a really long identifier. - * @type {events.Event.} - */ -Event. - MultilineIdentifier. - someMethod = function() {}; -}); -""" - -_TEST_SCOPE_SCRIPT = """ -function foo () { - // This goog.scope call is invalid. - goog.scope(function() { - - }); -} -""" - -_TEST_MULTIPLE_SCOPE_SCRIPT = """ -goog.scope(function() { - // do nothing -}); - -function foo() { - var test = goog.scope; // We should not see goog.scope mentioned. -} - -// This goog.scope invalid. There can be only one. -goog.scope(function() { - -}); -""" - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/checker.py b/tools/closure_linter/closure_linter/checker.py deleted file mode 100755 index 1c984173b06639..00000000000000 --- a/tools/closure_linter/closure_linter/checker.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Core methods for checking JS files for common style guide violations.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import gflags as flags - -from closure_linter import aliaspass -from closure_linter import checkerbase -from closure_linter import closurizednamespacesinfo -from closure_linter import javascriptlintrules - - -flags.DEFINE_list('closurized_namespaces', '', - 'Namespace prefixes, used for testing of' - 'goog.provide/require') -flags.DEFINE_list('ignored_extra_namespaces', '', - 'Fully qualified namespaces that should be not be reported ' - 'as extra by the linter.') - - -class JavaScriptStyleChecker(checkerbase.CheckerBase): - """Checker that applies JavaScriptLintRules.""" - - def __init__(self, state_tracker, error_handler): - """Initialize an JavaScriptStyleChecker object. - - Args: - state_tracker: State tracker. - error_handler: Error handler to pass all errors to. - """ - self._namespaces_info = None - self._alias_pass = None - if flags.FLAGS.closurized_namespaces: - self._namespaces_info = ( - closurizednamespacesinfo.ClosurizedNamespacesInfo( - flags.FLAGS.closurized_namespaces, - flags.FLAGS.ignored_extra_namespaces)) - - self._alias_pass = aliaspass.AliasPass( - flags.FLAGS.closurized_namespaces, error_handler) - - checkerbase.CheckerBase.__init__( - self, - error_handler=error_handler, - lint_rules=javascriptlintrules.JavaScriptLintRules( - self._namespaces_info), - state_tracker=state_tracker) - - def Check(self, start_token, limited_doc_checks=False, is_html=False, - stop_token=None): - """Checks a token stream for lint warnings/errors. - - Adds a separate pass for computing dependency information based on - goog.require and goog.provide statements prior to the main linting pass. - - Args: - start_token: The first token in the token stream. - limited_doc_checks: Whether to perform limited checks. - is_html: Whether this token stream is HTML. - stop_token: If given, checks should stop at this token. - """ - self._lint_rules.Initialize(self, limited_doc_checks, is_html) - - self._state_tracker.DocFlagPass(start_token, self._error_handler) - - if self._alias_pass: - self._alias_pass.Process(start_token) - - # To maximize the amount of errors that get reported before a parse error - # is displayed, don't run the dependency pass if a parse error exists. - if self._namespaces_info: - self._namespaces_info.Reset() - self._ExecutePass(start_token, self._DependencyPass, stop_token) - - self._ExecutePass(start_token, self._LintPass, stop_token) - - # If we have a stop_token, we didn't end up reading the whole file and, - # thus, don't call Finalize to do end-of-file checks. - if not stop_token: - self._lint_rules.Finalize(self._state_tracker) - - def _DependencyPass(self, token): - """Processes an individual token for dependency information. - - Used to encapsulate the logic needed to process an individual token so that - it can be passed to _ExecutePass. - - Args: - token: The token to process. - """ - self._namespaces_info.ProcessToken(token, self._state_tracker) diff --git a/tools/closure_linter/closure_linter/checkerbase.py b/tools/closure_linter/closure_linter/checkerbase.py deleted file mode 100755 index 6679ded05be1e1..00000000000000 --- a/tools/closure_linter/closure_linter/checkerbase.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Base classes for writing checkers that operate on tokens.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'jacobr@google.com (Jacob Richman)') - -from closure_linter import errorrules -from closure_linter.common import error - - -class LintRulesBase(object): - """Base class for all classes defining the lint rules for a language.""" - - def __init__(self): - self.__checker = None - - def Initialize(self, checker, limited_doc_checks, is_html): - """Initializes to prepare to check a file. - - Args: - checker: Class to report errors to. - limited_doc_checks: Whether doc checking is relaxed for this file. - is_html: Whether the file is an HTML file with extracted contents. - """ - self.__checker = checker - self._limited_doc_checks = limited_doc_checks - self._is_html = is_html - - def _HandleError(self, code, message, token, position=None, - fix_data=None): - """Call the HandleError function for the checker we are associated with.""" - if errorrules.ShouldReportError(code): - self.__checker.HandleError(code, message, token, position, fix_data) - - def _SetLimitedDocChecks(self, limited_doc_checks): - """Sets whether doc checking is relaxed for this file. - - Args: - limited_doc_checks: Whether doc checking is relaxed for this file. - """ - self._limited_doc_checks = limited_doc_checks - - def CheckToken(self, token, parser_state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration. - parser_state: Object that indicates the parser state in the page. - - Raises: - TypeError: If not overridden. - """ - raise TypeError('Abstract method CheckToken not implemented') - - def Finalize(self, parser_state): - """Perform all checks that need to occur after all lines are processed. - - Args: - parser_state: State of the parser after parsing all tokens - - Raises: - TypeError: If not overridden. - """ - raise TypeError('Abstract method Finalize not implemented') - - -class CheckerBase(object): - """This class handles checking a LintRules object against a file.""" - - def __init__(self, error_handler, lint_rules, state_tracker): - """Initialize a checker object. - - Args: - error_handler: Object that handles errors. - lint_rules: LintRules object defining lint errors given a token - and state_tracker object. - state_tracker: Object that tracks the current state in the token stream. - - """ - self._error_handler = error_handler - self._lint_rules = lint_rules - self._state_tracker = state_tracker - - self._has_errors = False - - def HandleError(self, code, message, token, position=None, - fix_data=None): - """Prints out the given error message including a line number. - - Args: - code: The error code. - message: The error to print. - token: The token where the error occurred, or None if it was a file-wide - issue. - position: The position of the error, defaults to None. - fix_data: Metadata used for fixing the error. - """ - self._has_errors = True - self._error_handler.HandleError( - error.Error(code, message, token, position, fix_data)) - - def HasErrors(self): - """Returns true if the style checker has found any errors. - - Returns: - True if the style checker has found any errors. - """ - return self._has_errors - - def Check(self, start_token, limited_doc_checks=False, is_html=False, - stop_token=None): - """Checks a token stream, reporting errors to the error reporter. - - Args: - start_token: First token in token stream. - limited_doc_checks: Whether doc checking is relaxed for this file. - is_html: Whether the file being checked is an HTML file with extracted - contents. - stop_token: If given, check should stop at this token. - """ - - self._lint_rules.Initialize(self, limited_doc_checks, is_html) - self._ExecutePass(start_token, self._LintPass, stop_token=stop_token) - self._lint_rules.Finalize(self._state_tracker) - - def _LintPass(self, token): - """Checks an individual token for lint warnings/errors. - - Used to encapsulate the logic needed to check an individual token so that it - can be passed to _ExecutePass. - - Args: - token: The token to check. - """ - self._lint_rules.CheckToken(token, self._state_tracker) - - def _ExecutePass(self, token, pass_function, stop_token=None): - """Calls the given function for every token in the given token stream. - - As each token is passed to the given function, state is kept up to date and, - depending on the error_trace flag, errors are either caught and reported, or - allowed to bubble up so developers can see the full stack trace. If a parse - error is specified, the pass will proceed as normal until the token causing - the parse error is reached. - - Args: - token: The first token in the token stream. - pass_function: The function to call for each token in the token stream. - stop_token: The last token to check (if given). - - Raises: - Exception: If any error occurred while calling the given function. - """ - - self._state_tracker.Reset() - while token: - # When we are looking at a token and decided to delete the whole line, we - # will delete all of them in the "HandleToken()" below. So the current - # token and subsequent ones may already be deleted here. The way we - # delete a token does not wipe out the previous and next pointers of the - # deleted token. So we need to check the token itself to make sure it is - # not deleted. - if not token.is_deleted: - # End the pass at the stop token - if stop_token and token is stop_token: - return - - self._state_tracker.HandleToken( - token, self._state_tracker.GetLastNonSpaceToken()) - pass_function(token) - self._state_tracker.HandleAfterToken(token) - - token = token.next diff --git a/tools/closure_linter/closure_linter/closurizednamespacesinfo.py b/tools/closure_linter/closure_linter/closurizednamespacesinfo.py deleted file mode 100755 index e7cbfd3318974b..00000000000000 --- a/tools/closure_linter/closure_linter/closurizednamespacesinfo.py +++ /dev/null @@ -1,578 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Logic for computing dependency information for closurized JavaScript files. - -Closurized JavaScript files express dependencies using goog.require and -goog.provide statements. In order for the linter to detect when a statement is -missing or unnecessary, all identifiers in the JavaScript file must first be -processed to determine if they constitute the creation or usage of a dependency. -""" - - - -import re - -from closure_linter import javascripttokens -from closure_linter import tokenutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - -DEFAULT_EXTRA_NAMESPACES = [ - 'goog.testing.asserts', - 'goog.testing.jsunit', -] - - -class UsedNamespace(object): - """A type for information about a used namespace.""" - - def __init__(self, namespace, identifier, token, alias_definition): - """Initializes the instance. - - Args: - namespace: the namespace of an identifier used in the file - identifier: the complete identifier - token: the token that uses the namespace - alias_definition: a boolean stating whether the namespace is only to used - for an alias definition and should not be required. - """ - self.namespace = namespace - self.identifier = identifier - self.token = token - self.alias_definition = alias_definition - - def GetLine(self): - return self.token.line_number - - def __repr__(self): - return 'UsedNamespace(%s)' % ', '.join( - ['%s=%s' % (k, repr(v)) for k, v in self.__dict__.iteritems()]) - - -class ClosurizedNamespacesInfo(object): - """Dependency information for closurized JavaScript files. - - Processes token streams for dependency creation or usage and provides logic - for determining if a given require or provide statement is unnecessary or if - there are missing require or provide statements. - """ - - def __init__(self, closurized_namespaces, ignored_extra_namespaces): - """Initializes an instance the ClosurizedNamespacesInfo class. - - Args: - closurized_namespaces: A list of namespace prefixes that should be - processed for dependency information. Non-matching namespaces are - ignored. - ignored_extra_namespaces: A list of namespaces that should not be reported - as extra regardless of whether they are actually used. - """ - self._closurized_namespaces = closurized_namespaces - self._ignored_extra_namespaces = (ignored_extra_namespaces + - DEFAULT_EXTRA_NAMESPACES) - self.Reset() - - def Reset(self): - """Resets the internal state to prepare for processing a new file.""" - - # A list of goog.provide tokens in the order they appeared in the file. - self._provide_tokens = [] - - # A list of goog.require tokens in the order they appeared in the file. - self._require_tokens = [] - - # Namespaces that are already goog.provided. - self._provided_namespaces = [] - - # Namespaces that are already goog.required. - self._required_namespaces = [] - - # Note that created_namespaces and used_namespaces contain both namespaces - # and identifiers because there are many existing cases where a method or - # constant is provided directly instead of its namespace. Ideally, these - # two lists would only have to contain namespaces. - - # A list of tuples where the first element is the namespace of an identifier - # created in the file, the second is the identifier itself and the third is - # the line number where it's created. - self._created_namespaces = [] - - # A list of UsedNamespace instances. - self._used_namespaces = [] - - # A list of seemingly-unnecessary namespaces that are goog.required() and - # annotated with @suppress {extraRequire}. - self._suppressed_requires = [] - - # A list of goog.provide tokens which are duplicates. - self._duplicate_provide_tokens = [] - - # A list of goog.require tokens which are duplicates. - self._duplicate_require_tokens = [] - - # Whether this file is in a goog.scope. Someday, we may add support - # for checking scopified namespaces, but for now let's just fail - # in a more reasonable way. - self._scopified_file = False - - # TODO(user): Handle the case where there are 2 different requires - # that can satisfy the same dependency, but only one is necessary. - - def GetProvidedNamespaces(self): - """Returns the namespaces which are already provided by this file. - - Returns: - A list of strings where each string is a 'namespace' corresponding to an - existing goog.provide statement in the file being checked. - """ - return set(self._provided_namespaces) - - def GetRequiredNamespaces(self): - """Returns the namespaces which are already required by this file. - - Returns: - A list of strings where each string is a 'namespace' corresponding to an - existing goog.require statement in the file being checked. - """ - return set(self._required_namespaces) - - def IsExtraProvide(self, token): - """Returns whether the given goog.provide token is unnecessary. - - Args: - token: A goog.provide token. - - Returns: - True if the given token corresponds to an unnecessary goog.provide - statement, otherwise False. - """ - namespace = tokenutil.GetStringAfterToken(token) - - if self.GetClosurizedNamespace(namespace) is None: - return False - - if token in self._duplicate_provide_tokens: - return True - - # TODO(user): There's probably a faster way to compute this. - for created_namespace, created_identifier, _ in self._created_namespaces: - if namespace == created_namespace or namespace == created_identifier: - return False - - return True - - def IsExtraRequire(self, token): - """Returns whether the given goog.require token is unnecessary. - - Args: - token: A goog.require token. - - Returns: - True if the given token corresponds to an unnecessary goog.require - statement, otherwise False. - """ - namespace = tokenutil.GetStringAfterToken(token) - - if self.GetClosurizedNamespace(namespace) is None: - return False - - if namespace in self._ignored_extra_namespaces: - return False - - if token in self._duplicate_require_tokens: - return True - - if namespace in self._suppressed_requires: - return False - - # If the namespace contains a component that is initial caps, then that - # must be the last component of the namespace. - parts = namespace.split('.') - if len(parts) > 1 and parts[-2][0].isupper(): - return True - - # TODO(user): There's probably a faster way to compute this. - for ns in self._used_namespaces: - if (not ns.alias_definition and ( - namespace == ns.namespace or namespace == ns.identifier)): - return False - - return True - - def GetMissingProvides(self): - """Returns the dict of missing provided namespaces for the current file. - - Returns: - Returns a dictionary of key as string and value as integer where each - string(key) is a namespace that should be provided by this file, but is - not and integer(value) is first line number where it's defined. - """ - missing_provides = dict() - for namespace, identifier, line_number in self._created_namespaces: - if (not self._IsPrivateIdentifier(identifier) and - namespace not in self._provided_namespaces and - identifier not in self._provided_namespaces and - namespace not in self._required_namespaces and - namespace not in missing_provides): - missing_provides[namespace] = line_number - - return missing_provides - - def GetMissingRequires(self): - """Returns the dict of missing required namespaces for the current file. - - For each non-private identifier used in the file, find either a - goog.require, goog.provide or a created identifier that satisfies it. - goog.require statements can satisfy the identifier by requiring either the - namespace of the identifier or the identifier itself. goog.provide - statements can satisfy the identifier by providing the namespace of the - identifier. A created identifier can only satisfy the used identifier if - it matches it exactly (necessary since things can be defined on a - namespace in more than one file). Note that provided namespaces should be - a subset of created namespaces, but we check both because in some cases we - can't always detect the creation of the namespace. - - Returns: - Returns a dictionary of key as string and value integer where each - string(key) is a namespace that should be required by this file, but is - not and integer(value) is first line number where it's used. - """ - external_dependencies = set(self._required_namespaces) - - # Assume goog namespace is always available. - external_dependencies.add('goog') - # goog.module is treated as a builtin, too (for goog.module.get). - external_dependencies.add('goog.module') - - created_identifiers = set() - for unused_namespace, identifier, unused_line_number in ( - self._created_namespaces): - created_identifiers.add(identifier) - - missing_requires = dict() - illegal_alias_statements = dict() - - def ShouldRequireNamespace(namespace, identifier): - """Checks if a namespace would normally be required.""" - return ( - not self._IsPrivateIdentifier(identifier) and - namespace not in external_dependencies and - namespace not in self._provided_namespaces and - identifier not in external_dependencies and - identifier not in created_identifiers and - namespace not in missing_requires) - - # First check all the used identifiers where we know that their namespace - # needs to be provided (unless they are optional). - for ns in self._used_namespaces: - namespace = ns.namespace - identifier = ns.identifier - if (not ns.alias_definition and - ShouldRequireNamespace(namespace, identifier)): - missing_requires[namespace] = ns.GetLine() - - # Now that all required namespaces are known, we can check if the alias - # definitions (that are likely being used for typeannotations that don't - # need explicit goog.require statements) are already covered. If not - # the user shouldn't use the alias. - for ns in self._used_namespaces: - if (not ns.alias_definition or - not ShouldRequireNamespace(ns.namespace, ns.identifier)): - continue - if self._FindNamespace(ns.identifier, self._provided_namespaces, - created_identifiers, external_dependencies, - missing_requires): - continue - namespace = ns.identifier.rsplit('.', 1)[0] - illegal_alias_statements[namespace] = ns.token - - return missing_requires, illegal_alias_statements - - def _FindNamespace(self, identifier, *namespaces_list): - """Finds the namespace of an identifier given a list of other namespaces. - - Args: - identifier: An identifier whose parent needs to be defined. - e.g. for goog.bar.foo we search something that provides - goog.bar. - *namespaces_list: var args of iterables of namespace identifiers - Returns: - The namespace that the given identifier is part of or None. - """ - identifier = identifier.rsplit('.', 1)[0] - identifier_prefix = identifier + '.' - for namespaces in namespaces_list: - for namespace in namespaces: - if namespace == identifier or namespace.startswith(identifier_prefix): - return namespace - return None - - def _IsPrivateIdentifier(self, identifier): - """Returns whether the given identifier is private.""" - pieces = identifier.split('.') - for piece in pieces: - if piece.endswith('_'): - return True - return False - - def IsFirstProvide(self, token): - """Returns whether token is the first provide token.""" - return self._provide_tokens and token == self._provide_tokens[0] - - def IsFirstRequire(self, token): - """Returns whether token is the first require token.""" - return self._require_tokens and token == self._require_tokens[0] - - def IsLastProvide(self, token): - """Returns whether token is the last provide token.""" - return self._provide_tokens and token == self._provide_tokens[-1] - - def IsLastRequire(self, token): - """Returns whether token is the last require token.""" - return self._require_tokens and token == self._require_tokens[-1] - - def ProcessToken(self, token, state_tracker): - """Processes the given token for dependency information. - - Args: - token: The token to process. - state_tracker: The JavaScript state tracker. - """ - - # Note that this method is in the critical path for the linter and has been - # optimized for performance in the following ways: - # - Tokens are checked by type first to minimize the number of function - # calls necessary to determine if action needs to be taken for the token. - # - The most common tokens types are checked for first. - # - The number of function calls has been minimized (thus the length of this - # function. - - if token.type == TokenType.IDENTIFIER: - # TODO(user): Consider saving the whole identifier in metadata. - whole_identifier_string = tokenutil.GetIdentifierForToken(token) - if whole_identifier_string is None: - # We only want to process the identifier one time. If the whole string - # identifier is None, that means this token was part of a multi-token - # identifier, but it was not the first token of the identifier. - return - - # In the odd case that a goog.require is encountered inside a function, - # just ignore it (e.g. dynamic loading in test runners). - if token.string == 'goog.require' and not state_tracker.InFunction(): - self._require_tokens.append(token) - namespace = tokenutil.GetStringAfterToken(token) - if namespace in self._required_namespaces: - self._duplicate_require_tokens.append(token) - else: - self._required_namespaces.append(namespace) - - # If there is a suppression for the require, add a usage for it so it - # gets treated as a regular goog.require (i.e. still gets sorted). - if self._HasSuppression(state_tracker, 'extraRequire'): - self._suppressed_requires.append(namespace) - self._AddUsedNamespace(state_tracker, namespace, token) - - elif token.string == 'goog.provide': - self._provide_tokens.append(token) - namespace = tokenutil.GetStringAfterToken(token) - if namespace in self._provided_namespaces: - self._duplicate_provide_tokens.append(token) - else: - self._provided_namespaces.append(namespace) - - # If there is a suppression for the provide, add a creation for it so it - # gets treated as a regular goog.provide (i.e. still gets sorted). - if self._HasSuppression(state_tracker, 'extraProvide'): - self._AddCreatedNamespace(state_tracker, namespace, token.line_number) - - elif token.string == 'goog.scope': - self._scopified_file = True - - elif token.string == 'goog.setTestOnly': - - # Since the message is optional, we don't want to scan to later lines. - for t in tokenutil.GetAllTokensInSameLine(token): - if t.type == TokenType.STRING_TEXT: - message = t.string - - if re.match(r'^\w+(\.\w+)+$', message): - # This looks like a namespace. If it's a Closurized namespace, - # consider it created. - base_namespace = message.split('.', 1)[0] - if base_namespace in self._closurized_namespaces: - self._AddCreatedNamespace(state_tracker, message, - token.line_number) - - break - else: - jsdoc = state_tracker.GetDocComment() - if token.metadata and token.metadata.aliased_symbol: - whole_identifier_string = token.metadata.aliased_symbol - elif (token.string == 'goog.module.get' and - not self._HasSuppression(state_tracker, 'extraRequire')): - # Cannot use _AddUsedNamespace as this is not an identifier, but - # already the entire namespace that's required. - namespace = tokenutil.GetStringAfterToken(token) - namespace = UsedNamespace(namespace, namespace, token, - alias_definition=False) - self._used_namespaces.append(namespace) - if jsdoc and jsdoc.HasFlag('typedef'): - self._AddCreatedNamespace(state_tracker, whole_identifier_string, - token.line_number, - namespace=self.GetClosurizedNamespace( - whole_identifier_string)) - else: - is_alias_definition = (token.metadata and - token.metadata.is_alias_definition) - self._AddUsedNamespace(state_tracker, whole_identifier_string, - token, is_alias_definition) - - elif token.type == TokenType.SIMPLE_LVALUE: - identifier = token.values['identifier'] - start_token = tokenutil.GetIdentifierStart(token) - if start_token and start_token != token: - # Multi-line identifier being assigned. Get the whole identifier. - identifier = tokenutil.GetIdentifierForToken(start_token) - else: - start_token = token - # If an alias is defined on the start_token, use it instead. - if (start_token and - start_token.metadata and - start_token.metadata.aliased_symbol and - not start_token.metadata.is_alias_definition): - identifier = start_token.metadata.aliased_symbol - - if identifier: - namespace = self.GetClosurizedNamespace(identifier) - if state_tracker.InFunction(): - self._AddUsedNamespace(state_tracker, identifier, token) - elif namespace and namespace != 'goog': - self._AddCreatedNamespace(state_tracker, identifier, - token.line_number, namespace=namespace) - - elif token.type == TokenType.DOC_FLAG: - flag = token.attached_object - flag_type = flag.flag_type - if flag and flag.HasType() and flag.jstype: - is_interface = state_tracker.GetDocComment().HasFlag('interface') - if flag_type == 'implements' or (flag_type == 'extends' - and is_interface): - identifier = flag.jstype.alias or flag.jstype.identifier - self._AddUsedNamespace(state_tracker, identifier, token) - # Since we process doctypes only for implements and extends, the - # type is a simple one and we don't need any iteration for subtypes. - - def _AddCreatedNamespace(self, state_tracker, identifier, line_number, - namespace=None): - """Adds the namespace of an identifier to the list of created namespaces. - - If the identifier is annotated with a 'missingProvide' suppression, it is - not added. - - Args: - state_tracker: The JavaScriptStateTracker instance. - identifier: The identifier to add. - line_number: Line number where namespace is created. - namespace: The namespace of the identifier or None if the identifier is - also the namespace. - """ - if not namespace: - namespace = identifier - - if self._HasSuppression(state_tracker, 'missingProvide'): - return - - self._created_namespaces.append([namespace, identifier, line_number]) - - def _AddUsedNamespace(self, state_tracker, identifier, token, - is_alias_definition=False): - """Adds the namespace of an identifier to the list of used namespaces. - - If the identifier is annotated with a 'missingRequire' suppression, it is - not added. - - Args: - state_tracker: The JavaScriptStateTracker instance. - identifier: An identifier which has been used. - token: The token in which the namespace is used. - is_alias_definition: If the used namespace is part of an alias_definition. - Aliased symbols need their parent namespace to be available, if it is - not yet required through another symbol, an error will be thrown. - """ - if self._HasSuppression(state_tracker, 'missingRequire'): - return - - namespace = self.GetClosurizedNamespace(identifier) - # b/5362203 If its a variable in scope then its not a required namespace. - if namespace and not state_tracker.IsVariableInScope(namespace): - namespace = UsedNamespace(namespace, identifier, token, - is_alias_definition) - self._used_namespaces.append(namespace) - - def _HasSuppression(self, state_tracker, suppression): - jsdoc = state_tracker.GetDocComment() - return jsdoc and suppression in jsdoc.suppressions - - def GetClosurizedNamespace(self, identifier): - """Given an identifier, returns the namespace that identifier is from. - - Args: - identifier: The identifier to extract a namespace from. - - Returns: - The namespace the given identifier resides in, or None if one could not - be found. - """ - if identifier.startswith('goog.global'): - # Ignore goog.global, since it is, by definition, global. - return None - - parts = identifier.split('.') - for namespace in self._closurized_namespaces: - if not identifier.startswith(namespace + '.'): - continue - - # The namespace for a class is the shortest prefix ending in a class - # name, which starts with a capital letter but is not a capitalized word. - # - # We ultimately do not want to allow requiring or providing of inner - # classes/enums. Instead, a file should provide only the top-level class - # and users should require only that. - namespace = [] - for part in parts: - if part == 'prototype' or part.isupper(): - return '.'.join(namespace) - namespace.append(part) - if part[0].isupper(): - return '.'.join(namespace) - - # At this point, we know there's no class or enum, so the namespace is - # just the identifier with the last part removed. With the exception of - # apply, inherits, and call, which should also be stripped. - if parts[-1] in ('apply', 'inherits', 'call'): - parts.pop() - parts.pop() - - # If the last part ends with an underscore, it is a private variable, - # method, or enum. The namespace is whatever is before it. - if parts and parts[-1].endswith('_'): - parts.pop() - - return '.'.join(parts) - - return None diff --git a/tools/closure_linter/closure_linter/closurizednamespacesinfo_test.py b/tools/closure_linter/closure_linter/closurizednamespacesinfo_test.py deleted file mode 100755 index 7aeae21956af8d..00000000000000 --- a/tools/closure_linter/closure_linter/closurizednamespacesinfo_test.py +++ /dev/null @@ -1,873 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for ClosurizedNamespacesInfo.""" - - - -import unittest as googletest -from closure_linter import aliaspass -from closure_linter import closurizednamespacesinfo -from closure_linter import ecmametadatapass -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - - -def _ToLineDict(illegal_alias_stmts): - """Replaces tokens with the respective line number.""" - return {k: v.line_number for k, v in illegal_alias_stmts.iteritems()} - - -class ClosurizedNamespacesInfoTest(googletest.TestCase): - """Tests for ClosurizedNamespacesInfo.""" - - _test_cases = { - 'goog.global.anything': None, - 'package.CONSTANT': 'package', - 'package.methodName': 'package', - 'package.subpackage.methodName': 'package.subpackage', - 'package.subpackage.methodName.apply': 'package.subpackage', - 'package.ClassName.something': 'package.ClassName', - 'package.ClassName.Enum.VALUE.methodName': 'package.ClassName', - 'package.ClassName.CONSTANT': 'package.ClassName', - 'package.namespace.CONSTANT.methodName': 'package.namespace', - 'package.ClassName.inherits': 'package.ClassName', - 'package.ClassName.apply': 'package.ClassName', - 'package.ClassName.methodName.apply': 'package.ClassName', - 'package.ClassName.methodName.call': 'package.ClassName', - 'package.ClassName.prototype.methodName': 'package.ClassName', - 'package.ClassName.privateMethod_': 'package.ClassName', - 'package.className.privateProperty_': 'package.className', - 'package.className.privateProperty_.methodName': 'package.className', - 'package.ClassName.PrivateEnum_': 'package.ClassName', - 'package.ClassName.prototype.methodName.apply': 'package.ClassName', - 'package.ClassName.property.subProperty': 'package.ClassName', - 'package.className.prototype.something.somethingElse': 'package.className' - } - - def testGetClosurizedNamespace(self): - """Tests that the correct namespace is returned for various identifiers.""" - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=['package'], ignored_extra_namespaces=[]) - for identifier, expected_namespace in self._test_cases.items(): - actual_namespace = namespaces_info.GetClosurizedNamespace(identifier) - self.assertEqual( - expected_namespace, - actual_namespace, - 'expected namespace "' + str(expected_namespace) + - '" for identifier "' + str(identifier) + '" but was "' + - str(actual_namespace) + '"') - - def testIgnoredExtraNamespaces(self): - """Tests that ignored_extra_namespaces are ignored.""" - token = self._GetRequireTokens('package.Something') - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=['package'], - ignored_extra_namespaces=['package.Something']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should be valid since it is in ignored namespaces.') - - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - ['package'], []) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be invalid since it is not in ignored namespaces.') - - def testIsExtraProvide_created(self): - """Tests that provides for created namespaces are not extra.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is created.') - - def testIsExtraProvide_createdIdentifier(self): - """Tests that provides for created identifiers are not extra.""" - input_lines = [ - 'goog.provide(\'package.Foo.methodName\');', - 'package.Foo.methodName = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is created.') - - def testIsExtraProvide_notCreated(self): - """Tests that provides for non-created namespaces are extra.""" - input_lines = ['goog.provide(\'package.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is not created.') - - def testIsExtraProvide_notCreatedMultipartClosurizedNamespace(self): - """Tests that provides for non-created namespaces are extra.""" - input_lines = ['goog.provide(\'multi.part.namespace.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['multi.part']) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is not created.') - - def testIsExtraProvide_duplicate(self): - """Tests that providing a namespace twice makes the second one extra.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - # Advance to the second goog.provide token. - token = tokenutil.Search(token.next, TokenType.IDENTIFIER) - - self.assertTrue(namespaces_info.IsExtraProvide(token), - 'Should be extra since it is already provided.') - - def testIsExtraProvide_notClosurized(self): - """Tests that provides of non-closurized namespaces are not extra.""" - input_lines = ['goog.provide(\'notclosurized.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraProvide(token), - 'Should not be extra since it is not closurized.') - - def testIsExtraRequire_used(self): - """Tests that requires for used namespaces are not extra.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'var x = package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is used.') - - def testIsExtraRequire_usedIdentifier(self): - """Tests that requires for used methods on classes are extra.""" - input_lines = [ - 'goog.require(\'package.Foo.methodName\');', - 'var x = package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should require the package, not the method specifically.') - - def testIsExtraRequire_notUsed(self): - """Tests that requires for unused namespaces are extra.""" - input_lines = ['goog.require(\'package.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be extra since it is not used.') - - def testIsExtraRequire_notUsedMultiPartClosurizedNamespace(self): - """Tests unused require with multi-part closurized namespaces.""" - - input_lines = ['goog.require(\'multi.part.namespace.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['multi.part']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'Should be extra since it is not used.') - - def testIsExtraRequire_notClosurized(self): - """Tests that requires of non-closurized namespaces are not extra.""" - input_lines = ['goog.require(\'notclosurized.Foo\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is not closurized.') - - def testIsExtraRequire_objectOnClass(self): - """Tests that requiring an object on a class is extra.""" - input_lines = [ - 'goog.require(\'package.Foo.Enum\');', - 'var x = package.Foo.Enum.VALUE1;', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'The whole class, not the object, should be required.'); - - def testIsExtraRequire_constantOnClass(self): - """Tests that requiring a constant on a class is extra.""" - input_lines = [ - 'goog.require(\'package.Foo.CONSTANT\');', - 'var x = package.Foo.CONSTANT', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertTrue(namespaces_info.IsExtraRequire(token), - 'The class, not the constant, should be required.'); - - def testIsExtraRequire_constantNotOnClass(self): - """Tests that requiring a constant not on a class is OK.""" - input_lines = [ - 'goog.require(\'package.subpackage.CONSTANT\');', - 'var x = package.subpackage.CONSTANT', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Constants can be required except on classes.'); - - def testIsExtraRequire_methodNotOnClass(self): - """Tests that requiring a method not on a class is OK.""" - input_lines = [ - 'goog.require(\'package.subpackage.method\');', - 'var x = package.subpackage.method()', - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Methods can be required except on classes.'); - - def testIsExtraRequire_defaults(self): - """Tests that there are no warnings about extra requires for test utils""" - input_lines = ['goog.require(\'goog.testing.jsunit\');'] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['goog']) - - self.assertFalse(namespaces_info.IsExtraRequire(token), - 'Should not be extra since it is for testing.') - - def testGetMissingProvides_provided(self): - """Tests that provided functions don't cause a missing provide.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript( - input_lines, ['package']) - - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_providedIdentifier(self): - """Tests that provided identifiers don't cause a missing provide.""" - input_lines = [ - 'goog.provide(\'package.Foo.methodName\');', - 'package.Foo.methodName = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_providedParentIdentifier(self): - """Tests that provided identifiers on a class don't cause a missing provide - on objects attached to that class.""" - input_lines = [ - 'goog.provide(\'package.foo.ClassName\');', - 'package.foo.ClassName.methodName = function() {};', - 'package.foo.ClassName.ObjectName = 1;', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_unprovided(self): - """Tests that unprovided functions cause a missing provide.""" - input_lines = ['package.Foo = function() {};'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_provides = namespaces_info.GetMissingProvides() - self.assertEquals(1, len(missing_provides)) - missing_provide = missing_provides.popitem() - self.assertEquals('package.Foo', missing_provide[0]) - self.assertEquals(1, missing_provide[1]) - - def testGetMissingProvides_privatefunction(self): - """Tests that unprovided private functions don't cause a missing provide.""" - input_lines = ['package.Foo_ = function() {};'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingProvides_required(self): - """Tests that required namespaces don't cause a missing provide.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName = function() {};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - self.assertEquals(0, len(namespaces_info.GetMissingProvides())) - - def testGetMissingRequires_required(self): - """Tests that required namespaces don't cause a missing require.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredIdentifier(self): - """Tests that required namespaces satisfy identifiers on that namespace.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredNamespace(self): - """Tests that required namespaces satisfy the namespace.""" - input_lines = [ - 'goog.require(\'package.soy.fooTemplate\');', - 'render(package.soy.fooTemplate);' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_requiredParentClass(self): - """Tests that requiring a parent class of an object is sufficient to prevent - a missing require on that object.""" - input_lines = [ - 'goog.require(\'package.Foo\');', - 'package.Foo.methodName();', - 'package.Foo.methodName(package.Foo.ObjectName);' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_unrequired(self): - """Tests that unrequired namespaces cause a missing require.""" - input_lines = ['package.Foo();'] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires)) - missing_req = missing_requires.popitem() - self.assertEquals('package.Foo', missing_req[0]) - self.assertEquals(1, missing_req[1]) - - def testGetMissingRequires_provided(self): - """Tests that provided namespaces satisfy identifiers on that namespace.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_created(self): - """Tests that created namespaces do not satisfy usage of an identifier.""" - input_lines = [ - 'package.Foo = function();', - 'package.Foo.methodName();', - 'package.Foo.anotherMethodName1();', - 'package.Foo.anotherMethodName2();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires)) - missing_require = missing_requires.popitem() - self.assertEquals('package.Foo', missing_require[0]) - # Make sure line number of first occurrence is reported - self.assertEquals(2, missing_require[1]) - - def testGetMissingRequires_createdIdentifier(self): - """Tests that created identifiers satisfy usage of the identifier.""" - input_lines = [ - 'package.Foo.methodName = function();', - 'package.Foo.methodName();' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(0, len(missing_requires)) - - def testGetMissingRequires_implements(self): - """Tests that a parametrized type requires the correct identifier.""" - input_lines = [ - '/** @constructor @implements {package.Bar} */', - 'package.Foo = function();', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertItemsEqual({'package.Bar': 1}, missing_requires) - - def testGetMissingRequires_objectOnClass(self): - """Tests that we should require a class, not the object on the class.""" - input_lines = [ - 'goog.require(\'package.Foo.Enum\');', - 'var x = package.Foo.Enum.VALUE1;', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['package']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(1, len(missing_requires), - 'The whole class, not the object, should be required.') - - def testGetMissingRequires_variableWithSameName(self): - """Tests that we should not goog.require variables and parameters. - - b/5362203 Variables in scope are not missing namespaces. - """ - input_lines = [ - 'goog.provide(\'Foo\');', - 'Foo.A = function();', - 'Foo.A.prototype.method = function(ab) {', - ' if (ab) {', - ' var docs;', - ' var lvalue = new Obj();', - ' // Variable in scope hence not goog.require here.', - ' docs.foo.abc = 1;', - ' lvalue.next();', - ' }', - ' // Since js is function scope this should also not goog.require.', - ' docs.foo.func();', - ' // Its not a variable in scope hence goog.require.', - ' dummy.xyz.reset();', - ' return this.method2();', - '};', - 'Foo.A.prototype.method1 = function(docs, abcd, xyz) {', - ' // Parameter hence not goog.require.', - ' docs.nodes.length = 2;', - ' lvalue.abc.reset();', - '};' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['Foo', - 'docs', - 'lvalue', - 'dummy']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals(2, len(missing_requires)) - self.assertItemsEqual( - {'dummy.xyz': 14, - 'lvalue.abc': 20}, missing_requires) - - def testIsFirstProvide(self): - """Tests operation of the isFirstProvide method.""" - input_lines = [ - 'goog.provide(\'package.Foo\');', - 'package.Foo.methodName();' - ] - - token, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - input_lines, ['package']) - self.assertTrue(namespaces_info.IsFirstProvide(token)) - - def testGetWholeIdentifierString(self): - """Tests that created identifiers satisfy usage of the identifier.""" - input_lines = [ - 'package.Foo.', - ' veryLong.', - ' identifier;' - ] - - token = testutil.TokenizeSource(input_lines) - - self.assertEquals('package.Foo.veryLong.identifier', - tokenutil.GetIdentifierForToken(token)) - - self.assertEquals(None, - tokenutil.GetIdentifierForToken(token.next)) - - def testScopified(self): - """Tests that a goog.scope call is noticed.""" - input_lines = [ - 'goog.scope(function() {', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertTrue(namespaces_info._scopified_file) - - def testScope_unusedAlias(self): - """Tests that an unused alias symbol is illegal.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_usedMultilevelAlias(self): - """Tests that an used alias symbol in a deep namespace is ok.""" - input_lines = [ - 'goog.require(\'goog.Events\');', - 'goog.scope(function() {', - 'var Event = goog.Events.DeepNamespace.Event;', - 'Event();', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_usedAlias(self): - """Tests that aliased symbols result in correct requires.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - 'var dom = goog.dom;', - 'Event(dom.classes.get);', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, illegal_alias_stmts) - self.assertEquals({'goog.dom.classes': 4, 'goog.events.Event': 4}, - missing_requires) - - def testModule_alias(self): - """Tests that goog.module style aliases are supported.""" - input_lines = [ - 'goog.module(\'test.module\');', - 'var Unused = goog.require(\'goog.Unused\');', - 'var AliasedClass = goog.require(\'goog.AliasedClass\');', - 'var x = new AliasedClass();', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - namespaceToken = self._GetRequireTokens('goog.AliasedClass') - self.assertFalse(namespaces_info.IsExtraRequire(namespaceToken), - 'AliasedClass should be marked as used') - unusedToken = self._GetRequireTokens('goog.Unused') - self.assertTrue(namespaces_info.IsExtraRequire(unusedToken), - 'Unused should be marked as not used') - - def testModule_aliasInScope(self): - """Tests that goog.module style aliases are supported.""" - input_lines = [ - 'goog.module(\'test.module\');', - 'var AliasedClass = goog.require(\'goog.AliasedClass\');', - 'goog.scope(function() {', - 'var x = new AliasedClass();', - '});', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - namespaceToken = self._GetRequireTokens('goog.AliasedClass') - self.assertFalse(namespaces_info.IsExtraRequire(namespaceToken), - 'AliasedClass should be marked as used') - - def testModule_getAlwaysProvided(self): - """Tests that goog.module.get is recognized as a built-in.""" - input_lines = [ - 'goog.provide(\'test.MyClass\');', - 'goog.require(\'goog.someModule\');', - 'goog.scope(function() {', - 'var someModule = goog.module.get(\'goog.someModule\');', - 'test.MyClass = function() {};', - '});', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertEquals({}, namespaces_info.GetMissingRequires()[0]) - - def testModule_requireForGet(self): - """Tests that goog.module.get needs a goog.require call.""" - input_lines = [ - 'goog.provide(\'test.MyClass\');', - 'function foo() {', - ' var someModule = goog.module.get(\'goog.someModule\');', - ' someModule.doSth();', - '}', - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - self.assertEquals({'goog.someModule': 3}, - namespaces_info.GetMissingRequires()[0]) - - def testScope_usedTypeAlias(self): - """Tests aliased symbols in type annotations.""" - input_lines = [ - 'goog.scope(function() {', - 'var Event = goog.events.Event;', - '/** @type {Event} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_partialAlias_typeOnly(self): - """Tests a partial alias only used in type annotations. - - In this example, some goog.events namespace would need to be required - so that evaluating goog.events.bar doesn't throw an error. - """ - input_lines = [ - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Foo} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_partialAlias(self): - """Tests a partial alias in conjunction with a type annotation. - - In this example, the partial alias is already defined by another type, - therefore the doc-only type doesn't need to be required. - """ - input_lines = [ - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({'goog.events.bar.EventType': 4}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_partialAliasRequires(self): - """Tests partial aliases with correct requires.""" - input_lines = [ - 'goog.require(\'goog.events.bar.EventType\');', - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_partialAliasRequiresBoth(self): - """Tests partial aliases with correct requires.""" - input_lines = [ - 'goog.require(\'goog.events.bar.Event\');', - 'goog.require(\'goog.events.bar.EventType\');', - 'goog.scope(function() {', - 'var bar = goog.events.bar;', - '/** @type {bar.Event} */;', - 'bar.EventType();' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - event_token = self._GetRequireTokens('goog.events.bar.Event') - self.assertTrue(namespaces_info.IsExtraRequire(event_token)) - - def testScope_partialAliasNoSubtypeRequires(self): - """Tests that partial aliases don't yield subtype requires (regression).""" - input_lines = [ - 'goog.provide(\'goog.events.Foo\');', - 'goog.scope(function() {', - 'goog.events.Foo = {};', - 'var Foo = goog.events.Foo;' - 'Foo.CssName_ = {};' - 'var CssName_ = Foo.CssName_;' - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, _ = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - - def testScope_aliasNamespace(self): - """Tests that an unused alias namespace is not required when available. - - In the example goog.events.Bar is not required, because the namespace - goog.events is already defined because goog.events.Foo is required. - """ - input_lines = [ - 'goog.require(\'goog.events.Foo\');', - 'goog.scope(function() {', - 'var Bar = goog.events.Bar;', - '/** @type {Bar} */;', - 'goog.events.Foo;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({}, illegal_alias_stmts) - - def testScope_aliasNamespaceIllegal(self): - """Tests that an unused alias namespace is not required when available.""" - input_lines = [ - 'goog.scope(function() {', - 'var Bar = goog.events.Bar;', - '/** @type {Bar} */;', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_requires, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, missing_requires) - self.assertEquals({'goog.events': 2}, _ToLineDict(illegal_alias_stmts)) - - def testScope_provides(self): - """Tests that aliased symbols result in correct provides.""" - input_lines = [ - 'goog.scope(function() {', - 'goog.bar = {};', - 'var bar = goog.bar;', - 'bar.Foo = {};', - '});' - ] - - namespaces_info = self._GetNamespacesInfoForScript(input_lines, ['goog']) - missing_provides = namespaces_info.GetMissingProvides() - self.assertEquals({'goog.bar.Foo': 4}, missing_provides) - _, illegal_alias_stmts = namespaces_info.GetMissingRequires() - self.assertEquals({}, illegal_alias_stmts) - - def testSetTestOnlyNamespaces(self): - """Tests that a namespace in setTestOnly makes it a valid provide.""" - namespaces_info = self._GetNamespacesInfoForScript([ - 'goog.setTestOnly(\'goog.foo.barTest\');' - ], ['goog']) - - token = self._GetProvideTokens('goog.foo.barTest') - self.assertFalse(namespaces_info.IsExtraProvide(token)) - - token = self._GetProvideTokens('goog.foo.bazTest') - self.assertTrue(namespaces_info.IsExtraProvide(token)) - - def testSetTestOnlyComment(self): - """Ensure a comment in setTestOnly does not cause a created namespace.""" - namespaces_info = self._GetNamespacesInfoForScript([ - 'goog.setTestOnly(\'this is a comment\');' - ], ['goog']) - - self.assertEquals( - [], namespaces_info._created_namespaces, - 'A comment in setTestOnly should not modify created namespaces.') - - def _GetNamespacesInfoForScript(self, script, closurized_namespaces=None): - _, namespaces_info = self._GetStartTokenAndNamespacesInfoForScript( - script, closurized_namespaces) - - return namespaces_info - - def _GetStartTokenAndNamespacesInfoForScript( - self, script, closurized_namespaces): - - token = testutil.TokenizeSource(script) - return token, self._GetInitializedNamespacesInfo( - token, closurized_namespaces, []) - - def _GetInitializedNamespacesInfo(self, token, closurized_namespaces, - ignored_extra_namespaces): - """Returns a namespaces info initialized with the given token stream.""" - namespaces_info = closurizednamespacesinfo.ClosurizedNamespacesInfo( - closurized_namespaces=closurized_namespaces, - ignored_extra_namespaces=ignored_extra_namespaces) - state_tracker = javascriptstatetracker.JavaScriptStateTracker() - - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - ecma_pass.Process(token) - - state_tracker.DocFlagPass(token, error_handler=None) - - alias_pass = aliaspass.AliasPass(closurized_namespaces) - alias_pass.Process(token) - - while token: - state_tracker.HandleToken(token, state_tracker.GetLastNonSpaceToken()) - namespaces_info.ProcessToken(token, state_tracker) - state_tracker.HandleAfterToken(token) - token = token.next - - return namespaces_info - - def _GetProvideTokens(self, namespace): - """Returns a list of tokens for a goog.require of the given namespace.""" - line_text = 'goog.require(\'' + namespace + '\');\n' - return testutil.TokenizeSource([line_text]) - - def _GetRequireTokens(self, namespace): - """Returns a list of tokens for a goog.require of the given namespace.""" - line_text = 'goog.require(\'' + namespace + '\');\n' - return testutil.TokenizeSource([line_text]) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/common/__init__.py b/tools/closure_linter/closure_linter/common/__init__.py deleted file mode 100755 index 57930436ce4323..00000000000000 --- a/tools/closure_linter/closure_linter/common/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Package indicator for gjslint.common.""" diff --git a/tools/closure_linter/closure_linter/common/error.py b/tools/closure_linter/closure_linter/common/error.py deleted file mode 100755 index 4209c235b85425..00000000000000 --- a/tools/closure_linter/closure_linter/common/error.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Error object commonly used in linters.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class Error(object): - """Object representing a style error.""" - - def __init__(self, code, message, token=None, position=None, fix_data=None): - """Initialize the error object. - - Args: - code: The numeric error code. - message: The error message string. - token: The tokens.Token where the error occurred. - position: The position of the error within the token. - fix_data: Data to be used in autofixing. Codes with fix_data are: - GOOG_REQUIRES_NOT_ALPHABETIZED - List of string value tokens that are - class names in goog.requires calls. - """ - self.code = code - self.message = message - self.token = token - self.position = position - if token: - self.start_index = token.start_index - else: - self.start_index = 0 - self.fix_data = fix_data - if self.position: - self.start_index += self.position.start - - def Compare(a, b): - """Compare two error objects, by source code order. - - Args: - a: First error object. - b: Second error object. - - Returns: - A Negative/0/Positive number when a is before/the same as/after b. - """ - line_diff = a.token.line_number - b.token.line_number - if line_diff: - return line_diff - - return a.start_index - b.start_index - Compare = staticmethod(Compare) diff --git a/tools/closure_linter/closure_linter/common/erroraccumulator.py b/tools/closure_linter/closure_linter/common/erroraccumulator.py deleted file mode 100755 index 55844ba60356fa..00000000000000 --- a/tools/closure_linter/closure_linter/common/erroraccumulator.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Linter error handler class that accumulates an array of errors.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -from closure_linter.common import errorhandler - - -class ErrorAccumulator(errorhandler.ErrorHandler): - """Error handler object that accumulates errors in a list.""" - - def __init__(self): - self._errors = [] - - def HandleError(self, error): - """Append the error to the list. - - Args: - error: The error object - """ - self._errors.append(error) - - def GetErrors(self): - """Returns the accumulated errors. - - Returns: - A sequence of errors. - """ - return self._errors diff --git a/tools/closure_linter/closure_linter/common/errorhandler.py b/tools/closure_linter/closure_linter/common/errorhandler.py deleted file mode 100755 index 764d54d84cb3c1..00000000000000 --- a/tools/closure_linter/closure_linter/common/errorhandler.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Interface for a linter error handler. - -Error handlers aggregate a set of errors from multiple files and can optionally -perform some action based on the reported errors, for example, logging the error -or automatically fixing it. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class ErrorHandler(object): - """Error handler interface.""" - - def __init__(self): - if self.__class__ == ErrorHandler: - raise NotImplementedError('class ErrorHandler is abstract') - - def HandleFile(self, filename, first_token): - """Notifies this ErrorHandler that subsequent errors are in filename. - - Args: - filename: The file being linted. - first_token: The first token of the file. - """ - - def HandleError(self, error): - """Append the error to the list. - - Args: - error: The error object - """ - - def FinishFile(self): - """Finishes handling the current file. - - Should be called after all errors in a file have been handled. - """ - - def GetErrors(self): - """Returns the accumulated errors. - - Returns: - A sequence of errors. - """ diff --git a/tools/closure_linter/closure_linter/common/erroroutput.py b/tools/closure_linter/closure_linter/common/erroroutput.py deleted file mode 100644 index 149738b5d4f173..00000000000000 --- a/tools/closure_linter/closure_linter/common/erroroutput.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Utility functions to format errors.""" - - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'nnaze@google.com (Nathan Naze)') - - -def GetUnixErrorOutput(filename, error, new_error=False): - """Get a output line for an error in UNIX format.""" - - line = '' - - if error.token: - line = '%d' % error.token.line_number - - error_code = '%04d' % error.code - if new_error: - error_code = 'New Error ' + error_code - return '%s:%s:(%s) %s' % (filename, line, error_code, error.message) - - -def GetErrorOutput(error, new_error=False): - """Get a output line for an error in regular format.""" - - line = '' - if error.token: - line = 'Line %d, ' % error.token.line_number - - code = 'E:%04d' % error.code - - error_message = error.message - if new_error: - error_message = 'New Error ' + error_message - - return '%s%s: %s' % (line, code, error.message) diff --git a/tools/closure_linter/closure_linter/common/filetestcase.py b/tools/closure_linter/closure_linter/common/filetestcase.py deleted file mode 100755 index 7cd83cd1dcf58c..00000000000000 --- a/tools/closure_linter/closure_linter/common/filetestcase.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Test case that runs a checker on a file, matching errors against annotations. - -Runs the given checker on the given file, accumulating all errors. The list -of errors is then matched against those annotated in the file. Based heavily -on devtools/javascript/gpylint/full_test.py. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import re - -import gflags as flags -import unittest as googletest -from closure_linter.common import erroraccumulator - - -class AnnotatedFileTestCase(googletest.TestCase): - """Test case to run a linter against a single file.""" - - # Matches an all caps letters + underscores error identifer - _MESSAGE = {'msg': '[A-Z][A-Z_]+'} - # Matches a //, followed by an optional line number with a +/-, followed by a - # list of message IDs. Used to extract expected messages from testdata files. - # TODO(robbyw): Generalize to use different commenting patterns. - _EXPECTED_RE = re.compile(r'\s*//\s*(?:(?P[+-]?[0-9]+):)?' - r'\s*(?P%(msg)s(?:,\s*%(msg)s)*)' % _MESSAGE) - - def __init__(self, filename, lint_callable, converter): - """Create a single file lint test case. - - Args: - filename: Filename to test. - lint_callable: Callable that lints a file. This is usually runner.Run(). - converter: Function taking an error string and returning an error code. - """ - - googletest.TestCase.__init__(self, 'runTest') - self._filename = filename - self._messages = [] - self._lint_callable = lint_callable - self._converter = converter - - def setUp(self): - flags.FLAGS.dot_on_next_line = True - - def tearDown(self): - flags.FLAGS.dot_on_next_line = False - - def shortDescription(self): - """Provides a description for the test.""" - return 'Run linter on %s' % self._filename - - def runTest(self): - """Runs the test.""" - try: - filename = self._filename - stream = open(filename) - except IOError as ex: - raise IOError('Could not find testdata resource for %s: %s' % - (self._filename, ex)) - - expected = self._GetExpectedMessages(stream) - got = self._ProcessFileAndGetMessages(filename) - self.assertEqual(expected, got) - - def _GetExpectedMessages(self, stream): - """Parse a file and get a sorted list of expected messages.""" - messages = [] - for i, line in enumerate(stream): - match = self._EXPECTED_RE.search(line) - if match: - line = match.group('line') - msg_ids = match.group('msgs') - if line is None: - line = i + 1 - elif line.startswith('+') or line.startswith('-'): - line = i + 1 + int(line) - else: - line = int(line) - for msg_id in msg_ids.split(','): - # Ignore a spurious message from the license preamble. - if msg_id != 'WITHOUT': - messages.append((line, self._converter(msg_id.strip()))) - stream.seek(0) - messages.sort() - return messages - - def _ProcessFileAndGetMessages(self, filename): - """Trap gjslint's output parse it to get messages added.""" - error_accumulator = erroraccumulator.ErrorAccumulator() - self._lint_callable(filename, error_accumulator) - - errors = error_accumulator.GetErrors() - - # Convert to expected tuple format. - - error_msgs = [(error.token.line_number, error.code) for error in errors] - error_msgs.sort() - return error_msgs diff --git a/tools/closure_linter/closure_linter/common/htmlutil.py b/tools/closure_linter/closure_linter/common/htmlutil.py deleted file mode 100755 index 26d44c5908353d..00000000000000 --- a/tools/closure_linter/closure_linter/common/htmlutil.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Utilities for dealing with HTML.""" - -__author__ = ('robbyw@google.com (Robert Walker)') - -import cStringIO -import formatter -import htmllib -import HTMLParser -import re - - -class ScriptExtractor(htmllib.HTMLParser): - """Subclass of HTMLParser that extracts script contents from an HTML file. - - Also inserts appropriate blank lines so that line numbers in the extracted - code match the line numbers in the original HTML. - """ - - def __init__(self): - """Initialize a ScriptExtractor.""" - htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) - self._in_script = False - self._text = '' - - def start_script(self, attrs): - """Internal handler for the start of a script tag. - - Args: - attrs: The attributes of the script tag, as a list of tuples. - """ - for attribute in attrs: - if attribute[0].lower() == 'src': - # Skip script tags with a src specified. - return - self._in_script = True - - def end_script(self): - """Internal handler for the end of a script tag.""" - self._in_script = False - - def handle_data(self, data): - """Internal handler for character data. - - Args: - data: The character data from the HTML file. - """ - if self._in_script: - # If the last line contains whitespace only, i.e. is just there to - # properly align a tag, strip the whitespace. - if data.rstrip(' \t') != data.rstrip(' \t\n\r\f'): - data = data.rstrip(' \t') - self._text += data - else: - self._AppendNewlines(data) - - def handle_comment(self, data): - """Internal handler for HTML comments. - - Args: - data: The text of the comment. - """ - self._AppendNewlines(data) - - def _AppendNewlines(self, data): - """Count the number of newlines in the given string and append them. - - This ensures line numbers are correct for reported errors. - - Args: - data: The data to count newlines in. - """ - # We append 'x' to both sides of the string to ensure that splitlines - # gives us an accurate count. - for i in xrange(len(('x' + data + 'x').splitlines()) - 1): - self._text += '\n' - - def GetScriptLines(self): - """Return the extracted script lines. - - Returns: - The extracted script lines as a list of strings. - """ - return self._text.splitlines() - - -def GetScriptLines(f): - """Extract script tag contents from the given HTML file. - - Args: - f: The HTML file. - - Returns: - Lines in the HTML file that are from script tags. - """ - extractor = ScriptExtractor() - - # The HTML parser chokes on text like Array., so we patch - # that bug by replacing the < with < - escaping all text inside script - # tags would be better but it's a bit of a catch 22. - contents = f.read() - contents = re.sub(r'<([^\s\w/])', - lambda x: '<%s' % x.group(1), - contents) - - extractor.feed(contents) - extractor.close() - return extractor.GetScriptLines() - - -def StripTags(str): - """Returns the string with HTML tags stripped. - - Args: - str: An html string. - - Returns: - The html string with all tags stripped. If there was a parse error, returns - the text successfully parsed so far. - """ - # Brute force approach to stripping as much HTML as possible. If there is a - # parsing error, don't strip text before parse error position, and continue - # trying from there. - final_text = '' - finished = False - while not finished: - try: - strip = _HtmlStripper() - strip.feed(str) - strip.close() - str = strip.get_output() - final_text += str - finished = True - except HTMLParser.HTMLParseError, e: - final_text += str[:e.offset] - str = str[e.offset + 1:] - - return final_text - - -class _HtmlStripper(HTMLParser.HTMLParser): - """Simple class to strip tags from HTML. - - Does so by doing nothing when encountering tags, and appending character data - to a buffer when that is encountered. - """ - def __init__(self): - self.reset() - self.__output = cStringIO.StringIO() - - def handle_data(self, d): - self.__output.write(d) - - def get_output(self): - return self.__output.getvalue() diff --git a/tools/closure_linter/closure_linter/common/lintrunner.py b/tools/closure_linter/closure_linter/common/lintrunner.py deleted file mode 100755 index 07842c7bfeb36f..00000000000000 --- a/tools/closure_linter/closure_linter/common/lintrunner.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Interface for a lint running wrapper.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class LintRunner(object): - """Interface for a lint running wrapper.""" - - def __init__(self): - if self.__class__ == LintRunner: - raise NotImplementedError('class LintRunner is abstract') - - def Run(self, filenames, error_handler): - """Run a linter on the given filenames. - - Args: - filenames: The filenames to check - error_handler: An ErrorHandler object - - Returns: - The error handler, which may have been used to collect error info. - """ diff --git a/tools/closure_linter/closure_linter/common/matcher.py b/tools/closure_linter/closure_linter/common/matcher.py deleted file mode 100755 index 9b4402c6718bc7..00000000000000 --- a/tools/closure_linter/closure_linter/common/matcher.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Regular expression based JavaScript matcher classes.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -from closure_linter.common import position -from closure_linter.common import tokens - -# Shorthand -Token = tokens.Token -Position = position.Position - - -class Matcher(object): - """A token matcher. - - Specifies a pattern to match, the type of token it represents, what mode the - token changes to, and what mode the token applies to. - - Modes allow more advanced grammars to be incorporated, and are also necessary - to tokenize line by line. We can have different patterns apply to different - modes - i.e. looking for documentation while in comment mode. - - Attributes: - regex: The regular expression representing this matcher. - type: The type of token indicated by a successful match. - result_mode: The mode to move to after a successful match. - """ - - def __init__(self, regex, token_type, result_mode=None, line_start=False): - """Create a new matcher template. - - Args: - regex: The regular expression to match. - token_type: The type of token a successful match indicates. - result_mode: What mode to change to after a successful match. Defaults to - None, which means to not change the current mode. - line_start: Whether this matcher should only match string at the start - of a line. - """ - self.regex = regex - self.type = token_type - self.result_mode = result_mode - self.line_start = line_start diff --git a/tools/closure_linter/closure_linter/common/position.py b/tools/closure_linter/closure_linter/common/position.py deleted file mode 100755 index cebf17ef36277e..00000000000000 --- a/tools/closure_linter/closure_linter/common/position.py +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Classes to represent positions within strings.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class Position(object): - """Object representing a segment of a string. - - Attributes: - start: The index in to the string where the segment starts. - length: The length of the string segment. - """ - - def __init__(self, start, length): - """Initialize the position object. - - Args: - start: The start index. - length: The number of characters to include. - """ - self.start = start - self.length = length - - def Get(self, string): - """Returns this range of the given string. - - Args: - string: The string to slice. - - Returns: - The string within the range specified by this object. - """ - return string[self.start:self.start + self.length] - - def Set(self, target, source): - """Sets this range within the target string to the source string. - - Args: - target: The target string. - source: The source string. - - Returns: - The resulting string - """ - return target[:self.start] + source + target[self.start + self.length:] - - def AtEnd(string): - """Create a Position representing the end of the given string. - - Args: - string: The string to represent the end of. - - Returns: - The created Position object. - """ - return Position(len(string), 0) - AtEnd = staticmethod(AtEnd) - - def IsAtEnd(self, string): - """Returns whether this position is at the end of the given string. - - Args: - string: The string to test for the end of. - - Returns: - Whether this position is at the end of the given string. - """ - return self.start == len(string) and self.length == 0 - - def AtBeginning(): - """Create a Position representing the beginning of any string. - - Returns: - The created Position object. - """ - return Position(0, 0) - AtBeginning = staticmethod(AtBeginning) - - def IsAtBeginning(self): - """Returns whether this position is at the beginning of any string. - - Returns: - Whether this position is at the beginning of any string. - """ - return self.start == 0 and self.length == 0 - - def All(string): - """Create a Position representing the entire string. - - Args: - string: The string to represent the entirety of. - - Returns: - The created Position object. - """ - return Position(0, len(string)) - All = staticmethod(All) - - def Index(index): - """Returns a Position object for the specified index. - - Args: - index: The index to select, inclusively. - - Returns: - The created Position object. - """ - return Position(index, 1) - Index = staticmethod(Index) diff --git a/tools/closure_linter/closure_linter/common/simplefileflags.py b/tools/closure_linter/closure_linter/common/simplefileflags.py deleted file mode 100755 index 3402bef3a1d36e..00000000000000 --- a/tools/closure_linter/closure_linter/common/simplefileflags.py +++ /dev/null @@ -1,190 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Determines the list of files to be checked from command line arguments.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import glob -import os -import re - -import gflags as flags - - -FLAGS = flags.FLAGS - -flags.DEFINE_multistring( - 'recurse', - None, - 'Recurse in to the subdirectories of the given path', - short_name='r') -flags.DEFINE_list( - 'exclude_directories', - ('_demos'), - 'Exclude the specified directories (only applicable along with -r or ' - '--presubmit)', - short_name='e') -flags.DEFINE_list( - 'exclude_files', - ('deps.js'), - 'Exclude the specified files', - short_name='x') - - -def MatchesSuffixes(filename, suffixes): - """Returns whether the given filename matches one of the given suffixes. - - Args: - filename: Filename to check. - suffixes: Sequence of suffixes to check. - - Returns: - Whether the given filename matches one of the given suffixes. - """ - suffix = filename[filename.rfind('.'):] - return suffix in suffixes - - -def _GetUserSpecifiedFiles(argv, suffixes): - """Returns files to be linted, specified directly on the command line. - - Can handle the '*' wildcard in filenames, but no other wildcards. - - Args: - argv: Sequence of command line arguments. The second and following arguments - are assumed to be files that should be linted. - suffixes: Expected suffixes for the file type being checked. - - Returns: - A sequence of files to be linted. - """ - files = argv[1:] or [] - all_files = [] - lint_files = [] - - # Perform any necessary globs. - for f in files: - if f.find('*') != -1: - for result in glob.glob(f): - all_files.append(result) - else: - all_files.append(f) - - for f in all_files: - if MatchesSuffixes(f, suffixes): - lint_files.append(f) - return lint_files - - -def _GetRecursiveFiles(suffixes): - """Returns files to be checked specified by the --recurse flag. - - Args: - suffixes: Expected suffixes for the file type being checked. - - Returns: - A list of files to be checked. - """ - lint_files = [] - # Perform any request recursion - if FLAGS.recurse: - for start in FLAGS.recurse: - for root, subdirs, files in os.walk(start): - for f in files: - if MatchesSuffixes(f, suffixes): - lint_files.append(os.path.join(root, f)) - return lint_files - - -def GetAllSpecifiedFiles(argv, suffixes): - """Returns all files specified by the user on the commandline. - - Args: - argv: Sequence of command line arguments. The second and following arguments - are assumed to be files that should be linted. - suffixes: Expected suffixes for the file type - - Returns: - A list of all files specified directly or indirectly (via flags) on the - command line by the user. - """ - files = _GetUserSpecifiedFiles(argv, suffixes) - - if FLAGS.recurse: - files += _GetRecursiveFiles(suffixes) - - return FilterFiles(files) - - -def FilterFiles(files): - """Filters the list of files to be linted be removing any excluded files. - - Filters out files excluded using --exclude_files and --exclude_directories. - - Args: - files: Sequence of files that needs filtering. - - Returns: - Filtered list of files to be linted. - """ - num_files = len(files) - - ignore_dirs_regexs = [] - for ignore in FLAGS.exclude_directories: - ignore_dirs_regexs.append(re.compile(r'(^|[\\/])%s[\\/]' % ignore)) - - result_files = [] - for f in files: - add_file = True - for exclude in FLAGS.exclude_files: - if f.endswith('/' + exclude) or f == exclude: - add_file = False - break - for ignore in ignore_dirs_regexs: - if ignore.search(f): - # Break out of ignore loop so we don't add to - # filtered files. - add_file = False - break - if add_file: - # Convert everything to absolute paths so we can easily remove duplicates - # using a set. - result_files.append(os.path.abspath(f)) - - skipped = num_files - len(result_files) - if skipped: - print 'Skipping %d file(s).' % skipped - - return set(result_files) - - -def GetFileList(argv, file_type, suffixes): - """Parse the flags and return the list of files to check. - - Args: - argv: Sequence of command line arguments. - suffixes: Sequence of acceptable suffixes for the file type. - - Returns: - The list of files to check. - """ - return sorted(GetAllSpecifiedFiles(argv, suffixes)) - - -def IsEmptyArgumentList(argv): - return not (len(argv[1:]) or FLAGS.recurse) diff --git a/tools/closure_linter/closure_linter/common/tokenizer.py b/tools/closure_linter/closure_linter/common/tokenizer.py deleted file mode 100755 index 9420ea3267a5a2..00000000000000 --- a/tools/closure_linter/closure_linter/common/tokenizer.py +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Regular expression based lexer.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -from closure_linter.common import tokens - -# Shorthand -Type = tokens.TokenType - - -class Tokenizer(object): - """General purpose tokenizer. - - Attributes: - mode: The latest mode of the tokenizer. This allows patterns to distinguish - if they are mid-comment, mid-parameter list, etc. - matchers: Dictionary of modes to sequences of matchers that define the - patterns to check at any given time. - default_types: Dictionary of modes to types, defining what type to give - non-matched text when in the given mode. Defaults to Type.NORMAL. - """ - - def __init__(self, starting_mode, matchers, default_types): - """Initialize the tokenizer. - - Args: - starting_mode: Mode to start in. - matchers: Dictionary of modes to sequences of matchers that defines the - patterns to check at any given time. - default_types: Dictionary of modes to types, defining what type to give - non-matched text when in the given mode. Defaults to Type.NORMAL. - """ - self.__starting_mode = starting_mode - self.matchers = matchers - self.default_types = default_types - - def TokenizeFile(self, file): - """Tokenizes the given file. - - Args: - file: An iterable that yields one line of the file at a time. - - Returns: - The first token in the file - """ - # The current mode. - self.mode = self.__starting_mode - # The first token in the stream. - self.__first_token = None - # The last token added to the token stream. - self.__last_token = None - # The current line number. - self.__line_number = 0 - - for line in file: - self.__line_number += 1 - self.__TokenizeLine(line) - - return self.__first_token - - def _CreateToken(self, string, token_type, line, line_number, values=None): - """Creates a new Token object (or subclass). - - Args: - string: The string of input the token represents. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - - Returns: - The newly created Token object. - """ - return tokens.Token(string, token_type, line, line_number, values, - line_number) - - def __TokenizeLine(self, line): - """Tokenizes the given line. - - Args: - line: The contents of the line. - """ - string = line.rstrip('\n\r\f') - line_number = self.__line_number - self.__start_index = 0 - - if not string: - self.__AddToken(self._CreateToken('', Type.BLANK_LINE, line, line_number)) - return - - normal_token = '' - index = 0 - while index < len(string): - for matcher in self.matchers[self.mode]: - if matcher.line_start and index > 0: - continue - - match = matcher.regex.match(string, index) - - if match: - if normal_token: - self.__AddToken( - self.__CreateNormalToken(self.mode, normal_token, line, - line_number)) - normal_token = '' - - # Add the match. - self.__AddToken(self._CreateToken(match.group(), matcher.type, line, - line_number, match.groupdict())) - - # Change the mode to the correct one for after this match. - self.mode = matcher.result_mode or self.mode - - # Shorten the string to be matched. - index = match.end() - - break - - else: - # If the for loop finishes naturally (i.e. no matches) we just add the - # first character to the string of consecutive non match characters. - # These will constitute a NORMAL token. - if string: - normal_token += string[index:index + 1] - index += 1 - - if normal_token: - self.__AddToken( - self.__CreateNormalToken(self.mode, normal_token, line, line_number)) - - def __CreateNormalToken(self, mode, string, line, line_number): - """Creates a normal token. - - Args: - mode: The current mode. - string: The string to tokenize. - line: The line of text. - line_number: The line number within the file. - - Returns: - A Token object, of the default type for the current mode. - """ - type = Type.NORMAL - if mode in self.default_types: - type = self.default_types[mode] - return self._CreateToken(string, type, line, line_number) - - def __AddToken(self, token): - """Add the given token to the token stream. - - Args: - token: The token to add. - """ - # Store the first token, or point the previous token to this one. - if not self.__first_token: - self.__first_token = token - else: - self.__last_token.next = token - - # Establish the doubly linked list - token.previous = self.__last_token - self.__last_token = token - - # Compute the character indices - token.start_index = self.__start_index - self.__start_index += token.length diff --git a/tools/closure_linter/closure_linter/common/tokens.py b/tools/closure_linter/closure_linter/common/tokens.py deleted file mode 100755 index 4703998752b036..00000000000000 --- a/tools/closure_linter/closure_linter/common/tokens.py +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Classes to represent tokens and positions within them.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -class TokenType(object): - """Token types common to all languages.""" - NORMAL = 'normal' - WHITESPACE = 'whitespace' - BLANK_LINE = 'blank line' - - -class Token(object): - """Token class for intelligent text splitting. - - The token class represents a string of characters and an identifying type. - - Attributes: - type: The type of token. - string: The characters the token comprises. - length: The length of the token. - line: The text of the line the token is found in. - line_number: The number of the line the token is found in. - values: Dictionary of values returned from the tokens regex match. - previous: The token before this one. - next: The token after this one. - start_index: The character index in the line where this token starts. - attached_object: Object containing more information about this token. - metadata: Object containing metadata about this token. Must be added by - a separate metadata pass. - """ - - def __init__(self, string, token_type, line, line_number, values=None, - orig_line_number=None): - """Creates a new Token object. - - Args: - string: The string of input the token contains. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - orig_line_number: The line number of the original file this token comes - from. This should be only set during the tokenization process. For newly - created error fix tokens after that, it should be None. - """ - self.type = token_type - self.string = string - self.length = len(string) - self.line = line - self.line_number = line_number - self.orig_line_number = orig_line_number - self.values = values - self.is_deleted = False - - # These parts can only be computed when the file is fully tokenized - self.previous = None - self.next = None - self.start_index = None - - # This part is set in statetracker.py - # TODO(robbyw): Wrap this in to metadata - self.attached_object = None - - # This part is set in *metadatapass.py - self.metadata = None - - def IsFirstInLine(self): - """Tests if this token is the first token in its line. - - Returns: - Whether the token is the first token in its line. - """ - return not self.previous or self.previous.line_number != self.line_number - - def IsLastInLine(self): - """Tests if this token is the last token in its line. - - Returns: - Whether the token is the last token in its line. - """ - return not self.next or self.next.line_number != self.line_number - - def IsType(self, token_type): - """Tests if this token is of the given type. - - Args: - token_type: The type to test for. - - Returns: - True if the type of this token matches the type passed in. - """ - return self.type == token_type - - def IsAnyType(self, *token_types): - """Tests if this token is any of the given types. - - Args: - token_types: The types to check. Also accepts a single array. - - Returns: - True if the type of this token is any of the types passed in. - """ - if not isinstance(token_types[0], basestring): - return self.type in token_types[0] - else: - return self.type in token_types - - def __repr__(self): - return '' % (self.type, self.string, - self.values, self.line_number, - self.metadata) - - def __iter__(self): - """Returns a token iterator.""" - node = self - while node: - yield node - node = node.next - - def __reversed__(self): - """Returns a reverse-direction token iterator.""" - node = self - while node: - yield node - node = node.previous diff --git a/tools/closure_linter/closure_linter/common/tokens_test.py b/tools/closure_linter/closure_linter/common/tokens_test.py deleted file mode 100644 index 01ec89d01bc357..00000000000000 --- a/tools/closure_linter/closure_linter/common/tokens_test.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -__author__ = 'nnaze@google.com (Nathan Naze)' - -import unittest as googletest -from closure_linter.common import tokens - - -def _CreateDummyToken(): - return tokens.Token('foo', None, 1, 1) - - -def _CreateDummyTokens(count): - dummy_tokens = [] - for _ in xrange(count): - dummy_tokens.append(_CreateDummyToken()) - return dummy_tokens - - -def _SetTokensAsNeighbors(neighbor_tokens): - for i in xrange(len(neighbor_tokens)): - prev_index = i - 1 - next_index = i + 1 - - if prev_index >= 0: - neighbor_tokens[i].previous = neighbor_tokens[prev_index] - - if next_index < len(neighbor_tokens): - neighbor_tokens[i].next = neighbor_tokens[next_index] - - -class TokensTest(googletest.TestCase): - - def testIsFirstInLine(self): - - # First token in file (has no previous). - self.assertTrue(_CreateDummyToken().IsFirstInLine()) - - a, b = _CreateDummyTokens(2) - _SetTokensAsNeighbors([a, b]) - - # Tokens on same line - a.line_number = 30 - b.line_number = 30 - - self.assertFalse(b.IsFirstInLine()) - - # Tokens on different lines - b.line_number = 31 - self.assertTrue(b.IsFirstInLine()) - - def testIsLastInLine(self): - # Last token in file (has no next). - self.assertTrue(_CreateDummyToken().IsLastInLine()) - - a, b = _CreateDummyTokens(2) - _SetTokensAsNeighbors([a, b]) - - # Tokens on same line - a.line_number = 30 - b.line_number = 30 - self.assertFalse(a.IsLastInLine()) - - b.line_number = 31 - self.assertTrue(a.IsLastInLine()) - - def testIsType(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertTrue(a.IsType('fakeType1')) - self.assertFalse(a.IsType('fakeType2')) - - def testIsAnyType(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertTrue(a.IsAnyType(['fakeType1', 'fakeType2'])) - self.assertFalse(a.IsAnyType(['fakeType3', 'fakeType4'])) - - def testRepr(self): - a = tokens.Token('foo', 'fakeType1', 1, 1) - self.assertEquals('', str(a)) - - def testIter(self): - dummy_tokens = _CreateDummyTokens(5) - _SetTokensAsNeighbors(dummy_tokens) - a, b, c, d, e = dummy_tokens - - i = iter(a) - self.assertListEqual([a, b, c, d, e], list(i)) - - def testReverseIter(self): - dummy_tokens = _CreateDummyTokens(5) - _SetTokensAsNeighbors(dummy_tokens) - a, b, c, d, e = dummy_tokens - - ri = reversed(e) - self.assertListEqual([e, d, c, b, a], list(ri)) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/ecmalintrules.py b/tools/closure_linter/closure_linter/ecmalintrules.py deleted file mode 100755 index c07dffc86eeae3..00000000000000 --- a/tools/closure_linter/closure_linter/ecmalintrules.py +++ /dev/null @@ -1,844 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Core methods for checking EcmaScript files for common style guide violations. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'jacobr@google.com (Jacob Richman)') - -import re - -import gflags as flags - -from closure_linter import checkerbase -from closure_linter import ecmametadatapass -from closure_linter import error_check -from closure_linter import errorrules -from closure_linter import errors -from closure_linter import indentation -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - - -FLAGS = flags.FLAGS -flags.DEFINE_list('custom_jsdoc_tags', '', 'Extra jsdoc tags to allow') -# TODO(user): When flipping this to True, remove logic from unit tests -# that overrides this flag. -flags.DEFINE_boolean('dot_on_next_line', False, 'Require dots to be' - 'placed on the next line for wrapped expressions') - -# TODO(robbyw): Check for extra parens on return statements -# TODO(robbyw): Check for 0px in strings -# TODO(robbyw): Ensure inline jsDoc is in {} -# TODO(robbyw): Check for valid JS types in parameter docs - -# Shorthand -Context = ecmametadatapass.EcmaContext -Error = error.Error -Modes = javascripttokenizer.JavaScriptModes -Position = position.Position -Rule = error_check.Rule -Type = javascripttokens.JavaScriptTokenType - - -class EcmaScriptLintRules(checkerbase.LintRulesBase): - """EmcaScript lint style checking rules. - - Can be used to find common style errors in JavaScript, ActionScript and other - Ecma like scripting languages. Style checkers for Ecma scripting languages - should inherit from this style checker. - Please do not add any state to EcmaScriptLintRules or to any subclasses. - - All state should be added to the StateTracker subclass used for a particular - language. - """ - - # It will be initialized in constructor so the flags are initialized. - max_line_length = -1 - - # Static constants. - MISSING_PARAMETER_SPACE = re.compile(r',\S') - - EXTRA_SPACE = re.compile(r'(\(\s|\s\))') - - ENDS_WITH_SPACE = re.compile(r'\s$') - - ILLEGAL_TAB = re.compile(r'\t') - - # Regex used to split up complex types to check for invalid use of ? and |. - TYPE_SPLIT = re.compile(r'[,<>()]') - - # Regex for form of author lines after the @author tag. - AUTHOR_SPEC = re.compile(r'(\s*)[^\s]+@[^(\s]+(\s*)\(.+\)') - - # Acceptable tokens to remove for line too long testing. - LONG_LINE_IGNORE = frozenset( - ['*', '//', '@see'] + - ['@%s' % tag for tag in statetracker.DocFlag.HAS_TYPE]) - - JSDOC_FLAGS_DESCRIPTION_NOT_REQUIRED = frozenset([ - '@fileoverview', '@param', '@return', '@returns']) - - def __init__(self): - """Initialize this lint rule object.""" - checkerbase.LintRulesBase.__init__(self) - if EcmaScriptLintRules.max_line_length == -1: - EcmaScriptLintRules.max_line_length = errorrules.GetMaxLineLength() - - def Initialize(self, checker, limited_doc_checks, is_html): - """Initialize this lint rule object before parsing a new file.""" - checkerbase.LintRulesBase.Initialize(self, checker, limited_doc_checks, - is_html) - self._indentation = indentation.IndentationRules() - - def HandleMissingParameterDoc(self, token, param_name): - """Handle errors associated with a parameter missing a @param tag.""" - raise TypeError('Abstract method HandleMissingParameterDoc not implemented') - - def _CheckLineLength(self, last_token, state): - """Checks whether the line is too long. - - Args: - last_token: The last token in the line. - state: parser_state object that indicates the current state in the page - """ - # Start from the last token so that we have the flag object attached to - # and DOC_FLAG tokens. - line_number = last_token.line_number - token = last_token - - # Build a representation of the string where spaces indicate potential - # line-break locations. - line = [] - while token and token.line_number == line_number: - if state.IsTypeToken(token): - line.insert(0, 'x' * len(token.string)) - elif token.type in (Type.IDENTIFIER, Type.OPERATOR): - # Dots are acceptable places to wrap (may be tokenized as identifiers). - line.insert(0, token.string.replace('.', ' ')) - else: - line.insert(0, token.string) - token = token.previous - - line = ''.join(line) - line = line.rstrip('\n\r\f') - try: - length = len(unicode(line, 'utf-8')) - except (LookupError, UnicodeDecodeError): - # Unknown encoding. The line length may be wrong, as was originally the - # case for utf-8 (see bug 1735846). For now just accept the default - # length, but as we find problems we can either add test for other - # possible encodings or return without an error to protect against - # false positives at the cost of more false negatives. - length = len(line) - - if length > EcmaScriptLintRules.max_line_length: - - # If the line matches one of the exceptions, then it's ok. - for long_line_regexp in self.GetLongLineExceptions(): - if long_line_regexp.match(last_token.line): - return - - # If the line consists of only one "word", or multiple words but all - # except one are ignoreable, then it's ok. - parts = set(line.split()) - - # We allow two "words" (type and name) when the line contains @param - max_parts = 1 - if '@param' in parts: - max_parts = 2 - - # Custom tags like @requires may have url like descriptions, so ignore - # the tag, similar to how we handle @see. - custom_tags = set(['@%s' % f for f in FLAGS.custom_jsdoc_tags]) - if (len(parts.difference(self.LONG_LINE_IGNORE | custom_tags)) - > max_parts): - self._HandleError( - errors.LINE_TOO_LONG, - 'Line too long (%d characters).' % len(line), last_token) - - def _CheckJsDocType(self, token, js_type): - """Checks the given type for style errors. - - Args: - token: The DOC_FLAG token for the flag whose type to check. - js_type: The flag's typeannotation.TypeAnnotation instance. - """ - if not js_type: return - - if js_type.type_group and len(js_type.sub_types) == 2: - identifiers = [t.identifier for t in js_type.sub_types] - if 'null' in identifiers: - # Don't warn if the identifier is a template type (e.g. {TYPE|null}. - if not identifiers[0].isupper() and not identifiers[1].isupper(): - self._HandleError( - errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL, - 'Prefer "?Type" to "Type|null": "%s"' % js_type, token) - - # TODO(user): We should report an error for wrong usage of '?' and '|' - # e.g. {?number|string|null} etc. - - for sub_type in js_type.IterTypes(): - self._CheckJsDocType(token, sub_type) - - def _CheckForMissingSpaceBeforeToken(self, token): - """Checks for a missing space at the beginning of a token. - - Reports a MISSING_SPACE error if the token does not begin with a space or - the previous token doesn't end with a space and the previous token is on the - same line as the token. - - Args: - token: The token being checked - """ - # TODO(user): Check if too many spaces? - if (len(token.string) == len(token.string.lstrip()) and - token.previous and token.line_number == token.previous.line_number and - len(token.previous.string) - len(token.previous.string.rstrip()) == 0): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space before "%s"' % token.string, - token, - position=Position.AtBeginning()) - - def _CheckOperator(self, token): - """Checks an operator for spacing and line style. - - Args: - token: The operator token. - """ - last_code = token.metadata.last_code - - if not self._ExpectSpaceBeforeOperator(token): - if (token.previous and token.previous.type == Type.WHITESPACE and - last_code and last_code.type in (Type.NORMAL, Type.IDENTIFIER) and - last_code.line_number == token.line_number): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "%s"' % token.string, - token.previous, position=Position.All(token.previous.string)) - - elif (token.previous and - not token.previous.IsComment() and - not tokenutil.IsDot(token) and - token.previous.type in Type.EXPRESSION_ENDER_TYPES): - self._HandleError(errors.MISSING_SPACE, - 'Missing space before "%s"' % token.string, token, - position=Position.AtBeginning()) - - # Check wrapping of operators. - next_code = tokenutil.GetNextCodeToken(token) - - is_dot = tokenutil.IsDot(token) - wrapped_before = last_code and last_code.line_number != token.line_number - wrapped_after = next_code and next_code.line_number != token.line_number - - if FLAGS.dot_on_next_line and is_dot and wrapped_after: - self._HandleError( - errors.LINE_ENDS_WITH_DOT, - '"." must go on the following line', - token) - if (not is_dot and wrapped_before and - not token.metadata.IsUnaryOperator()): - self._HandleError( - errors.LINE_STARTS_WITH_OPERATOR, - 'Binary operator must go on previous line "%s"' % token.string, - token) - - def _IsLabel(self, token): - # A ':' token is considered part of a label if it occurs in a case - # statement, a plain label, or an object literal, i.e. is not part of a - # ternary. - - return (token.string == ':' and - token.metadata.context.type in (Context.LITERAL_ELEMENT, - Context.CASE_BLOCK, - Context.STATEMENT)) - - def _ExpectSpaceBeforeOperator(self, token): - """Returns whether a space should appear before the given operator token. - - Args: - token: The operator token. - - Returns: - Whether there should be a space before the token. - """ - if token.string == ',' or token.metadata.IsUnaryPostOperator(): - return False - - if tokenutil.IsDot(token): - return False - - # Colons should appear in labels, object literals, the case of a switch - # statement, and ternary operator. Only want a space in the case of the - # ternary operator. - if self._IsLabel(token): - return False - - if token.metadata.IsUnaryOperator() and token.IsFirstInLine(): - return False - - return True - - def CheckToken(self, token, state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration - state: parser_state object that indicates the current state in the page - """ - # Store some convenience variables - first_in_line = token.IsFirstInLine() - last_in_line = token.IsLastInLine() - last_non_space_token = state.GetLastNonSpaceToken() - - token_type = token.type - - # Process the line change. - if not self._is_html and error_check.ShouldCheck(Rule.INDENTATION): - # TODO(robbyw): Support checking indentation in HTML files. - indentation_errors = self._indentation.CheckToken(token, state) - for indentation_error in indentation_errors: - self._HandleError(*indentation_error) - - if last_in_line: - self._CheckLineLength(token, state) - - if token_type == Type.PARAMETERS: - # Find missing spaces in parameter lists. - if self.MISSING_PARAMETER_SPACE.search(token.string): - fix_data = ', '.join([s.strip() for s in token.string.split(',')]) - self._HandleError(errors.MISSING_SPACE, 'Missing space after ","', - token, position=None, fix_data=fix_data.strip()) - - # Find extra spaces at the beginning of parameter lists. Make sure - # we aren't at the beginning of a continuing multi-line list. - if not first_in_line: - space_count = len(token.string) - len(token.string.lstrip()) - if space_count: - self._HandleError(errors.EXTRA_SPACE, 'Extra space after "("', - token, position=Position(0, space_count)) - - elif (token_type == Type.START_BLOCK and - token.metadata.context.type == Context.BLOCK): - self._CheckForMissingSpaceBeforeToken(token) - - elif token_type == Type.END_BLOCK: - last_code = token.metadata.last_code - if state.InFunction() and state.IsFunctionClose(): - if state.InTopLevelFunction(): - # A semicolons should not be included at the end of a function - # declaration. - if not state.InAssignedFunction(): - if not last_in_line and token.next.type == Type.SEMICOLON: - self._HandleError( - errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, - 'Illegal semicolon after function declaration', - token.next, position=Position.All(token.next.string)) - - # A semicolon should be included at the end of a function expression - # that is not immediately called or used by a dot operator. - if (state.InAssignedFunction() and token.next - and token.next.type != Type.SEMICOLON): - next_token = tokenutil.GetNextCodeToken(token) - is_immediately_used = (next_token.type == Type.START_PAREN or - tokenutil.IsDot(next_token)) - if not is_immediately_used: - self._HandleError( - errors.MISSING_SEMICOLON_AFTER_FUNCTION, - 'Missing semicolon after function assigned to a variable', - token, position=Position.AtEnd(token.string)) - - if state.InInterfaceMethod() and last_code.type != Type.START_BLOCK: - self._HandleError(errors.INTERFACE_METHOD_CANNOT_HAVE_CODE, - 'Interface methods cannot contain code', last_code) - - elif (state.IsBlockClose() and - token.next and token.next.type == Type.SEMICOLON): - if (last_code.metadata.context.parent.type != Context.OBJECT_LITERAL - and last_code.metadata.context.type != Context.OBJECT_LITERAL): - self._HandleError( - errors.REDUNDANT_SEMICOLON, - 'No semicolon is required to end a code block', - token.next, position=Position.All(token.next.string)) - - elif token_type == Type.SEMICOLON: - if token.previous and token.previous.type == Type.WHITESPACE: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before ";"', - token.previous, position=Position.All(token.previous.string)) - - if token.next and token.next.line_number == token.line_number: - if token.metadata.context.type != Context.FOR_GROUP_BLOCK: - # TODO(robbyw): Error about no multi-statement lines. - pass - - elif token.next.type not in ( - Type.WHITESPACE, Type.SEMICOLON, Type.END_PAREN): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space after ";" in for statement', - token.next, - position=Position.AtBeginning()) - - last_code = token.metadata.last_code - if last_code and last_code.type == Type.SEMICOLON: - # Allow a single double semi colon in for loops for cases like: - # for (;;) { }. - # NOTE(user): This is not a perfect check, and will not throw an error - # for cases like: for (var i = 0;; i < n; i++) {}, but then your code - # probably won't work either. - for_token = tokenutil.CustomSearch( - last_code, - lambda token: token.type == Type.KEYWORD and token.string == 'for', - end_func=lambda token: token.type == Type.SEMICOLON, - distance=None, - reverse=True) - - if not for_token: - self._HandleError(errors.REDUNDANT_SEMICOLON, 'Redundant semicolon', - token, position=Position.All(token.string)) - - elif token_type == Type.START_PAREN: - # Ensure that opening parentheses have a space before any keyword - # that is not being invoked like a member function. - if (token.previous and token.previous.type == Type.KEYWORD and - (not token.previous.metadata or - not token.previous.metadata.last_code or - not token.previous.metadata.last_code.string or - token.previous.metadata.last_code.string[-1:] != '.')): - self._HandleError(errors.MISSING_SPACE, 'Missing space before "("', - token, position=Position.AtBeginning()) - elif token.previous and token.previous.type == Type.WHITESPACE: - before_space = token.previous.previous - # Ensure that there is no extra space before a function invocation, - # even if the function being invoked happens to be a keyword. - if (before_space and before_space.line_number == token.line_number and - before_space.type == Type.IDENTIFIER or - (before_space.type == Type.KEYWORD and before_space.metadata and - before_space.metadata.last_code and - before_space.metadata.last_code.string and - before_space.metadata.last_code.string[-1:] == '.')): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "("', - token.previous, position=Position.All(token.previous.string)) - - elif token_type == Type.START_BRACKET: - self._HandleStartBracket(token, last_non_space_token) - elif token_type in (Type.END_PAREN, Type.END_BRACKET): - # Ensure there is no space before closing parentheses, except when - # it's in a for statement with an omitted section, or when it's at the - # beginning of a line. - if (token.previous and token.previous.type == Type.WHITESPACE and - not token.previous.IsFirstInLine() and - not (last_non_space_token and last_non_space_token.line_number == - token.line_number and - last_non_space_token.type == Type.SEMICOLON)): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "%s"' % - token.string, token.previous, - position=Position.All(token.previous.string)) - - elif token_type == Type.WHITESPACE: - if self.ILLEGAL_TAB.search(token.string): - if token.IsFirstInLine(): - if token.next: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace before "%s"' % token.next.string, - token, position=Position.All(token.string)) - else: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace', - token, position=Position.All(token.string)) - else: - self._HandleError( - errors.ILLEGAL_TAB, - 'Illegal tab in whitespace after "%s"' % token.previous.string, - token, position=Position.All(token.string)) - - # Check whitespace length if it's not the first token of the line and - # if it's not immediately before a comment. - if last_in_line: - # Check for extra whitespace at the end of a line. - self._HandleError(errors.EXTRA_SPACE, 'Extra space at end of line', - token, position=Position.All(token.string)) - elif not first_in_line and not token.next.IsComment(): - if token.length > 1: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space after "%s"' % - token.previous.string, token, - position=Position(1, len(token.string) - 1)) - - elif token_type == Type.OPERATOR: - self._CheckOperator(token) - elif token_type == Type.DOC_FLAG: - flag = token.attached_object - - if flag.flag_type == 'bug': - # TODO(robbyw): Check for exactly 1 space on the left. - string = token.next.string.lstrip() - string = string.split(' ', 1)[0] - - if not string.isdigit(): - self._HandleError(errors.NO_BUG_NUMBER_AFTER_BUG_TAG, - '@bug should be followed by a bug number', token) - - elif flag.flag_type == 'suppress': - if flag.type is None: - # A syntactically invalid suppress tag will get tokenized as a normal - # flag, indicating an error. - self._HandleError( - errors.INCORRECT_SUPPRESS_SYNTAX, - 'Invalid suppress syntax: should be @suppress {errortype}. ' - 'Spaces matter.', token) - else: - for suppress_type in flag.jstype.IterIdentifiers(): - if suppress_type not in state.GetDocFlag().SUPPRESS_TYPES: - self._HandleError( - errors.INVALID_SUPPRESS_TYPE, - 'Invalid suppression type: %s' % suppress_type, token) - - elif (error_check.ShouldCheck(Rule.WELL_FORMED_AUTHOR) and - flag.flag_type == 'author'): - # TODO(user): In non strict mode check the author tag for as much as - # it exists, though the full form checked below isn't required. - string = token.next.string - result = self.AUTHOR_SPEC.match(string) - if not result: - self._HandleError(errors.INVALID_AUTHOR_TAG_DESCRIPTION, - 'Author tag line should be of the form: ' - '@author foo@somewhere.com (Your Name)', - token.next) - else: - # Check spacing between email address and name. Do this before - # checking earlier spacing so positions are easier to calculate for - # autofixing. - num_spaces = len(result.group(2)) - if num_spaces < 1: - self._HandleError(errors.MISSING_SPACE, - 'Missing space after email address', - token.next, position=Position(result.start(2), 0)) - elif num_spaces > 1: - self._HandleError( - errors.EXTRA_SPACE, 'Extra space after email address', - token.next, - position=Position(result.start(2) + 1, num_spaces - 1)) - - # Check for extra spaces before email address. Can't be too few, if - # not at least one we wouldn't match @author tag. - num_spaces = len(result.group(1)) - if num_spaces > 1: - self._HandleError(errors.EXTRA_SPACE, - 'Extra space before email address', - token.next, position=Position(1, num_spaces - 1)) - - elif (flag.flag_type in state.GetDocFlag().HAS_DESCRIPTION and - not self._limited_doc_checks): - if flag.flag_type == 'param': - if flag.name is None: - self._HandleError(errors.MISSING_JSDOC_PARAM_NAME, - 'Missing name in @param tag', token) - - if not flag.description or flag.description is None: - flag_name = token.type - if 'name' in token.values: - flag_name = '@' + token.values['name'] - - if flag_name not in self.JSDOC_FLAGS_DESCRIPTION_NOT_REQUIRED: - self._HandleError( - errors.MISSING_JSDOC_TAG_DESCRIPTION, - 'Missing description in %s tag' % flag_name, token) - else: - self._CheckForMissingSpaceBeforeToken(flag.description_start_token) - - if flag.HasType(): - if flag.type_start_token is not None: - self._CheckForMissingSpaceBeforeToken( - token.attached_object.type_start_token) - - if flag.jstype and not flag.jstype.IsEmpty(): - self._CheckJsDocType(token, flag.jstype) - - if error_check.ShouldCheck(Rule.BRACES_AROUND_TYPE) and ( - flag.type_start_token.type != Type.DOC_START_BRACE or - flag.type_end_token.type != Type.DOC_END_BRACE): - self._HandleError( - errors.MISSING_BRACES_AROUND_TYPE, - 'Type must always be surrounded by curly braces.', token) - - if token_type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): - if (token.values['name'] not in state.GetDocFlag().LEGAL_DOC and - token.values['name'] not in FLAGS.custom_jsdoc_tags): - self._HandleError( - errors.INVALID_JSDOC_TAG, - 'Invalid JsDoc tag: %s' % token.values['name'], token) - - if (error_check.ShouldCheck(Rule.NO_BRACES_AROUND_INHERIT_DOC) and - token.values['name'] == 'inheritDoc' and - token_type == Type.DOC_INLINE_FLAG): - self._HandleError(errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC, - 'Unnecessary braces around @inheritDoc', - token) - - elif token_type == Type.SIMPLE_LVALUE: - identifier = token.values['identifier'] - - if ((not state.InFunction() or state.InConstructor()) and - state.InTopLevel() and not state.InObjectLiteralDescendant()): - jsdoc = state.GetDocComment() - if not state.HasDocComment(identifier): - # Only test for documentation on identifiers with .s in them to - # avoid checking things like simple variables. We don't require - # documenting assignments to .prototype itself (bug 1880803). - if (not state.InConstructor() and - identifier.find('.') != -1 and not - identifier.endswith('.prototype') and not - self._limited_doc_checks): - comment = state.GetLastComment() - if not (comment and comment.lower().count('jsdoc inherited')): - self._HandleError( - errors.MISSING_MEMBER_DOCUMENTATION, - "No docs found for member '%s'" % identifier, - token) - elif jsdoc and (not state.InConstructor() or - identifier.startswith('this.')): - # We are at the top level and the function/member is documented. - if identifier.endswith('_') and not identifier.endswith('__'): - # Can have a private class which inherits documentation from a - # public superclass. - # - # @inheritDoc is deprecated in favor of using @override, and they - if (jsdoc.HasFlag('override') and not jsdoc.HasFlag('constructor') - and ('accessControls' not in jsdoc.suppressions)): - self._HandleError( - errors.INVALID_OVERRIDE_PRIVATE, - '%s should not override a private member.' % identifier, - jsdoc.GetFlag('override').flag_token) - if (jsdoc.HasFlag('inheritDoc') and not jsdoc.HasFlag('constructor') - and ('accessControls' not in jsdoc.suppressions)): - self._HandleError( - errors.INVALID_INHERIT_DOC_PRIVATE, - '%s should not inherit from a private member.' % identifier, - jsdoc.GetFlag('inheritDoc').flag_token) - if (not jsdoc.HasFlag('private') and - ('underscore' not in jsdoc.suppressions) and not - ((jsdoc.HasFlag('inheritDoc') or jsdoc.HasFlag('override')) and - ('accessControls' in jsdoc.suppressions))): - self._HandleError( - errors.MISSING_PRIVATE, - 'Member "%s" must have @private JsDoc.' % - identifier, token) - if jsdoc.HasFlag('private') and 'underscore' in jsdoc.suppressions: - self._HandleError( - errors.UNNECESSARY_SUPPRESS, - '@suppress {underscore} is not necessary with @private', - jsdoc.suppressions['underscore']) - elif (jsdoc.HasFlag('private') and - not self.InExplicitlyTypedLanguage()): - # It is convention to hide public fields in some ECMA - # implementations from documentation using the @private tag. - self._HandleError( - errors.EXTRA_PRIVATE, - 'Member "%s" must not have @private JsDoc' % - identifier, token) - - # These flags are only legal on localizable message definitions; - # such variables always begin with the prefix MSG_. - for f in ('desc', 'hidden', 'meaning'): - if (jsdoc.HasFlag(f) - and not identifier.startswith('MSG_') - and identifier.find('.MSG_') == -1): - self._HandleError( - errors.INVALID_USE_OF_DESC_TAG, - 'Member "%s" should not have @%s JsDoc' % (identifier, f), - token) - - # Check for illegaly assigning live objects as prototype property values. - index = identifier.find('.prototype.') - # Ignore anything with additional .s after the prototype. - if index != -1 and identifier.find('.', index + 11) == -1: - equal_operator = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - next_code = tokenutil.SearchExcept(equal_operator, Type.NON_CODE_TYPES) - if next_code and ( - next_code.type in (Type.START_BRACKET, Type.START_BLOCK) or - next_code.IsOperator('new')): - self._HandleError( - errors.ILLEGAL_PROTOTYPE_MEMBER_VALUE, - 'Member %s cannot have a non-primitive value' % identifier, - token) - - elif token_type == Type.END_PARAMETERS: - # Find extra space at the end of parameter lists. We check the token - # prior to the current one when it is a closing paren. - if (token.previous and token.previous.type == Type.PARAMETERS - and self.ENDS_WITH_SPACE.search(token.previous.string)): - self._HandleError(errors.EXTRA_SPACE, 'Extra space before ")"', - token.previous) - - jsdoc = state.GetDocComment() - if state.GetFunction().is_interface: - if token.previous and token.previous.type == Type.PARAMETERS: - self._HandleError( - errors.INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS, - 'Interface constructor cannot have parameters', - token.previous) - elif (state.InTopLevel() and jsdoc and not jsdoc.HasFlag('see') - and not jsdoc.InheritsDocumentation() - and not state.InObjectLiteralDescendant() and not - jsdoc.IsInvalidated()): - distance, edit = jsdoc.CompareParameters(state.GetParams()) - if distance: - params_iter = iter(state.GetParams()) - docs_iter = iter(jsdoc.ordered_params) - - for op in edit: - if op == 'I': - # Insertion. - # Parsing doc comments is the same for all languages - # but some languages care about parameters that don't have - # doc comments and some languages don't care. - # Languages that don't allow variables to by typed such as - # JavaScript care but languages such as ActionScript or Java - # that allow variables to be typed don't care. - if not self._limited_doc_checks: - self.HandleMissingParameterDoc(token, params_iter.next()) - - elif op == 'D': - # Deletion - self._HandleError(errors.EXTRA_PARAMETER_DOCUMENTATION, - 'Found docs for non-existing parameter: "%s"' % - docs_iter.next(), token) - elif op == 'S': - # Substitution - if not self._limited_doc_checks: - self._HandleError( - errors.WRONG_PARAMETER_DOCUMENTATION, - 'Parameter mismatch: got "%s", expected "%s"' % - (params_iter.next(), docs_iter.next()), token) - - else: - # Equality - just advance the iterators - params_iter.next() - docs_iter.next() - - elif token_type == Type.STRING_TEXT: - # If this is the first token after the start of the string, but it's at - # the end of a line, we know we have a multi-line string. - if token.previous.type in ( - Type.SINGLE_QUOTE_STRING_START, - Type.DOUBLE_QUOTE_STRING_START) and last_in_line: - self._HandleError(errors.MULTI_LINE_STRING, - 'Multi-line strings are not allowed', token) - - # This check is orthogonal to the ones above, and repeats some types, so - # it is a plain if and not an elif. - if token.type in Type.COMMENT_TYPES: - if self.ILLEGAL_TAB.search(token.string): - self._HandleError(errors.ILLEGAL_TAB, - 'Illegal tab in comment "%s"' % token.string, token) - - trimmed = token.string.rstrip() - if last_in_line and token.string != trimmed: - # Check for extra whitespace at the end of a line. - self._HandleError( - errors.EXTRA_SPACE, 'Extra space at end of line', token, - position=Position(len(trimmed), len(token.string) - len(trimmed))) - - # This check is also orthogonal since it is based on metadata. - if token.metadata.is_implied_semicolon: - self._HandleError(errors.MISSING_SEMICOLON, - 'Missing semicolon at end of line', token) - - def _HandleStartBracket(self, token, last_non_space_token): - """Handles a token that is an open bracket. - - Args: - token: The token to handle. - last_non_space_token: The last token that was not a space. - """ - if (not token.IsFirstInLine() and token.previous.type == Type.WHITESPACE and - last_non_space_token and - last_non_space_token.type in Type.EXPRESSION_ENDER_TYPES): - self._HandleError( - errors.EXTRA_SPACE, 'Extra space before "["', - token.previous, position=Position.All(token.previous.string)) - # If the [ token is the first token in a line we shouldn't complain - # about a missing space before [. This is because some Ecma script - # languages allow syntax like: - # [Annotation] - # class MyClass {...} - # So we don't want to blindly warn about missing spaces before [. - # In the the future, when rules for computing exactly how many spaces - # lines should be indented are added, then we can return errors for - # [ tokens that are improperly indented. - # For example: - # var someVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongVariableName = - # [a,b,c]; - # should trigger a proper indentation warning message as [ is not indented - # by four spaces. - elif (not token.IsFirstInLine() and token.previous and - token.previous.type not in ( - [Type.WHITESPACE, Type.START_PAREN, Type.START_BRACKET] + - Type.EXPRESSION_ENDER_TYPES)): - self._HandleError(errors.MISSING_SPACE, 'Missing space before "["', - token, position=Position.AtBeginning()) - - def Finalize(self, state): - """Perform all checks that need to occur after all lines are processed. - - Args: - state: State of the parser after parsing all tokens - - Raises: - TypeError: If not overridden. - """ - last_non_space_token = state.GetLastNonSpaceToken() - # Check last line for ending with newline. - if state.GetLastLine() and not ( - state.GetLastLine().isspace() or - state.GetLastLine().rstrip('\n\r\f') != state.GetLastLine()): - self._HandleError( - errors.FILE_MISSING_NEWLINE, - 'File does not end with new line. (%s)' % state.GetLastLine(), - last_non_space_token) - - try: - self._indentation.Finalize() - except Exception, e: - self._HandleError( - errors.FILE_DOES_NOT_PARSE, - str(e), - last_non_space_token) - - def GetLongLineExceptions(self): - """Gets a list of regexps for lines which can be longer than the limit. - - Returns: - A list of regexps, used as matches (rather than searches). - """ - return [] - - def InExplicitlyTypedLanguage(self): - """Returns whether this ecma implementation is explicitly typed.""" - return False diff --git a/tools/closure_linter/closure_linter/ecmametadatapass.py b/tools/closure_linter/closure_linter/ecmametadatapass.py deleted file mode 100755 index 50621610efe08d..00000000000000 --- a/tools/closure_linter/closure_linter/ecmametadatapass.py +++ /dev/null @@ -1,574 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Metadata pass for annotating tokens in EcmaScript files.""" - -__author__ = ('robbyw@google.com (Robert Walker)') - -from closure_linter import javascripttokens -from closure_linter import tokenutil - - -TokenType = javascripttokens.JavaScriptTokenType - - -class ParseError(Exception): - """Exception indicating a parse error at the given token. - - Attributes: - token: The token where the parse error occurred. - """ - - def __init__(self, token, message=None): - """Initialize a parse error at the given token with an optional message. - - Args: - token: The token where the parse error occurred. - message: A message describing the parse error. - """ - Exception.__init__(self, message) - self.token = token - - -class EcmaContext(object): - """Context object for EcmaScript languages. - - Attributes: - type: The context type. - start_token: The token where this context starts. - end_token: The token where this context ends. - parent: The parent context. - """ - - # The root context. - ROOT = 'root' - - # A block of code. - BLOCK = 'block' - - # A pseudo-block of code for a given case or default section. - CASE_BLOCK = 'case_block' - - # Block of statements in a for loop's parentheses. - FOR_GROUP_BLOCK = 'for_block' - - # An implied block of code for 1 line if, while, and for statements - IMPLIED_BLOCK = 'implied_block' - - # An index in to an array or object. - INDEX = 'index' - - # An array literal in []. - ARRAY_LITERAL = 'array_literal' - - # An object literal in {}. - OBJECT_LITERAL = 'object_literal' - - # An individual element in an array or object literal. - LITERAL_ELEMENT = 'literal_element' - - # The portion of a ternary statement between ? and : - TERNARY_TRUE = 'ternary_true' - - # The portion of a ternary statment after : - TERNARY_FALSE = 'ternary_false' - - # The entire switch statment. This will contain a GROUP with the variable - # and a BLOCK with the code. - - # Since that BLOCK is not a normal block, it can not contain statements except - # for case and default. - SWITCH = 'switch' - - # A normal comment. - COMMENT = 'comment' - - # A JsDoc comment. - DOC = 'doc' - - # An individual statement. - STATEMENT = 'statement' - - # Code within parentheses. - GROUP = 'group' - - # Parameter names in a function declaration. - PARAMETERS = 'parameters' - - # A set of variable declarations appearing after the 'var' keyword. - VAR = 'var' - - # Context types that are blocks. - BLOCK_TYPES = frozenset([ - ROOT, BLOCK, CASE_BLOCK, FOR_GROUP_BLOCK, IMPLIED_BLOCK]) - - def __init__(self, context_type, start_token, parent=None): - """Initializes the context object. - - Args: - context_type: The context type. - start_token: The token where this context starts. - parent: The parent context. - - Attributes: - type: The context type. - start_token: The token where this context starts. - end_token: The token where this context ends. - parent: The parent context. - children: The child contexts of this context, in order. - """ - self.type = context_type - self.start_token = start_token - self.end_token = None - - self.parent = None - self.children = [] - - if parent: - parent.AddChild(self) - - def __repr__(self): - """Returns a string representation of the context object.""" - stack = [] - context = self - while context: - stack.append(context.type) - context = context.parent - return 'Context(%s)' % ' > '.join(stack) - - def AddChild(self, child): - """Adds a child to this context and sets child's parent to this context. - - Args: - child: A child EcmaContext. The child's parent will be set to this - context. - """ - - child.parent = self - - self.children.append(child) - self.children.sort(EcmaContext._CompareContexts) - - def GetRoot(self): - """Get the root context that contains this context, if any.""" - context = self - while context: - if context.type is EcmaContext.ROOT: - return context - context = context.parent - - @staticmethod - def _CompareContexts(context1, context2): - """Sorts contexts 1 and 2 by start token document position.""" - return tokenutil.Compare(context1.start_token, context2.start_token) - - -class EcmaMetaData(object): - """Token metadata for EcmaScript languages. - - Attributes: - last_code: The last code token to appear before this one. - context: The context this token appears in. - operator_type: The operator type, will be one of the *_OPERATOR constants - defined below. - aliased_symbol: The full symbol being identified, as a string (e.g. an - 'XhrIo' alias for 'goog.net.XhrIo'). Only applicable to identifier - tokens. This is set in aliaspass.py and is a best guess. - is_alias_definition: True if the symbol is part of an alias definition. - If so, these symbols won't be counted towards goog.requires/provides. - """ - - UNARY_OPERATOR = 'unary' - - UNARY_POST_OPERATOR = 'unary_post' - - BINARY_OPERATOR = 'binary' - - TERNARY_OPERATOR = 'ternary' - - def __init__(self): - """Initializes a token metadata object.""" - self.last_code = None - self.context = None - self.operator_type = None - self.is_implied_semicolon = False - self.is_implied_block = False - self.is_implied_block_close = False - self.aliased_symbol = None - self.is_alias_definition = False - - def __repr__(self): - """Returns a string representation of the context object.""" - parts = ['%r' % self.context] - if self.operator_type: - parts.append('optype: %r' % self.operator_type) - if self.is_implied_semicolon: - parts.append('implied;') - if self.aliased_symbol: - parts.append('alias for: %s' % self.aliased_symbol) - return 'MetaData(%s)' % ', '.join(parts) - - def IsUnaryOperator(self): - return self.operator_type in (EcmaMetaData.UNARY_OPERATOR, - EcmaMetaData.UNARY_POST_OPERATOR) - - def IsUnaryPostOperator(self): - return self.operator_type == EcmaMetaData.UNARY_POST_OPERATOR - - -class EcmaMetaDataPass(object): - """A pass that iterates over all tokens and builds metadata about them.""" - - def __init__(self): - """Initialize the meta data pass object.""" - self.Reset() - - def Reset(self): - """Resets the metadata pass to prepare for the next file.""" - self._token = None - self._context = None - self._AddContext(EcmaContext.ROOT) - self._last_code = None - - def _CreateContext(self, context_type): - """Overridable by subclasses to create the appropriate context type.""" - return EcmaContext(context_type, self._token, self._context) - - def _CreateMetaData(self): - """Overridable by subclasses to create the appropriate metadata type.""" - return EcmaMetaData() - - def _AddContext(self, context_type): - """Adds a context of the given type to the context stack. - - Args: - context_type: The type of context to create - """ - self._context = self._CreateContext(context_type) - - def _PopContext(self): - """Moves up one level in the context stack. - - Returns: - The former context. - - Raises: - ParseError: If the root context is popped. - """ - top_context = self._context - top_context.end_token = self._token - self._context = top_context.parent - if self._context: - return top_context - else: - raise ParseError(self._token) - - def _PopContextType(self, *stop_types): - """Pops the context stack until a context of the given type is popped. - - Args: - *stop_types: The types of context to pop to - stops at the first match. - - Returns: - The context object of the given type that was popped. - """ - last = None - while not last or last.type not in stop_types: - last = self._PopContext() - return last - - def _EndStatement(self): - """Process the end of a statement.""" - self._PopContextType(EcmaContext.STATEMENT) - if self._context.type == EcmaContext.IMPLIED_BLOCK: - self._token.metadata.is_implied_block_close = True - self._PopContext() - - def _ProcessContext(self): - """Process the context at the current token. - - Returns: - The context that should be assigned to the current token, or None if - the current context after this method should be used. - - Raises: - ParseError: When the token appears in an invalid context. - """ - token = self._token - token_type = token.type - - if self._context.type in EcmaContext.BLOCK_TYPES: - # Whenever we're in a block, we add a statement context. We make an - # exception for switch statements since they can only contain case: and - # default: and therefore don't directly contain statements. - # The block we add here may be immediately removed in some cases, but - # that causes no harm. - parent = self._context.parent - if not parent or parent.type != EcmaContext.SWITCH: - self._AddContext(EcmaContext.STATEMENT) - - elif self._context.type == EcmaContext.ARRAY_LITERAL: - self._AddContext(EcmaContext.LITERAL_ELEMENT) - - if token_type == TokenType.START_PAREN: - if self._last_code and self._last_code.IsKeyword('for'): - # for loops contain multiple statements in the group unlike while, - # switch, if, etc. - self._AddContext(EcmaContext.FOR_GROUP_BLOCK) - else: - self._AddContext(EcmaContext.GROUP) - - elif token_type == TokenType.END_PAREN: - result = self._PopContextType(EcmaContext.GROUP, - EcmaContext.FOR_GROUP_BLOCK) - keyword_token = result.start_token.metadata.last_code - # keyword_token will not exist if the open paren is the first line of the - # file, for example if all code is wrapped in an immediately executed - # annonymous function. - if keyword_token and keyword_token.string in ('if', 'for', 'while'): - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - if next_code.type != TokenType.START_BLOCK: - # Check for do-while. - is_do_while = False - pre_keyword_token = keyword_token.metadata.last_code - if (pre_keyword_token and - pre_keyword_token.type == TokenType.END_BLOCK): - start_block_token = pre_keyword_token.metadata.context.start_token - is_do_while = start_block_token.metadata.last_code.string == 'do' - - # If it's not do-while, it's an implied block. - if not is_do_while: - self._AddContext(EcmaContext.IMPLIED_BLOCK) - token.metadata.is_implied_block = True - - return result - - # else (not else if) with no open brace after it should be considered the - # start of an implied block, similar to the case with if, for, and while - # above. - elif (token_type == TokenType.KEYWORD and - token.string == 'else'): - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - if (next_code.type != TokenType.START_BLOCK and - (next_code.type != TokenType.KEYWORD or next_code.string != 'if')): - self._AddContext(EcmaContext.IMPLIED_BLOCK) - token.metadata.is_implied_block = True - - elif token_type == TokenType.START_PARAMETERS: - self._AddContext(EcmaContext.PARAMETERS) - - elif token_type == TokenType.END_PARAMETERS: - return self._PopContextType(EcmaContext.PARAMETERS) - - elif token_type == TokenType.START_BRACKET: - if (self._last_code and - self._last_code.type in TokenType.EXPRESSION_ENDER_TYPES): - self._AddContext(EcmaContext.INDEX) - else: - self._AddContext(EcmaContext.ARRAY_LITERAL) - - elif token_type == TokenType.END_BRACKET: - return self._PopContextType(EcmaContext.INDEX, EcmaContext.ARRAY_LITERAL) - - elif token_type == TokenType.START_BLOCK: - if (self._last_code.type in (TokenType.END_PAREN, - TokenType.END_PARAMETERS) or - self._last_code.IsKeyword('else') or - self._last_code.IsKeyword('do') or - self._last_code.IsKeyword('try') or - self._last_code.IsKeyword('finally') or - (self._last_code.IsOperator(':') and - self._last_code.metadata.context.type == EcmaContext.CASE_BLOCK)): - # else, do, try, and finally all might have no () before {. - # Also, handle the bizzare syntax case 10: {...}. - self._AddContext(EcmaContext.BLOCK) - else: - self._AddContext(EcmaContext.OBJECT_LITERAL) - - elif token_type == TokenType.END_BLOCK: - context = self._PopContextType(EcmaContext.BLOCK, - EcmaContext.OBJECT_LITERAL) - if self._context.type == EcmaContext.SWITCH: - # The end of the block also means the end of the switch statement it - # applies to. - return self._PopContext() - return context - - elif token.IsKeyword('switch'): - self._AddContext(EcmaContext.SWITCH) - - elif (token_type == TokenType.KEYWORD and - token.string in ('case', 'default') and - self._context.type != EcmaContext.OBJECT_LITERAL): - # Pop up to but not including the switch block. - while self._context.parent.type != EcmaContext.SWITCH: - self._PopContext() - if self._context.parent is None: - raise ParseError(token, 'Encountered case/default statement ' - 'without switch statement') - - elif token.IsOperator('?'): - self._AddContext(EcmaContext.TERNARY_TRUE) - - elif token.IsOperator(':'): - if self._context.type == EcmaContext.OBJECT_LITERAL: - self._AddContext(EcmaContext.LITERAL_ELEMENT) - - elif self._context.type == EcmaContext.TERNARY_TRUE: - self._PopContext() - self._AddContext(EcmaContext.TERNARY_FALSE) - - # Handle nested ternary statements like: - # foo = bar ? baz ? 1 : 2 : 3 - # When we encounter the second ":" the context is - # ternary_false > ternary_true > statement > root - elif (self._context.type == EcmaContext.TERNARY_FALSE and - self._context.parent.type == EcmaContext.TERNARY_TRUE): - self._PopContext() # Leave current ternary false context. - self._PopContext() # Leave current parent ternary true - self._AddContext(EcmaContext.TERNARY_FALSE) - - elif self._context.parent.type == EcmaContext.SWITCH: - self._AddContext(EcmaContext.CASE_BLOCK) - - elif token.IsKeyword('var'): - self._AddContext(EcmaContext.VAR) - - elif token.IsOperator(','): - while self._context.type not in (EcmaContext.VAR, - EcmaContext.ARRAY_LITERAL, - EcmaContext.OBJECT_LITERAL, - EcmaContext.STATEMENT, - EcmaContext.PARAMETERS, - EcmaContext.GROUP): - self._PopContext() - - elif token_type == TokenType.SEMICOLON: - self._EndStatement() - - def Process(self, first_token): - """Processes the token stream starting with the given token.""" - self._token = first_token - while self._token: - self._ProcessToken() - - if self._token.IsCode(): - self._last_code = self._token - - self._token = self._token.next - - try: - self._PopContextType(self, EcmaContext.ROOT) - except ParseError: - # Ignore the "popped to root" error. - pass - - def _ProcessToken(self): - """Process the given token.""" - token = self._token - token.metadata = self._CreateMetaData() - context = (self._ProcessContext() or self._context) - token.metadata.context = context - token.metadata.last_code = self._last_code - - # Determine the operator type of the token, if applicable. - if token.type == TokenType.OPERATOR: - token.metadata.operator_type = self._GetOperatorType(token) - - # Determine if there is an implied semicolon after the token. - if token.type != TokenType.SEMICOLON: - next_code = tokenutil.SearchExcept(token, TokenType.NON_CODE_TYPES) - # A statement like if (x) does not need a semicolon after it - is_implied_block = self._context == EcmaContext.IMPLIED_BLOCK - is_last_code_in_line = token.IsCode() and ( - not next_code or next_code.line_number != token.line_number) - is_continued_operator = (token.type == TokenType.OPERATOR and - not token.metadata.IsUnaryPostOperator()) - is_continued_dot = token.string == '.' - next_code_is_operator = next_code and next_code.type == TokenType.OPERATOR - is_end_of_block = ( - token.type == TokenType.END_BLOCK and - token.metadata.context.type != EcmaContext.OBJECT_LITERAL) - is_multiline_string = token.type == TokenType.STRING_TEXT - is_continued_var_decl = (token.IsKeyword('var') and - next_code and - (next_code.type in [TokenType.IDENTIFIER, - TokenType.SIMPLE_LVALUE]) and - token.line_number < next_code.line_number) - next_code_is_block = next_code and next_code.type == TokenType.START_BLOCK - if (is_last_code_in_line and - self._StatementCouldEndInContext() and - not is_multiline_string and - not is_end_of_block and - not is_continued_var_decl and - not is_continued_operator and - not is_continued_dot and - not next_code_is_operator and - not is_implied_block and - not next_code_is_block): - token.metadata.is_implied_semicolon = True - self._EndStatement() - - def _StatementCouldEndInContext(self): - """Returns if the current statement (if any) may end in this context.""" - # In the basic statement or variable declaration context, statement can - # always end in this context. - if self._context.type in (EcmaContext.STATEMENT, EcmaContext.VAR): - return True - - # End of a ternary false branch inside a statement can also be the - # end of the statement, for example: - # var x = foo ? foo.bar() : null - # In this case the statement ends after the null, when the context stack - # looks like ternary_false > var > statement > root. - if (self._context.type == EcmaContext.TERNARY_FALSE and - self._context.parent.type in (EcmaContext.STATEMENT, EcmaContext.VAR)): - return True - - # In all other contexts like object and array literals, ternary true, etc. - # the statement can't yet end. - return False - - def _GetOperatorType(self, token): - """Returns the operator type of the given operator token. - - Args: - token: The token to get arity for. - - Returns: - The type of the operator. One of the *_OPERATOR constants defined in - EcmaMetaData. - """ - if token.string == '?': - return EcmaMetaData.TERNARY_OPERATOR - - if token.string in TokenType.UNARY_OPERATORS: - return EcmaMetaData.UNARY_OPERATOR - - last_code = token.metadata.last_code - if not last_code or last_code.type == TokenType.END_BLOCK: - return EcmaMetaData.UNARY_OPERATOR - - if (token.string in TokenType.UNARY_POST_OPERATORS and - last_code.type in TokenType.EXPRESSION_ENDER_TYPES): - return EcmaMetaData.UNARY_POST_OPERATOR - - if (token.string in TokenType.UNARY_OK_OPERATORS and - last_code.type not in TokenType.EXPRESSION_ENDER_TYPES and - last_code.string not in TokenType.UNARY_POST_OPERATORS): - return EcmaMetaData.UNARY_OPERATOR - - return EcmaMetaData.BINARY_OPERATOR diff --git a/tools/closure_linter/closure_linter/error_check.py b/tools/closure_linter/closure_linter/error_check.py deleted file mode 100755 index 8d657fe9174fff..00000000000000 --- a/tools/closure_linter/closure_linter/error_check.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -"""Specific JSLint errors checker.""" - - - -import gflags as flags - -FLAGS = flags.FLAGS - - -class Rule(object): - """Different rules to check.""" - - # Documentations for specific rules goes in flag definition. - BLANK_LINES_AT_TOP_LEVEL = 'blank_lines_at_top_level' - INDENTATION = 'indentation' - WELL_FORMED_AUTHOR = 'well_formed_author' - NO_BRACES_AROUND_INHERIT_DOC = 'no_braces_around_inherit_doc' - BRACES_AROUND_TYPE = 'braces_around_type' - OPTIONAL_TYPE_MARKER = 'optional_type_marker' - VARIABLE_ARG_MARKER = 'variable_arg_marker' - UNUSED_PRIVATE_MEMBERS = 'unused_private_members' - UNUSED_LOCAL_VARIABLES = 'unused_local_variables' - - # Rule to raise all known errors. - ALL = 'all' - - # All rules that are to be checked when using the strict flag. E.g. the rules - # that are specific to the stricter Closure style. - CLOSURE_RULES = frozenset([BLANK_LINES_AT_TOP_LEVEL, - INDENTATION, - WELL_FORMED_AUTHOR, - NO_BRACES_AROUND_INHERIT_DOC, - BRACES_AROUND_TYPE, - OPTIONAL_TYPE_MARKER, - VARIABLE_ARG_MARKER]) - - -flags.DEFINE_boolean('strict', False, - 'Whether to validate against the stricter Closure style. ' - 'This includes ' + (', '.join(Rule.CLOSURE_RULES)) + '.') -flags.DEFINE_multistring('jslint_error', [], - 'List of specific lint errors to check. Here is a list' - ' of accepted values:\n' - ' - ' + Rule.ALL + ': enables all following errors.\n' - ' - ' + Rule.BLANK_LINES_AT_TOP_LEVEL + ': validates' - 'number of blank lines between blocks at top level.\n' - ' - ' + Rule.INDENTATION + ': checks correct ' - 'indentation of code.\n' - ' - ' + Rule.WELL_FORMED_AUTHOR + ': validates the ' - '@author JsDoc tags.\n' - ' - ' + Rule.NO_BRACES_AROUND_INHERIT_DOC + ': ' - 'forbids braces around @inheritdoc JsDoc tags.\n' - ' - ' + Rule.BRACES_AROUND_TYPE + ': enforces braces ' - 'around types in JsDoc tags.\n' - ' - ' + Rule.OPTIONAL_TYPE_MARKER + ': checks correct ' - 'use of optional marker = in param types.\n' - ' - ' + Rule.UNUSED_PRIVATE_MEMBERS + ': checks for ' - 'unused private variables.\n' - ' - ' + Rule.UNUSED_LOCAL_VARIABLES + ': checks for ' - 'unused local variables.\n') - - -def ShouldCheck(rule): - """Returns whether the optional rule should be checked. - - Computes different flags (strict, jslint_error, jslint_noerror) to find out if - this specific rule should be checked. - - Args: - rule: Name of the rule (see Rule). - - Returns: - True if the rule should be checked according to the flags, otherwise False. - """ - if rule in FLAGS.jslint_error or Rule.ALL in FLAGS.jslint_error: - return True - # Checks strict rules. - return FLAGS.strict and rule in Rule.CLOSURE_RULES diff --git a/tools/closure_linter/closure_linter/error_fixer.py b/tools/closure_linter/closure_linter/error_fixer.py deleted file mode 100755 index 88f9c720ab3517..00000000000000 --- a/tools/closure_linter/closure_linter/error_fixer.py +++ /dev/null @@ -1,618 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Main class responsible for automatically fixing simple style violations.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = 'robbyw@google.com (Robert Walker)' - -import re - -import gflags as flags -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import tokenutil -from closure_linter.common import errorhandler - -# Shorthand -Token = javascripttokens.JavaScriptToken -Type = javascripttokens.JavaScriptTokenType - -END_OF_FLAG_TYPE = re.compile(r'(}?\s*)$') - -# Regex to represent common mistake inverting author name and email as -# @author User Name (user@company) -INVERTED_AUTHOR_SPEC = re.compile(r'(?P\s*)' - r'(?P[^(]+)' - r'(?P\s+)' - r'\(' - r'(?P[^\s]+@[^)\s]+)' - r'\)' - r'(?P.*)') - -FLAGS = flags.FLAGS -flags.DEFINE_boolean('disable_indentation_fixing', False, - 'Whether to disable automatic fixing of indentation.') -flags.DEFINE_list('fix_error_codes', [], 'A list of specific error codes to ' - 'fix. Defaults to all supported error codes when empty. ' - 'See errors.py for a list of error codes.') - - -class ErrorFixer(errorhandler.ErrorHandler): - """Object that fixes simple style errors.""" - - def __init__(self, external_file=None): - """Initialize the error fixer. - - Args: - external_file: If included, all output will be directed to this file - instead of overwriting the files the errors are found in. - """ - errorhandler.ErrorHandler.__init__(self) - - self._file_name = None - self._file_token = None - self._external_file = external_file - - try: - self._fix_error_codes = set([errors.ByName(error.upper()) for error in - FLAGS.fix_error_codes]) - except KeyError as ke: - raise ValueError('Unknown error code ' + ke.args[0]) - - def HandleFile(self, filename, first_token): - """Notifies this ErrorPrinter that subsequent errors are in filename. - - Args: - filename: The name of the file about to be checked. - first_token: The first token in the file. - """ - self._file_name = filename - self._file_is_html = filename.endswith('.html') or filename.endswith('.htm') - self._file_token = first_token - self._file_fix_count = 0 - self._file_changed_lines = set() - - def _AddFix(self, tokens): - """Adds the fix to the internal count. - - Args: - tokens: The token or sequence of tokens changed to fix an error. - """ - self._file_fix_count += 1 - if hasattr(tokens, 'line_number'): - self._file_changed_lines.add(tokens.line_number) - else: - for token in tokens: - self._file_changed_lines.add(token.line_number) - - def _FixJsDocPipeNull(self, js_type): - """Change number|null or null|number to ?number. - - Args: - js_type: The typeannotation.TypeAnnotation instance to fix. - """ - - # Recurse into all sub_types if the error was at a deeper level. - map(self._FixJsDocPipeNull, js_type.IterTypes()) - - if js_type.type_group and len(js_type.sub_types) == 2: - # Find and remove the null sub_type: - sub_type = None - for sub_type in js_type.sub_types: - if sub_type.identifier == 'null': - map(tokenutil.DeleteToken, sub_type.tokens) - self._AddFix(sub_type.tokens) - break - else: - return - - first_token = js_type.FirstToken() - question_mark = Token('?', Type.DOC_TYPE_MODIFIER, first_token.line, - first_token.line_number) - tokenutil.InsertTokenBefore(question_mark, first_token) - js_type.tokens.insert(0, question_mark) - js_type.tokens.remove(sub_type) - js_type.or_null = True - - # Now also remove the separator, which is in the parent's token list, - # either before or after the sub_type, there is exactly one. Scan for it. - for token in js_type.tokens: - if (token and isinstance(token, Token) and - token.type == Type.DOC_TYPE_MODIFIER and token.string == '|'): - tokenutil.DeleteToken(token) - self._AddFix(token) - break - - def HandleError(self, error): - """Attempts to fix the error. - - Args: - error: The error object - """ - code = error.code - token = error.token - - if self._fix_error_codes and code not in self._fix_error_codes: - return - - if code == errors.JSDOC_PREFER_QUESTION_TO_PIPE_NULL: - self._FixJsDocPipeNull(token.attached_object.jstype) - - elif code == errors.JSDOC_MISSING_OPTIONAL_TYPE: - iterator = token.attached_object.type_end_token - if iterator.type == Type.DOC_END_BRACE or iterator.string.isspace(): - iterator = iterator.previous - - ending_space = len(iterator.string) - len(iterator.string.rstrip()) - iterator.string = '%s=%s' % (iterator.string.rstrip(), - ' ' * ending_space) - - # Create a new flag object with updated type info. - token.attached_object = javascriptstatetracker.JsDocFlag(token) - self._AddFix(token) - - elif code == errors.JSDOC_MISSING_VAR_ARGS_TYPE: - iterator = token.attached_object.type_start_token - if iterator.type == Type.DOC_START_BRACE or iterator.string.isspace(): - iterator = iterator.next - - starting_space = len(iterator.string) - len(iterator.string.lstrip()) - iterator.string = '%s...%s' % (' ' * starting_space, - iterator.string.lstrip()) - - # Create a new flag object with updated type info. - token.attached_object = javascriptstatetracker.JsDocFlag(token) - self._AddFix(token) - - elif code in (errors.MISSING_SEMICOLON_AFTER_FUNCTION, - errors.MISSING_SEMICOLON): - semicolon_token = Token(';', Type.SEMICOLON, token.line, - token.line_number) - tokenutil.InsertTokenAfter(semicolon_token, token) - token.metadata.is_implied_semicolon = False - semicolon_token.metadata.is_implied_semicolon = False - self._AddFix(token) - - elif code in (errors.ILLEGAL_SEMICOLON_AFTER_FUNCTION, - errors.REDUNDANT_SEMICOLON, - errors.COMMA_AT_END_OF_LITERAL): - self._DeleteToken(token) - self._AddFix(token) - - elif code == errors.INVALID_JSDOC_TAG: - if token.string == '@returns': - token.string = '@return' - self._AddFix(token) - - elif code == errors.FILE_MISSING_NEWLINE: - # This error is fixed implicitly by the way we restore the file - self._AddFix(token) - - elif code == errors.MISSING_SPACE: - if error.fix_data: - token.string = error.fix_data - self._AddFix(token) - elif error.position: - if error.position.IsAtBeginning(): - tokenutil.InsertSpaceTokenAfter(token.previous) - elif error.position.IsAtEnd(token.string): - tokenutil.InsertSpaceTokenAfter(token) - else: - token.string = error.position.Set(token.string, ' ') - self._AddFix(token) - - elif code == errors.EXTRA_SPACE: - if error.position: - token.string = error.position.Set(token.string, '') - self._AddFix(token) - - elif code == errors.MISSING_LINE: - if error.position.IsAtBeginning(): - tokenutil.InsertBlankLineAfter(token.previous) - else: - tokenutil.InsertBlankLineAfter(token) - self._AddFix(token) - - elif code == errors.EXTRA_LINE: - self._DeleteToken(token) - self._AddFix(token) - - elif code == errors.WRONG_BLANK_LINE_COUNT: - if not token.previous: - # TODO(user): Add an insertBefore method to tokenutil. - return - - num_lines = error.fix_data - should_delete = False - - if num_lines < 0: - num_lines *= -1 - should_delete = True - - for unused_i in xrange(1, num_lines + 1): - if should_delete: - # TODO(user): DeleteToken should update line numbers. - self._DeleteToken(token.previous) - else: - tokenutil.InsertBlankLineAfter(token.previous) - self._AddFix(token) - - elif code == errors.UNNECESSARY_DOUBLE_QUOTED_STRING: - end_quote = tokenutil.Search(token, Type.DOUBLE_QUOTE_STRING_END) - if end_quote: - single_quote_start = Token( - "'", Type.SINGLE_QUOTE_STRING_START, token.line, token.line_number) - single_quote_end = Token( - "'", Type.SINGLE_QUOTE_STRING_START, end_quote.line, - token.line_number) - - tokenutil.InsertTokenAfter(single_quote_start, token) - tokenutil.InsertTokenAfter(single_quote_end, end_quote) - self._DeleteToken(token) - self._DeleteToken(end_quote) - self._AddFix([token, end_quote]) - - elif code == errors.MISSING_BRACES_AROUND_TYPE: - fixed_tokens = [] - start_token = token.attached_object.type_start_token - - if start_token.type != Type.DOC_START_BRACE: - leading_space = ( - len(start_token.string) - len(start_token.string.lstrip())) - if leading_space: - start_token = tokenutil.SplitToken(start_token, leading_space) - # Fix case where start and end token were the same. - if token.attached_object.type_end_token == start_token.previous: - token.attached_object.type_end_token = start_token - - new_token = Token('{', Type.DOC_START_BRACE, start_token.line, - start_token.line_number) - tokenutil.InsertTokenAfter(new_token, start_token.previous) - token.attached_object.type_start_token = new_token - fixed_tokens.append(new_token) - - end_token = token.attached_object.type_end_token - if end_token.type != Type.DOC_END_BRACE: - # If the start token was a brace, the end token will be a - # FLAG_ENDING_TYPE token, if there wasn't a starting brace then - # the end token is the last token of the actual type. - last_type = end_token - if not fixed_tokens: - last_type = end_token.previous - - while last_type.string.isspace(): - last_type = last_type.previous - - # If there was no starting brace then a lone end brace wouldn't have - # been type end token. Now that we've added any missing start brace, - # see if the last effective type token was an end brace. - if last_type.type != Type.DOC_END_BRACE: - trailing_space = (len(last_type.string) - - len(last_type.string.rstrip())) - if trailing_space: - tokenutil.SplitToken(last_type, - len(last_type.string) - trailing_space) - - new_token = Token('}', Type.DOC_END_BRACE, last_type.line, - last_type.line_number) - tokenutil.InsertTokenAfter(new_token, last_type) - token.attached_object.type_end_token = new_token - fixed_tokens.append(new_token) - - self._AddFix(fixed_tokens) - - elif code == errors.LINE_STARTS_WITH_OPERATOR: - # Remove whitespace following the operator so the line starts clean. - self._StripSpace(token, before=False) - - # Remove the operator. - tokenutil.DeleteToken(token) - self._AddFix(token) - - insertion_point = tokenutil.GetPreviousCodeToken(token) - - # Insert a space between the previous token and the new operator. - space = Token(' ', Type.WHITESPACE, insertion_point.line, - insertion_point.line_number) - tokenutil.InsertTokenAfter(space, insertion_point) - - # Insert the operator on the end of the previous line. - new_token = Token(token.string, token.type, insertion_point.line, - insertion_point.line_number) - tokenutil.InsertTokenAfter(new_token, space) - self._AddFix(new_token) - - elif code == errors.LINE_ENDS_WITH_DOT: - # Remove whitespace preceding the operator to remove trailing whitespace. - self._StripSpace(token, before=True) - - # Remove the dot. - tokenutil.DeleteToken(token) - self._AddFix(token) - - insertion_point = tokenutil.GetNextCodeToken(token) - - # Insert the dot at the beginning of the next line of code. - new_token = Token(token.string, token.type, insertion_point.line, - insertion_point.line_number) - tokenutil.InsertTokenBefore(new_token, insertion_point) - self._AddFix(new_token) - - elif code == errors.GOOG_REQUIRES_NOT_ALPHABETIZED: - require_start_token = error.fix_data - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixRequires(require_start_token) - - self._AddFix(require_start_token) - - elif code == errors.GOOG_PROVIDES_NOT_ALPHABETIZED: - provide_start_token = error.fix_data - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixProvides(provide_start_token) - - self._AddFix(provide_start_token) - - elif code == errors.UNNECESSARY_BRACES_AROUND_INHERIT_DOC: - if token.previous.string == '{' and token.next.string == '}': - self._DeleteToken(token.previous) - self._DeleteToken(token.next) - self._AddFix([token]) - - elif code == errors.INVALID_AUTHOR_TAG_DESCRIPTION: - match = INVERTED_AUTHOR_SPEC.match(token.string) - if match: - token.string = '%s%s%s(%s)%s' % (match.group('leading_whitespace'), - match.group('email'), - match.group('whitespace_after_name'), - match.group('name'), - match.group('trailing_characters')) - self._AddFix(token) - - elif (code == errors.WRONG_INDENTATION and - not FLAGS.disable_indentation_fixing): - token = tokenutil.GetFirstTokenInSameLine(token) - actual = error.position.start - expected = error.position.length - - # Cases where first token is param but with leading spaces. - if (len(token.string.lstrip()) == len(token.string) - actual and - token.string.lstrip()): - token.string = token.string.lstrip() - actual = 0 - - if token.type in (Type.WHITESPACE, Type.PARAMETERS) and actual != 0: - token.string = token.string.lstrip() + (' ' * expected) - self._AddFix([token]) - else: - # We need to add indentation. - new_token = Token(' ' * expected, Type.WHITESPACE, - token.line, token.line_number) - # Note that we'll never need to add indentation at the first line, - # since it will always not be indented. Therefore it's safe to assume - # token.previous exists. - tokenutil.InsertTokenAfter(new_token, token.previous) - self._AddFix([token]) - - elif code in [errors.MALFORMED_END_OF_SCOPE_COMMENT, - errors.MISSING_END_OF_SCOPE_COMMENT]: - # Only fix cases where }); is found with no trailing content on the line - # other than a comment. Value of 'token' is set to } for this error. - if (token.type == Type.END_BLOCK and - token.next.type == Type.END_PAREN and - token.next.next.type == Type.SEMICOLON): - current_token = token.next.next.next - removed_tokens = [] - while current_token and current_token.line_number == token.line_number: - if current_token.IsAnyType(Type.WHITESPACE, - Type.START_SINGLE_LINE_COMMENT, - Type.COMMENT): - removed_tokens.append(current_token) - current_token = current_token.next - else: - return - - if removed_tokens: - self._DeleteTokens(removed_tokens[0], len(removed_tokens)) - - whitespace_token = Token(' ', Type.WHITESPACE, token.line, - token.line_number) - start_comment_token = Token('//', Type.START_SINGLE_LINE_COMMENT, - token.line, token.line_number) - comment_token = Token(' goog.scope', Type.COMMENT, token.line, - token.line_number) - insertion_tokens = [whitespace_token, start_comment_token, - comment_token] - - tokenutil.InsertTokensAfter(insertion_tokens, token.next.next) - self._AddFix(removed_tokens + insertion_tokens) - - elif code in [errors.EXTRA_GOOG_PROVIDE, errors.EXTRA_GOOG_REQUIRE]: - tokens_in_line = tokenutil.GetAllTokensInSameLine(token) - num_delete_tokens = len(tokens_in_line) - # If line being deleted is preceded and succeed with blank lines then - # delete one blank line also. - if (tokens_in_line[0].previous and tokens_in_line[-1].next - and tokens_in_line[0].previous.type == Type.BLANK_LINE - and tokens_in_line[-1].next.type == Type.BLANK_LINE): - num_delete_tokens += 1 - self._DeleteTokens(tokens_in_line[0], num_delete_tokens) - self._AddFix(tokens_in_line) - - elif code in [errors.MISSING_GOOG_PROVIDE, errors.MISSING_GOOG_REQUIRE]: - missing_namespaces = error.fix_data[0] - need_blank_line = error.fix_data[1] or (not token.previous) - - insert_location = Token('', Type.NORMAL, '', token.line_number - 1) - dummy_first_token = insert_location - tokenutil.InsertTokenBefore(insert_location, token) - - # If inserting a blank line check blank line does not exist before - # token to avoid extra blank lines. - if (need_blank_line and insert_location.previous - and insert_location.previous.type != Type.BLANK_LINE): - tokenutil.InsertBlankLineAfter(insert_location) - insert_location = insert_location.next - - for missing_namespace in missing_namespaces: - new_tokens = self._GetNewRequireOrProvideTokens( - code == errors.MISSING_GOOG_PROVIDE, - missing_namespace, insert_location.line_number + 1) - tokenutil.InsertLineAfter(insert_location, new_tokens) - insert_location = new_tokens[-1] - self._AddFix(new_tokens) - - # If inserting a blank line check blank line does not exist after - # token to avoid extra blank lines. - if (need_blank_line and insert_location.next - and insert_location.next.type != Type.BLANK_LINE): - tokenutil.InsertBlankLineAfter(insert_location) - - tokenutil.DeleteToken(dummy_first_token) - - def _StripSpace(self, token, before): - """Strip whitespace tokens either preceding or following the given token. - - Args: - token: The token. - before: If true, strip space before the token, if false, after it. - """ - token = token.previous if before else token.next - while token and token.type == Type.WHITESPACE: - tokenutil.DeleteToken(token) - token = token.previous if before else token.next - - def _GetNewRequireOrProvideTokens(self, is_provide, namespace, line_number): - """Returns a list of tokens to create a goog.require/provide statement. - - Args: - is_provide: True if getting tokens for a provide, False for require. - namespace: The required or provided namespaces to get tokens for. - line_number: The line number the new require or provide statement will be - on. - - Returns: - Tokens to create a new goog.require or goog.provide statement. - """ - string = 'goog.require' - if is_provide: - string = 'goog.provide' - line_text = string + '(\'' + namespace + '\');\n' - return [ - Token(string, Type.IDENTIFIER, line_text, line_number), - Token('(', Type.START_PAREN, line_text, line_number), - Token('\'', Type.SINGLE_QUOTE_STRING_START, line_text, line_number), - Token(namespace, Type.STRING_TEXT, line_text, line_number), - Token('\'', Type.SINGLE_QUOTE_STRING_END, line_text, line_number), - Token(')', Type.END_PAREN, line_text, line_number), - Token(';', Type.SEMICOLON, line_text, line_number) - ] - - def _DeleteToken(self, token): - """Deletes the specified token from the linked list of tokens. - - Updates instance variables pointing to tokens such as _file_token if - they reference the deleted token. - - Args: - token: The token to delete. - """ - if token == self._file_token: - self._file_token = token.next - - tokenutil.DeleteToken(token) - - def _DeleteTokens(self, token, token_count): - """Deletes the given number of tokens starting with the given token. - - Updates instance variables pointing to tokens such as _file_token if - they reference the deleted token. - - Args: - token: The first token to delete. - token_count: The total number of tokens to delete. - """ - if token == self._file_token: - for unused_i in xrange(token_count): - self._file_token = self._file_token.next - - tokenutil.DeleteTokens(token, token_count) - - def FinishFile(self): - """Called when the current file has finished style checking. - - Used to go back and fix any errors in the file. It currently supports both - js and html files. For js files it does a simple dump of all tokens, but in - order to support html file, we need to merge the original file with the new - token set back together. This works because the tokenized html file is the - original html file with all non js lines kept but blanked out with one blank - line token per line of html. - """ - if self._file_fix_count: - # Get the original file content for html. - if self._file_is_html: - f = open(self._file_name, 'r') - original_lines = f.readlines() - f.close() - - f = self._external_file - if not f: - error_noun = 'error' if self._file_fix_count == 1 else 'errors' - print 'Fixed %d %s in %s' % ( - self._file_fix_count, error_noun, self._file_name) - f = open(self._file_name, 'w') - - token = self._file_token - # Finding the first not deleted token. - while token.is_deleted: - token = token.next - # If something got inserted before first token (e.g. due to sorting) - # then move to start. Bug 8398202. - while token.previous: - token = token.previous - char_count = 0 - line = '' - while token: - line += token.string - char_count += len(token.string) - - if token.IsLastInLine(): - # We distinguish if a blank line in html was from stripped original - # file or newly added error fix by looking at the "org_line_number" - # field on the token. It is only set in the tokenizer, so for all - # error fixes, the value should be None. - if (line or not self._file_is_html or - token.orig_line_number is None): - f.write(line) - f.write('\n') - else: - f.write(original_lines[token.orig_line_number - 1]) - line = '' - if char_count > 80 and token.line_number in self._file_changed_lines: - print 'WARNING: Line %d of %s is now longer than 80 characters.' % ( - token.line_number, self._file_name) - - char_count = 0 - - token = token.next - - if not self._external_file: - # Close the file if we created it - f.close() diff --git a/tools/closure_linter/closure_linter/error_fixer_test.py b/tools/closure_linter/closure_linter/error_fixer_test.py deleted file mode 100644 index 49f449de42f36f..00000000000000 --- a/tools/closure_linter/closure_linter/error_fixer_test.py +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the error_fixer module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - - - -import unittest as googletest -from closure_linter import error_fixer -from closure_linter import testutil - - -class ErrorFixerTest(googletest.TestCase): - """Unit tests for error_fixer.""" - - def setUp(self): - self.error_fixer = error_fixer.ErrorFixer() - - def testDeleteToken(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCRIPT) - second_token = start_token.next - self.error_fixer.HandleFile('test_file', start_token) - - self.error_fixer._DeleteToken(start_token) - - self.assertEqual(second_token, self.error_fixer._file_token) - - def testDeleteTokens(self): - start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCRIPT) - fourth_token = start_token.next.next.next - self.error_fixer.HandleFile('test_file', start_token) - - self.error_fixer._DeleteTokens(start_token, 3) - - self.assertEqual(fourth_token, self.error_fixer._file_token) - -_TEST_SCRIPT = """\ -var x = 3; -""" - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/errorrecord.py b/tools/closure_linter/closure_linter/errorrecord.py deleted file mode 100644 index ce9fb908c75e71..00000000000000 --- a/tools/closure_linter/closure_linter/errorrecord.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -"""A simple, pickle-serializable class to represent a lint error.""" - -__author__ = 'nnaze@google.com (Nathan Naze)' - -import gflags as flags - -from closure_linter import errors -from closure_linter.common import erroroutput - -FLAGS = flags.FLAGS - - -class ErrorRecord(object): - """Record-keeping struct that can be serialized back from a process. - - Attributes: - path: Path to the file. - error_string: Error string for the user. - new_error: Whether this is a "new error" (see errors.NEW_ERRORS). - """ - - def __init__(self, path, error_string, new_error): - self.path = path - self.error_string = error_string - self.new_error = new_error - - -def MakeErrorRecord(path, error): - """Make an error record with correctly formatted error string. - - Errors are not able to be serialized (pickled) over processes because of - their pointers to the complex token/context graph. We use an intermediary - serializable class to pass back just the relevant information. - - Args: - path: Path of file the error was found in. - error: An error.Error instance. - - Returns: - _ErrorRecord instance. - """ - new_error = error.code in errors.NEW_ERRORS - - if FLAGS.unix_mode: - error_string = erroroutput.GetUnixErrorOutput( - path, error, new_error=new_error) - else: - error_string = erroroutput.GetErrorOutput(error, new_error=new_error) - - return ErrorRecord(path, error_string, new_error) diff --git a/tools/closure_linter/closure_linter/errorrules.py b/tools/closure_linter/closure_linter/errorrules.py deleted file mode 100755 index b1b72aab6dabdc..00000000000000 --- a/tools/closure_linter/closure_linter/errorrules.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Linter error rules class for Closure Linter.""" - -__author__ = 'robbyw@google.com (Robert Walker)' - -import gflags as flags -from closure_linter import errors - - -FLAGS = flags.FLAGS -flags.DEFINE_boolean('jsdoc', True, - 'Whether to report errors for missing JsDoc.') -flags.DEFINE_list('disable', None, - 'Disable specific error. Usage Ex.: gjslint --disable 1,' - '0011 foo.js.') -flags.DEFINE_integer('max_line_length', 80, 'Maximum line length allowed ' - 'without warning.', lower_bound=1) - -disabled_error_nums = None - - -def GetMaxLineLength(): - """Returns allowed maximum length of line. - - Returns: - Length of line allowed without any warning. - """ - return FLAGS.max_line_length - - -def ShouldReportError(error): - """Whether the given error should be reported. - - Returns: - True for all errors except missing documentation errors and disabled - errors. For missing documentation, it returns the value of the - jsdoc flag. - """ - global disabled_error_nums - if disabled_error_nums is None: - disabled_error_nums = [] - if FLAGS.disable: - for error_str in FLAGS.disable: - error_num = 0 - try: - error_num = int(error_str) - except ValueError: - pass - disabled_error_nums.append(error_num) - - return ((FLAGS.jsdoc or error not in ( - errors.MISSING_PARAMETER_DOCUMENTATION, - errors.MISSING_RETURN_DOCUMENTATION, - errors.MISSING_MEMBER_DOCUMENTATION, - errors.MISSING_PRIVATE, - errors.MISSING_JSDOC_TAG_THIS)) and - (not FLAGS.disable or error not in disabled_error_nums)) diff --git a/tools/closure_linter/closure_linter/errorrules_test.py b/tools/closure_linter/closure_linter/errorrules_test.py deleted file mode 100644 index cb903785e60fec..00000000000000 --- a/tools/closure_linter/closure_linter/errorrules_test.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# Copyright 2013 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Medium tests for the gjslint errorrules. - -Currently its just verifying that warnings can't be disabled. -""" - - - -import gflags as flags -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import erroraccumulator - -flags.FLAGS.strict = True -flags.FLAGS.limited_doc_files = ('dummy.js', 'externs.js') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') - - -class ErrorRulesTest(googletest.TestCase): - """Test case to for gjslint errorrules.""" - - def testNoMaxLineLengthFlagExists(self): - """Tests that --max_line_length flag does not exists.""" - self.assertTrue('max_line_length' not in flags.FLAGS.FlagDict()) - - def testGetMaxLineLength(self): - """Tests warning are reported for line greater than 80. - """ - - # One line > 100 and one line > 80 and < 100. So should produce two - # line too long error. - original = [ - 'goog.require(\'dummy.aa\');', - '', - 'function a() {', - ' dummy.aa.i = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13' - ' + 14 + 15 + 16 + 17 + 18 + 19 + 20;', - ' dummy.aa.j = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13' - ' + 14 + 15 + 16 + 17 + 18;', - '}', - '' - ] - - # Expect line too long. - expected = [errors.LINE_TOO_LONG, errors.LINE_TOO_LONG] - - self._AssertErrors(original, expected) - - def testNoDisableFlagExists(self): - """Tests that --disable flag does not exists.""" - self.assertTrue('disable' not in flags.FLAGS.FlagDict()) - - def testWarningsNotDisabled(self): - """Tests warnings are reported when nothing is disabled. - """ - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - '', - 'function a() {', - ' dummy.aa.i = 1;', - ' dummy.Cc.i = 1;', - ' dummy.Dd.i = 1;', - '}', - ] - - expected = [errors.GOOG_REQUIRES_NOT_ALPHABETIZED, - errors.FILE_MISSING_NEWLINE] - - self._AssertErrors(original, expected) - - def _AssertErrors(self, original, expected_errors, include_header=True): - """Asserts that the error fixer corrects original to expected.""" - if include_header: - original = self._GetHeader() + original - - # Trap gjslint's output parse it to get messages added. - error_accumulator = erroraccumulator.ErrorAccumulator() - runner.Run('testing.js', error_accumulator, source=original) - error_nums = [e.code for e in error_accumulator.GetErrors()] - - error_nums.sort() - expected_errors.sort() - self.assertListEqual(error_nums, expected_errors) - - def _GetHeader(self): - """Returns a fake header for a JavaScript file.""" - return [ - '// Copyright 2011 Google Inc. All Rights Reserved.', - '', - '/**', - ' * @fileoverview Fake file overview.', - ' * @author fake@google.com (Fake Person)', - ' */', - '' - ] - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/errors.py b/tools/closure_linter/closure_linter/errors.py deleted file mode 100755 index 356ee0c5a6441d..00000000000000 --- a/tools/closure_linter/closure_linter/errors.py +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Error codes for JavaScript style checker.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - - -def ByName(name): - """Get the error code for the given error name. - - Args: - name: The name of the error - - Returns: - The error code - """ - return globals()[name] - - -# "File-fatal" errors - these errors stop further parsing of a single file -FILE_NOT_FOUND = -1 -FILE_DOES_NOT_PARSE = -2 - -# Spacing -EXTRA_SPACE = 1 -MISSING_SPACE = 2 -EXTRA_LINE = 3 -MISSING_LINE = 4 -ILLEGAL_TAB = 5 -WRONG_INDENTATION = 6 -WRONG_BLANK_LINE_COUNT = 7 - -# Semicolons -MISSING_SEMICOLON = 10 -MISSING_SEMICOLON_AFTER_FUNCTION = 11 -ILLEGAL_SEMICOLON_AFTER_FUNCTION = 12 -REDUNDANT_SEMICOLON = 13 - -# Miscellaneous -ILLEGAL_PROTOTYPE_MEMBER_VALUE = 100 -LINE_TOO_LONG = 110 -LINE_STARTS_WITH_OPERATOR = 120 -COMMA_AT_END_OF_LITERAL = 121 -LINE_ENDS_WITH_DOT = 122 -MULTI_LINE_STRING = 130 -UNNECESSARY_DOUBLE_QUOTED_STRING = 131 -UNUSED_PRIVATE_MEMBER = 132 -UNUSED_LOCAL_VARIABLE = 133 - -# Requires, provides -GOOG_REQUIRES_NOT_ALPHABETIZED = 140 -GOOG_PROVIDES_NOT_ALPHABETIZED = 141 -MISSING_GOOG_REQUIRE = 142 -MISSING_GOOG_PROVIDE = 143 -EXTRA_GOOG_REQUIRE = 144 -EXTRA_GOOG_PROVIDE = 145 -ALIAS_STMT_NEEDS_GOOG_REQUIRE = 146 - -# JsDoc -INVALID_JSDOC_TAG = 200 -INVALID_USE_OF_DESC_TAG = 201 -NO_BUG_NUMBER_AFTER_BUG_TAG = 202 -MISSING_PARAMETER_DOCUMENTATION = 210 -EXTRA_PARAMETER_DOCUMENTATION = 211 -WRONG_PARAMETER_DOCUMENTATION = 212 -MISSING_JSDOC_TAG_TYPE = 213 -MISSING_JSDOC_TAG_DESCRIPTION = 214 -MISSING_JSDOC_PARAM_NAME = 215 -OUT_OF_ORDER_JSDOC_TAG_TYPE = 216 -MISSING_RETURN_DOCUMENTATION = 217 -UNNECESSARY_RETURN_DOCUMENTATION = 218 -MISSING_BRACES_AROUND_TYPE = 219 -MISSING_MEMBER_DOCUMENTATION = 220 -MISSING_PRIVATE = 221 -EXTRA_PRIVATE = 222 -INVALID_OVERRIDE_PRIVATE = 223 -INVALID_INHERIT_DOC_PRIVATE = 224 -MISSING_JSDOC_TAG_THIS = 225 -UNNECESSARY_BRACES_AROUND_INHERIT_DOC = 226 -INVALID_AUTHOR_TAG_DESCRIPTION = 227 -JSDOC_PREFER_QUESTION_TO_PIPE_NULL = 230 -JSDOC_ILLEGAL_QUESTION_WITH_PIPE = 231 -JSDOC_MISSING_OPTIONAL_TYPE = 232 -JSDOC_MISSING_OPTIONAL_PREFIX = 233 -JSDOC_MISSING_VAR_ARGS_TYPE = 234 -JSDOC_MISSING_VAR_ARGS_NAME = 235 -JSDOC_DOES_NOT_PARSE = 236 -# TODO(robbyw): Split this in to more specific syntax problems. -INCORRECT_SUPPRESS_SYNTAX = 250 -INVALID_SUPPRESS_TYPE = 251 -UNNECESSARY_SUPPRESS = 252 - -# File ending -FILE_MISSING_NEWLINE = 300 -FILE_IN_BLOCK = 301 - -# Interfaces -INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS = 400 -INTERFACE_METHOD_CANNOT_HAVE_CODE = 401 - -# Comments -MISSING_END_OF_SCOPE_COMMENT = 500 -MALFORMED_END_OF_SCOPE_COMMENT = 501 - -# goog.scope - Namespace aliasing -# TODO(nnaze) Add additional errors here and in aliaspass.py -INVALID_USE_OF_GOOG_SCOPE = 600 -EXTRA_GOOG_SCOPE_USAGE = 601 - -# ActionScript specific errors: -# TODO(user): move these errors to their own file and move all JavaScript -# specific errors to their own file as well. -# All ActionScript specific errors should have error number at least 1000. -FUNCTION_MISSING_RETURN_TYPE = 1132 -PARAMETER_MISSING_TYPE = 1133 -VAR_MISSING_TYPE = 1134 -PARAMETER_MISSING_DEFAULT_VALUE = 1135 -IMPORTS_NOT_ALPHABETIZED = 1140 -IMPORT_CONTAINS_WILDCARD = 1141 -UNUSED_IMPORT = 1142 -INVALID_TRACE_SEVERITY_LEVEL = 1250 -MISSING_TRACE_SEVERITY_LEVEL = 1251 -MISSING_TRACE_MESSAGE = 1252 -REMOVE_TRACE_BEFORE_SUBMIT = 1253 -REMOVE_COMMENT_BEFORE_SUBMIT = 1254 -# End of list of ActionScript specific errors. - -NEW_ERRORS = frozenset([ - # Errors added after 2.0.2: - WRONG_INDENTATION, - MISSING_SEMICOLON, - # Errors added after 2.3.9: - JSDOC_MISSING_VAR_ARGS_TYPE, - JSDOC_MISSING_VAR_ARGS_NAME, - # Errors added after 2.3.15: - ALIAS_STMT_NEEDS_GOOG_REQUIRE, - JSDOC_DOES_NOT_PARSE, - LINE_ENDS_WITH_DOT, - # Errors added after 2.3.17: - ]) diff --git a/tools/closure_linter/closure_linter/fixjsstyle.py b/tools/closure_linter/closure_linter/fixjsstyle.py deleted file mode 100755 index 2d65e0398fdcc6..00000000000000 --- a/tools/closure_linter/closure_linter/fixjsstyle.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Automatically fix simple style guide violations.""" - -__author__ = 'robbyw@google.com (Robert Walker)' - -import StringIO -import sys - -import gflags as flags - -from closure_linter import error_fixer -from closure_linter import runner -from closure_linter.common import simplefileflags as fileflags - -FLAGS = flags.FLAGS -flags.DEFINE_list('additional_extensions', None, 'List of additional file ' - 'extensions (not js) that should be treated as ' - 'JavaScript files.') -flags.DEFINE_boolean('dry_run', False, 'Do not modify the file, only print it.') - - -def main(argv=None): - """Main function. - - Args: - argv: Sequence of command line arguments. - """ - if argv is None: - argv = flags.FLAGS(sys.argv) - - suffixes = ['.js'] - if FLAGS.additional_extensions: - suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] - - files = fileflags.GetFileList(argv, 'JavaScript', suffixes) - - output_buffer = None - if FLAGS.dry_run: - output_buffer = StringIO.StringIO() - - fixer = error_fixer.ErrorFixer(output_buffer) - - # Check the list of files. - for filename in files: - runner.Run(filename, fixer) - if FLAGS.dry_run: - print output_buffer.getvalue() - - -if __name__ == '__main__': - main() diff --git a/tools/closure_linter/closure_linter/fixjsstyle_test.py b/tools/closure_linter/closure_linter/fixjsstyle_test.py deleted file mode 100755 index 34de3f8488d351..00000000000000 --- a/tools/closure_linter/closure_linter/fixjsstyle_test.py +++ /dev/null @@ -1,615 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Medium tests for the gpylint auto-fixer.""" - -__author__ = 'robbyw@google.com (Robby Walker)' - -import StringIO - -import gflags as flags -import unittest as googletest -from closure_linter import error_fixer -from closure_linter import runner - - -_RESOURCE_PREFIX = 'closure_linter/testdata' - -flags.FLAGS.strict = True -flags.FLAGS.limited_doc_files = ('dummy.js', 'externs.js') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') - - -class FixJsStyleTest(googletest.TestCase): - """Test case to for gjslint auto-fixing.""" - - def setUp(self): - flags.FLAGS.dot_on_next_line = True - - def tearDown(self): - flags.FLAGS.dot_on_next_line = False - - def testFixJsStyle(self): - test_cases = [ - ['fixjsstyle.in.js', 'fixjsstyle.out.js'], - ['indentation.js', 'fixjsstyle.indentation.out.js'], - ['fixjsstyle.html.in.html', 'fixjsstyle.html.out.html'], - ['fixjsstyle.oplineend.in.js', 'fixjsstyle.oplineend.out.js']] - for [running_input_file, running_output_file] in test_cases: - print 'Checking %s vs %s' % (running_input_file, running_output_file) - input_filename = None - golden_filename = None - current_filename = None - try: - input_filename = '%s/%s' % (_RESOURCE_PREFIX, running_input_file) - current_filename = input_filename - - golden_filename = '%s/%s' % (_RESOURCE_PREFIX, running_output_file) - current_filename = golden_filename - except IOError as ex: - raise IOError('Could not find testdata resource for %s: %s' % - (current_filename, ex)) - - if running_input_file == 'fixjsstyle.in.js': - with open(input_filename) as f: - for line in f: - # Go to last line. - pass - self.assertTrue(line == line.rstrip(), '%s file should not end ' - 'with a new line.' % (input_filename)) - - # Autofix the file, sending output to a fake file. - actual = StringIO.StringIO() - runner.Run(input_filename, error_fixer.ErrorFixer(actual)) - - # Now compare the files. - actual.seek(0) - expected = open(golden_filename, 'r') - - # Uncomment to generate new golden files and run - # open('/'.join(golden_filename.split('/')[4:]), 'w').write(actual.read()) - # actual.seek(0) - - self.assertEqual(actual.readlines(), expected.readlines()) - - def testAddProvideFirstLine(self): - """Tests handling of case where goog.provide is added.""" - original = [ - 'dummy.bb.cc = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.bb\');', - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testAddRequireFirstLine(self): - """Tests handling of case where goog.require is added.""" - original = [ - 'a = dummy.bb.cc;', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteProvideAndAddProvideFirstLine(self): - """Tests handling of case where goog.provide is deleted and added. - - Bug 14832597. - """ - original = [ - 'goog.provide(\'dummy.aa\');', - '', - 'dummy.bb.cc = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.bb\');', - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.provide(\'dummy.aa\');', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteProvideAndAddRequireFirstLine(self): - """Tests handling where goog.provide is deleted and goog.require added. - - Bug 14832597. - """ - original = [ - 'goog.provide(\'dummy.aa\');', - '', - 'a = dummy.bb.cc;', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.provide(\'dummy.aa\');', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteRequireAndAddRequireFirstLine(self): - """Tests handling of case where goog.require is deleted and added. - - Bug 14832597. - """ - original = [ - 'goog.require(\'dummy.aa\');', - '', - 'a = dummy.bb.cc;', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - '', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.require(\'dummy.aa\');', - 'a = dummy.bb.cc;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testDeleteRequireAndAddProvideFirstLine(self): - """Tests handling where goog.require is deleted and goog.provide added. - - Bug 14832597. - """ - original = [ - 'goog.require(\'dummy.aa\');', - '', - 'dummy.bb.cc = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.bb\');', - '', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - original = [ - 'goog.require(\'dummy.aa\');', - 'dummy.bb.cc = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMultipleProvideInsert(self): - original = [ - 'goog.provide(\'dummy.bb\');', - 'goog.provide(\'dummy.dd\');', - '', - 'dummy.aa.ff = 1;', - 'dummy.bb.ff = 1;', - 'dummy.cc.ff = 1;', - 'dummy.dd.ff = 1;', - 'dummy.ee.ff = 1;', - ] - - expected = [ - 'goog.provide(\'dummy.aa\');', - 'goog.provide(\'dummy.bb\');', - 'goog.provide(\'dummy.cc\');', - 'goog.provide(\'dummy.dd\');', - 'goog.provide(\'dummy.ee\');', - '', - 'dummy.aa.ff = 1;', - 'dummy.bb.ff = 1;', - 'dummy.cc.ff = 1;', - 'dummy.dd.ff = 1;', - 'dummy.ee.ff = 1;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMultipleRequireInsert(self): - original = [ - 'goog.require(\'dummy.bb\');', - 'goog.require(\'dummy.dd\');', - '', - 'a = dummy.aa.ff;', - 'b = dummy.bb.ff;', - 'c = dummy.cc.ff;', - 'd = dummy.dd.ff;', - 'e = dummy.ee.ff;', - ] - - expected = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.bb\');', - 'goog.require(\'dummy.cc\');', - 'goog.require(\'dummy.dd\');', - 'goog.require(\'dummy.ee\');', - '', - 'a = dummy.aa.ff;', - 'b = dummy.bb.ff;', - 'c = dummy.cc.ff;', - 'd = dummy.dd.ff;', - 'e = dummy.ee.ff;', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testUnsortedRequires(self): - """Tests handling of unsorted goog.require statements without header. - - Bug 8398202. - """ - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - '', - 'function a() {', - ' dummy.aa.i = 1;', - ' dummy.Cc.i = 1;', - ' dummy.Dd.i = 1;', - '}', - ] - - expected = [ - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - 'goog.require(\'dummy.aa\');', - '', - 'function a() {', - ' dummy.aa.i = 1;', - ' dummy.Cc.i = 1;', - ' dummy.Dd.i = 1;', - '}', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMissingExtraAndUnsortedRequires(self): - """Tests handling of missing extra and unsorted goog.require statements.""" - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.Dd\');', - '', - 'var x = new dummy.Bb();', - 'dummy.Cc.someMethod();', - 'dummy.aa.someMethod();', - ] - - expected = [ - 'goog.require(\'dummy.Bb\');', - 'goog.require(\'dummy.Cc\');', - 'goog.require(\'dummy.aa\');', - '', - 'var x = new dummy.Bb();', - 'dummy.Cc.someMethod();', - 'dummy.aa.someMethod();', - ] - - self._AssertFixes(original, expected) - - def testExtraRequireOnFirstLine(self): - """Tests handling of extra goog.require statement on the first line. - - There was a bug when fixjsstyle quits with an exception. It happened if - - the first line of the file is an extra goog.require() statement, - - goog.require() statements are not sorted. - """ - original = [ - 'goog.require(\'dummy.aa\');', - 'goog.require(\'dummy.cc\');', - 'goog.require(\'dummy.bb\');', - '', - 'var x = new dummy.bb();', - 'var y = new dummy.cc();', - ] - - expected = [ - 'goog.require(\'dummy.bb\');', - 'goog.require(\'dummy.cc\');', - '', - 'var x = new dummy.bb();', - 'var y = new dummy.cc();', - ] - - self._AssertFixes(original, expected, include_header=False) - - def testUnsortedProvides(self): - """Tests handling of unsorted goog.provide statements without header. - - Bug 8398202. - """ - original = [ - 'goog.provide(\'dummy.aa\');', - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.Dd\');', - '', - 'dummy.aa = function() {};' - 'dummy.Cc = function() {};' - 'dummy.Dd = function() {};' - ] - - expected = [ - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.Dd\');', - 'goog.provide(\'dummy.aa\');', - '', - 'dummy.aa = function() {};' - 'dummy.Cc = function() {};' - 'dummy.Dd = function() {};' - ] - - self._AssertFixes(original, expected, include_header=False) - - def testMissingExtraAndUnsortedProvides(self): - """Tests handling of missing extra and unsorted goog.provide statements.""" - original = [ - 'goog.provide(\'dummy.aa\');', - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.Dd\');', - '', - 'dummy.Cc = function() {};', - 'dummy.Bb = function() {};', - 'dummy.aa.someMethod = function();', - ] - - expected = [ - 'goog.provide(\'dummy.Bb\');', - 'goog.provide(\'dummy.Cc\');', - 'goog.provide(\'dummy.aa\');', - '', - 'dummy.Cc = function() {};', - 'dummy.Bb = function() {};', - 'dummy.aa.someMethod = function();', - ] - - self._AssertFixes(original, expected) - - def testNoRequires(self): - """Tests positioning of missing requires without existing requires.""" - original = [ - 'goog.provide(\'dummy.Something\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - expected = [ - 'goog.provide(\'dummy.Something\');', - '', - 'goog.require(\'dummy.Bb\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - self._AssertFixes(original, expected) - - def testNoProvides(self): - """Tests positioning of missing provides without existing provides.""" - original = [ - 'goog.require(\'dummy.Bb\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - expected = [ - 'goog.provide(\'dummy.Something\');', - '', - 'goog.require(\'dummy.Bb\');', - '', - 'dummy.Something = function() {};', - '', - 'var x = new dummy.Bb();', - ] - - self._AssertFixes(original, expected) - - def testOutputOkayWhenFirstTokenIsDeleted(self): - """Tests that autofix output is is correct when first token is deleted. - - Regression test for bug 4581567 - """ - original = ['"use strict";'] - expected = ["'use strict';"] - - self._AssertFixes(original, expected, include_header=False) - - def testGoogScopeIndentation(self): - """Tests Handling a typical end-of-scope indentation fix.""" - original = [ - 'goog.scope(function() {', - ' // TODO(brain): Take over the world.', - '}); // goog.scope', - ] - - expected = [ - 'goog.scope(function() {', - '// TODO(brain): Take over the world.', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testMissingEndOfScopeComment(self): - """Tests Handling a missing comment at end of goog.scope.""" - original = [ - 'goog.scope(function() {', - '});', - ] - - expected = [ - 'goog.scope(function() {', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testMissingEndOfScopeCommentWithOtherComment(self): - """Tests handling an irrelevant comment at end of goog.scope.""" - original = [ - 'goog.scope(function() {', - "}); // I don't belong here!", - ] - - expected = [ - 'goog.scope(function() {', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testMalformedEndOfScopeComment(self): - """Tests Handling a malformed comment at end of goog.scope.""" - original = [ - 'goog.scope(function() {', - '}); // goog.scope FTW', - ] - - expected = [ - 'goog.scope(function() {', - '}); // goog.scope', - ] - - self._AssertFixes(original, expected) - - def testEndsWithIdentifier(self): - """Tests Handling case where script ends with identifier. Bug 7643404.""" - original = [ - 'goog.provide(\'xyz\');', - '', - 'abc' - ] - - expected = [ - 'goog.provide(\'xyz\');', - '', - 'abc;' - ] - - self._AssertFixes(original, expected) - - def testFileStartsWithSemicolon(self): - """Tests handling files starting with semicolon. - - b/10062516 - """ - original = [ - ';goog.provide(\'xyz\');', - '', - 'abc;' - ] - - expected = [ - 'goog.provide(\'xyz\');', - '', - 'abc;' - ] - - self._AssertFixes(original, expected, include_header=False) - - def testCodeStartsWithSemicolon(self): - """Tests handling code in starting with semicolon after comments. - - b/10062516 - """ - original = [ - ';goog.provide(\'xyz\');', - '', - 'abc;' - ] - - expected = [ - 'goog.provide(\'xyz\');', - '', - 'abc;' - ] - - self._AssertFixes(original, expected) - - def _AssertFixes(self, original, expected, include_header=True): - """Asserts that the error fixer corrects original to expected.""" - if include_header: - original = self._GetHeader() + original - expected = self._GetHeader() + expected - - actual = StringIO.StringIO() - runner.Run('testing.js', error_fixer.ErrorFixer(actual), original) - actual.seek(0) - - expected = [x + '\n' for x in expected] - - self.assertListEqual(actual.readlines(), expected) - - def _GetHeader(self): - """Returns a fake header for a JavaScript file.""" - return [ - '// Copyright 2011 Google Inc. All Rights Reserved.', - '', - '/**', - ' * @fileoverview Fake file overview.', - ' * @author fake@google.com (Fake Person)', - ' */', - '' - ] - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/full_test.py b/tools/closure_linter/closure_linter/full_test.py deleted file mode 100755 index d0a1557dc23dbe..00000000000000 --- a/tools/closure_linter/closure_linter/full_test.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Full regression-type (Medium) tests for gjslint. - -Tests every error that can be thrown by gjslint. Based heavily on -devtools/javascript/gpylint/full_test.py -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import os -import sys -import unittest - -import gflags as flags -import unittest as googletest - -from closure_linter import error_check -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import filetestcase - -_RESOURCE_PREFIX = 'closure_linter/testdata' - -flags.FLAGS.strict = True -flags.FLAGS.custom_jsdoc_tags = ('customtag', 'requires') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') -flags.FLAGS.limited_doc_files = ('externs.js', 'dummy.js', - 'limited_doc_checks.js') -flags.FLAGS.jslint_error = error_check.Rule.ALL - -# List of files under testdata to test. -# We need to list files explicitly since pyglib can't list directories. -# TODO(user): Figure out how to list the directory. -_TEST_FILES = [ - 'all_js_wrapped.js', - 'blank_lines.js', - 'ends_with_block.js', - 'empty_file.js', - 'externs.js', - 'externs_jsdoc.js', - 'goog_scope.js', - 'html_parse_error.html', - 'indentation.js', - 'interface.js', - 'jsdoc.js', - 'limited_doc_checks.js', - 'minimal.js', - 'other.js', - 'provide_blank.js', - 'provide_extra.js', - 'provide_missing.js', - 'require_alias.js', - 'require_all_caps.js', - 'require_blank.js', - 'require_extra.js', - 'require_function.js', - 'require_function_missing.js', - 'require_function_through_both.js', - 'require_function_through_namespace.js', - 'require_interface.js', - 'require_interface_alias.js', - 'require_interface_base.js', - 'require_lower_case.js', - 'require_missing.js', - 'require_numeric.js', - 'require_provide_blank.js', - 'require_provide_missing.js', - 'require_provide_ok.js', - 'semicolon_missing.js', - 'simple.html', - 'spaces.js', - 'tokenizer.js', - 'unparseable.js', - 'unused_local_variables.js', - 'unused_private_members.js', - 'utf8.html', -] - - -class GJsLintTestSuite(unittest.TestSuite): - """Test suite to run a GJsLintTest for each of several files. - - If sys.argv[1:] is non-empty, it is interpreted as a list of filenames in - testdata to test. Otherwise, _TEST_FILES is used. - """ - - def __init__(self, tests=()): - unittest.TestSuite.__init__(self, tests) - - argv = sys.argv and sys.argv[1:] or [] - if argv: - test_files = argv - else: - test_files = _TEST_FILES - for test_file in test_files: - resource_path = os.path.join(_RESOURCE_PREFIX, test_file) - self.addTest( - filetestcase.AnnotatedFileTestCase( - resource_path, - runner.Run, - errors.ByName)) - -if __name__ == '__main__': - # Don't let main parse args; it happens in the TestSuite. - googletest.main(argv=sys.argv[0:1], defaultTest='GJsLintTestSuite') diff --git a/tools/closure_linter/closure_linter/gjslint.py b/tools/closure_linter/closure_linter/gjslint.py deleted file mode 100755 index 824e025dcb00de..00000000000000 --- a/tools/closure_linter/closure_linter/gjslint.py +++ /dev/null @@ -1,319 +0,0 @@ -#!/usr/bin/env python -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Checks JavaScript files for common style guide violations. - -gjslint.py is designed to be used as a PRESUBMIT script to check for javascript -style guide violations. As of now, it checks for the following violations: - - * Missing and extra spaces - * Lines longer than 80 characters - * Missing newline at end of file - * Missing semicolon after function declaration - * Valid JsDoc including parameter matching - -Someday it will validate to the best of its ability against the entirety of the -JavaScript style guide. - -This file is a front end that parses arguments and flags. The core of the code -is in tokenizer.py and checker.py. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'nnaze@google.com (Nathan Naze)',) - -import errno -import itertools -import os -import platform -import re -import sys -import time - -import gflags as flags - -from closure_linter import errorrecord -from closure_linter import runner -from closure_linter.common import erroraccumulator -from closure_linter.common import simplefileflags as fileflags - -# Attempt import of multiprocessing (should be available in Python 2.6 and up). -try: - # pylint: disable=g-import-not-at-top - import multiprocessing -except ImportError: - multiprocessing = None - -FLAGS = flags.FLAGS -flags.DEFINE_boolean('unix_mode', False, - 'Whether to emit warnings in standard unix format.') -flags.DEFINE_boolean('beep', True, 'Whether to beep when errors are found.') -flags.DEFINE_boolean('time', False, 'Whether to emit timing statistics.') -flags.DEFINE_boolean('quiet', False, 'Whether to minimize logged messages. ' - 'Most useful for per-file linting, such as that performed ' - 'by the presubmit linter service.') -flags.DEFINE_boolean('check_html', False, - 'Whether to check javascript in html files.') -flags.DEFINE_boolean('summary', False, - 'Whether to show an error count summary.') -flags.DEFINE_list('additional_extensions', None, 'List of additional file ' - 'extensions (not js) that should be treated as ' - 'JavaScript files.') -flags.DEFINE_boolean('multiprocess', - platform.system() is 'Linux' and bool(multiprocessing), - 'Whether to attempt parallelized linting using the ' - 'multiprocessing module. Enabled by default on Linux ' - 'if the multiprocessing module is present (Python 2.6+). ' - 'Otherwise disabled by default. ' - 'Disabling may make debugging easier.') -flags.ADOPT_module_key_flags(fileflags) -flags.ADOPT_module_key_flags(runner) - - -GJSLINT_ONLY_FLAGS = ['--unix_mode', '--beep', '--nobeep', '--time', - '--check_html', '--summary', '--quiet'] - - - -def _MultiprocessCheckPaths(paths): - """Run _CheckPath over mutltiple processes. - - Tokenization, passes, and checks are expensive operations. Running in a - single process, they can only run on one CPU/core. Instead, - shard out linting over all CPUs with multiprocessing to parallelize. - - Args: - paths: paths to check. - - Yields: - errorrecord.ErrorRecords for any found errors. - """ - - pool = multiprocessing.Pool() - - path_results = pool.imap(_CheckPath, paths) - for results in path_results: - for result in results: - yield result - - # Force destruct before returning, as this can sometimes raise spurious - # "interrupted system call" (EINTR), which we can ignore. - try: - pool.close() - pool.join() - del pool - except OSError as err: - if err.errno is not errno.EINTR: - raise err - - -def _CheckPaths(paths): - """Run _CheckPath on all paths in one thread. - - Args: - paths: paths to check. - - Yields: - errorrecord.ErrorRecords for any found errors. - """ - - for path in paths: - results = _CheckPath(path) - for record in results: - yield record - - -def _CheckPath(path): - """Check a path and return any errors. - - Args: - path: paths to check. - - Returns: - A list of errorrecord.ErrorRecords for any found errors. - """ - - error_handler = erroraccumulator.ErrorAccumulator() - runner.Run(path, error_handler) - - make_error_record = lambda err: errorrecord.MakeErrorRecord(path, err) - return map(make_error_record, error_handler.GetErrors()) - - -def _GetFilePaths(argv): - suffixes = ['.js'] - if FLAGS.additional_extensions: - suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] - if FLAGS.check_html: - suffixes += ['.html', '.htm'] - return fileflags.GetFileList(argv, 'JavaScript', suffixes) - - -# Error printing functions - - -def _PrintFileSummary(paths, records): - """Print a detailed summary of the number of errors in each file.""" - - paths = list(paths) - paths.sort() - - for path in paths: - path_errors = [e for e in records if e.path == path] - print '%s: %d' % (path, len(path_errors)) - - -def _PrintFileSeparator(path): - print '----- FILE : %s -----' % path - - -def _PrintSummary(paths, error_records): - """Print a summary of the number of errors and files.""" - - error_count = len(error_records) - all_paths = set(paths) - all_paths_count = len(all_paths) - - if error_count is 0: - print '%d files checked, no errors found.' % all_paths_count - - new_error_count = len([e for e in error_records if e.new_error]) - - error_paths = set([e.path for e in error_records]) - error_paths_count = len(error_paths) - no_error_paths_count = all_paths_count - error_paths_count - - if (error_count or new_error_count) and not FLAGS.quiet: - error_noun = 'error' if error_count == 1 else 'errors' - new_error_noun = 'error' if new_error_count == 1 else 'errors' - error_file_noun = 'file' if error_paths_count == 1 else 'files' - ok_file_noun = 'file' if no_error_paths_count == 1 else 'files' - print ('Found %d %s, including %d new %s, in %d %s (%d %s OK).' % - (error_count, - error_noun, - new_error_count, - new_error_noun, - error_paths_count, - error_file_noun, - no_error_paths_count, - ok_file_noun)) - - -def _PrintErrorRecords(error_records): - """Print error records strings in the expected format.""" - - current_path = None - for record in error_records: - - if current_path != record.path: - current_path = record.path - if not FLAGS.unix_mode: - _PrintFileSeparator(current_path) - - print record.error_string - - -def _FormatTime(t): - """Formats a duration as a human-readable string. - - Args: - t: A duration in seconds. - - Returns: - A formatted duration string. - """ - if t < 1: - return '%dms' % round(t * 1000) - else: - return '%.2fs' % t - - - - -def main(argv=None): - """Main function. - - Args: - argv: Sequence of command line arguments. - """ - if argv is None: - argv = flags.FLAGS(sys.argv) - - if FLAGS.time: - start_time = time.time() - - suffixes = ['.js'] - if FLAGS.additional_extensions: - suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions] - if FLAGS.check_html: - suffixes += ['.html', '.htm'] - paths = fileflags.GetFileList(argv, 'JavaScript', suffixes) - - if FLAGS.multiprocess: - records_iter = _MultiprocessCheckPaths(paths) - else: - records_iter = _CheckPaths(paths) - - records_iter, records_iter_copy = itertools.tee(records_iter, 2) - _PrintErrorRecords(records_iter_copy) - - error_records = list(records_iter) - _PrintSummary(paths, error_records) - - exit_code = 0 - - # If there are any errors - if error_records: - exit_code += 1 - - # If there are any new errors - if [r for r in error_records if r.new_error]: - exit_code += 2 - - if exit_code: - if FLAGS.summary: - _PrintFileSummary(paths, error_records) - - if FLAGS.beep: - # Make a beep noise. - sys.stdout.write(chr(7)) - - # Write out instructions for using fixjsstyle script to fix some of the - # reported errors. - fix_args = [] - for flag in sys.argv[1:]: - for f in GJSLINT_ONLY_FLAGS: - if flag.startswith(f): - break - else: - fix_args.append(flag) - - if not FLAGS.quiet: - print """ -Some of the errors reported by GJsLint may be auto-fixable using the script -fixjsstyle. Please double check any changes it makes and report any bugs. The -script can be run by executing: - -fixjsstyle %s """ % ' '.join(fix_args) - - if FLAGS.time: - print 'Done in %s.' % _FormatTime(time.time() - start_time) - - sys.exit(exit_code) - - -if __name__ == '__main__': - main() diff --git a/tools/closure_linter/closure_linter/indentation.py b/tools/closure_linter/closure_linter/indentation.py deleted file mode 100755 index d48ad2b862c43a..00000000000000 --- a/tools/closure_linter/closure_linter/indentation.py +++ /dev/null @@ -1,617 +0,0 @@ -#!/usr/bin/env python -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Methods for checking EcmaScript files for indentation issues.""" - -__author__ = ('robbyw@google.com (Robert Walker)') - -import gflags as flags - -from closure_linter import ecmametadatapass -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - - -flags.DEFINE_boolean('debug_indentation', False, - 'Whether to print debugging information for indentation.') - - -# Shorthand -Context = ecmametadatapass.EcmaContext -Error = error.Error -Position = position.Position -Type = javascripttokens.JavaScriptTokenType - - -# The general approach: -# -# 1. Build a stack of tokens that can affect indentation. -# For each token, we determine if it is a block or continuation token. -# Some tokens need to be temporarily overwritten in case they are removed -# before the end of the line. -# Much of the work here is determining which tokens to keep on the stack -# at each point. Operators, for example, should be removed once their -# expression or line is gone, while parentheses must stay until the matching -# end parentheses is found. -# -# 2. Given that stack, determine the allowable indentations. -# Due to flexible indentation rules in JavaScript, there may be many -# allowable indentations for each stack. We follows the general -# "no false positives" approach of GJsLint and build the most permissive -# set possible. - - -class TokenInfo(object): - """Stores information about a token. - - Attributes: - token: The token - is_block: Whether the token represents a block indentation. - is_transient: Whether the token should be automatically removed without - finding a matching end token. - overridden_by: TokenInfo for a token that overrides the indentation that - this token would require. - is_permanent_override: Whether the override on this token should persist - even after the overriding token is removed from the stack. For example: - x([ - 1], - 2); - needs this to be set so the last line is not required to be a continuation - indent. - line_number: The effective line number of this token. Will either be the - actual line number or the one before it in the case of a mis-wrapped - operator. - """ - - def __init__(self, token, is_block=False): - """Initializes a TokenInfo object. - - Args: - token: The token - is_block: Whether the token represents a block indentation. - """ - self.token = token - self.overridden_by = None - self.is_permanent_override = False - self.is_block = is_block - self.is_transient = not is_block and token.type not in ( - Type.START_PAREN, Type.START_PARAMETERS) - self.line_number = token.line_number - - def __repr__(self): - result = '\n %s' % self.token - if self.overridden_by: - result = '%s OVERRIDDEN [by "%s"]' % ( - result, self.overridden_by.token.string) - result += ' {is_block: %s, is_transient: %s}' % ( - self.is_block, self.is_transient) - return result - - -class IndentationRules(object): - """EmcaScript indentation rules. - - Can be used to find common indentation errors in JavaScript, ActionScript and - other Ecma like scripting languages. - """ - - def __init__(self): - """Initializes the IndentationRules checker.""" - self._stack = [] - - # Map from line number to number of characters it is off in indentation. - self._start_index_offset = {} - - def Finalize(self): - if self._stack: - old_stack = self._stack - self._stack = [] - raise Exception('INTERNAL ERROR: indentation stack is not empty: %r' % - old_stack) - - def CheckToken(self, token, state): - """Checks a token for indentation errors. - - Args: - token: The current token under consideration - state: Additional information about the current tree state - - Returns: - An error array [error code, error string, error token] if the token is - improperly indented, or None if indentation is correct. - """ - - token_type = token.type - indentation_errors = [] - stack = self._stack - is_first = self._IsFirstNonWhitespaceTokenInLine(token) - - # Add tokens that could decrease indentation before checking. - if token_type == Type.END_PAREN: - self._PopTo(Type.START_PAREN) - - elif token_type == Type.END_PARAMETERS: - self._PopTo(Type.START_PARAMETERS) - - elif token_type == Type.END_BRACKET: - self._PopTo(Type.START_BRACKET) - - elif token_type == Type.END_BLOCK: - start_token = self._PopTo(Type.START_BLOCK) - # Check for required goog.scope comment. - if start_token: - goog_scope = tokenutil.GoogScopeOrNoneFromStartBlock(start_token.token) - if goog_scope is not None: - if not token.line.endswith('; // goog.scope\n'): - if (token.line.find('//') > -1 and - token.line.find('goog.scope') > - token.line.find('//')): - indentation_errors.append([ - errors.MALFORMED_END_OF_SCOPE_COMMENT, - ('Malformed end of goog.scope comment. Please use the ' - 'exact following syntax to close the scope:\n' - '}); // goog.scope'), - token, - Position(token.start_index, token.length)]) - else: - indentation_errors.append([ - errors.MISSING_END_OF_SCOPE_COMMENT, - ('Missing comment for end of goog.scope which opened at line ' - '%d. End the scope with:\n' - '}); // goog.scope' % - (start_token.line_number)), - token, - Position(token.start_index, token.length)]) - - elif token_type == Type.KEYWORD and token.string in ('case', 'default'): - self._Add(self._PopTo(Type.START_BLOCK)) - - elif token_type == Type.SEMICOLON: - self._PopTransient() - - if (is_first and - token_type not in (Type.COMMENT, Type.DOC_PREFIX, Type.STRING_TEXT)): - if flags.FLAGS.debug_indentation: - print 'Line #%d: stack %r' % (token.line_number, stack) - - # Ignore lines that start in JsDoc since we don't check them properly yet. - # TODO(robbyw): Support checking JsDoc indentation. - # Ignore lines that start as multi-line strings since indentation is N/A. - # Ignore lines that start with operators since we report that already. - # Ignore lines with tabs since we report that already. - expected = self._GetAllowableIndentations() - actual = self._GetActualIndentation(token) - - # Special case comments describing else, case, and default. Allow them - # to outdent to the parent block. - if token_type in Type.COMMENT_TYPES: - next_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - if next_code and next_code.type == Type.END_BLOCK: - next_code = tokenutil.SearchExcept(next_code, Type.NON_CODE_TYPES) - if next_code and next_code.string in ('else', 'case', 'default'): - # TODO(robbyw): This almost certainly introduces false negatives. - expected |= self._AddToEach(expected, -2) - - if actual >= 0 and actual not in expected: - expected = sorted(expected) - indentation_errors.append([ - errors.WRONG_INDENTATION, - 'Wrong indentation: expected any of {%s} but got %d' % ( - ', '.join('%d' % x for x in expected if x < 80), actual), - token, - Position(actual, expected[0])]) - self._start_index_offset[token.line_number] = expected[0] - actual - - # Add tokens that could increase indentation. - if token_type == Type.START_BRACKET: - self._Add(TokenInfo( - token=token, - is_block=token.metadata.context.type == Context.ARRAY_LITERAL)) - - elif token_type == Type.START_BLOCK or token.metadata.is_implied_block: - self._Add(TokenInfo(token=token, is_block=True)) - - elif token_type in (Type.START_PAREN, Type.START_PARAMETERS): - self._Add(TokenInfo(token=token, is_block=False)) - - elif token_type == Type.KEYWORD and token.string == 'return': - self._Add(TokenInfo(token)) - - elif not token.IsLastInLine() and ( - token.IsAssignment() or token.IsOperator('?')): - self._Add(TokenInfo(token=token)) - - # Handle implied block closes. - if token.metadata.is_implied_block_close: - self._PopToImpliedBlock() - - # Add some tokens only if they appear at the end of the line. - is_last = self._IsLastCodeInLine(token) - if is_last: - next_code_token = tokenutil.GetNextCodeToken(token) - # Increase required indentation if this is an overlong wrapped statement - # ending in an operator. - if token_type == Type.OPERATOR: - if token.string == ':': - if stack and stack[-1].token.string == '?': - # When a ternary : is on a different line than its '?', it doesn't - # add indentation. - if token.line_number == stack[-1].token.line_number: - self._Add(TokenInfo(token)) - elif token.metadata.context.type == Context.CASE_BLOCK: - # Pop transient tokens from say, line continuations, e.g., - # case x. - # y: - # Want to pop the transient 4 space continuation indent. - self._PopTransient() - # Starting the body of the case statement, which is a type of - # block. - self._Add(TokenInfo(token=token, is_block=True)) - elif token.metadata.context.type == Context.LITERAL_ELEMENT: - # When in an object literal, acts as operator indicating line - # continuations. - self._Add(TokenInfo(token)) - else: - # ':' might also be a statement label, no effect on indentation in - # this case. - pass - - elif token.string != ',': - self._Add(TokenInfo(token)) - else: - # The token is a comma. - if token.metadata.context.type == Context.VAR: - self._Add(TokenInfo(token)) - elif token.metadata.context.type != Context.PARAMETERS: - self._PopTransient() - # Increase required indentation if this is the end of a statement that's - # continued with an operator on the next line (e.g. the '.'). - elif (next_code_token and next_code_token.type == Type.OPERATOR and - not next_code_token.metadata.IsUnaryOperator()): - self._Add(TokenInfo(token)) - elif token_type == Type.PARAMETERS and token.string.endswith(','): - # Parameter lists. - self._Add(TokenInfo(token)) - elif token.IsKeyword('var'): - self._Add(TokenInfo(token)) - elif token.metadata.is_implied_semicolon: - self._PopTransient() - elif token.IsAssignment(): - self._Add(TokenInfo(token)) - - return indentation_errors - - def _AddToEach(self, original, amount): - """Returns a new set with the given amount added to each element. - - Args: - original: The original set of numbers - amount: The amount to add to each element - - Returns: - A new set containing each element of the original set added to the amount. - """ - return set([x + amount for x in original]) - - _HARD_STOP_TYPES = (Type.START_PAREN, Type.START_PARAMETERS, - Type.START_BRACKET) - - _HARD_STOP_STRINGS = ('return', '?') - - def _IsHardStop(self, token): - """Determines if the given token can have a hard stop after it. - - Args: - token: token to examine - - Returns: - Whether the token can have a hard stop after it. - - Hard stops are indentations defined by the position of another token as in - indentation lined up with return, (, [, and ?. - """ - return (token.type in self._HARD_STOP_TYPES or - token.string in self._HARD_STOP_STRINGS or - token.IsAssignment()) - - def _GetAllowableIndentations(self): - """Computes the set of allowable indentations. - - Returns: - The set of allowable indentations, given the current stack. - """ - expected = set([0]) - hard_stops = set([]) - - # Whether the tokens are still in the same continuation, meaning additional - # indentation is optional. As an example: - # x = 5 + - # 6 + - # 7; - # The second '+' does not add any required indentation. - in_same_continuation = False - - for token_info in self._stack: - token = token_info.token - - # Handle normal additive indentation tokens. - if not token_info.overridden_by and token.string != 'return': - if token_info.is_block: - expected = self._AddToEach(expected, 2) - hard_stops = self._AddToEach(hard_stops, 2) - in_same_continuation = False - elif in_same_continuation: - expected |= self._AddToEach(expected, 4) - hard_stops |= self._AddToEach(hard_stops, 4) - else: - expected = self._AddToEach(expected, 4) - hard_stops |= self._AddToEach(hard_stops, 4) - in_same_continuation = True - - # Handle hard stops after (, [, return, =, and ? - if self._IsHardStop(token): - override_is_hard_stop = (token_info.overridden_by and - self._IsHardStop( - token_info.overridden_by.token)) - if token.type == Type.START_PAREN and token.previous: - # For someFunction(...) we allow to indent at the beginning of the - # identifier +4 - prev = token.previous - if (prev.type == Type.IDENTIFIER and - prev.line_number == token.line_number): - hard_stops.add(prev.start_index + 4) - if not override_is_hard_stop: - start_index = token.start_index - if token.line_number in self._start_index_offset: - start_index += self._start_index_offset[token.line_number] - if (token.type in (Type.START_PAREN, Type.START_PARAMETERS) and - not token_info.overridden_by): - hard_stops.add(start_index + 1) - - elif token.string == 'return' and not token_info.overridden_by: - hard_stops.add(start_index + 7) - - elif token.type == Type.START_BRACKET: - hard_stops.add(start_index + 1) - - elif token.IsAssignment(): - hard_stops.add(start_index + len(token.string) + 1) - - elif token.IsOperator('?') and not token_info.overridden_by: - hard_stops.add(start_index + 2) - - return (expected | hard_stops) or set([0]) - - def _GetActualIndentation(self, token): - """Gets the actual indentation of the line containing the given token. - - Args: - token: Any token on the line. - - Returns: - The actual indentation of the line containing the given token. Returns - -1 if this line should be ignored due to the presence of tabs. - """ - # Move to the first token in the line - token = tokenutil.GetFirstTokenInSameLine(token) - - # If it is whitespace, it is the indentation. - if token.type == Type.WHITESPACE: - if token.string.find('\t') >= 0: - return -1 - else: - return len(token.string) - elif token.type == Type.PARAMETERS: - return len(token.string) - len(token.string.lstrip()) - else: - return 0 - - def _IsFirstNonWhitespaceTokenInLine(self, token): - """Determines if the given token is the first non-space token on its line. - - Args: - token: The token. - - Returns: - True if the token is the first non-whitespace token on its line. - """ - if token.type in (Type.WHITESPACE, Type.BLANK_LINE): - return False - if token.IsFirstInLine(): - return True - return (token.previous and token.previous.IsFirstInLine() and - token.previous.type == Type.WHITESPACE) - - def _IsLastCodeInLine(self, token): - """Determines if the given token is the last code token on its line. - - Args: - token: The token. - - Returns: - True if the token is the last code token on its line. - """ - if token.type in Type.NON_CODE_TYPES: - return False - start_token = token - while True: - token = token.next - if not token or token.line_number != start_token.line_number: - return True - if token.type not in Type.NON_CODE_TYPES: - return False - - def _AllFunctionPropertyAssignTokens(self, start_token, end_token): - """Checks if tokens are (likely) a valid function property assignment. - - Args: - start_token: Start of the token range. - end_token: End of the token range. - - Returns: - True if all tokens between start_token and end_token are legal tokens - within a function declaration and assignment into a property. - """ - for token in tokenutil.GetTokenRange(start_token, end_token): - fn_decl_tokens = (Type.FUNCTION_DECLARATION, - Type.PARAMETERS, - Type.START_PARAMETERS, - Type.END_PARAMETERS, - Type.END_PAREN) - if (token.type not in fn_decl_tokens and - token.IsCode() and - not tokenutil.IsIdentifierOrDot(token) and - not token.IsAssignment() and - not (token.type == Type.OPERATOR and token.string == ',')): - return False - return True - - def _Add(self, token_info): - """Adds the given token info to the stack. - - Args: - token_info: The token information to add. - """ - if self._stack and self._stack[-1].token == token_info.token: - # Don't add the same token twice. - return - - if token_info.is_block or token_info.token.type == Type.START_PAREN: - scope_token = tokenutil.GoogScopeOrNoneFromStartBlock(token_info.token) - token_info.overridden_by = TokenInfo(scope_token) if scope_token else None - - if (token_info.token.type == Type.START_BLOCK and - token_info.token.metadata.context.type == Context.BLOCK): - # Handle function() {} assignments: their block contents get special - # treatment and are allowed to just indent by two whitespace. - # For example - # long.long.name = function( - # a) { - # In this case the { and the = are on different lines. But the - # override should still apply for all previous stack tokens that are - # part of an assignment of a block. - - has_assignment = any(x for x in self._stack if x.token.IsAssignment()) - if has_assignment: - last_token = token_info.token.previous - for stack_info in reversed(self._stack): - if (last_token and - not self._AllFunctionPropertyAssignTokens(stack_info.token, - last_token)): - break - stack_info.overridden_by = token_info - stack_info.is_permanent_override = True - last_token = stack_info.token - - index = len(self._stack) - 1 - while index >= 0: - stack_info = self._stack[index] - stack_token = stack_info.token - - if stack_info.line_number == token_info.line_number: - # In general, tokens only override each other when they are on - # the same line. - stack_info.overridden_by = token_info - if (token_info.token.type == Type.START_BLOCK and - (stack_token.IsAssignment() or - stack_token.type in (Type.IDENTIFIER, Type.START_PAREN))): - # Multi-line blocks have lasting overrides, as in: - # callFn({ - # a: 10 - # }, - # 30); - # b/11450054. If a string is not closed properly then close_block - # could be null. - close_block = token_info.token.metadata.context.end_token - stack_info.is_permanent_override = close_block and ( - close_block.line_number != token_info.token.line_number) - else: - break - index -= 1 - - self._stack.append(token_info) - - def _Pop(self): - """Pops the top token from the stack. - - Returns: - The popped token info. - """ - token_info = self._stack.pop() - if token_info.token.type not in (Type.START_BLOCK, Type.START_BRACKET): - # Remove any temporary overrides. - self._RemoveOverrides(token_info) - else: - # For braces and brackets, which can be object and array literals, remove - # overrides when the literal is closed on the same line. - token_check = token_info.token - same_type = token_check.type - goal_type = None - if token_info.token.type == Type.START_BRACKET: - goal_type = Type.END_BRACKET - else: - goal_type = Type.END_BLOCK - line_number = token_info.token.line_number - count = 0 - while token_check and token_check.line_number == line_number: - if token_check.type == goal_type: - count -= 1 - if not count: - self._RemoveOverrides(token_info) - break - if token_check.type == same_type: - count += 1 - token_check = token_check.next - return token_info - - def _PopToImpliedBlock(self): - """Pops the stack until an implied block token is found.""" - while not self._Pop().token.metadata.is_implied_block: - pass - - def _PopTo(self, stop_type): - """Pops the stack until a token of the given type is popped. - - Args: - stop_type: The type of token to pop to. - - Returns: - The token info of the given type that was popped. - """ - last = None - while True: - last = self._Pop() - if last.token.type == stop_type: - break - return last - - def _RemoveOverrides(self, token_info): - """Marks any token that was overridden by this token as active again. - - Args: - token_info: The token that is being removed from the stack. - """ - for stack_token in self._stack: - if (stack_token.overridden_by == token_info and - not stack_token.is_permanent_override): - stack_token.overridden_by = None - - def _PopTransient(self): - """Pops all transient tokens - i.e. not blocks, literals, or parens.""" - while self._stack and self._stack[-1].is_transient: - self._Pop() diff --git a/tools/closure_linter/closure_linter/javascriptlintrules.py b/tools/closure_linter/closure_linter/javascriptlintrules.py deleted file mode 100644 index 9578009daacb5a..00000000000000 --- a/tools/closure_linter/closure_linter/javascriptlintrules.py +++ /dev/null @@ -1,754 +0,0 @@ -#!/usr/bin/env python -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Methods for checking JS files for common style guide violations. - -These style guide violations should only apply to JavaScript and not an Ecma -scripting languages. -""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)', - 'jacobr@google.com (Jacob Richman)') - -import re - -from closure_linter import ecmalintrules -from closure_linter import error_check -from closure_linter import errors -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import tokenutil -from closure_linter.common import error -from closure_linter.common import position - -# Shorthand -Error = error.Error -Position = position.Position -Rule = error_check.Rule -Type = javascripttokens.JavaScriptTokenType - - -class JavaScriptLintRules(ecmalintrules.EcmaScriptLintRules): - """JavaScript lint rules that catch JavaScript specific style errors.""" - - def __init__(self, namespaces_info): - """Initializes a JavaScriptLintRules instance.""" - ecmalintrules.EcmaScriptLintRules.__init__(self) - self._namespaces_info = namespaces_info - self._declared_private_member_tokens = {} - self._declared_private_members = set() - self._used_private_members = set() - # A stack of dictionaries, one for each function scope entered. Each - # dictionary is keyed by an identifier that defines a local variable and has - # a token as its value. - self._unused_local_variables_by_scope = [] - - def HandleMissingParameterDoc(self, token, param_name): - """Handle errors associated with a parameter missing a param tag.""" - self._HandleError(errors.MISSING_PARAMETER_DOCUMENTATION, - 'Missing docs for parameter: "%s"' % param_name, token) - - # pylint: disable=too-many-statements - def CheckToken(self, token, state): - """Checks a token, given the current parser_state, for warnings and errors. - - Args: - token: The current token under consideration - state: parser_state object that indicates the current state in the page - """ - - # Call the base class's CheckToken function. - super(JavaScriptLintRules, self).CheckToken(token, state) - - # Store some convenience variables - namespaces_info = self._namespaces_info - - if error_check.ShouldCheck(Rule.UNUSED_LOCAL_VARIABLES): - self._CheckUnusedLocalVariables(token, state) - - if error_check.ShouldCheck(Rule.UNUSED_PRIVATE_MEMBERS): - # Find all assignments to private members. - if token.type == Type.SIMPLE_LVALUE: - identifier = token.string - if identifier.endswith('_') and not identifier.endswith('__'): - doc_comment = state.GetDocComment() - suppressed = doc_comment and ( - 'underscore' in doc_comment.suppressions or - 'unusedPrivateMembers' in doc_comment.suppressions) - if not suppressed: - # Look for static members defined on a provided namespace. - if namespaces_info: - namespace = namespaces_info.GetClosurizedNamespace(identifier) - provided_namespaces = namespaces_info.GetProvidedNamespaces() - else: - namespace = None - provided_namespaces = set() - - # Skip cases of this.something_.somethingElse_. - regex = re.compile(r'^this\.[a-zA-Z_]+$') - if namespace in provided_namespaces or regex.match(identifier): - variable = identifier.split('.')[-1] - self._declared_private_member_tokens[variable] = token - self._declared_private_members.add(variable) - elif not identifier.endswith('__'): - # Consider setting public members of private members to be a usage. - for piece in identifier.split('.'): - if piece.endswith('_'): - self._used_private_members.add(piece) - - # Find all usages of private members. - if token.type == Type.IDENTIFIER: - for piece in token.string.split('.'): - if piece.endswith('_'): - self._used_private_members.add(piece) - - if token.type == Type.DOC_FLAG: - flag = token.attached_object - - if flag.flag_type == 'param' and flag.name_token is not None: - self._CheckForMissingSpaceBeforeToken( - token.attached_object.name_token) - - if flag.type is not None and flag.name is not None: - if error_check.ShouldCheck(Rule.VARIABLE_ARG_MARKER): - # Check for variable arguments marker in type. - if flag.jstype.IsVarArgsType() and flag.name != 'var_args': - self._HandleError(errors.JSDOC_MISSING_VAR_ARGS_NAME, - 'Variable length argument %s must be renamed ' - 'to var_args.' % flag.name, - token) - elif not flag.jstype.IsVarArgsType() and flag.name == 'var_args': - self._HandleError(errors.JSDOC_MISSING_VAR_ARGS_TYPE, - 'Variable length argument %s type must start ' - 'with \'...\'.' % flag.name, - token) - - if error_check.ShouldCheck(Rule.OPTIONAL_TYPE_MARKER): - # Check for optional marker in type. - if (flag.jstype.opt_arg and - not flag.name.startswith('opt_')): - self._HandleError(errors.JSDOC_MISSING_OPTIONAL_PREFIX, - 'Optional parameter name %s must be prefixed ' - 'with opt_.' % flag.name, - token) - elif (not flag.jstype.opt_arg and - flag.name.startswith('opt_')): - self._HandleError(errors.JSDOC_MISSING_OPTIONAL_TYPE, - 'Optional parameter %s type must end with =.' % - flag.name, - token) - - if flag.flag_type in state.GetDocFlag().HAS_TYPE: - # Check for both missing type token and empty type braces '{}' - # Missing suppress types are reported separately and we allow enums, - # const, private, public and protected without types. - if (flag.flag_type not in state.GetDocFlag().CAN_OMIT_TYPE - and (not flag.jstype or flag.jstype.IsEmpty())): - self._HandleError(errors.MISSING_JSDOC_TAG_TYPE, - 'Missing type in %s tag' % token.string, token) - - elif flag.name_token and flag.type_end_token and tokenutil.Compare( - flag.type_end_token, flag.name_token) > 0: - self._HandleError( - errors.OUT_OF_ORDER_JSDOC_TAG_TYPE, - 'Type should be immediately after %s tag' % token.string, - token) - - elif token.type == Type.DOUBLE_QUOTE_STRING_START: - next_token = token.next - while next_token.type == Type.STRING_TEXT: - if javascripttokenizer.JavaScriptTokenizer.SINGLE_QUOTE.search( - next_token.string): - break - next_token = next_token.next - else: - self._HandleError( - errors.UNNECESSARY_DOUBLE_QUOTED_STRING, - 'Single-quoted string preferred over double-quoted string.', - token, - position=Position.All(token.string)) - - elif token.type == Type.END_DOC_COMMENT: - doc_comment = state.GetDocComment() - - # When @externs appears in a @fileoverview comment, it should trigger - # the same limited doc checks as a special filename like externs.js. - if doc_comment.HasFlag('fileoverview') and doc_comment.HasFlag('externs'): - self._SetLimitedDocChecks(True) - - if (error_check.ShouldCheck(Rule.BLANK_LINES_AT_TOP_LEVEL) and - not self._is_html and - state.InTopLevel() and - not state.InNonScopeBlock()): - - # Check if we're in a fileoverview or constructor JsDoc. - is_constructor = ( - doc_comment.HasFlag('constructor') or - doc_comment.HasFlag('interface')) - # @fileoverview is an optional tag so if the dosctring is the first - # token in the file treat it as a file level docstring. - is_file_level_comment = ( - doc_comment.HasFlag('fileoverview') or - not doc_comment.start_token.previous) - - # If the comment is not a file overview, and it does not immediately - # precede some code, skip it. - # NOTE: The tokenutil methods are not used here because of their - # behavior at the top of a file. - next_token = token.next - if (not next_token or - (not is_file_level_comment and - next_token.type in Type.NON_CODE_TYPES)): - return - - # Don't require extra blank lines around suppression of extra - # goog.require errors. - if (doc_comment.SuppressionOnly() and - next_token.type == Type.IDENTIFIER and - next_token.string in ['goog.provide', 'goog.require']): - return - - # Find the start of this block (include comments above the block, unless - # this is a file overview). - block_start = doc_comment.start_token - if not is_file_level_comment: - token = block_start.previous - while token and token.type in Type.COMMENT_TYPES: - block_start = token - token = token.previous - - # Count the number of blank lines before this block. - blank_lines = 0 - token = block_start.previous - while token and token.type in [Type.WHITESPACE, Type.BLANK_LINE]: - if token.type == Type.BLANK_LINE: - # A blank line. - blank_lines += 1 - elif token.type == Type.WHITESPACE and not token.line.strip(): - # A line with only whitespace on it. - blank_lines += 1 - token = token.previous - - # Log errors. - error_message = False - expected_blank_lines = 0 - - # Only need blank line before file overview if it is not the beginning - # of the file, e.g. copyright is first. - if is_file_level_comment and blank_lines == 0 and block_start.previous: - error_message = 'Should have a blank line before a file overview.' - expected_blank_lines = 1 - elif is_constructor and blank_lines != 3: - error_message = ( - 'Should have 3 blank lines before a constructor/interface.') - expected_blank_lines = 3 - elif (not is_file_level_comment and not is_constructor and - blank_lines != 2): - error_message = 'Should have 2 blank lines between top-level blocks.' - expected_blank_lines = 2 - - if error_message: - self._HandleError( - errors.WRONG_BLANK_LINE_COUNT, error_message, - block_start, position=Position.AtBeginning(), - fix_data=expected_blank_lines - blank_lines) - - elif token.type == Type.END_BLOCK: - if state.InFunction() and state.IsFunctionClose(): - is_immediately_called = (token.next and - token.next.type == Type.START_PAREN) - - function = state.GetFunction() - if not self._limited_doc_checks: - if (function.has_return and function.doc and - not is_immediately_called and - not function.doc.HasFlag('return') and - not function.doc.InheritsDocumentation() and - not function.doc.HasFlag('constructor')): - # Check for proper documentation of return value. - self._HandleError( - errors.MISSING_RETURN_DOCUMENTATION, - 'Missing @return JsDoc in function with non-trivial return', - function.doc.end_token, position=Position.AtBeginning()) - elif (not function.has_return and - not function.has_throw and - function.doc and - function.doc.HasFlag('return') and - not state.InInterfaceMethod()): - flag = function.doc.GetFlag('return') - valid_no_return_names = ['undefined', 'void', '*'] - invalid_return = flag.jstype is None or not any( - sub_type.identifier in valid_no_return_names - for sub_type in flag.jstype.IterTypeGroup()) - - if invalid_return: - self._HandleError( - errors.UNNECESSARY_RETURN_DOCUMENTATION, - 'Found @return JsDoc on function that returns nothing', - flag.flag_token, position=Position.AtBeginning()) - - # b/4073735. Method in object literal definition of prototype can - # safely reference 'this'. - prototype_object_literal = False - block_start = None - previous_code = None - previous_previous_code = None - - # Search for cases where prototype is defined as object literal. - # previous_previous_code - # | previous_code - # | | block_start - # | | | - # a.b.prototype = { - # c : function() { - # this.d = 1; - # } - # } - - # If in object literal, find first token of block so to find previous - # tokens to check above condition. - if state.InObjectLiteral(): - block_start = state.GetCurrentBlockStart() - - # If an object literal then get previous token (code type). For above - # case it should be '='. - if block_start: - previous_code = tokenutil.SearchExcept(block_start, - Type.NON_CODE_TYPES, - reverse=True) - - # If previous token to block is '=' then get its previous token. - if previous_code and previous_code.IsOperator('='): - previous_previous_code = tokenutil.SearchExcept(previous_code, - Type.NON_CODE_TYPES, - reverse=True) - - # If variable/token before '=' ends with '.prototype' then its above - # case of prototype defined with object literal. - prototype_object_literal = (previous_previous_code and - previous_previous_code.string.endswith( - '.prototype')) - - if (function.has_this and function.doc and - not function.doc.HasFlag('this') and - not function.is_constructor and - not function.is_interface and - '.prototype.' not in function.name and - not prototype_object_literal): - self._HandleError( - errors.MISSING_JSDOC_TAG_THIS, - 'Missing @this JsDoc in function referencing "this". (' - 'this usually means you are trying to reference "this" in ' - 'a static function, or you have forgotten to mark a ' - 'constructor with @constructor)', - function.doc.end_token, position=Position.AtBeginning()) - - elif token.type == Type.IDENTIFIER: - if token.string == 'goog.inherits' and not state.InFunction(): - if state.GetLastNonSpaceToken().line_number == token.line_number: - self._HandleError( - errors.MISSING_LINE, - 'Missing newline between constructor and goog.inherits', - token, - position=Position.AtBeginning()) - - extra_space = state.GetLastNonSpaceToken().next - while extra_space != token: - if extra_space.type == Type.BLANK_LINE: - self._HandleError( - errors.EXTRA_LINE, - 'Extra line between constructor and goog.inherits', - extra_space) - extra_space = extra_space.next - - # TODO(robbyw): Test the last function was a constructor. - # TODO(robbyw): Test correct @extends and @implements documentation. - - elif (token.string == 'goog.provide' and - not state.InFunction() and - namespaces_info is not None): - namespace = tokenutil.GetStringAfterToken(token) - - # Report extra goog.provide statement. - if not namespace or namespaces_info.IsExtraProvide(token): - if not namespace: - msg = 'Empty namespace in goog.provide' - else: - msg = 'Unnecessary goog.provide: ' + namespace - - # Hint to user if this is a Test namespace. - if namespace.endswith('Test'): - msg += (' *Test namespaces must be mentioned in the ' - 'goog.setTestOnly() call') - - self._HandleError( - errors.EXTRA_GOOG_PROVIDE, - msg, - token, position=Position.AtBeginning()) - - if namespaces_info.IsLastProvide(token): - # Report missing provide statements after the last existing provide. - missing_provides = namespaces_info.GetMissingProvides() - if missing_provides: - self._ReportMissingProvides( - missing_provides, - tokenutil.GetLastTokenInSameLine(token).next, - False) - - # If there are no require statements, missing requires should be - # reported after the last provide. - if not namespaces_info.GetRequiredNamespaces(): - missing_requires, illegal_alias_statements = ( - namespaces_info.GetMissingRequires()) - if missing_requires: - self._ReportMissingRequires( - missing_requires, - tokenutil.GetLastTokenInSameLine(token).next, - True) - if illegal_alias_statements: - self._ReportIllegalAliasStatement(illegal_alias_statements) - - elif (token.string == 'goog.require' and - not state.InFunction() and - namespaces_info is not None): - namespace = tokenutil.GetStringAfterToken(token) - - # If there are no provide statements, missing provides should be - # reported before the first require. - if (namespaces_info.IsFirstRequire(token) and - not namespaces_info.GetProvidedNamespaces()): - missing_provides = namespaces_info.GetMissingProvides() - if missing_provides: - self._ReportMissingProvides( - missing_provides, - tokenutil.GetFirstTokenInSameLine(token), - True) - - # Report extra goog.require statement. - if not namespace or namespaces_info.IsExtraRequire(token): - if not namespace: - msg = 'Empty namespace in goog.require' - else: - msg = 'Unnecessary goog.require: ' + namespace - - self._HandleError( - errors.EXTRA_GOOG_REQUIRE, - msg, - token, position=Position.AtBeginning()) - - # Report missing goog.require statements. - if namespaces_info.IsLastRequire(token): - missing_requires, illegal_alias_statements = ( - namespaces_info.GetMissingRequires()) - if missing_requires: - self._ReportMissingRequires( - missing_requires, - tokenutil.GetLastTokenInSameLine(token).next, - False) - if illegal_alias_statements: - self._ReportIllegalAliasStatement(illegal_alias_statements) - - elif token.type == Type.OPERATOR: - last_in_line = token.IsLastInLine() - # If the token is unary and appears to be used in a unary context - # it's ok. Otherwise, if it's at the end of the line or immediately - # before a comment, it's ok. - # Don't report an error before a start bracket - it will be reported - # by that token's space checks. - if (not token.metadata.IsUnaryOperator() and not last_in_line - and not token.next.IsComment() - and not token.next.IsOperator(',') - and not tokenutil.IsDot(token) - and token.next.type not in (Type.WHITESPACE, Type.END_PAREN, - Type.END_BRACKET, Type.SEMICOLON, - Type.START_BRACKET)): - self._HandleError( - errors.MISSING_SPACE, - 'Missing space after "%s"' % token.string, - token, - position=Position.AtEnd(token.string)) - elif token.type == Type.WHITESPACE: - first_in_line = token.IsFirstInLine() - last_in_line = token.IsLastInLine() - # Check whitespace length if it's not the first token of the line and - # if it's not immediately before a comment. - if not last_in_line and not first_in_line and not token.next.IsComment(): - # Ensure there is no space after opening parentheses. - if (token.previous.type in (Type.START_PAREN, Type.START_BRACKET, - Type.FUNCTION_NAME) - or token.next.type == Type.START_PARAMETERS): - self._HandleError( - errors.EXTRA_SPACE, - 'Extra space after "%s"' % token.previous.string, - token, - position=Position.All(token.string)) - elif token.type == Type.SEMICOLON: - previous_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, - reverse=True) - if not previous_token: - self._HandleError( - errors.REDUNDANT_SEMICOLON, - 'Semicolon without any statement', - token, - position=Position.AtEnd(token.string)) - elif (previous_token.type == Type.KEYWORD and - previous_token.string not in ['break', 'continue', 'return']): - self._HandleError( - errors.REDUNDANT_SEMICOLON, - ('Semicolon after \'%s\' without any statement.' - ' Looks like an error.' % previous_token.string), - token, - position=Position.AtEnd(token.string)) - - def _CheckUnusedLocalVariables(self, token, state): - """Checks for unused local variables in function blocks. - - Args: - token: The token to check. - state: The state tracker. - """ - # We don't use state.InFunction because that disregards scope functions. - in_function = state.FunctionDepth() > 0 - if token.type == Type.SIMPLE_LVALUE or token.type == Type.IDENTIFIER: - if in_function: - identifier = token.string - # Check whether the previous token was var. - previous_code_token = tokenutil.CustomSearch( - token, - lambda t: t.type not in Type.NON_CODE_TYPES, - reverse=True) - if previous_code_token and previous_code_token.IsKeyword('var'): - # Add local variable declaration to the top of the unused locals - # stack. - self._unused_local_variables_by_scope[-1][identifier] = token - elif token.type == Type.IDENTIFIER: - # This covers most cases where the variable is used as an identifier. - self._MarkLocalVariableUsed(token.string) - elif token.type == Type.SIMPLE_LVALUE and '.' in identifier: - # This covers cases where a value is assigned to a property of the - # variable. - self._MarkLocalVariableUsed(token.string) - elif token.type == Type.START_BLOCK: - if in_function and state.IsFunctionOpen(): - # Push a new map onto the stack - self._unused_local_variables_by_scope.append({}) - elif token.type == Type.END_BLOCK: - if state.IsFunctionClose(): - # Pop the stack and report any remaining locals as unused. - unused_local_variables = self._unused_local_variables_by_scope.pop() - for unused_token in unused_local_variables.values(): - self._HandleError( - errors.UNUSED_LOCAL_VARIABLE, - 'Unused local variable: %s.' % unused_token.string, - unused_token) - elif token.type == Type.DOC_FLAG: - # Flags that use aliased symbols should be counted. - flag = token.attached_object - js_type = flag and flag.jstype - if flag and flag.flag_type in state.GetDocFlag().HAS_TYPE and js_type: - self._MarkAliasUsed(js_type) - - def _MarkAliasUsed(self, js_type): - """Marks aliases in a type as used. - - Recursively iterates over all subtypes in a jsdoc type annotation and - tracks usage of aliased symbols (which may be local variables). - Marks the local variable as used in the scope nearest to the current - scope that matches the given token. - - Args: - js_type: The jsdoc type, a typeannotation.TypeAnnotation object. - """ - if js_type.alias: - self._MarkLocalVariableUsed(js_type.identifier) - for sub_type in js_type.IterTypes(): - self._MarkAliasUsed(sub_type) - - def _MarkLocalVariableUsed(self, identifier): - """Marks the local variable as used in the relevant scope. - - Marks the local variable in the scope nearest to the current scope that - matches the given identifier as used. - - Args: - identifier: The identifier representing the potential usage of a local - variable. - """ - identifier = identifier.split('.', 1)[0] - # Find the first instance of the identifier in the stack of function scopes - # and mark it used. - for unused_local_variables in reversed( - self._unused_local_variables_by_scope): - if identifier in unused_local_variables: - del unused_local_variables[identifier] - break - - def _ReportMissingProvides(self, missing_provides, token, need_blank_line): - """Reports missing provide statements to the error handler. - - Args: - missing_provides: A dictionary of string(key) and integer(value) where - each string(key) is a namespace that should be provided, but is not - and integer(value) is first line number where it's required. - token: The token where the error was detected (also where the new provides - will be inserted. - need_blank_line: Whether a blank line needs to be inserted after the new - provides are inserted. May be True, False, or None, where None - indicates that the insert location is unknown. - """ - - missing_provides_msg = 'Missing the following goog.provide statements:\n' - missing_provides_msg += '\n'.join(['goog.provide(\'%s\');' % x for x in - sorted(missing_provides)]) - missing_provides_msg += '\n' - - missing_provides_msg += '\nFirst line where provided: \n' - missing_provides_msg += '\n'.join( - [' %s : line %d' % (x, missing_provides[x]) for x in - sorted(missing_provides)]) - missing_provides_msg += '\n' - - self._HandleError( - errors.MISSING_GOOG_PROVIDE, - missing_provides_msg, - token, position=Position.AtBeginning(), - fix_data=(missing_provides.keys(), need_blank_line)) - - def _ReportMissingRequires(self, missing_requires, token, need_blank_line): - """Reports missing require statements to the error handler. - - Args: - missing_requires: A dictionary of string(key) and integer(value) where - each string(key) is a namespace that should be required, but is not - and integer(value) is first line number where it's required. - token: The token where the error was detected (also where the new requires - will be inserted. - need_blank_line: Whether a blank line needs to be inserted before the new - requires are inserted. May be True, False, or None, where None - indicates that the insert location is unknown. - """ - - missing_requires_msg = 'Missing the following goog.require statements:\n' - missing_requires_msg += '\n'.join(['goog.require(\'%s\');' % x for x in - sorted(missing_requires)]) - missing_requires_msg += '\n' - - missing_requires_msg += '\nFirst line where required: \n' - missing_requires_msg += '\n'.join( - [' %s : line %d' % (x, missing_requires[x]) for x in - sorted(missing_requires)]) - missing_requires_msg += '\n' - - self._HandleError( - errors.MISSING_GOOG_REQUIRE, - missing_requires_msg, - token, position=Position.AtBeginning(), - fix_data=(missing_requires.keys(), need_blank_line)) - - def _ReportIllegalAliasStatement(self, illegal_alias_statements): - """Reports alias statements that would need a goog.require.""" - for namespace, token in illegal_alias_statements.iteritems(): - self._HandleError( - errors.ALIAS_STMT_NEEDS_GOOG_REQUIRE, - 'The alias definition would need the namespace \'%s\' which is not ' - 'required through any other symbol.' % namespace, - token, position=Position.AtBeginning()) - - def Finalize(self, state): - """Perform all checks that need to occur after all lines are processed.""" - # Call the base class's Finalize function. - super(JavaScriptLintRules, self).Finalize(state) - - if error_check.ShouldCheck(Rule.UNUSED_PRIVATE_MEMBERS): - # Report an error for any declared private member that was never used. - unused_private_members = (self._declared_private_members - - self._used_private_members) - - for variable in unused_private_members: - token = self._declared_private_member_tokens[variable] - self._HandleError(errors.UNUSED_PRIVATE_MEMBER, - 'Unused private member: %s.' % token.string, - token) - - # Clear state to prepare for the next file. - self._declared_private_member_tokens = {} - self._declared_private_members = set() - self._used_private_members = set() - - namespaces_info = self._namespaces_info - if namespaces_info is not None: - # If there are no provide or require statements, missing provides and - # requires should be reported on line 1. - if (not namespaces_info.GetProvidedNamespaces() and - not namespaces_info.GetRequiredNamespaces()): - missing_provides = namespaces_info.GetMissingProvides() - if missing_provides: - self._ReportMissingProvides( - missing_provides, state.GetFirstToken(), None) - - missing_requires, illegal_alias = namespaces_info.GetMissingRequires() - if missing_requires: - self._ReportMissingRequires( - missing_requires, state.GetFirstToken(), None) - if illegal_alias: - self._ReportIllegalAliasStatement(illegal_alias) - - self._CheckSortedRequiresProvides(state.GetFirstToken()) - - def _CheckSortedRequiresProvides(self, token): - """Checks that all goog.require and goog.provide statements are sorted. - - Note that this method needs to be run after missing statements are added to - preserve alphabetical order. - - Args: - token: The first token in the token stream. - """ - sorter = requireprovidesorter.RequireProvideSorter() - first_provide_token = sorter.CheckProvides(token) - if first_provide_token: - new_order = sorter.GetFixedProvideString(first_provide_token) - self._HandleError( - errors.GOOG_PROVIDES_NOT_ALPHABETIZED, - 'goog.provide classes must be alphabetized. The correct code is:\n' + - new_order, - first_provide_token, - position=Position.AtBeginning(), - fix_data=first_provide_token) - - first_require_token = sorter.CheckRequires(token) - if first_require_token: - new_order = sorter.GetFixedRequireString(first_require_token) - self._HandleError( - errors.GOOG_REQUIRES_NOT_ALPHABETIZED, - 'goog.require classes must be alphabetized. The correct code is:\n' + - new_order, - first_require_token, - position=Position.AtBeginning(), - fix_data=first_require_token) - - def GetLongLineExceptions(self): - """Gets a list of regexps for lines which can be longer than the limit. - - Returns: - A list of regexps, used as matches (rather than searches). - """ - return [ - re.compile(r'(var .+\s*=\s*)?goog\.require\(.+\);?\s*$'), - re.compile(r'goog\.(provide|module|setTestOnly)\(.+\);?\s*$'), - re.compile(r'[\s/*]*@visibility\s*{.*}[\s*/]*$'), - ] diff --git a/tools/closure_linter/closure_linter/javascriptstatetracker.py b/tools/closure_linter/closure_linter/javascriptstatetracker.py deleted file mode 100755 index e0a42f66a84aae..00000000000000 --- a/tools/closure_linter/closure_linter/javascriptstatetracker.py +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env python -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Parser for JavaScript files.""" - - - -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import tokenutil - -# Shorthand -Type = javascripttokens.JavaScriptTokenType - - -class JsDocFlag(statetracker.DocFlag): - """Javascript doc flag object. - - Attribute: - flag_type: param, return, define, type, etc. - flag_token: The flag token. - type_start_token: The first token specifying the flag JS type, - including braces. - type_end_token: The last token specifying the flag JS type, - including braces. - type: The type spec string. - jstype: The type spec, a TypeAnnotation instance. - name_token: The token specifying the flag name. - name: The flag name - description_start_token: The first token in the description. - description_end_token: The end token in the description. - description: The description. - """ - - # Please keep these lists alphabetized. - - # Some projects use the following extensions to JsDoc. - # TODO(robbyw): determine which of these, if any, should be illegal. - EXTENDED_DOC = frozenset([ - 'class', 'code', 'desc', 'final', 'hidden', 'inheritDoc', 'link', - 'meaning', 'provideGoog', 'throws']) - - LEGAL_DOC = EXTENDED_DOC | statetracker.DocFlag.LEGAL_DOC - - -class JavaScriptStateTracker(statetracker.StateTracker): - """JavaScript state tracker. - - Inherits from the core EcmaScript StateTracker adding extra state tracking - functionality needed for JavaScript. - """ - - def __init__(self): - """Initializes a JavaScript token stream state tracker.""" - statetracker.StateTracker.__init__(self, JsDocFlag) - - def Reset(self): - self._scope_depth = 0 - self._block_stack = [] - super(JavaScriptStateTracker, self).Reset() - - def InTopLevel(self): - """Compute whether we are at the top level in the class. - - This function call is language specific. In some languages like - JavaScript, a function is top level if it is not inside any parenthesis. - In languages such as ActionScript, a function is top level if it is directly - within a class. - - Returns: - Whether we are at the top level in the class. - """ - return self._scope_depth == self.ParenthesesDepth() - - def InFunction(self): - """Returns true if the current token is within a function. - - This js-specific override ignores goog.scope functions. - - Returns: - True if the current token is within a function. - """ - return self._scope_depth != self.FunctionDepth() - - def InNonScopeBlock(self): - """Compute whether we are nested within a non-goog.scope block. - - Returns: - True if the token is not enclosed in a block that does not originate from - a goog.scope statement. False otherwise. - """ - return self._scope_depth != self.BlockDepth() - - def GetBlockType(self, token): - """Determine the block type given a START_BLOCK token. - - Code blocks come after parameters, keywords like else, and closing parens. - - Args: - token: The current token. Can be assumed to be type START_BLOCK - Returns: - Code block type for current token. - """ - last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, reverse=True) - if last_code.type in (Type.END_PARAMETERS, Type.END_PAREN, - Type.KEYWORD) and not last_code.IsKeyword('return'): - return self.CODE - else: - return self.OBJECT_LITERAL - - def GetCurrentBlockStart(self): - """Gets the start token of current block. - - Returns: - Starting token of current block. None if not in block. - """ - if self._block_stack: - return self._block_stack[-1] - else: - return None - - def HandleToken(self, token, last_non_space_token): - """Handles the given token and updates state. - - Args: - token: The token to handle. - last_non_space_token: The last non space token encountered - """ - if token.type == Type.START_BLOCK: - self._block_stack.append(token) - if token.type == Type.IDENTIFIER and token.string == 'goog.scope': - self._scope_depth += 1 - if token.type == Type.END_BLOCK: - start_token = self._block_stack.pop() - if tokenutil.GoogScopeOrNoneFromStartBlock(start_token): - self._scope_depth -= 1 - super(JavaScriptStateTracker, self).HandleToken(token, - last_non_space_token) diff --git a/tools/closure_linter/closure_linter/javascriptstatetracker_test.py b/tools/closure_linter/closure_linter/javascriptstatetracker_test.py deleted file mode 100644 index 76dabd2c70d58a..00000000000000 --- a/tools/closure_linter/closure_linter/javascriptstatetracker_test.py +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the javascriptstatetracker module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - - -import unittest as googletest - -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - - -_FUNCTION_SCRIPT = """\ -var a = 3; - -function foo(aaa, bbb, ccc) { - var b = 4; -} - - -/** - * JSDoc comment. - */ -var bar = function(ddd, eee, fff) { - -}; - - -/** - * Verify that nested functions get their proper parameters recorded. - */ -var baz = function(ggg, hhh, iii) { - var qux = function(jjj, kkk, lll) { - }; - // make sure that entering a new block does not change baz' parameters. - {}; -}; - -""" - - -class FunctionTest(googletest.TestCase): - - def testFunctionParse(self): - functions, _ = testutil.ParseFunctionsAndComments(_FUNCTION_SCRIPT) - self.assertEquals(4, len(functions)) - - # First function - function = functions[0] - self.assertEquals(['aaa', 'bbb', 'ccc'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(3, start_token.line_number) - self.assertEquals(0, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(5, end_token.line_number) - self.assertEquals(0, end_token.start_index) - - self.assertEquals('foo', function.name) - - self.assertIsNone(function.doc) - - # Second function - function = functions[1] - self.assertEquals(['ddd', 'eee', 'fff'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(11, start_token.line_number) - self.assertEquals(10, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(13, end_token.line_number) - self.assertEquals(0, end_token.start_index) - - self.assertEquals('bar', function.name) - - self.assertIsNotNone(function.doc) - - # Check function JSDoc - doc = function.doc - doc_tokens = tokenutil.GetTokenRange(doc.start_token, doc.end_token) - - comment_type = javascripttokens.JavaScriptTokenType.COMMENT - comment_tokens = filter(lambda t: t.type is comment_type, doc_tokens) - - self.assertEquals('JSDoc comment.', - tokenutil.TokensToString(comment_tokens).strip()) - - # Third function - function = functions[2] - self.assertEquals(['ggg', 'hhh', 'iii'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(19, start_token.line_number) - self.assertEquals(10, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(24, end_token.line_number) - self.assertEquals(0, end_token.start_index) - - self.assertEquals('baz', function.name) - self.assertIsNotNone(function.doc) - - # Fourth function (inside third function) - function = functions[3] - self.assertEquals(['jjj', 'kkk', 'lll'], function.parameters) - - start_token = function.start_token - end_token = function.end_token - - self.assertEquals( - javascripttokens.JavaScriptTokenType.FUNCTION_DECLARATION, - function.start_token.type) - - self.assertEquals('function', start_token.string) - self.assertEquals(20, start_token.line_number) - self.assertEquals(12, start_token.start_index) - - self.assertEquals('}', end_token.string) - self.assertEquals(21, end_token.line_number) - self.assertEquals(2, end_token.start_index) - - self.assertEquals('qux', function.name) - self.assertIsNone(function.doc) - - - -class CommentTest(googletest.TestCase): - - def testGetDescription(self): - comment = self._ParseComment(""" - /** - * Comment targeting goog.foo. - * - * This is the second line. - * @param {number} foo The count of foo. - */ - target;""") - - self.assertEqual( - 'Comment targeting goog.foo.\n\nThis is the second line.', - comment.description) - - def testCommentGetTarget(self): - self.assertCommentTarget('goog.foo', """ - /** - * Comment targeting goog.foo. - */ - goog.foo = 6; - """) - - self.assertCommentTarget('bar', """ - /** - * Comment targeting bar. - */ - var bar = "Karate!"; - """) - - self.assertCommentTarget('doThing', """ - /** - * Comment targeting doThing. - */ - function doThing() {}; - """) - - self.assertCommentTarget('this.targetProperty', """ - goog.bar.Baz = function() { - /** - * Comment targeting targetProperty. - */ - this.targetProperty = 3; - }; - """) - - self.assertCommentTarget('goog.bar.prop', """ - /** - * Comment targeting goog.bar.prop. - */ - goog.bar.prop; - """) - - self.assertCommentTarget('goog.aaa.bbb', """ - /** - * Comment targeting goog.aaa.bbb. - */ - (goog.aaa.bbb) - """) - - self.assertCommentTarget('theTarget', """ - /** - * Comment targeting symbol preceded by newlines, whitespace, - * and parens -- things we ignore. - */ - (theTarget) - """) - - self.assertCommentTarget(None, """ - /** - * @fileoverview File overview. - */ - (notATarget) - """) - - self.assertCommentTarget(None, """ - /** - * Comment that doesn't find a target. - */ - """) - - self.assertCommentTarget('theTarget.is.split.across.lines', """ - /** - * Comment that addresses a symbol split across lines. - */ - (theTarget.is.split - .across.lines) - """) - - self.assertCommentTarget('theTarget.is.split.across.lines', """ - /** - * Comment that addresses a symbol split across lines. - */ - (theTarget.is.split. - across.lines) - """) - - def _ParseComment(self, script): - """Parse a script that contains one comment and return it.""" - _, comments = testutil.ParseFunctionsAndComments(script) - self.assertEquals(1, len(comments)) - return comments[0] - - def assertCommentTarget(self, target, script): - comment = self._ParseComment(script) - self.assertEquals(target, comment.GetTargetIdentifier()) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/javascripttokenizer.py b/tools/closure_linter/closure_linter/javascripttokenizer.py deleted file mode 100755 index 2ee5b81ee13c65..00000000000000 --- a/tools/closure_linter/closure_linter/javascripttokenizer.py +++ /dev/null @@ -1,463 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Regular expression based JavaScript parsing classes.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import copy -import re - -from closure_linter import javascripttokens -from closure_linter.common import matcher -from closure_linter.common import tokenizer - -# Shorthand -Type = javascripttokens.JavaScriptTokenType -Matcher = matcher.Matcher - - -class JavaScriptModes(object): - """Enumeration of the different matcher modes used for JavaScript.""" - TEXT_MODE = 'text' - SINGLE_QUOTE_STRING_MODE = 'single_quote_string' - DOUBLE_QUOTE_STRING_MODE = 'double_quote_string' - BLOCK_COMMENT_MODE = 'block_comment' - DOC_COMMENT_MODE = 'doc_comment' - DOC_COMMENT_LEX_SPACES_MODE = 'doc_comment_spaces' - LINE_COMMENT_MODE = 'line_comment' - PARAMETER_MODE = 'parameter' - FUNCTION_MODE = 'function' - - -class JavaScriptTokenizer(tokenizer.Tokenizer): - """JavaScript tokenizer. - - Convert JavaScript code in to an array of tokens. - """ - - # Useful patterns for JavaScript parsing. - IDENTIFIER_CHAR = r'A-Za-z0-9_$' - - # Number patterns based on: - # http://www.mozilla.org/js/language/js20-2000-07/formal/lexer-grammar.html - MANTISSA = r""" - (\d+(?!\.)) | # Matches '10' - (\d+\.(?!\d)) | # Matches '10.' - (\d*\.\d+) # Matches '.5' or '10.5' - """ - DECIMAL_LITERAL = r'(%s)([eE][-+]?\d+)?' % MANTISSA - HEX_LITERAL = r'0[xX][0-9a-fA-F]+' - NUMBER = re.compile(r""" - ((%s)|(%s)) - """ % (HEX_LITERAL, DECIMAL_LITERAL), re.VERBOSE) - - # Strings come in three parts - first we match the start of the string, then - # the contents, then the end. The contents consist of any character except a - # backslash or end of string, or a backslash followed by any character, or a - # backslash followed by end of line to support correct parsing of multi-line - # strings. - SINGLE_QUOTE = re.compile(r"'") - SINGLE_QUOTE_TEXT = re.compile(r"([^'\\]|\\(.|$))+") - DOUBLE_QUOTE = re.compile(r'"') - DOUBLE_QUOTE_TEXT = re.compile(r'([^"\\]|\\(.|$))+') - - START_SINGLE_LINE_COMMENT = re.compile(r'//') - END_OF_LINE_SINGLE_LINE_COMMENT = re.compile(r'//$') - - START_DOC_COMMENT = re.compile(r'/\*\*') - START_BLOCK_COMMENT = re.compile(r'/\*') - END_BLOCK_COMMENT = re.compile(r'\*/') - BLOCK_COMMENT_TEXT = re.compile(r'([^*]|\*(?!/))+') - - # Comment text is anything that we are not going to parse into another special - # token like (inline) flags or end comments. Complicated regex to match - # most normal characters, and '*', '{', '}', and '@' when we are sure that - # it is safe. Expression [^*{\s]@ must come first, or the other options will - # match everything before @, and we won't match @'s that aren't part of flags - # like in email addresses in the @author tag. - DOC_COMMENT_TEXT = re.compile(r'([^*{}\s]@|[^*{}@]|\*(?!/))+') - DOC_COMMENT_NO_SPACES_TEXT = re.compile(r'([^*{}\s]@|[^*{}@\s]|\*(?!/))+') - # Match anything that is allowed in a type definition, except for tokens - # needed to parse it (and the lookahead assertion for "*/"). - DOC_COMMENT_TYPE_TEXT = re.compile(r'([^*|!?=<>(){}:,\s]|\*(?!/))+') - - # Match the prefix ' * ' that starts every line of jsdoc. Want to include - # spaces after the '*', but nothing else that occurs after a '*', and don't - # want to match the '*' in '*/'. - DOC_PREFIX = re.compile(r'\s*\*(\s+|(?!/))') - - START_BLOCK = re.compile('{') - END_BLOCK = re.compile('}') - - REGEX_CHARACTER_CLASS = r""" - \[ # Opening bracket - ([^\]\\]|\\.)* # Anything but a ] or \, - # or a backslash followed by anything - \] # Closing bracket - """ - # We ensure the regex is followed by one of the above tokens to avoid - # incorrectly parsing something like x / y / z as x REGEX(/ y /) z - POST_REGEX_LIST = [ - ';', ',', r'\.', r'\)', r'\]', '$', r'\/\/', r'\/\*', ':', '}'] - - REGEX = re.compile(r""" - / # opening slash - (?!\*) # not the start of a comment - (\\.|[^\[\/\\]|(%s))* # a backslash followed by anything, - # or anything but a / or [ or \, - # or a character class - / # closing slash - [gimsx]* # optional modifiers - (?=\s*(%s)) - """ % (REGEX_CHARACTER_CLASS, '|'.join(POST_REGEX_LIST)), - re.VERBOSE) - - ANYTHING = re.compile(r'.*') - PARAMETERS = re.compile(r'[^\)]+') - CLOSING_PAREN_WITH_SPACE = re.compile(r'\)\s*') - - FUNCTION_DECLARATION = re.compile(r'\bfunction\b') - - OPENING_PAREN = re.compile(r'\(') - CLOSING_PAREN = re.compile(r'\)') - - OPENING_BRACKET = re.compile(r'\[') - CLOSING_BRACKET = re.compile(r'\]') - - # We omit these JS keywords from the list: - # function - covered by FUNCTION_DECLARATION. - # delete, in, instanceof, new, typeof - included as operators. - # this - included in identifiers. - # null, undefined - not included, should go in some "special constant" list. - KEYWORD_LIST = [ - 'break', - 'case', - 'catch', - 'continue', - 'default', - 'do', - 'else', - 'finally', - 'for', - 'if', - 'return', - 'switch', - 'throw', - 'try', - 'var', - 'while', - 'with', - ] - - # List of regular expressions to match as operators. Some notes: for our - # purposes, the comma behaves similarly enough to a normal operator that we - # include it here. r'\bin\b' actually matches 'in' surrounded by boundary - # characters - this may not match some very esoteric uses of the in operator. - # Operators that are subsets of larger operators must come later in this list - # for proper matching, e.g., '>>' must come AFTER '>>>'. - OPERATOR_LIST = [ - ',', - r'\+\+', - '===', - '!==', - '>>>=', - '>>>', - '==', - '>=', - '<=', - '!=', - '<<=', - '>>=', - '<<', - '>>', - '=>', - '>', - '<', - r'\+=', - r'\+', - '--', - r'\^=', - '-=', - '-', - '/=', - '/', - r'\*=', - r'\*', - '%=', - '%', - '&&', - r'\|\|', - '&=', - '&', - r'\|=', - r'\|', - '=', - '!', - ':', - r'\?', - r'\^', - r'\bdelete\b', - r'\bin\b', - r'\binstanceof\b', - r'\bnew\b', - r'\btypeof\b', - r'\bvoid\b', - r'\.', - ] - OPERATOR = re.compile('|'.join(OPERATOR_LIST)) - - WHITESPACE = re.compile(r'\s+') - SEMICOLON = re.compile(r';') - # Technically JavaScript identifiers can't contain '.', but we treat a set of - # nested identifiers as a single identifier, except for trailing dots. - NESTED_IDENTIFIER = r'[a-zA-Z_$]([%s]|\.[a-zA-Z_$])*' % IDENTIFIER_CHAR - IDENTIFIER = re.compile(NESTED_IDENTIFIER) - - SIMPLE_LVALUE = re.compile(r""" - (?P%s) # a valid identifier - (?=\s* # optional whitespace - \= # look ahead to equal sign - (?!=)) # not follwed by equal - """ % NESTED_IDENTIFIER, re.VERBOSE) - - # A doc flag is a @ sign followed by non-space characters that appears at the - # beginning of the line, after whitespace, or after a '{'. The look-behind - # check is necessary to not match someone@google.com as a flag. - DOC_FLAG = re.compile(r'(^|(?<=\s))@(?P[a-zA-Z]+)') - # To properly parse parameter names and complex doctypes containing - # whitespace, we need to tokenize whitespace into a token after certain - # doctags. All statetracker.HAS_TYPE that are not listed here must not contain - # any whitespace in their types. - DOC_FLAG_LEX_SPACES = re.compile( - r'(^|(?<=\s))@(?P%s)\b' % - '|'.join([ - 'const', - 'enum', - 'extends', - 'final', - 'implements', - 'param', - 'private', - 'protected', - 'public', - 'return', - 'type', - 'typedef' - ])) - - DOC_INLINE_FLAG = re.compile(r'(?<={)@(?P[a-zA-Z]+)') - - DOC_TYPE_BLOCK_START = re.compile(r'[<(]') - DOC_TYPE_BLOCK_END = re.compile(r'[>)]') - DOC_TYPE_MODIFIERS = re.compile(r'[!?|,:=]') - - # Star followed by non-slash, i.e a star that does not end a comment. - # This is used for TYPE_GROUP below. - SAFE_STAR = r'(\*(?!/))' - - COMMON_DOC_MATCHERS = [ - # Find the end of the comment. - Matcher(END_BLOCK_COMMENT, Type.END_DOC_COMMENT, - JavaScriptModes.TEXT_MODE), - - # Tokenize documented flags like @private. - Matcher(DOC_INLINE_FLAG, Type.DOC_INLINE_FLAG), - Matcher(DOC_FLAG_LEX_SPACES, Type.DOC_FLAG, - JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE), - - # Encountering a doc flag should leave lex spaces mode. - Matcher(DOC_FLAG, Type.DOC_FLAG, JavaScriptModes.DOC_COMMENT_MODE), - - # Tokenize braces so we can find types. - Matcher(START_BLOCK, Type.DOC_START_BRACE), - Matcher(END_BLOCK, Type.DOC_END_BRACE), - - # And some more to parse types. - Matcher(DOC_TYPE_BLOCK_START, Type.DOC_TYPE_START_BLOCK), - Matcher(DOC_TYPE_BLOCK_END, Type.DOC_TYPE_END_BLOCK), - - Matcher(DOC_TYPE_MODIFIERS, Type.DOC_TYPE_MODIFIER), - Matcher(DOC_COMMENT_TYPE_TEXT, Type.COMMENT), - - Matcher(DOC_PREFIX, Type.DOC_PREFIX, None, True)] - - # When text is not matched, it is given this default type based on mode. - # If unspecified in this map, the default default is Type.NORMAL. - JAVASCRIPT_DEFAULT_TYPES = { - JavaScriptModes.DOC_COMMENT_MODE: Type.COMMENT, - JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: Type.COMMENT - } - - @classmethod - def BuildMatchers(cls): - """Builds the token matcher group. - - The token matcher groups work as follows: it is a list of Matcher objects. - The matchers will be tried in this order, and the first to match will be - returned. Hence the order is important because the matchers that come first - overrule the matchers that come later. - - Returns: - The completed token matcher group. - """ - # Match a keyword string followed by a non-identifier character in order to - # not match something like doSomething as do + Something. - keyword = re.compile('(%s)((?=[^%s])|$)' % ( - '|'.join(cls.KEYWORD_LIST), cls.IDENTIFIER_CHAR)) - return { - - # Matchers for basic text mode. - JavaScriptModes.TEXT_MODE: [ - # Check a big group - strings, starting comments, and regexes - all - # of which could be intertwined. 'string with /regex/', - # /regex with 'string'/, /* comment with /regex/ and string */ (and - # so on) - Matcher(cls.START_DOC_COMMENT, Type.START_DOC_COMMENT, - JavaScriptModes.DOC_COMMENT_MODE), - Matcher(cls.START_BLOCK_COMMENT, Type.START_BLOCK_COMMENT, - JavaScriptModes.BLOCK_COMMENT_MODE), - Matcher(cls.END_OF_LINE_SINGLE_LINE_COMMENT, - Type.START_SINGLE_LINE_COMMENT), - Matcher(cls.START_SINGLE_LINE_COMMENT, - Type.START_SINGLE_LINE_COMMENT, - JavaScriptModes.LINE_COMMENT_MODE), - Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_START, - JavaScriptModes.SINGLE_QUOTE_STRING_MODE), - Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_START, - JavaScriptModes.DOUBLE_QUOTE_STRING_MODE), - Matcher(cls.REGEX, Type.REGEX), - - # Next we check for start blocks appearing outside any of the items - # above. - Matcher(cls.START_BLOCK, Type.START_BLOCK), - Matcher(cls.END_BLOCK, Type.END_BLOCK), - - # Then we search for function declarations. - Matcher(cls.FUNCTION_DECLARATION, Type.FUNCTION_DECLARATION, - JavaScriptModes.FUNCTION_MODE), - - # Next, we convert non-function related parens to tokens. - Matcher(cls.OPENING_PAREN, Type.START_PAREN), - Matcher(cls.CLOSING_PAREN, Type.END_PAREN), - - # Next, we convert brackets to tokens. - Matcher(cls.OPENING_BRACKET, Type.START_BRACKET), - Matcher(cls.CLOSING_BRACKET, Type.END_BRACKET), - - # Find numbers. This has to happen before operators because - # scientific notation numbers can have + and - in them. - Matcher(cls.NUMBER, Type.NUMBER), - - # Find operators and simple assignments - Matcher(cls.SIMPLE_LVALUE, Type.SIMPLE_LVALUE), - Matcher(cls.OPERATOR, Type.OPERATOR), - - # Find key words and whitespace. - Matcher(keyword, Type.KEYWORD), - Matcher(cls.WHITESPACE, Type.WHITESPACE), - - # Find identifiers. - Matcher(cls.IDENTIFIER, Type.IDENTIFIER), - - # Finally, we convert semicolons to tokens. - Matcher(cls.SEMICOLON, Type.SEMICOLON)], - - # Matchers for single quote strings. - JavaScriptModes.SINGLE_QUOTE_STRING_MODE: [ - Matcher(cls.SINGLE_QUOTE_TEXT, Type.STRING_TEXT), - Matcher(cls.SINGLE_QUOTE, Type.SINGLE_QUOTE_STRING_END, - JavaScriptModes.TEXT_MODE)], - - # Matchers for double quote strings. - JavaScriptModes.DOUBLE_QUOTE_STRING_MODE: [ - Matcher(cls.DOUBLE_QUOTE_TEXT, Type.STRING_TEXT), - Matcher(cls.DOUBLE_QUOTE, Type.DOUBLE_QUOTE_STRING_END, - JavaScriptModes.TEXT_MODE)], - - # Matchers for block comments. - JavaScriptModes.BLOCK_COMMENT_MODE: [ - # First we check for exiting a block comment. - Matcher(cls.END_BLOCK_COMMENT, Type.END_BLOCK_COMMENT, - JavaScriptModes.TEXT_MODE), - - # Match non-comment-ending text.. - Matcher(cls.BLOCK_COMMENT_TEXT, Type.COMMENT)], - - # Matchers for doc comments. - JavaScriptModes.DOC_COMMENT_MODE: cls.COMMON_DOC_MATCHERS + [ - Matcher(cls.DOC_COMMENT_TEXT, Type.COMMENT)], - - JavaScriptModes.DOC_COMMENT_LEX_SPACES_MODE: cls.COMMON_DOC_MATCHERS + [ - Matcher(cls.WHITESPACE, Type.COMMENT), - Matcher(cls.DOC_COMMENT_NO_SPACES_TEXT, Type.COMMENT)], - - # Matchers for single line comments. - JavaScriptModes.LINE_COMMENT_MODE: [ - # We greedy match until the end of the line in line comment mode. - Matcher(cls.ANYTHING, Type.COMMENT, JavaScriptModes.TEXT_MODE)], - - # Matchers for code after the function keyword. - JavaScriptModes.FUNCTION_MODE: [ - # Must match open paren before anything else and move into parameter - # mode, otherwise everything inside the parameter list is parsed - # incorrectly. - Matcher(cls.OPENING_PAREN, Type.START_PARAMETERS, - JavaScriptModes.PARAMETER_MODE), - Matcher(cls.WHITESPACE, Type.WHITESPACE), - Matcher(cls.IDENTIFIER, Type.FUNCTION_NAME)], - - # Matchers for function parameters - JavaScriptModes.PARAMETER_MODE: [ - # When in function parameter mode, a closing paren is treated - # specially. Everything else is treated as lines of parameters. - Matcher(cls.CLOSING_PAREN_WITH_SPACE, Type.END_PARAMETERS, - JavaScriptModes.TEXT_MODE), - Matcher(cls.PARAMETERS, Type.PARAMETERS, - JavaScriptModes.PARAMETER_MODE)]} - - def __init__(self, parse_js_doc=True): - """Create a tokenizer object. - - Args: - parse_js_doc: Whether to do detailed parsing of javascript doc comments, - or simply treat them as normal comments. Defaults to parsing JsDoc. - """ - matchers = self.BuildMatchers() - if not parse_js_doc: - # Make a copy so the original doesn't get modified. - matchers = copy.deepcopy(matchers) - matchers[JavaScriptModes.DOC_COMMENT_MODE] = matchers[ - JavaScriptModes.BLOCK_COMMENT_MODE] - - tokenizer.Tokenizer.__init__(self, JavaScriptModes.TEXT_MODE, matchers, - self.JAVASCRIPT_DEFAULT_TYPES) - - def _CreateToken(self, string, token_type, line, line_number, values=None): - """Creates a new JavaScriptToken object. - - Args: - string: The string of input the token contains. - token_type: The type of token. - line: The text of the line this token is in. - line_number: The line number of the token. - values: A dict of named values within the token. For instance, a - function declaration may have a value called 'name' which captures the - name of the function. - """ - return javascripttokens.JavaScriptToken(string, token_type, line, - line_number, values, line_number) diff --git a/tools/closure_linter/closure_linter/javascripttokens.py b/tools/closure_linter/closure_linter/javascripttokens.py deleted file mode 100755 index f5815d2bf86119..00000000000000 --- a/tools/closure_linter/closure_linter/javascripttokens.py +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Classes to represent JavaScript tokens.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -from closure_linter.common import tokens - -class JavaScriptTokenType(tokens.TokenType): - """Enumeration of JavaScript token types, and useful sets of token types.""" - NUMBER = 'number' - START_SINGLE_LINE_COMMENT = '//' - START_BLOCK_COMMENT = '/*' - START_DOC_COMMENT = '/**' - END_BLOCK_COMMENT = '*/' - END_DOC_COMMENT = 'doc */' - COMMENT = 'comment' - SINGLE_QUOTE_STRING_START = "'string" - SINGLE_QUOTE_STRING_END = "string'" - DOUBLE_QUOTE_STRING_START = '"string' - DOUBLE_QUOTE_STRING_END = 'string"' - STRING_TEXT = 'string' - START_BLOCK = '{' - END_BLOCK = '}' - START_PAREN = '(' - END_PAREN = ')' - START_BRACKET = '[' - END_BRACKET = ']' - REGEX = '/regex/' - FUNCTION_DECLARATION = 'function(...)' - FUNCTION_NAME = 'function functionName(...)' - START_PARAMETERS = 'startparams(' - PARAMETERS = 'pa,ra,ms' - END_PARAMETERS = ')endparams' - SEMICOLON = ';' - DOC_FLAG = '@flag' - DOC_INLINE_FLAG = '{@flag ...}' - DOC_START_BRACE = 'doc {' - DOC_END_BRACE = 'doc }' - DOC_PREFIX = 'comment prefix: * ' - DOC_TYPE_START_BLOCK = 'Type <' - DOC_TYPE_END_BLOCK = 'Type >' - DOC_TYPE_MODIFIER = 'modifier' - SIMPLE_LVALUE = 'lvalue=' - KEYWORD = 'keyword' - OPERATOR = 'operator' - IDENTIFIER = 'identifier' - - STRING_TYPES = frozenset([ - SINGLE_QUOTE_STRING_START, SINGLE_QUOTE_STRING_END, - DOUBLE_QUOTE_STRING_START, DOUBLE_QUOTE_STRING_END, STRING_TEXT]) - - COMMENT_TYPES = frozenset([ - START_SINGLE_LINE_COMMENT, COMMENT, - START_BLOCK_COMMENT, START_DOC_COMMENT, - END_BLOCK_COMMENT, END_DOC_COMMENT, - DOC_START_BRACE, DOC_END_BRACE, - DOC_FLAG, DOC_INLINE_FLAG, DOC_PREFIX, - DOC_TYPE_START_BLOCK, DOC_TYPE_END_BLOCK, DOC_TYPE_MODIFIER]) - - FLAG_DESCRIPTION_TYPES = frozenset([ - DOC_INLINE_FLAG, COMMENT, DOC_START_BRACE, DOC_END_BRACE, - DOC_TYPE_START_BLOCK, DOC_TYPE_END_BLOCK, DOC_TYPE_MODIFIER]) - - FLAG_ENDING_TYPES = frozenset([DOC_FLAG, END_DOC_COMMENT]) - - NON_CODE_TYPES = COMMENT_TYPES | frozenset([ - tokens.TokenType.WHITESPACE, tokens.TokenType.BLANK_LINE]) - - UNARY_OPERATORS = ['!', 'new', 'delete', 'typeof', 'void'] - - UNARY_OK_OPERATORS = ['--', '++', '-', '+'] + UNARY_OPERATORS - - UNARY_POST_OPERATORS = ['--', '++'] - - # An expression ender is any token that can end an object - i.e. we could have - # x.y or [1, 2], or (10 + 9) or {a: 10}. - EXPRESSION_ENDER_TYPES = [tokens.TokenType.NORMAL, IDENTIFIER, NUMBER, - SIMPLE_LVALUE, END_BRACKET, END_PAREN, END_BLOCK, - SINGLE_QUOTE_STRING_END, DOUBLE_QUOTE_STRING_END] - - -class JavaScriptToken(tokens.Token): - """JavaScript token subclass of Token, provides extra instance checks. - - The following token types have data in attached_object: - - All JsDoc flags: a parser.JsDocFlag object. - """ - - def IsKeyword(self, keyword): - """Tests if this token is the given keyword. - - Args: - keyword: The keyword to compare to. - - Returns: - True if this token is a keyword token with the given name. - """ - return self.type == JavaScriptTokenType.KEYWORD and self.string == keyword - - def IsOperator(self, operator): - """Tests if this token is the given operator. - - Args: - operator: The operator to compare to. - - Returns: - True if this token is a operator token with the given name. - """ - return self.type == JavaScriptTokenType.OPERATOR and self.string == operator - - def IsAssignment(self): - """Tests if this token is an assignment operator. - - Returns: - True if this token is an assignment operator. - """ - return (self.type == JavaScriptTokenType.OPERATOR and - self.string.endswith('=') and - self.string not in ('==', '!=', '>=', '<=', '===', '!==')) - - def IsComment(self): - """Tests if this token is any part of a comment. - - Returns: - True if this token is any part of a comment. - """ - return self.type in JavaScriptTokenType.COMMENT_TYPES - - def IsCode(self): - """Tests if this token is code, as opposed to a comment or whitespace.""" - return self.type not in JavaScriptTokenType.NON_CODE_TYPES - - def __repr__(self): - return '' % (self.line_number, - self.type, self.string, - self.values, - self.metadata) diff --git a/tools/closure_linter/closure_linter/not_strict_test.py b/tools/closure_linter/closure_linter/not_strict_test.py deleted file mode 100755 index c92c13ee031e1b..00000000000000 --- a/tools/closure_linter/closure_linter/not_strict_test.py +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for gjslint --nostrict. - -Tests errors that can be thrown by gjslint when not in strict mode. -""" - - - -import os -import sys -import unittest - -import gflags as flags -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import filetestcase - -_RESOURCE_PREFIX = 'closure_linter/testdata' - -flags.FLAGS.strict = False -flags.FLAGS.custom_jsdoc_tags = ('customtag', 'requires') -flags.FLAGS.closurized_namespaces = ('goog', 'dummy') -flags.FLAGS.limited_doc_files = ('externs.js', 'dummy.js', - 'limited_doc_checks.js') - - -# List of files under testdata to test. -# We need to list files explicitly since pyglib can't list directories. -_TEST_FILES = [ - 'not_strict.js' - ] - - -class GJsLintTestSuite(unittest.TestSuite): - """Test suite to run a GJsLintTest for each of several files. - - If sys.argv[1:] is non-empty, it is interpreted as a list of filenames in - testdata to test. Otherwise, _TEST_FILES is used. - """ - - def __init__(self, tests=()): - unittest.TestSuite.__init__(self, tests) - - argv = sys.argv and sys.argv[1:] or [] - if argv: - test_files = argv - else: - test_files = _TEST_FILES - for test_file in test_files: - resource_path = os.path.join(_RESOURCE_PREFIX, test_file) - self.addTest(filetestcase.AnnotatedFileTestCase(resource_path, - runner.Run, - errors.ByName)) - -if __name__ == '__main__': - # Don't let main parse args; it happens in the TestSuite. - googletest.main(argv=sys.argv[0:1], defaultTest='GJsLintTestSuite') diff --git a/tools/closure_linter/closure_linter/requireprovidesorter.py b/tools/closure_linter/closure_linter/requireprovidesorter.py deleted file mode 100755 index e7e08a13c2946f..00000000000000 --- a/tools/closure_linter/closure_linter/requireprovidesorter.py +++ /dev/null @@ -1,329 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Contains logic for sorting goog.provide and goog.require statements. - -Closurized JavaScript files use goog.provide and goog.require statements at the -top of the file to manage dependencies. These statements should be sorted -alphabetically, however, it is common for them to be accompanied by inline -comments or suppression annotations. In order to sort these statements without -disrupting their comments and annotations, the association between statements -and comments/annotations must be maintained while sorting. - - RequireProvideSorter: Handles checking/fixing of provide/require statements. -""" - - - -from closure_linter import javascripttokens -from closure_linter import tokenutil - -# Shorthand -Type = javascripttokens.JavaScriptTokenType - - -class RequireProvideSorter(object): - """Checks for and fixes alphabetization of provide and require statements. - - When alphabetizing, comments on the same line or comments directly above a - goog.provide or goog.require statement are associated with that statement and - stay with the statement as it gets sorted. - """ - - def CheckProvides(self, token): - """Checks alphabetization of goog.provide statements. - - Iterates over tokens in given token stream, identifies goog.provide tokens, - and checks that they occur in alphabetical order by the object being - provided. - - Args: - token: A token in the token stream before any goog.provide tokens. - - Returns: - The first provide token in the token stream. - - None is returned if all goog.provide statements are already sorted. - """ - provide_tokens = self._GetRequireOrProvideTokens(token, 'goog.provide') - provide_strings = self._GetRequireOrProvideTokenStrings(provide_tokens) - sorted_provide_strings = sorted(provide_strings) - if provide_strings != sorted_provide_strings: - return provide_tokens[0] - return None - - def CheckRequires(self, token): - """Checks alphabetization of goog.require statements. - - Iterates over tokens in given token stream, identifies goog.require tokens, - and checks that they occur in alphabetical order by the dependency being - required. - - Args: - token: A token in the token stream before any goog.require tokens. - - Returns: - The first require token in the token stream. - - None is returned if all goog.require statements are already sorted. - """ - require_tokens = self._GetRequireOrProvideTokens(token, 'goog.require') - require_strings = self._GetRequireOrProvideTokenStrings(require_tokens) - sorted_require_strings = sorted(require_strings) - if require_strings != sorted_require_strings: - return require_tokens[0] - return None - - def FixProvides(self, token): - """Sorts goog.provide statements in the given token stream alphabetically. - - Args: - token: The first token in the token stream. - """ - self._FixProvidesOrRequires( - self._GetRequireOrProvideTokens(token, 'goog.provide')) - - def FixRequires(self, token): - """Sorts goog.require statements in the given token stream alphabetically. - - Args: - token: The first token in the token stream. - """ - self._FixProvidesOrRequires( - self._GetRequireOrProvideTokens(token, 'goog.require')) - - def _FixProvidesOrRequires(self, tokens): - """Sorts goog.provide or goog.require statements. - - Args: - tokens: A list of goog.provide or goog.require tokens in the order they - appear in the token stream. i.e. the first token in this list must - be the first goog.provide or goog.require token. - """ - strings = self._GetRequireOrProvideTokenStrings(tokens) - sorted_strings = sorted(strings) - - # Make a separate pass to remove any blank lines between goog.require/ - # goog.provide tokens. - first_token = tokens[0] - last_token = tokens[-1] - i = last_token - while i != first_token and i is not None: - if i.type is Type.BLANK_LINE: - tokenutil.DeleteToken(i) - i = i.previous - - # A map from required/provided object name to tokens that make up the line - # it was on, including any comments immediately before it or after it on the - # same line. - tokens_map = self._GetTokensMap(tokens) - - # Iterate over the map removing all tokens. - for name in tokens_map: - tokens_to_delete = tokens_map[name] - for i in tokens_to_delete: - tokenutil.DeleteToken(i) - - # Save token to rest of file. Sorted token will be inserted before this. - rest_of_file = tokens_map[strings[-1]][-1].next - - # Re-add all tokens in the map in alphabetical order. - insert_after = tokens[0].previous - for string in sorted_strings: - for i in tokens_map[string]: - if rest_of_file: - tokenutil.InsertTokenBefore(i, rest_of_file) - else: - tokenutil.InsertTokenAfter(i, insert_after) - insert_after = i - - def _GetRequireOrProvideTokens(self, token, token_string): - """Gets all goog.provide or goog.require tokens in the given token stream. - - Args: - token: The first token in the token stream. - token_string: One of 'goog.provide' or 'goog.require' to indicate which - tokens to find. - - Returns: - A list of goog.provide or goog.require tokens in the order they appear in - the token stream. - """ - tokens = [] - while token: - if token.type == Type.IDENTIFIER: - if token.string == token_string: - tokens.append(token) - elif token.string not in [ - 'goog.provide', 'goog.require', 'goog.setTestOnly']: - # These 3 identifiers are at the top of the file. So if any other - # identifier is encountered, return. - # TODO(user): Once it's decided what ordering goog.require - # should use, add 'goog.module' to the list above and implement the - # decision. - break - token = token.next - - return tokens - - def _GetRequireOrProvideTokenStrings(self, tokens): - """Gets a list of strings corresponding to the given list of tokens. - - The string will be the next string in the token stream after each token in - tokens. This is used to find the object being provided/required by a given - goog.provide or goog.require token. - - Args: - tokens: A list of goog.provide or goog.require tokens. - - Returns: - A list of object names that are being provided or required by the given - list of tokens. For example: - - ['object.a', 'object.c', 'object.b'] - """ - token_strings = [] - for token in tokens: - if not token.is_deleted: - name = tokenutil.GetStringAfterToken(token) - token_strings.append(name) - return token_strings - - def _GetTokensMap(self, tokens): - """Gets a map from object name to tokens associated with that object. - - Starting from the goog.provide/goog.require token, searches backwards in the - token stream for any lines that start with a comment. These lines are - associated with the goog.provide/goog.require token. Also associates any - tokens on the same line as the goog.provide/goog.require token with that - token. - - Args: - tokens: A list of goog.provide or goog.require tokens. - - Returns: - A dictionary that maps object names to the tokens associated with the - goog.provide or goog.require of that object name. For example: - - { - 'object.a': [JavaScriptToken, JavaScriptToken, ...], - 'object.b': [...] - } - - The list of tokens includes any comment lines above the goog.provide or - goog.require statement and everything after the statement on the same - line. For example, all of the following would be associated with - 'object.a': - - /** @suppress {extraRequire} */ - goog.require('object.a'); // Some comment. - """ - tokens_map = {} - for token in tokens: - object_name = tokenutil.GetStringAfterToken(token) - # If the previous line starts with a comment, presume that the comment - # relates to the goog.require or goog.provide and keep them together when - # sorting. - first_token = token - previous_first_token = tokenutil.GetFirstTokenInPreviousLine(first_token) - while (previous_first_token and - previous_first_token.IsAnyType(Type.COMMENT_TYPES)): - first_token = previous_first_token - previous_first_token = tokenutil.GetFirstTokenInPreviousLine( - first_token) - - # Find the last token on the line. - last_token = tokenutil.GetLastTokenInSameLine(token) - - all_tokens = self._GetTokenList(first_token, last_token) - tokens_map[object_name] = all_tokens - return tokens_map - - def _GetTokenList(self, first_token, last_token): - """Gets a list of all tokens from first_token to last_token, inclusive. - - Args: - first_token: The first token to get. - last_token: The last token to get. - - Returns: - A list of all tokens between first_token and last_token, including both - first_token and last_token. - - Raises: - Exception: If the token stream ends before last_token is reached. - """ - token_list = [] - token = first_token - while token != last_token: - if not token: - raise Exception('ran out of tokens') - token_list.append(token) - token = token.next - token_list.append(last_token) - - return token_list - - def GetFixedRequireString(self, token): - """Get fixed/sorted order of goog.require statements. - - Args: - token: The first token in the token stream. - - Returns: - A string for correct sorted order of goog.require. - """ - return self._GetFixedRequireOrProvideString( - self._GetRequireOrProvideTokens(token, 'goog.require')) - - def GetFixedProvideString(self, token): - """Get fixed/sorted order of goog.provide statements. - - Args: - token: The first token in the token stream. - - Returns: - A string for correct sorted order of goog.provide. - """ - return self._GetFixedRequireOrProvideString( - self._GetRequireOrProvideTokens(token, 'goog.provide')) - - def _GetFixedRequireOrProvideString(self, tokens): - """Sorts goog.provide or goog.require statements. - - Args: - tokens: A list of goog.provide or goog.require tokens in the order they - appear in the token stream. i.e. the first token in this list must - be the first goog.provide or goog.require token. - - Returns: - A string for sorted goog.require or goog.provide statements - """ - - # A map from required/provided object name to tokens that make up the line - # it was on, including any comments immediately before it or after it on the - # same line. - tokens_map = self._GetTokensMap(tokens) - sorted_strings = sorted(tokens_map.keys()) - - new_order = '' - for string in sorted_strings: - for i in tokens_map[string]: - new_order += i.string - if i.IsLastInLine(): - new_order += '\n' - - return new_order diff --git a/tools/closure_linter/closure_linter/requireprovidesorter_test.py b/tools/closure_linter/closure_linter/requireprovidesorter_test.py deleted file mode 100644 index fecb6d04dad9ce..00000000000000 --- a/tools/closure_linter/closure_linter/requireprovidesorter_test.py +++ /dev/null @@ -1,155 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for RequireProvideSorter.""" - - - -import unittest as googletest -from closure_linter import javascripttokens -from closure_linter import requireprovidesorter -from closure_linter import testutil - -# pylint: disable=g-bad-name -TokenType = javascripttokens.JavaScriptTokenType - - -class RequireProvideSorterTest(googletest.TestCase): - """Tests for RequireProvideSorter.""" - - def testGetFixedProvideString(self): - """Tests that fixed string constains proper comments also.""" - input_lines = [ - 'goog.provide(\'package.xyz\');', - '/** @suppress {extraprovide} **/', - 'goog.provide(\'package.abcd\');' - ] - - expected_lines = [ - '/** @suppress {extraprovide} **/', - 'goog.provide(\'package.abcd\');', - 'goog.provide(\'package.xyz\');' - ] - - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - fixed_provide_string = sorter.GetFixedProvideString(token) - - self.assertEquals(expected_lines, fixed_provide_string.splitlines()) - - def testGetFixedRequireString(self): - """Tests that fixed string constains proper comments also.""" - input_lines = [ - 'goog.require(\'package.xyz\');', - '/** This is needed for scope. **/', - 'goog.require(\'package.abcd\');' - ] - - expected_lines = [ - '/** This is needed for scope. **/', - 'goog.require(\'package.abcd\');', - 'goog.require(\'package.xyz\');' - ] - - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - fixed_require_string = sorter.GetFixedRequireString(token) - - self.assertEquals(expected_lines, fixed_require_string.splitlines()) - - def testFixRequires_removeBlankLines(self): - """Tests that blank lines are omitted in sorted goog.require statements.""" - input_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassB\');', - '', - 'goog.require(\'package.subpackage.ClassA\');' - ] - expected_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassA\');', - 'goog.require(\'package.subpackage.ClassB\');' - ] - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixRequires(token) - - self.assertEquals(expected_lines, self._GetLines(token)) - - def fixRequiresTest_withTestOnly(self, position): - """Regression-tests sorting even with a goog.setTestOnly statement. - - Args: - position: The position in the list where to insert the goog.setTestOnly - statement. Will be used to test all possible combinations for - this test. - """ - input_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassB\');', - 'goog.require(\'package.subpackage.ClassA\');' - ] - expected_lines = [ - 'goog.provide(\'package.subpackage.Whatever\');', - '', - 'goog.require(\'package.subpackage.ClassA\');', - 'goog.require(\'package.subpackage.ClassB\');' - ] - input_lines.insert(position, 'goog.setTestOnly();') - expected_lines.insert(position, 'goog.setTestOnly();') - - token = testutil.TokenizeSourceAndRunEcmaPass(input_lines) - - sorter = requireprovidesorter.RequireProvideSorter() - sorter.FixRequires(token) - - self.assertEquals(expected_lines, self._GetLines(token)) - - def testFixRequires_withTestOnly(self): - """Regression-tests sorting even after a goog.setTestOnly statement.""" - - # goog.setTestOnly at first line. - self.fixRequiresTest_withTestOnly(position=0) - - # goog.setTestOnly after goog.provide. - self.fixRequiresTest_withTestOnly(position=1) - - # goog.setTestOnly before goog.require. - self.fixRequiresTest_withTestOnly(position=2) - - # goog.setTestOnly after goog.require. - self.fixRequiresTest_withTestOnly(position=4) - - def _GetLines(self, token): - """Returns an array of lines based on the specified token stream.""" - lines = [] - line = '' - while token: - line += token.string - if token.IsLastInLine(): - lines.append(line) - line = '' - token = token.next - return lines - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/runner.py b/tools/closure_linter/closure_linter/runner.py deleted file mode 100644 index 04e7fa4ac87a1c..00000000000000 --- a/tools/closure_linter/closure_linter/runner.py +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Main lint function. Tokenizes file, runs passes, and feeds to checker.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = 'nnaze@google.com (Nathan Naze)' - -import traceback - -import gflags as flags - -from closure_linter import checker -from closure_linter import ecmalintrules -from closure_linter import ecmametadatapass -from closure_linter import error_check -from closure_linter import errors -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokenizer - -from closure_linter.common import error -from closure_linter.common import htmlutil -from closure_linter.common import tokens - -flags.DEFINE_list('limited_doc_files', ['dummy.js', 'externs.js'], - 'List of files with relaxed documentation checks. Will not ' - 'report errors for missing documentation, some missing ' - 'descriptions, or methods whose @return tags don\'t have a ' - 'matching return statement.') -flags.DEFINE_boolean('error_trace', False, - 'Whether to show error exceptions.') -flags.ADOPT_module_key_flags(checker) -flags.ADOPT_module_key_flags(ecmalintrules) -flags.ADOPT_module_key_flags(error_check) - - -def _GetLastNonWhiteSpaceToken(start_token): - """Get the last non-whitespace token in a token stream.""" - ret_token = None - - whitespace_tokens = frozenset([ - tokens.TokenType.WHITESPACE, tokens.TokenType.BLANK_LINE]) - for t in start_token: - if t.type not in whitespace_tokens: - ret_token = t - - return ret_token - - -def _IsHtml(filename): - return filename.endswith('.html') or filename.endswith('.htm') - - -def _Tokenize(fileobj): - """Tokenize a file. - - Args: - fileobj: file-like object (or iterable lines) with the source. - - Returns: - The first token in the token stream and the ending mode of the tokenizer. - """ - tokenizer = javascripttokenizer.JavaScriptTokenizer() - start_token = tokenizer.TokenizeFile(fileobj) - return start_token, tokenizer.mode - - -def _IsLimitedDocCheck(filename, limited_doc_files): - """Whether this this a limited-doc file. - - Args: - filename: The filename. - limited_doc_files: Iterable of strings. Suffixes of filenames that should - be limited doc check. - - Returns: - Whether the file should be limited check. - """ - for limited_doc_filename in limited_doc_files: - if filename.endswith(limited_doc_filename): - return True - return False - - -def Run(filename, error_handler, source=None): - """Tokenize, run passes, and check the given file. - - Args: - filename: The path of the file to check - error_handler: The error handler to report errors to. - source: A file-like object with the file source. If omitted, the file will - be read from the filename path. - """ - if not source: - try: - source = open(filename) - except IOError: - error_handler.HandleFile(filename, None) - error_handler.HandleError( - error.Error(errors.FILE_NOT_FOUND, 'File not found')) - error_handler.FinishFile() - return - - if _IsHtml(filename): - source_file = htmlutil.GetScriptLines(source) - else: - source_file = source - - token, tokenizer_mode = _Tokenize(source_file) - - error_handler.HandleFile(filename, token) - - # If we did not end in the basic mode, this a failed parse. - if tokenizer_mode is not javascripttokenizer.JavaScriptModes.TEXT_MODE: - error_handler.HandleError( - error.Error(errors.FILE_IN_BLOCK, - 'File ended in mode "%s".' % tokenizer_mode, - _GetLastNonWhiteSpaceToken(token))) - - # Run the ECMA pass - error_token = None - - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - error_token = RunMetaDataPass(token, ecma_pass, error_handler, filename) - - is_limited_doc_check = ( - _IsLimitedDocCheck(filename, flags.FLAGS.limited_doc_files)) - - _RunChecker(token, error_handler, - is_limited_doc_check, - is_html=_IsHtml(filename), - stop_token=error_token) - - error_handler.FinishFile() - - -def RunMetaDataPass(start_token, metadata_pass, error_handler, filename=''): - """Run a metadata pass over a token stream. - - Args: - start_token: The first token in a token stream. - metadata_pass: Metadata pass to run. - error_handler: The error handler to report errors to. - filename: Filename of the source. - - Returns: - The token where the error occurred (if any). - """ - - try: - metadata_pass.Process(start_token) - except ecmametadatapass.ParseError, parse_err: - if flags.FLAGS.error_trace: - traceback.print_exc() - error_token = parse_err.token - error_msg = str(parse_err) - error_handler.HandleError( - error.Error(errors.FILE_DOES_NOT_PARSE, - ('Error parsing file at token "%s". Unable to ' - 'check the rest of file.' - '\nError "%s"' % (error_token, error_msg)), error_token)) - return error_token - except Exception: # pylint: disable=broad-except - traceback.print_exc() - error_handler.HandleError( - error.Error( - errors.FILE_DOES_NOT_PARSE, - 'Internal error in %s' % filename)) - - -def _RunChecker(start_token, error_handler, - limited_doc_checks, is_html, - stop_token=None): - - state_tracker = javascriptstatetracker.JavaScriptStateTracker() - - style_checker = checker.JavaScriptStyleChecker( - state_tracker=state_tracker, - error_handler=error_handler) - - style_checker.Check(start_token, - is_html=is_html, - limited_doc_checks=limited_doc_checks, - stop_token=stop_token) diff --git a/tools/closure_linter/closure_linter/runner_test.py b/tools/closure_linter/closure_linter/runner_test.py deleted file mode 100644 index da5857d30950f6..00000000000000 --- a/tools/closure_linter/closure_linter/runner_test.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the runner module.""" - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import StringIO - - -import mox - - -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import error -from closure_linter.common import errorhandler -from closure_linter.common import tokens - - -class LimitedDocTest(googletest.TestCase): - - def testIsLimitedDocCheck(self): - self.assertTrue(runner._IsLimitedDocCheck('foo_test.js', ['_test.js'])) - self.assertFalse(runner._IsLimitedDocCheck('foo_bar.js', ['_test.js'])) - - self.assertTrue(runner._IsLimitedDocCheck( - 'foo_moo.js', ['moo.js', 'quack.js'])) - self.assertFalse(runner._IsLimitedDocCheck( - 'foo_moo.js', ['woof.js', 'quack.js'])) - - -class RunnerTest(googletest.TestCase): - - def setUp(self): - self.mox = mox.Mox() - - def testRunOnMissingFile(self): - mock_error_handler = self.mox.CreateMock(errorhandler.ErrorHandler) - - def ValidateError(err): - return (isinstance(err, error.Error) and - err.code is errors.FILE_NOT_FOUND and - err.token is None) - - mock_error_handler.HandleFile('does_not_exist.js', None) - mock_error_handler.HandleError(mox.Func(ValidateError)) - mock_error_handler.FinishFile() - - self.mox.ReplayAll() - - runner.Run('does_not_exist.js', mock_error_handler) - - self.mox.VerifyAll() - - def testBadTokenization(self): - mock_error_handler = self.mox.CreateMock(errorhandler.ErrorHandler) - - def ValidateError(err): - return (isinstance(err, error.Error) and - err.code is errors.FILE_IN_BLOCK and - err.token.string == '}') - - mock_error_handler.HandleFile('foo.js', mox.IsA(tokens.Token)) - mock_error_handler.HandleError(mox.Func(ValidateError)) - mock_error_handler.HandleError(mox.IsA(error.Error)) - mock_error_handler.FinishFile() - - self.mox.ReplayAll() - - source = StringIO.StringIO(_BAD_TOKENIZATION_SCRIPT) - runner.Run('foo.js', mock_error_handler, source) - - self.mox.VerifyAll() - - -_BAD_TOKENIZATION_SCRIPT = """ -function foo () { - var a = 3; - var b = 2; - return b + a; /* Comment not closed -} -""" - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/scopeutil.py b/tools/closure_linter/closure_linter/scopeutil.py deleted file mode 100644 index a7ca9b630a470c..00000000000000 --- a/tools/closure_linter/closure_linter/scopeutil.py +++ /dev/null @@ -1,206 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tools to match goog.scope alias statements.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import itertools - -from closure_linter import ecmametadatapass -from closure_linter import tokenutil -from closure_linter.javascripttokens import JavaScriptTokenType - - - -def IsGoogScopeBlock(context): - """Whether the given context is a goog.scope block. - - This function only checks that the block is a function block inside - a goog.scope() call. - - TODO(nnaze): Implement goog.scope checks that verify the call is - in the root context and contains only a single function literal. - - Args: - context: An EcmaContext of type block. - - Returns: - Whether the context is a goog.scope block. - """ - - if context.type != ecmametadatapass.EcmaContext.BLOCK: - return False - - if not _IsFunctionLiteralBlock(context): - return False - - # Check that this function is contained by a group - # of form "goog.scope(...)". - parent = context.parent - if parent and parent.type is ecmametadatapass.EcmaContext.GROUP: - - last_code_token = parent.start_token.metadata.last_code - - if (last_code_token and - last_code_token.type is JavaScriptTokenType.IDENTIFIER and - last_code_token.string == 'goog.scope'): - return True - - return False - - -def _IsFunctionLiteralBlock(block_context): - """Check if a context is a function literal block (without parameters). - - Example function literal block: 'function() {}' - - Args: - block_context: An EcmaContext of type block. - - Returns: - Whether this context is a function literal block. - """ - - previous_code_tokens_iter = itertools.ifilter( - lambda token: token not in JavaScriptTokenType.NON_CODE_TYPES, - reversed(block_context.start_token)) - - # Ignore the current token - next(previous_code_tokens_iter, None) - - # Grab the previous three tokens and put them in correct order. - previous_code_tokens = list(itertools.islice(previous_code_tokens_iter, 3)) - previous_code_tokens.reverse() - - # There aren't three previous tokens. - if len(previous_code_tokens) is not 3: - return False - - # Check that the previous three code tokens are "function ()" - previous_code_token_types = [token.type for token in previous_code_tokens] - if (previous_code_token_types == [ - JavaScriptTokenType.FUNCTION_DECLARATION, - JavaScriptTokenType.START_PARAMETERS, - JavaScriptTokenType.END_PARAMETERS]): - return True - - return False - - -def IsInClosurizedNamespace(symbol, closurized_namespaces): - """Match a goog.scope alias. - - Args: - symbol: An identifier like 'goog.events.Event'. - closurized_namespaces: Iterable of valid Closurized namespaces (strings). - - Returns: - True if symbol is an identifier in a Closurized namespace, otherwise False. - """ - for ns in closurized_namespaces: - if symbol.startswith(ns + '.'): - return True - - return False - - -def _GetVarAssignmentTokens(context): - """Returns the tokens from context if it is a var assignment. - - Args: - context: An EcmaContext. - - Returns: - If a var assignment, the tokens contained within it w/o the trailing - semicolon. - """ - if context.type != ecmametadatapass.EcmaContext.VAR: - return - - # Get the tokens in this statement. - if context.start_token and context.end_token: - statement_tokens = tokenutil.GetTokenRange(context.start_token, - context.end_token) - else: - return - - # And now just those tokens that are actually code. - is_non_code_type = lambda t: t.type not in JavaScriptTokenType.NON_CODE_TYPES - code_tokens = filter(is_non_code_type, statement_tokens) - - # Pop off the semicolon if present. - if code_tokens and code_tokens[-1].IsType(JavaScriptTokenType.SEMICOLON): - code_tokens.pop() - - if len(code_tokens) < 4: - return - - if (code_tokens[0].IsKeyword('var') and - code_tokens[1].IsType(JavaScriptTokenType.SIMPLE_LVALUE) and - code_tokens[2].IsOperator('=')): - return code_tokens - - -def MatchAlias(context): - """Match an alias statement (some identifier assigned to a variable). - - Example alias: var MyClass = proj.longNamespace.MyClass. - - Args: - context: An EcmaContext of type EcmaContext.VAR. - - Returns: - If a valid alias, returns a tuple of alias and symbol, otherwise None. - """ - code_tokens = _GetVarAssignmentTokens(context) - if code_tokens is None: - return - - if all(tokenutil.IsIdentifierOrDot(t) for t in code_tokens[3:]): - # var Foo = bar.Foo; - alias, symbol = code_tokens[1], code_tokens[3] - # Mark both tokens as an alias definition to not count them as usages. - alias.metadata.is_alias_definition = True - symbol.metadata.is_alias_definition = True - return alias.string, tokenutil.GetIdentifierForToken(symbol) - - -def MatchModuleAlias(context): - """Match an alias statement in a goog.module style import. - - Example alias: var MyClass = goog.require('proj.longNamespace.MyClass'). - - Args: - context: An EcmaContext. - - Returns: - If a valid alias, returns a tuple of alias and symbol, otherwise None. - """ - code_tokens = _GetVarAssignmentTokens(context) - if code_tokens is None: - return - - if(code_tokens[3].IsType(JavaScriptTokenType.IDENTIFIER) and - code_tokens[3].string == 'goog.require'): - # var Foo = goog.require('bar.Foo'); - alias = code_tokens[1] - symbol = tokenutil.GetStringAfterToken(code_tokens[3]) - if symbol: - alias.metadata.is_alias_definition = True - return alias.string, symbol diff --git a/tools/closure_linter/closure_linter/scopeutil_test.py b/tools/closure_linter/closure_linter/scopeutil_test.py deleted file mode 100644 index 722a95390022de..00000000000000 --- a/tools/closure_linter/closure_linter/scopeutil_test.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the scopeutil module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - - -import unittest as googletest - -from closure_linter import ecmametadatapass -from closure_linter import scopeutil -from closure_linter import testutil - - -def _FindContexts(start_token): - """Depth first search of all contexts referenced by a token stream. - - Includes contexts' parents, which might not be directly referenced - by any token in the stream. - - Args: - start_token: First token in the token stream. - - Yields: - All contexts referenced by this token stream. - """ - - seen_contexts = set() - - # For each token, yield the context if we haven't seen it before. - for token in start_token: - - token_context = token.metadata.context - contexts = [token_context] - - # Also grab all the context's ancestors. - parent = token_context.parent - while parent: - contexts.append(parent) - parent = parent.parent - - # Yield each of these contexts if we've not seen them. - for context in contexts: - if context not in seen_contexts: - yield context - - seen_contexts.add(context) - - -def _FindFirstContextOfType(token, context_type): - """Returns the first statement context.""" - for context in _FindContexts(token): - if context.type == context_type: - return context - - -def _ParseAssignment(script): - start_token = testutil.TokenizeSourceAndRunEcmaPass(script) - statement = _FindFirstContextOfType( - start_token, ecmametadatapass.EcmaContext.VAR) - return statement - - -class StatementTest(googletest.TestCase): - - def assertAlias(self, expected_match, script): - statement = _ParseAssignment(script) - match = scopeutil.MatchAlias(statement) - self.assertEquals(expected_match, match) - - def assertModuleAlias(self, expected_match, script): - statement = _ParseAssignment(script) - match = scopeutil.MatchModuleAlias(statement) - self.assertEquals(expected_match, match) - - def testSimpleAliases(self): - self.assertAlias( - ('foo', 'goog.foo'), - 'var foo = goog.foo;') - - self.assertAlias( - ('foo', 'goog.foo'), - 'var foo = goog.foo') # No semicolon - - def testAliasWithComment(self): - self.assertAlias( - ('Component', 'goog.ui.Component'), - 'var Component = /* comment */ goog.ui.Component;') - - def testMultilineAlias(self): - self.assertAlias( - ('Component', 'goog.ui.Component'), - 'var Component = \n goog.ui.\n Component;') - - def testNonSymbolAliasVarStatements(self): - self.assertAlias(None, 'var foo = 3;') - self.assertAlias(None, 'var foo = function() {};') - self.assertAlias(None, 'var foo = bar ? baz : qux;') - - def testModuleAlias(self): - self.assertModuleAlias( - ('foo', 'goog.foo'), - 'var foo = goog.require("goog.foo");') - self.assertModuleAlias( - None, - 'var foo = goog.require(notastring);') - - -class ScopeBlockTest(googletest.TestCase): - - @staticmethod - def _GetBlocks(source): - start_token = testutil.TokenizeSourceAndRunEcmaPass(source) - for context in _FindContexts(start_token): - if context.type is ecmametadatapass.EcmaContext.BLOCK: - yield context - - def assertNoBlocks(self, script): - blocks = list(self._GetBlocks(script)) - self.assertEquals([], blocks) - - def testNotBlocks(self): - # Ensure these are not considered blocks. - self.assertNoBlocks('goog.scope(if{});') - self.assertNoBlocks('goog.scope(for{});') - self.assertNoBlocks('goog.scope(switch{});') - self.assertNoBlocks('goog.scope(function foo{});') - - def testNonScopeBlocks(self): - - blocks = list(self._GetBlocks('goog.scope(try{});')) - self.assertEquals(1, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - blocks = list(self._GetBlocks('goog.scope(function(a,b){});')) - self.assertEquals(1, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - blocks = list(self._GetBlocks('goog.scope(try{} catch(){});')) - # Two blocks: try and catch. - self.assertEquals(2, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - blocks = list(self._GetBlocks('goog.scope(try{} catch(){} finally {});')) - self.assertEquals(3, len(blocks)) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - self.assertFalse(scopeutil.IsGoogScopeBlock(blocks.pop())) - - -class AliasTest(googletest.TestCase): - - def setUp(self): - self.start_token = testutil.TokenizeSourceAndRunEcmaPass(_TEST_SCRIPT) - - def testMatchAliasStatement(self): - matches = set() - for context in _FindContexts(self.start_token): - match = scopeutil.MatchAlias(context) - if match: - matches.add(match) - - self.assertEquals( - set([('bar', 'baz'), - ('foo', 'this.foo_'), - ('Component', 'goog.ui.Component'), - ('MyClass', 'myproject.foo.MyClass'), - ('NonClosurizedClass', 'aaa.bbb.NonClosurizedClass')]), - matches) - - def testMatchAliasStatement_withClosurizedNamespaces(self): - - closurized_namepaces = frozenset(['goog', 'myproject']) - - matches = set() - for context in _FindContexts(self.start_token): - match = scopeutil.MatchAlias(context) - if match: - unused_alias, symbol = match - if scopeutil.IsInClosurizedNamespace(symbol, closurized_namepaces): - matches.add(match) - - self.assertEquals( - set([('MyClass', 'myproject.foo.MyClass'), - ('Component', 'goog.ui.Component')]), - matches) - -_TEST_SCRIPT = """ -goog.scope(function() { - var Component = goog.ui.Component; // scope alias - var MyClass = myproject.foo.MyClass; // scope alias - - // Scope alias of non-Closurized namespace. - var NonClosurizedClass = aaa.bbb.NonClosurizedClass; - - var foo = this.foo_; // non-scope object property alias - var bar = baz; // variable alias - - var component = new Component(); -}); - -""" - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/statetracker.py b/tools/closure_linter/closure_linter/statetracker.py deleted file mode 100644 index 52e363972f200a..00000000000000 --- a/tools/closure_linter/closure_linter/statetracker.py +++ /dev/null @@ -1,1294 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Light weight EcmaScript state tracker that reads tokens and tracks state.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import re - -from closure_linter import javascripttokenizer -from closure_linter import javascripttokens -from closure_linter import tokenutil -from closure_linter import typeannotation - -# Shorthand -Type = javascripttokens.JavaScriptTokenType - - -class DocFlag(object): - """Generic doc flag object. - - Attribute: - flag_type: param, return, define, type, etc. - flag_token: The flag token. - type_start_token: The first token specifying the flag type, - including braces. - type_end_token: The last token specifying the flag type, - including braces. - type: The type spec string. - jstype: The type spec, a TypeAnnotation instance. - name_token: The token specifying the flag name. - name: The flag name - description_start_token: The first token in the description. - description_end_token: The end token in the description. - description: The description. - """ - - # Please keep these lists alphabetized. - - # The list of standard jsdoc tags is from - STANDARD_DOC = frozenset([ - 'author', - 'bug', - 'classTemplate', - 'consistentIdGenerator', - 'const', - 'constructor', - 'define', - 'deprecated', - 'dict', - 'enum', - 'export', - 'expose', - 'extends', - 'externs', - 'fileoverview', - 'idGenerator', - 'implements', - 'implicitCast', - 'interface', - 'lends', - 'license', - 'ngInject', # This annotation is specific to AngularJS. - 'noalias', - 'nocompile', - 'nosideeffects', - 'override', - 'owner', - 'package', - 'param', - 'preserve', - 'private', - 'protected', - 'public', - 'return', - 'see', - 'stableIdGenerator', - 'struct', - 'supported', - 'template', - 'this', - 'type', - 'typedef', - 'unrestricted', - ]) - - ANNOTATION = frozenset(['preserveTry', 'suppress']) - - LEGAL_DOC = STANDARD_DOC | ANNOTATION - - # Includes all Closure Compiler @suppress types. - # Not all of these annotations are interpreted by Closure Linter. - # - # Specific cases: - # - accessControls is supported by the compiler at the expression - # and method level to suppress warnings about private/protected - # access (method level applies to all references in the method). - # The linter mimics the compiler behavior. - SUPPRESS_TYPES = frozenset([ - 'accessControls', - 'ambiguousFunctionDecl', - 'checkDebuggerStatement', - 'checkRegExp', - 'checkStructDictInheritance', - 'checkTypes', - 'checkVars', - 'const', - 'constantProperty', - 'deprecated', - 'duplicate', - 'es5Strict', - 'externsValidation', - 'extraProvide', - 'extraRequire', - 'fileoverviewTags', - 'globalThis', - 'internetExplorerChecks', - 'invalidCasts', - 'missingProperties', - 'missingProvide', - 'missingRequire', - 'missingReturn', - 'nonStandardJsDocs', - 'strictModuleDepCheck', - 'suspiciousCode', - 'tweakValidation', - 'typeInvalidation', - 'undefinedNames', - 'undefinedVars', - 'underscore', - 'unknownDefines', - 'unnecessaryCasts', - 'unusedPrivateMembers', - 'uselessCode', - 'visibility', - 'with', - ]) - - HAS_DESCRIPTION = frozenset([ - 'define', - 'deprecated', - 'desc', - 'fileoverview', - 'license', - 'param', - 'preserve', - 'return', - 'supported', - ]) - - # Docflags whose argument should be parsed using the typeannotation parser. - HAS_TYPE = frozenset([ - 'const', - 'define', - 'enum', - 'extends', - 'final', - 'implements', - 'mods', - 'package', - 'param', - 'private', - 'protected', - 'public', - 'return', - 'suppress', - 'type', - 'typedef', - ]) - - # Docflags for which it's ok to omit the type (flag without an argument). - CAN_OMIT_TYPE = frozenset([ - 'const', - 'enum', - 'final', - 'package', - 'private', - 'protected', - 'public', - 'suppress', # We'll raise a separate INCORRECT_SUPPRESS_SYNTAX instead. - ]) - - # Docflags that only take a type as an argument and should not parse a - # following description. - TYPE_ONLY = frozenset([ - 'const', - 'enum', - 'extends', - 'implements', - 'package', - 'suppress', - 'type', - ]) - - HAS_NAME = frozenset(['param']) - - EMPTY_COMMENT_LINE = re.compile(r'^\s*\*?\s*$') - EMPTY_STRING = re.compile(r'^\s*$') - - def __init__(self, flag_token, error_handler=None): - """Creates the DocFlag object and attaches it to the given start token. - - Args: - flag_token: The starting token of the flag. - error_handler: An optional error handler for errors occurring while - parsing the doctype. - """ - self.flag_token = flag_token - self.flag_type = flag_token.string.strip().lstrip('@') - - # Extract type, if applicable. - self.type = None - self.jstype = None - self.type_start_token = None - self.type_end_token = None - if self.flag_type in self.HAS_TYPE: - brace = tokenutil.SearchUntil(flag_token, [Type.DOC_START_BRACE], - Type.FLAG_ENDING_TYPES) - if brace: - end_token, contents = _GetMatchingEndBraceAndContents(brace) - self.type = contents - self.jstype = typeannotation.Parse(brace, end_token, - error_handler) - self.type_start_token = brace - self.type_end_token = end_token - elif (self.flag_type in self.TYPE_ONLY and - flag_token.next.type not in Type.FLAG_ENDING_TYPES and - flag_token.line_number == flag_token.next.line_number): - # b/10407058. If the flag is expected to be followed by a type then - # search for type in same line only. If no token after flag in same - # line then conclude that no type is specified. - self.type_start_token = flag_token.next - self.type_end_token, self.type = _GetEndTokenAndContents( - self.type_start_token) - if self.type is not None: - self.type = self.type.strip() - self.jstype = typeannotation.Parse(flag_token, self.type_end_token, - error_handler) - - # Extract name, if applicable. - self.name_token = None - self.name = None - if self.flag_type in self.HAS_NAME: - # Handle bad case, name could be immediately after flag token. - self.name_token = _GetNextPartialIdentifierToken(flag_token) - - # Handle good case, if found token is after type start, look for - # a identifier (substring to cover cases like [cnt] b/4197272) after - # type end, since types contain identifiers. - if (self.type and self.name_token and - tokenutil.Compare(self.name_token, self.type_start_token) > 0): - self.name_token = _GetNextPartialIdentifierToken(self.type_end_token) - - if self.name_token: - self.name = self.name_token.string - - # Extract description, if applicable. - self.description_start_token = None - self.description_end_token = None - self.description = None - if self.flag_type in self.HAS_DESCRIPTION: - search_start_token = flag_token - if self.name_token and self.type_end_token: - if tokenutil.Compare(self.type_end_token, self.name_token) > 0: - search_start_token = self.type_end_token - else: - search_start_token = self.name_token - elif self.name_token: - search_start_token = self.name_token - elif self.type: - search_start_token = self.type_end_token - - interesting_token = tokenutil.Search(search_start_token, - Type.FLAG_DESCRIPTION_TYPES | Type.FLAG_ENDING_TYPES) - if interesting_token.type in Type.FLAG_DESCRIPTION_TYPES: - self.description_start_token = interesting_token - self.description_end_token, self.description = ( - _GetEndTokenAndContents(interesting_token)) - - def HasType(self): - """Returns whether this flag should have a type annotation.""" - return self.flag_type in self.HAS_TYPE - - def __repr__(self): - return '' % (self.flag_type, repr(self.jstype)) - - -class DocComment(object): - """JavaScript doc comment object. - - Attributes: - ordered_params: Ordered list of parameters documented. - start_token: The token that starts the doc comment. - end_token: The token that ends the doc comment. - suppressions: Map of suppression type to the token that added it. - """ - def __init__(self, start_token): - """Create the doc comment object. - - Args: - start_token: The first token in the doc comment. - """ - self.__flags = [] - self.start_token = start_token - self.end_token = None - self.suppressions = {} - self.invalidated = False - - @property - def ordered_params(self): - """Gives the list of parameter names as a list of strings.""" - params = [] - for flag in self.__flags: - if flag.flag_type == 'param' and flag.name: - params.append(flag.name) - return params - - def Invalidate(self): - """Indicate that the JSDoc is well-formed but we had problems parsing it. - - This is a short-circuiting mechanism so that we don't emit false - positives about well-formed doc comments just because we don't support - hot new syntaxes. - """ - self.invalidated = True - - def IsInvalidated(self): - """Test whether Invalidate() has been called.""" - return self.invalidated - - def AddSuppression(self, token): - """Add a new error suppression flag. - - Args: - token: The suppression flag token. - """ - flag = token and token.attached_object - if flag and flag.jstype: - for suppression in flag.jstype.IterIdentifiers(): - self.suppressions[suppression] = token - - def SuppressionOnly(self): - """Returns whether this comment contains only suppression flags.""" - if not self.__flags: - return False - - for flag in self.__flags: - if flag.flag_type != 'suppress': - return False - - return True - - def AddFlag(self, flag): - """Add a new document flag. - - Args: - flag: DocFlag object. - """ - self.__flags.append(flag) - - def InheritsDocumentation(self): - """Test if the jsdoc implies documentation inheritance. - - Returns: - True if documentation may be pulled off the superclass. - """ - return self.HasFlag('inheritDoc') or self.HasFlag('override') - - def HasFlag(self, flag_type): - """Test if the given flag has been set. - - Args: - flag_type: The type of the flag to check. - - Returns: - True if the flag is set. - """ - for flag in self.__flags: - if flag.flag_type == flag_type: - return True - return False - - def GetFlag(self, flag_type): - """Gets the last flag of the given type. - - Args: - flag_type: The type of the flag to get. - - Returns: - The last instance of the given flag type in this doc comment. - """ - for flag in reversed(self.__flags): - if flag.flag_type == flag_type: - return flag - - def GetDocFlags(self): - """Return the doc flags for this comment.""" - return list(self.__flags) - - def _YieldDescriptionTokens(self): - for token in self.start_token: - - if (token is self.end_token or - token.type is javascripttokens.JavaScriptTokenType.DOC_FLAG or - token.type not in javascripttokens.JavaScriptTokenType.COMMENT_TYPES): - return - - if token.type not in [ - javascripttokens.JavaScriptTokenType.START_DOC_COMMENT, - javascripttokens.JavaScriptTokenType.END_DOC_COMMENT, - javascripttokens.JavaScriptTokenType.DOC_PREFIX]: - yield token - - @property - def description(self): - return tokenutil.TokensToString( - self._YieldDescriptionTokens()) - - def GetTargetIdentifier(self): - """Returns the identifier (as a string) that this is a comment for. - - Note that this uses method uses GetIdentifierForToken to get the full - identifier, even if broken up by whitespace, newlines, or comments, - and thus could be longer than GetTargetToken().string. - - Returns: - The identifier for the token this comment is for. - """ - token = self.GetTargetToken() - if token: - return tokenutil.GetIdentifierForToken(token) - - def GetTargetToken(self): - """Get this comment's target token. - - Returns: - The token that is the target of this comment, or None if there isn't one. - """ - - # File overviews describe the file, not a token. - if self.HasFlag('fileoverview'): - return - - skip_types = frozenset([ - Type.WHITESPACE, - Type.BLANK_LINE, - Type.START_PAREN]) - - target_types = frozenset([ - Type.FUNCTION_NAME, - Type.IDENTIFIER, - Type.SIMPLE_LVALUE]) - - token = self.end_token.next - while token: - if token.type in target_types: - return token - - # Handles the case of a comment on "var foo = ...' - if token.IsKeyword('var'): - next_code_token = tokenutil.CustomSearch( - token, - lambda t: t.type not in Type.NON_CODE_TYPES) - - if (next_code_token and - next_code_token.IsType(Type.SIMPLE_LVALUE)): - return next_code_token - - return - - # Handles the case of a comment on "function foo () {}" - if token.type is Type.FUNCTION_DECLARATION: - next_code_token = tokenutil.CustomSearch( - token, - lambda t: t.type not in Type.NON_CODE_TYPES) - - if next_code_token.IsType(Type.FUNCTION_NAME): - return next_code_token - - return - - # Skip types will end the search. - if token.type not in skip_types: - return - - token = token.next - - def CompareParameters(self, params): - """Computes the edit distance and list from the function params to the docs. - - Uses the Levenshtein edit distance algorithm, with code modified from - http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python - - Args: - params: The parameter list for the function declaration. - - Returns: - The edit distance, the edit list. - """ - source_len, target_len = len(self.ordered_params), len(params) - edit_lists = [[]] - distance = [[]] - for i in range(target_len+1): - edit_lists[0].append(['I'] * i) - distance[0].append(i) - - for j in range(1, source_len+1): - edit_lists.append([['D'] * j]) - distance.append([j]) - - for i in range(source_len): - for j in range(target_len): - cost = 1 - if self.ordered_params[i] == params[j]: - cost = 0 - - deletion = distance[i][j+1] + 1 - insertion = distance[i+1][j] + 1 - substitution = distance[i][j] + cost - - edit_list = None - best = None - if deletion <= insertion and deletion <= substitution: - # Deletion is best. - best = deletion - edit_list = list(edit_lists[i][j+1]) - edit_list.append('D') - - elif insertion <= substitution: - # Insertion is best. - best = insertion - edit_list = list(edit_lists[i+1][j]) - edit_list.append('I') - edit_lists[i+1].append(edit_list) - - else: - # Substitution is best. - best = substitution - edit_list = list(edit_lists[i][j]) - if cost: - edit_list.append('S') - else: - edit_list.append('=') - - edit_lists[i+1].append(edit_list) - distance[i+1].append(best) - - return distance[source_len][target_len], edit_lists[source_len][target_len] - - def __repr__(self): - """Returns a string representation of this object. - - Returns: - A string representation of this object. - """ - return '' % ( - str(self.ordered_params), str(self.__flags)) - - -# -# Helper methods used by DocFlag and DocComment to parse out flag information. -# - - -def _GetMatchingEndBraceAndContents(start_brace): - """Returns the matching end brace and contents between the two braces. - - If any FLAG_ENDING_TYPE token is encountered before a matching end brace, then - that token is used as the matching ending token. Contents will have all - comment prefixes stripped out of them, and all comment prefixes in between the - start and end tokens will be split out into separate DOC_PREFIX tokens. - - Args: - start_brace: The DOC_START_BRACE token immediately before desired contents. - - Returns: - The matching ending token (DOC_END_BRACE or FLAG_ENDING_TYPE) and a string - of the contents between the matching tokens, minus any comment prefixes. - """ - open_count = 1 - close_count = 0 - contents = [] - - # We don't consider the start brace part of the type string. - token = start_brace.next - while open_count != close_count: - if token.type == Type.DOC_START_BRACE: - open_count += 1 - elif token.type == Type.DOC_END_BRACE: - close_count += 1 - - if token.type != Type.DOC_PREFIX: - contents.append(token.string) - - if token.type in Type.FLAG_ENDING_TYPES: - break - token = token.next - - #Don't include the end token (end brace, end doc comment, etc.) in type. - token = token.previous - contents = contents[:-1] - - return token, ''.join(contents) - - -def _GetNextPartialIdentifierToken(start_token): - """Returns the first token having identifier as substring after a token. - - Searches each token after the start to see if it contains an identifier. - If found, token is returned. If no identifier is found returns None. - Search is abandoned when a FLAG_ENDING_TYPE token is found. - - Args: - start_token: The token to start searching after. - - Returns: - The token found containing identifier, None otherwise. - """ - token = start_token.next - - while token and token.type not in Type.FLAG_ENDING_TYPES: - match = javascripttokenizer.JavaScriptTokenizer.IDENTIFIER.search( - token.string) - if match is not None and token.type == Type.COMMENT: - return token - - token = token.next - - return None - - -def _GetEndTokenAndContents(start_token): - """Returns last content token and all contents before FLAG_ENDING_TYPE token. - - Comment prefixes are split into DOC_PREFIX tokens and stripped from the - returned contents. - - Args: - start_token: The token immediately before the first content token. - - Returns: - The last content token and a string of all contents including start and - end tokens, with comment prefixes stripped. - """ - iterator = start_token - last_line = iterator.line_number - last_token = None - contents = '' - doc_depth = 0 - while not iterator.type in Type.FLAG_ENDING_TYPES or doc_depth > 0: - if (iterator.IsFirstInLine() and - DocFlag.EMPTY_COMMENT_LINE.match(iterator.line)): - # If we have a blank comment line, consider that an implicit - # ending of the description. This handles a case like: - # - # * @return {boolean} True - # * - # * Note: This is a sentence. - # - # The note is not part of the @return description, but there was - # no definitive ending token. Rather there was a line containing - # only a doc comment prefix or whitespace. - break - - # b/2983692 - # don't prematurely match against a @flag if inside a doc flag - # need to think about what is the correct behavior for unterminated - # inline doc flags - if (iterator.type == Type.DOC_START_BRACE and - iterator.next.type == Type.DOC_INLINE_FLAG): - doc_depth += 1 - elif (iterator.type == Type.DOC_END_BRACE and - doc_depth > 0): - doc_depth -= 1 - - if iterator.type in Type.FLAG_DESCRIPTION_TYPES: - contents += iterator.string - last_token = iterator - - iterator = iterator.next - if iterator.line_number != last_line: - contents += '\n' - last_line = iterator.line_number - - end_token = last_token - if DocFlag.EMPTY_STRING.match(contents): - contents = None - else: - # Strip trailing newline. - contents = contents[:-1] - - return end_token, contents - - -class Function(object): - """Data about a JavaScript function. - - Attributes: - block_depth: Block depth the function began at. - doc: The DocComment associated with the function. - has_return: If the function has a return value. - has_this: If the function references the 'this' object. - is_assigned: If the function is part of an assignment. - is_constructor: If the function is a constructor. - name: The name of the function, whether given in the function keyword or - as the lvalue the function is assigned to. - start_token: First token of the function (the function' keyword token). - end_token: Last token of the function (the closing '}' token). - parameters: List of parameter names. - """ - - def __init__(self, block_depth, is_assigned, doc, name): - self.block_depth = block_depth - self.is_assigned = is_assigned - self.is_constructor = doc and doc.HasFlag('constructor') - self.is_interface = doc and doc.HasFlag('interface') - self.has_return = False - self.has_throw = False - self.has_this = False - self.name = name - self.doc = doc - self.start_token = None - self.end_token = None - self.parameters = None - - -class StateTracker(object): - """EcmaScript state tracker. - - Tracks block depth, function names, etc. within an EcmaScript token stream. - """ - - OBJECT_LITERAL = 'o' - CODE = 'c' - - def __init__(self, doc_flag=DocFlag): - """Initializes a JavaScript token stream state tracker. - - Args: - doc_flag: An optional custom DocFlag used for validating - documentation flags. - """ - self._doc_flag = doc_flag - self.Reset() - - def Reset(self): - """Resets the state tracker to prepare for processing a new page.""" - self._block_depth = 0 - self._is_block_close = False - self._paren_depth = 0 - self._function_stack = [] - self._functions_by_name = {} - self._last_comment = None - self._doc_comment = None - self._cumulative_params = None - self._block_types = [] - self._last_non_space_token = None - self._last_line = None - self._first_token = None - self._documented_identifiers = set() - self._variables_in_scope = [] - - def DocFlagPass(self, start_token, error_handler): - """Parses doc flags. - - This pass needs to be executed before the aliaspass and we don't want to do - a full-blown statetracker dry run for these. - - Args: - start_token: The token at which to start iterating - error_handler: An error handler for error reporting. - """ - if not start_token: - return - doc_flag_types = (Type.DOC_FLAG, Type.DOC_INLINE_FLAG) - for token in start_token: - if token.type in doc_flag_types: - token.attached_object = self._doc_flag(token, error_handler) - - def InFunction(self): - """Returns true if the current token is within a function. - - Returns: - True if the current token is within a function. - """ - return bool(self._function_stack) - - def InConstructor(self): - """Returns true if the current token is within a constructor. - - Returns: - True if the current token is within a constructor. - """ - return self.InFunction() and self._function_stack[-1].is_constructor - - def InInterfaceMethod(self): - """Returns true if the current token is within an interface method. - - Returns: - True if the current token is within an interface method. - """ - if self.InFunction(): - if self._function_stack[-1].is_interface: - return True - else: - name = self._function_stack[-1].name - prototype_index = name.find('.prototype.') - if prototype_index != -1: - class_function_name = name[0:prototype_index] - if (class_function_name in self._functions_by_name and - self._functions_by_name[class_function_name].is_interface): - return True - - return False - - def InTopLevelFunction(self): - """Returns true if the current token is within a top level function. - - Returns: - True if the current token is within a top level function. - """ - return len(self._function_stack) == 1 and self.InTopLevel() - - def InAssignedFunction(self): - """Returns true if the current token is within a function variable. - - Returns: - True if if the current token is within a function variable - """ - return self.InFunction() and self._function_stack[-1].is_assigned - - def IsFunctionOpen(self): - """Returns true if the current token is a function block open. - - Returns: - True if the current token is a function block open. - """ - return (self._function_stack and - self._function_stack[-1].block_depth == self._block_depth - 1) - - def IsFunctionClose(self): - """Returns true if the current token is a function block close. - - Returns: - True if the current token is a function block close. - """ - return (self._function_stack and - self._function_stack[-1].block_depth == self._block_depth) - - def InBlock(self): - """Returns true if the current token is within a block. - - Returns: - True if the current token is within a block. - """ - return bool(self._block_depth) - - def IsBlockClose(self): - """Returns true if the current token is a block close. - - Returns: - True if the current token is a block close. - """ - return self._is_block_close - - def InObjectLiteral(self): - """Returns true if the current token is within an object literal. - - Returns: - True if the current token is within an object literal. - """ - return self._block_depth and self._block_types[-1] == self.OBJECT_LITERAL - - def InObjectLiteralDescendant(self): - """Returns true if the current token has an object literal ancestor. - - Returns: - True if the current token has an object literal ancestor. - """ - return self.OBJECT_LITERAL in self._block_types - - def InParentheses(self): - """Returns true if the current token is within parentheses. - - Returns: - True if the current token is within parentheses. - """ - return bool(self._paren_depth) - - def ParenthesesDepth(self): - """Returns the number of parens surrounding the token. - - Returns: - The number of parenthesis surrounding the token. - """ - return self._paren_depth - - def BlockDepth(self): - """Returns the number of blocks in which the token is nested. - - Returns: - The number of blocks in which the token is nested. - """ - return self._block_depth - - def FunctionDepth(self): - """Returns the number of functions in which the token is nested. - - Returns: - The number of functions in which the token is nested. - """ - return len(self._function_stack) - - def InTopLevel(self): - """Whether we are at the top level in the class. - - This function call is language specific. In some languages like - JavaScript, a function is top level if it is not inside any parenthesis. - In languages such as ActionScript, a function is top level if it is directly - within a class. - """ - raise TypeError('Abstract method InTopLevel not implemented') - - def GetBlockType(self, token): - """Determine the block type given a START_BLOCK token. - - Code blocks come after parameters, keywords like else, and closing parens. - - Args: - token: The current token. Can be assumed to be type START_BLOCK. - Returns: - Code block type for current token. - """ - raise TypeError('Abstract method GetBlockType not implemented') - - def GetParams(self): - """Returns the accumulated input params as an array. - - In some EcmasSript languages, input params are specified like - (param:Type, param2:Type2, ...) - in other they are specified just as - (param, param2) - We handle both formats for specifying parameters here and leave - it to the compilers for each language to detect compile errors. - This allows more code to be reused between lint checkers for various - EcmaScript languages. - - Returns: - The accumulated input params as an array. - """ - params = [] - if self._cumulative_params: - params = re.compile(r'\s+').sub('', self._cumulative_params).split(',') - # Strip out the type from parameters of the form name:Type. - params = map(lambda param: param.split(':')[0], params) - - return params - - def GetLastComment(self): - """Return the last plain comment that could be used as documentation. - - Returns: - The last plain comment that could be used as documentation. - """ - return self._last_comment - - def GetDocComment(self): - """Return the most recent applicable documentation comment. - - Returns: - The last applicable documentation comment. - """ - return self._doc_comment - - def HasDocComment(self, identifier): - """Returns whether the identifier has been documented yet. - - Args: - identifier: The identifier. - - Returns: - Whether the identifier has been documented yet. - """ - return identifier in self._documented_identifiers - - def InDocComment(self): - """Returns whether the current token is in a doc comment. - - Returns: - Whether the current token is in a doc comment. - """ - return self._doc_comment and self._doc_comment.end_token is None - - def GetDocFlag(self): - """Returns the current documentation flags. - - Returns: - The current documentation flags. - """ - return self._doc_flag - - def IsTypeToken(self, t): - if self.InDocComment() and t.type not in (Type.START_DOC_COMMENT, - Type.DOC_FLAG, Type.DOC_INLINE_FLAG, Type.DOC_PREFIX): - f = tokenutil.SearchUntil(t, [Type.DOC_FLAG], [Type.START_DOC_COMMENT], - None, True) - if (f and f.attached_object.type_start_token is not None and - f.attached_object.type_end_token is not None): - return (tokenutil.Compare(t, f.attached_object.type_start_token) > 0 and - tokenutil.Compare(t, f.attached_object.type_end_token) < 0) - return False - - def GetFunction(self): - """Return the function the current code block is a part of. - - Returns: - The current Function object. - """ - if self._function_stack: - return self._function_stack[-1] - - def GetBlockDepth(self): - """Return the block depth. - - Returns: - The current block depth. - """ - return self._block_depth - - def GetLastNonSpaceToken(self): - """Return the last non whitespace token.""" - return self._last_non_space_token - - def GetLastLine(self): - """Return the last line.""" - return self._last_line - - def GetFirstToken(self): - """Return the very first token in the file.""" - return self._first_token - - def IsVariableInScope(self, token_string): - """Checks if string is variable in current scope. - - For given string it checks whether the string is a defined variable - (including function param) in current state. - - E.g. if variables defined (variables in current scope) is docs - then docs, docs.length etc will be considered as variable in current - scope. This will help in avoding extra goog.require for variables. - - Args: - token_string: String to check if its is a variable in current scope. - - Returns: - true if given string is a variable in current scope. - """ - for variable in self._variables_in_scope: - if (token_string == variable - or token_string.startswith(variable + '.')): - return True - - return False - - def HandleToken(self, token, last_non_space_token): - """Handles the given token and updates state. - - Args: - token: The token to handle. - last_non_space_token: - """ - self._is_block_close = False - - if not self._first_token: - self._first_token = token - - # Track block depth. - type = token.type - if type == Type.START_BLOCK: - self._block_depth += 1 - - # Subclasses need to handle block start very differently because - # whether a block is a CODE or OBJECT_LITERAL block varies significantly - # by language. - self._block_types.append(self.GetBlockType(token)) - - # When entering a function body, record its parameters. - if self.InFunction(): - function = self._function_stack[-1] - if self._block_depth == function.block_depth + 1: - function.parameters = self.GetParams() - - # Track block depth. - elif type == Type.END_BLOCK: - self._is_block_close = not self.InObjectLiteral() - self._block_depth -= 1 - self._block_types.pop() - - # Track parentheses depth. - elif type == Type.START_PAREN: - self._paren_depth += 1 - - # Track parentheses depth. - elif type == Type.END_PAREN: - self._paren_depth -= 1 - - elif type == Type.COMMENT: - self._last_comment = token.string - - elif type == Type.START_DOC_COMMENT: - self._last_comment = None - self._doc_comment = DocComment(token) - - elif type == Type.END_DOC_COMMENT: - self._doc_comment.end_token = token - - elif type in (Type.DOC_FLAG, Type.DOC_INLINE_FLAG): - # Don't overwrite flags if they were already parsed in a previous pass. - if token.attached_object is None: - flag = self._doc_flag(token) - token.attached_object = flag - else: - flag = token.attached_object - self._doc_comment.AddFlag(flag) - - if flag.flag_type == 'suppress': - self._doc_comment.AddSuppression(token) - - elif type == Type.FUNCTION_DECLARATION: - last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, None, - True) - doc = None - # Only top-level functions are eligible for documentation. - if self.InTopLevel(): - doc = self._doc_comment - - name = '' - is_assigned = last_code and (last_code.IsOperator('=') or - last_code.IsOperator('||') or last_code.IsOperator('&&') or - (last_code.IsOperator(':') and not self.InObjectLiteral())) - if is_assigned: - # TODO(robbyw): This breaks for x[2] = ... - # Must use loop to find full function name in the case of line-wrapped - # declarations (bug 1220601) like: - # my.function.foo. - # bar = function() ... - identifier = tokenutil.Search(last_code, Type.SIMPLE_LVALUE, None, True) - while identifier and tokenutil.IsIdentifierOrDot(identifier): - name = identifier.string + name - # Traverse behind us, skipping whitespace and comments. - while True: - identifier = identifier.previous - if not identifier or not identifier.type in Type.NON_CODE_TYPES: - break - - else: - next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - while next_token and next_token.IsType(Type.FUNCTION_NAME): - name += next_token.string - next_token = tokenutil.Search(next_token, Type.FUNCTION_NAME, 2) - - function = Function(self._block_depth, is_assigned, doc, name) - function.start_token = token - - self._function_stack.append(function) - self._functions_by_name[name] = function - - # Add a delimiter in stack for scope variables to define start of - # function. This helps in popping variables of this function when - # function declaration ends. - self._variables_in_scope.append('') - - elif type == Type.START_PARAMETERS: - self._cumulative_params = '' - - elif type == Type.PARAMETERS: - self._cumulative_params += token.string - self._variables_in_scope.extend(self.GetParams()) - - elif type == Type.KEYWORD and token.string == 'return': - next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - if not next_token.IsType(Type.SEMICOLON): - function = self.GetFunction() - if function: - function.has_return = True - - elif type == Type.KEYWORD and token.string == 'throw': - function = self.GetFunction() - if function: - function.has_throw = True - - elif type == Type.KEYWORD and token.string == 'var': - function = self.GetFunction() - next_token = tokenutil.Search(token, [Type.IDENTIFIER, - Type.SIMPLE_LVALUE]) - - if next_token: - if next_token.type == Type.SIMPLE_LVALUE: - self._variables_in_scope.append(next_token.values['identifier']) - else: - self._variables_in_scope.append(next_token.string) - - elif type == Type.SIMPLE_LVALUE: - identifier = token.values['identifier'] - jsdoc = self.GetDocComment() - if jsdoc: - self._documented_identifiers.add(identifier) - - self._HandleIdentifier(identifier, True) - - elif type == Type.IDENTIFIER: - self._HandleIdentifier(token.string, False) - - # Detect documented non-assignments. - next_token = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES) - if next_token and next_token.IsType(Type.SEMICOLON): - if (self._last_non_space_token and - self._last_non_space_token.IsType(Type.END_DOC_COMMENT)): - self._documented_identifiers.add(token.string) - - def _HandleIdentifier(self, identifier, is_assignment): - """Process the given identifier. - - Currently checks if it references 'this' and annotates the function - accordingly. - - Args: - identifier: The identifer to process. - is_assignment: Whether the identifer is being written to. - """ - if identifier == 'this' or identifier.startswith('this.'): - function = self.GetFunction() - if function: - function.has_this = True - - def HandleAfterToken(self, token): - """Handle updating state after a token has been checked. - - This function should be used for destructive state changes such as - deleting a tracked object. - - Args: - token: The token to handle. - """ - type = token.type - if type == Type.SEMICOLON or type == Type.END_PAREN or ( - type == Type.END_BRACKET and - self._last_non_space_token.type not in ( - Type.SINGLE_QUOTE_STRING_END, Type.DOUBLE_QUOTE_STRING_END)): - # We end on any numeric array index, but keep going for string based - # array indices so that we pick up manually exported identifiers. - self._doc_comment = None - self._last_comment = None - - elif type == Type.END_BLOCK: - self._doc_comment = None - self._last_comment = None - - if self.InFunction() and self.IsFunctionClose(): - # TODO(robbyw): Detect the function's name for better errors. - function = self._function_stack.pop() - function.end_token = token - - # Pop all variables till delimiter ('') those were defined in the - # function being closed so make them out of scope. - while self._variables_in_scope and self._variables_in_scope[-1]: - self._variables_in_scope.pop() - - # Pop delimiter - if self._variables_in_scope: - self._variables_in_scope.pop() - - elif type == Type.END_PARAMETERS and self._doc_comment: - self._doc_comment = None - self._last_comment = None - - if not token.IsAnyType(Type.WHITESPACE, Type.BLANK_LINE): - self._last_non_space_token = token - - self._last_line = token.line diff --git a/tools/closure_linter/closure_linter/statetracker_test.py b/tools/closure_linter/closure_linter/statetracker_test.py deleted file mode 100755 index 494dc642fc5bde..00000000000000 --- a/tools/closure_linter/closure_linter/statetracker_test.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the statetracker module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - - - -import unittest as googletest - -from closure_linter import javascripttokens -from closure_linter import statetracker -from closure_linter import testutil - - -class _FakeDocFlag(object): - - def __repr__(self): - return '@%s %s' % (self.flag_type, self.name) - - -class IdentifierTest(googletest.TestCase): - - def testJustIdentifier(self): - a = javascripttokens.JavaScriptToken( - 'abc', javascripttokens.JavaScriptTokenType.IDENTIFIER, 'abc', 1) - - st = statetracker.StateTracker() - st.HandleToken(a, None) - - -class DocCommentTest(googletest.TestCase): - - @staticmethod - def _MakeDocFlagFake(flag_type, name=None): - flag = _FakeDocFlag() - flag.flag_type = flag_type - flag.name = name - return flag - - def testDocFlags(self): - comment = statetracker.DocComment(None) - - a = self._MakeDocFlagFake('param', 'foo') - comment.AddFlag(a) - - b = self._MakeDocFlagFake('param', '') - comment.AddFlag(b) - - c = self._MakeDocFlagFake('param', 'bar') - comment.AddFlag(c) - - self.assertEquals( - ['foo', 'bar'], - comment.ordered_params) - - self.assertEquals( - [a, b, c], - comment.GetDocFlags()) - - def testInvalidate(self): - comment = statetracker.DocComment(None) - - self.assertFalse(comment.invalidated) - self.assertFalse(comment.IsInvalidated()) - - comment.Invalidate() - - self.assertTrue(comment.invalidated) - self.assertTrue(comment.IsInvalidated()) - - def testSuppressionOnly(self): - comment = statetracker.DocComment(None) - - self.assertFalse(comment.SuppressionOnly()) - comment.AddFlag(self._MakeDocFlagFake('suppress')) - self.assertTrue(comment.SuppressionOnly()) - comment.AddFlag(self._MakeDocFlagFake('foo')) - self.assertFalse(comment.SuppressionOnly()) - - def testRepr(self): - comment = statetracker.DocComment(None) - comment.AddFlag(self._MakeDocFlagFake('param', 'foo')) - comment.AddFlag(self._MakeDocFlagFake('param', 'bar')) - - self.assertEquals( - '', - repr(comment)) - - def testDocFlagParam(self): - comment = self._ParseComment(""" - /** - * @param {string} [name] Name of customer. - */""") - flag = comment.GetFlag('param') - self.assertEquals('string', flag.type) - self.assertEquals('string', flag.jstype.ToString()) - self.assertEquals('[name]', flag.name) - - def _ParseComment(self, script): - """Parse a script that contains one comment and return it.""" - _, comments = testutil.ParseFunctionsAndComments(script) - self.assertEquals(1, len(comments)) - return comments[0] - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/strict_test.py b/tools/closure_linter/closure_linter/strict_test.py deleted file mode 100755 index 2634456874f1d2..00000000000000 --- a/tools/closure_linter/closure_linter/strict_test.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python -# Copyright 2013 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for gjslint --strict. - -Tests errors that can be thrown by gjslint when in strict mode. -""" - - - -import unittest - -import gflags as flags -import unittest as googletest - -from closure_linter import errors -from closure_linter import runner -from closure_linter.common import erroraccumulator - -flags.FLAGS.strict = True - - -class StrictTest(unittest.TestCase): - """Tests scenarios where strict generates warnings.""" - - def testUnclosedString(self): - """Tests warnings are reported when nothing is disabled. - - b/11450054. - """ - original = [ - 'bug = function() {', - ' (\'foo\'\');', - '};', - '', - ] - - expected = [errors.FILE_DOES_NOT_PARSE, errors.MULTI_LINE_STRING, - errors.FILE_IN_BLOCK] - self._AssertErrors(original, expected) - - def _AssertErrors(self, original, expected_errors): - """Asserts that the error fixer corrects original to expected.""" - - # Trap gjslint's output parse it to get messages added. - error_accumulator = erroraccumulator.ErrorAccumulator() - runner.Run('testing.js', error_accumulator, source=original) - error_nums = [e.code for e in error_accumulator.GetErrors()] - - error_nums.sort() - expected_errors.sort() - self.assertListEqual(error_nums, expected_errors) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/testdata/all_js_wrapped.js b/tools/closure_linter/closure_linter/testdata/all_js_wrapped.js deleted file mode 100644 index 6eb3b38f529257..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/all_js_wrapped.js +++ /dev/null @@ -1,5 +0,0 @@ -(function($) { - // My code goes here. - // linter should not throw random exceptions because the file starts with - // an open paren. Regression test for bug 2966755. -})(jQuery); diff --git a/tools/closure_linter/closure_linter/testdata/blank_lines.js b/tools/closure_linter/closure_linter/testdata/blank_lines.js deleted file mode 100644 index 1dc3da29053a0b..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/blank_lines.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @fileoverview This is a file overview with no lines above it, at the top of - * the file (GOOD). - */ -/** // WRONG_BLANK_LINE_COUNT - * @fileoverview This is a file overview with no lines above it (BAD). - */ - -/** - * @fileoverview This is a file overview with one line above it (GOOD). - */ - - -/** - * @fileoverview This is a file overview with two lines above it (GOOD). - */ - -/** // WRONG_BLANK_LINE_COUNT - * A constructor with 1 line above it (BAD). - * @constructor - */ -function someFunction() {} - - -/** // WRONG_BLANK_LINE_COUNT - * A constructor with 2 lines above it (BAD). - * @constructor - */ -function someFunction() {} - - - -/** - * A constructor with 3 lines above it (GOOD). - * @constructor - */ -function someFunction() {} - - - - -/** // WRONG_BLANK_LINE_COUNT - * A constructor with 4 lines above it (BAD). - * @constructor - */ -function someFunction() {} - -/** // WRONG_BLANK_LINE_COUNT - * Top level block with 1 line above it (BAD). - */ -function someFunction() {} - - -/** - * Top level block with 2 lines above it (GOOD). - */ -function someFunction() {} - - - -/** // WRONG_BLANK_LINE_COUNT - * Top level block with 3 lines above it (BAD). - */ -function someFunction() {} - - -// -1: EXTRA_SPACE -/** - * Top level block with 2 lines above it, one contains whitespace (GOOD). - */ -function someFunction() {} - - -// This comment should be ignored. -/** - * Top level block with 2 lines above it (GOOD). - */ -function someFunction() {} - -// Should not check jsdocs which are inside a block. -var x = { - /** - * @constructor - */ -}; - -/** - * This jsdoc-style comment should not be required to have two lines above it - * since it does not immediately precede any code. - */ -// This is a comment. - -/** - * This jsdoc-style comment should not be required to have two lines above it - * since it does not immediately precede any code. - */ -/** - * This is a comment. - */ - -/** - * This jsdoc-style comment should not be required to have two lines above it - * since it does not immediately precede any code. - */ diff --git a/tools/closure_linter/closure_linter/testdata/bugs.js b/tools/closure_linter/closure_linter/testdata/bugs.js deleted file mode 100644 index 735200545db11e..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/bugs.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2007 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// A file full of known bugs - this file serves only as a reference and is not -// tested in any way. - -/** - * @param {{foo} x This is a bad record type. - * @param {{foo}} y This is a good record type with bad spacing. - * @param {{foo}} This is a good record type with no parameter name. - */ -function f(x, y, z) { -} - - -// Should report extra space errors. -var magicProps = { renderRow: 0 }; - -// No error reported here for missing space before {. -if (x){ -} - -// Should have a "brace on wrong line" error. -if (x) -{ -} - -// We could consider not reporting it when wrapping makes it necessary, as in: -if (aLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongCondition) - { - // Code here. -} diff --git a/tools/closure_linter/closure_linter/testdata/ends_with_block.js b/tools/closure_linter/closure_linter/testdata/ends_with_block.js deleted file mode 100644 index 40aa872e30a9e9..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/ends_with_block.js +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2009 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Regression test for an old crasher. - -if (x) { - alert('Hello world'); -} diff --git a/tools/closure_linter/closure_linter/testdata/externs.js b/tools/closure_linter/closure_linter/testdata/externs.js deleted file mode 100644 index 94e2ad38a4f2a4..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/externs.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * Externs files are treated specially. We don't require documentation or - * return statements in functions when they are documented. - * - * @externs - */ - - -function VXMLBaseElement() {} - - -/** - * Should not complain about return tag with no return statement in - * externs.js file. - * @param {string} attrName The name of the attribute. - * @return {string} - */ -VXMLBaseElement.prototype.getAttribute = function(attrName) {}; - -VXMLBaseElement.prototype.undocumentedMethod = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/externs_jsdoc.js b/tools/closure_linter/closure_linter/testdata/externs_jsdoc.js deleted file mode 100644 index 926593f7c40207..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/externs_jsdoc.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Tests that the externs tag within a fileoverview comment is - * sufficient to identify an externs file. - * @externs - * - * Externs files are treated specially. We don't require documentation or - * return statements in functions when they are documented. - * - */ - - -function VXMLBaseElement() {} - - -/** - * Should not complain about return tag with no return statement in - * an externs file. - * @param {string} attrName The name of the attribute. - * @return {string} - */ -VXMLBaseElement.prototype.getAttribute = function(attrName) {}; - -VXMLBaseElement.prototype.undocumentedMethod = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/file_level_comment.js b/tools/closure_linter/closure_linter/testdata/file_level_comment.js deleted file mode 100644 index 86581155a0e6c9..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/file_level_comment.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * File level comment as the first thing in a file (GOOD). - * @license Copyright 2009 SomeThirdParty. - */ -/** // WRONG_BLANK_LINE_COUNT - * Comment block that is not the first thing in a file (BAD). - * @license Copyright 2009 SomeThirdParty. - */ - -/** // WRONG_BLANK_LINE_COUNT - * Top level comment with a single line above it (BAD). - * @license Copyright 2009 SomeThirdParty. - */ diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.html.in.html b/tools/closure_linter/closure_linter/testdata/fixjsstyle.html.in.html deleted file mode 100644 index c341bb9a394afb..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.html.in.html +++ /dev/null @@ -1,52 +0,0 @@ - - - - - -Tests - - - - - - - - - - - diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.html.out.html b/tools/closure_linter/closure_linter/testdata/fixjsstyle.html.out.html deleted file mode 100644 index bb9a16f003d989..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.html.out.html +++ /dev/null @@ -1,51 +0,0 @@ - - - - - -Tests - - - - - - - - - - - diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.in.js b/tools/closure_linter/closure_linter/testdata/fixjsstyle.in.js deleted file mode 100644 index 3a1ccb1f1f7c4f..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.in.js +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/** - * @fileoverview Autofix test script. - * - * @author robbyw@google.com (Robby Walker) - * @author robbyw@google.com (Robby Walker) - * @author robbyw@google.com(Robby Walker) - * @author robbyw@google.com - * @author robbyw@google.com Robby - */ - -goog.provide('w'); -goog.provide('Y'); -goog.provide('X'); -goog.provide('Z'); - -// Some comment about why this is suppressed top. -/** @suppress {extraRequire} */ -goog.require('dummy.NotUsedTop'); // Comment top. -goog.require('dummy.Bb'); -/** @suppress {extraRequire} */ -// Some comment about why this is suppressed different. -goog.require('dummy.NotUsedDifferentComment'); -goog.require('dummy.Cc'); -// Some comment about why this is suppressed middle. -/** @suppress {extraRequire} */ -goog.require('dummy.NotUsedMiddle'); // Comment middle. -goog.require('dummy.Dd'); -goog.require('dummy.aa'); -// Some comment about why this is suppressed bottom. -/** @suppress {extraRequire} */ -goog.require('dummy.NotUsedBottom'); // Comment bottom. - -var x = new dummy.Bb(); -dummy.Cc.someMethod(); -dummy.aa.someMethod(); - - -/** - * @param {number|null} badTypeWithExtraSpace |null -> ?. - * @returns {number} returns -> return. - */ -x.y = function( badTypeWithExtraSpace) { -} - - -/** @type {function():null|Array.} only 2nd |null -> ? */ -x.badType; - - -/** @type {Array.|null} only 2nd |null -> ? */ -x.wickedType; - - -/** @type { string | null } null -> ? */ -x.nullWithSpace; - -spaceBeforeSemicolon = 10 ; -spaceBeforeParen = 10 +(5 * 2); -arrayNoSpace =[10]; -arrayExtraSpace [10] = 10; -spaceBeforeClose = ([10 ] ); -spaceAfterStart = ( [ 10]); -extraSpaceAfterPlus = 10 + 20; -extraSpaceBeforeOperator = x ++; -extraSpaceBeforeOperator = x --; -extraSpaceBeforeComma = x(y , z); -missingSpaceBeforeOperator = x+ y; -missingSpaceAfterOperator = x +y; -missingBothSpaces = x+y; -equalsSpacing= 10; -equalsSpacing =10; -equalsSpacing=10; -equalsSpacing=[10]; -reallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongName=1000; - -"string should be single quotes"; - -// Regression test for interaction between space fixing and semicolon fixing - -// previously the fix for the missing space caused the function to be seen as -// a non-assigned function and then its semicolon was being stripped. -x=function() { -}; - -/** - * Missing a newline. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -};goog.inherits(x.y.z, a.b.c); - -/** - * Extra blank line. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; - -goog.inherits(x.y.z, a.b.c); - -/** - * Perfect! - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; -goog.inherits(x.y.z, a.b.c); - -// Whitespace at end of comment. -var removeWhiteSpaceAtEndOfLine; - -/** - * Whitespace at EOL (here and the line of code and the one below it). - * @type {string} - * @param {string} Description with whitespace at EOL. - */ -x = 10; - -/** - * @type number - */ -foo.bar = 3; - -/** - * @enum {boolean - */ -bar.baz = true; - -/** - * @extends Object} - */ -bar.foo = x; - -/** - * @type function(string, boolean) : void - */ -baz.bar = goog.nullFunction; - -/** {@inheritDoc} */ -baz.baz = function() { -}; - -TR_Node.splitDomTreeAt(splitNode, clone, /** @type Node */ (quoteNode)); - -x = [1, 2, 3,]; -x = { - a: 1, -}; - -if (x) { -}; - -for (i = 0;i < 10; i++) { -} -for (i = 0; i < 10;i++) { -} -for ( i = 0; i < 10; i++) { -} -for (i = 0 ; i < 10; i++) { -} -for (i = 0; i < 10 ; i++) { -} -for (i = 0; i < 10; i++ ) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0 ;i < 10; i++) { -} - -var x = 10 -var y = 100; - - -/** - * This is to test the ability to add or remove a = in type to mark optional - * parameters. - * @param {number=} firstArg Incorrect the name should start with opt_. Don't - * handle the fix (yet). - * @param {function(string=):number} opt_function This should end with a =. - * @param {function(number)} opt_otherFunc This should end with a =. - * @param {string} opt_otherArg Incorrect this should be string=. - * @param {{string, number}} opt_recordArg Incorrect this should - * be {string, number}=. - */ -function someFunction(firstArg, opt_function, opt_otherFunc, opt_otherArg, - opt_recordArg) { -} - - -/** - * This is to test the ability to add '...' in type with variable arguments. - * @param {number} firstArg First argument. - * @param {string} var_args This should start with '...'. - */ -function varArgFunction(firstArg, var_args) { -} - - -/** - * This is to test the ability to add '...' in type with variable arguments. - * @param {number} firstArg First argument. - * @param {{a, b}} var_args This should start with '...'. - */ -function varArgRecordTypeFunction(firstArg, var_args) { -} - -var indent = 'correct'; - indent = 'too far'; -if (indent) { -indent = 'too short'; -} -indent = function() { - return a + - b; -}; - - -/** - * Regression test, must insert whitespace before the 'b' when fixing - * indentation. Its different from below case of bug 3473113 as has spaces - * before parameter which was not working in part of the bug fix. - */ -indentWrongSpaces = function( - b) { -}; - - -/** - * Regression test, must insert whitespace before the 'b' when fixing - * indentation. - * @bug 3473113 - */ -indent = function( -b) { -}; - - - -/** - * This is to test the ability to remove multiple extra lines before a top-level - * block. - */ -function someFunction() {} -/** - * This is to test the ability to add multiple extra lines before a top-level - * block. - */ -function someFunction() {} - - -// This is a comment. -/** - * This is to test that blank lines removed before a top level block skips any - * comments above the block. - */ -function someFunction() {} -// This is a comment. -/** - * This is to test that blank lines added before a top level block skips any - * comments above the block. - */ -function someFunction() {} - - -/** - * Parameters don't have proper spaces. - * @param {number} a - * @param {number} b - * @param {number} d - * @param {number} e - * @param {number} f - */ -function someFunction(a, b,d, e, f) { -} - -// File does not end with newline \ No newline at end of file diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.indentation.out.js b/tools/closure_linter/closure_linter/testdata/fixjsstyle.indentation.out.js deleted file mode 100644 index 4d7c3853c8db5e..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.indentation.out.js +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Test file for indentation. - * @author robbyw@google.com (Robert Walker) - */ - -goog.provide('goog.editor.SeamlessField'); -goog.provide('goog.something'); - -goog.require('goog.events.KeyCodes'); -goog.require('goog.userAgent'); - -// Some good indentation examples. - -var x = 10; -var y = 'some really really really really really really really long string', - z = 14; -if (x == 10) { - x = 12; -} -if (x == 10 || - x == 12) { - x = 14; -} -if (x == 14) { - if (z >= x) { - y = 'test'; - } -} -x = x + - 10 + ( - 14 - ); -something = - 5; -var arr = [ - 1, 2, 3]; -var arr2 = [ - 1, - 2, - 3]; -var obj = { - a: 10, - b: 20 -}; -callAFunction(10, [100, 200], - 300); -callAFunction([ - 100, - 200 -], -300); -callAFunction('abc' + - 'def' + - 'ghi'); - -x.reallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongName - .someMember = 10; - - -// confused on allowed indentation in continued function assignments vs overlong -// wrapped function calls. -some.sample() // LINE_ENDS_WITH_DOT - .then(function(response) { - return 1; - }); - - -/** - * Some function. - * @return {number} The number ten. - */ -goog.something.x = function() { - return 10 + - 20; -}; - - -/** - * Some function. - * @param {number} longParameterName1 Some number. - * @param {number} longParameterName2 Some number. - * @param {number} longParameterName3 Some number. - * @return {number} Sum number. - */ -goog.something.y = function(longParameterName1, longParameterName2, - longParameterName3) { - return longParameterName1 + longParameterName2 + longParameterName3; -}; - - -/** - * Some function. - * @param {number} longParameterName1 Some number. - * @param {number} longParameterName2 Some number. - * @param {number} longParameterName3 Some number. - * @return {number} Sum number. - */ -goog.something.z = function(longParameterName1, longParameterName2, - longParameterName3) { - return longParameterName1 + longParameterName2 + longParameterName3; -}; - -if (opt_rootTagName) { - doc.appendChild(doc.createNode(3, - opt_rootTagName, - opt_namespaceUri || '')); -} - - -/** - * For a while this errored because the function call parens were overriding - * the other opening paren. - */ -goog.something.q = function() { - goog.something.x(a.getStartNode(), - a.getStartOffset(), a.getEndNode(), a.getEndOffset()); -}; - -function doSomething() { - var titleElement = goog.something(x, // UNUSED_LOCAL_VARIABLE - y); -} - -switch (x) { - case 10: - y = 100; - break; - - // This should be allowed. - case 20: - if (y) { - z = 0; - } - break; - - // This should be allowed, - // even with mutliple lines. - case 30: - if (y) { - z = 0; - } - break; - - case SadThatYouSwitch - .onSomethingLikeThis: - z = 10; - - case 40: - z = 20; - - default: - break; -} - -// Description of if case. -if (x) { - -// Description of else case should be allowed at this indent. -// Multiple lines is ok. -} else { - -} - - -/** @inheritDoc */ -goog.editor.SeamlessField.prototype.setupMutationEventHandlersGecko = - function() { - var x = 10; - x++; -}; - - -// Regression test for '.' at the end confusing the indentation checker if it is -// not considered to be part of the identifier. -/** @inheritDoc */ -goog.editor.SeamlessField.prototype - .setupMutationEventHandlersGecko = function() { - // -2: LINE_ENDS_WITH_DOT - var x = 10; - x++; -}; - -var someReallyReallyLongVariableName = - y ? /veryVeryVeryVeryVeryVeryVeryVeryLongRegex1/gi : - /slightlyLessLongRegex2/gi; - -var somethingOrOther = z ? - a : - b; - -var z = x ? y : - 'bar'; - -var z = x ? - y : - a; - -var z = z ? - a ? b : c : - d ? e : f; - -var z = z ? - a ? b : - c : - d ? e : f; - -var z = z ? - a ? - b : - c : - d ? e : f; - -var z = z ? - a ? b : c : - d ? e : - f ? g : h; - -var z = z ? - a + - i ? - b + - j : c : - d ? e : - f ? g : h; - - -if (x) { - var block = - // some comment - // and some more comment - (e.keyCode == goog.events.KeyCodes.TAB && !this.dispatchBeforeTab_(e)) || - // #2: to block a Firefox-specific bug where Macs try to navigate - // back a page when you hit command+left arrow or comamnd-right arrow. - // See https://bugzilla.mozilla.org/show_bug.cgi?id=341886 - // get Firefox to fix this. - (goog.userAgent.GECKO && e.metaKey && - (e.keyCode == goog.events.KeyCodes.LEFT || - e.keyCode == goog.events.KeyCodes.RIGHT)); -} - -if (x) { -} - -var somethingElse = { - HAS_W3C_RANGES: goog.userAgent.GECKO || goog.userAgent.WEBKIT || - goog.userAgent.OPERA, - - // A reasonably placed comment. - SOME_KEY: goog.userAgent.IE -}; - -var x = { - ySomethingReallyReallyLong: - 'foo', - z: 'bar' -}; - -// Some bad indentation. - -var a = 10; // WRONG_INDENTATION -var b = 10, - c = 12; // WRONG_INDENTATION -x = x + - 10; // WRONG_INDENTATION -if (x == 14) { - x = 15; // WRONG_INDENTATION - x = 16; // WRONG_INDENTATION -} - -var longFunctionName = function(opt_element) { - return opt_element ? - new z(q(opt_element)) : 100; - // -1: WRONG_INDENTATION -}; - -longFunctionName(a, b, c, - d, e, f); // WRONG_INDENTATION -longFunctionName(a, b, - c, // WRONG_INDENTATION - d); // WRONG_INDENTATION - -x = a ? b : - c; // WRONG_INDENTATION -y = a ? - b : c; // WRONG_INDENTATION - -switch (x) { - case 10: - break; // WRONG_INDENTATION - case 20: // WRONG_INDENTATION - break; - default: // WRONG_INDENTATION - break; -} - -while (true) { - x = 10; // WRONG_INDENTATION - break; // WRONG_INDENTATION -} - -function foo() { - return entryUrlTemplate - .replace( - '${authorResourceId}', - this.sanitizer_.sanitize(authorResourceId)); -} - -return [new x( - 10)]; -return [ - new x(10)]; - -return [new x( - 10)]; // WRONG_INDENTATION -return [new x( - 10)]; // WRONG_INDENTATION - -return {x: y( - z)}; -return { - x: y(z) -}; - -return {x: y( - z)}; // WRONG_INDENTATION -return {x: y( - z)}; // WRONG_INDENTATION - -return /** @type {Window} */ (x( - 'javascript:"' + encodeURI(loadingMessage) + '"')); // WRONG_INDENTATION - -x = { - y: function() {} -}; - -x = { - y: foo, - z: bar + - baz // WRONG_INDENTATION -}; - -x({ - a: b -}, -10); - -z = function(arr, f, val, opt_obj) { - x(arr, function(val, index) { - rval = f.call(opt_obj, rval, val, index, arr); - }); -}; - -var xyz = [100, - 200, - 300]; - -var def = [100, - 200]; // WRONG_INDENTATION - -var ghi = [100, - 200]; // WRONG_INDENTATION - -var abcdefg = ('a' + - 'b'); - -var x9 = z('7: ' + - x(x)); // WRONG_INDENTATION - -function abc() { - var z = d('div', // UNUSED_LOCAL_VARIABLE - { - a: 'b' - }); -} - -abcdefg('p', {x: 10}, - 'Para 1'); - -function bar1() { - return 3 + - 4; // WRONG_INDENTATION -} - -function bar2() { - return 3 + // WRONG_INDENTATION - 4; // WRONG_INDENTATION -} - -function bar3() { - return 3 + // WRONG_INDENTATION - 4; -} - -// Regression test for unfiled bug. Wrongly going into implied block after else -// when there was an explicit block (was an else if) caused false positive -// indentation errors. -if (true) { -} else if (doc.foo( - doc.getBar(baz))) { - var x = 3; -} - -// Regression tests for function indent + 4. -// (The first example is from the styleguide.) -if (veryLongFunctionNameA( - veryLongArgumentName) || - veryLongFunctionNameB( - veryLongArgumentName)) { - veryLongFunctionNameC(veryLongFunctionNameD( - veryLongFunctioNameE( - veryLongFunctionNameF))); -} - -if (outer(middle( - inner(first)))) {} -if (outer(middle( - inner(second)), - outer_second)) {} -if (nested.outer( - first)) {} -if (nested.outer(nested.middle( - first))) {} -if (nested - .outer(nested.middle( - first))) {} -if (nested.outer(first - .middle( - second), - third)) {} - -// goog.scope should not increase indentation. -goog.scope(function() { -var x = 5; -while (x > 0) { - --x; -} -}); // goog.scope - - -goog.scope(function() { // EXTRA_GOOG_SCOPE_USAGE -// +1: UNUSED_LOCAL_VARIABLE -var x = 5; // WRONG_INDENTATION -}); // goog.scope - -goog.scope(function() { // EXTRA_GOOG_SCOPE_USAGE -var x = 5; // UNUSED_LOCAL_VARIABLE -}); // goog.scope - -goog.scope(function() { // EXTRA_GOOG_SCOPE_USAGE -var x = 5; // UNUSED_LOCAL_VARIABLE -}); // goog.scope diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.oplineend.in.js b/tools/closure_linter/closure_linter/testdata/fixjsstyle.oplineend.in.js deleted file mode 100644 index 974af915d364ba..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.oplineend.in.js +++ /dev/null @@ -1,21 +0,0 @@ -// Correct dot placement: -var x = window.some() - .method() - .calls(); - -// Wrong dots: -window. - some(). - // With a comment in between. - method(). - calls(); - -// Wrong plus operator: -var y = 'hello' - + 'world' - // With a comment in between. - + '!'; - -// Correct plus operator (untouched): -var y = 'hello' + - 'world'; diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.oplineend.out.js b/tools/closure_linter/closure_linter/testdata/fixjsstyle.oplineend.out.js deleted file mode 100644 index c03e11730abc09..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.oplineend.out.js +++ /dev/null @@ -1,21 +0,0 @@ -// Correct dot placement: -var x = window.some() - .method() - .calls(); - -// Wrong dots: -window - .some() - // With a comment in between. - .method() - .calls(); - -// Wrong plus operator: -var y = 'hello' + - 'world' + - // With a comment in between. - '!'; - -// Correct plus operator (untouched): -var y = 'hello' + - 'world'; diff --git a/tools/closure_linter/closure_linter/testdata/fixjsstyle.out.js b/tools/closure_linter/closure_linter/testdata/fixjsstyle.out.js deleted file mode 100644 index 37fe2b8b3c7bd5..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/fixjsstyle.out.js +++ /dev/null @@ -1,310 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Autofix test script. - * - * @author robbyw@google.com (Robby Walker) - * @author robbyw@google.com (Robby Walker) - * @author robbyw@google.com (Robby Walker) - * @author robbyw@google.com (Robby Walker) - * @author robbyw@google.com (Robby) - * @author robbyw@google.com - * @author robbyw@google.com Robby - */ - -goog.provide('X'); -goog.provide('Y'); -goog.provide('Z'); -goog.provide('w'); - -goog.require('dummy.Bb'); -goog.require('dummy.Cc'); -// Some comment about why this is suppressed bottom. -/** @suppress {extraRequire} */ -goog.require('dummy.NotUsedBottom'); // Comment bottom. -/** @suppress {extraRequire} */ -// Some comment about why this is suppressed different. -goog.require('dummy.NotUsedDifferentComment'); -// Some comment about why this is suppressed middle. -/** @suppress {extraRequire} */ -goog.require('dummy.NotUsedMiddle'); // Comment middle. -// Some comment about why this is suppressed top. -/** @suppress {extraRequire} */ -goog.require('dummy.NotUsedTop'); // Comment top. -goog.require('dummy.aa'); - -var x = new dummy.Bb(); -dummy.Cc.someMethod(); -dummy.aa.someMethod(); - - -/** - * @param {?number} badTypeWithExtraSpace |null -> ?. - * @return {number} returns -> return. - */ -x.y = function(badTypeWithExtraSpace) { -}; - - -/** @type {function():null|Array.} only 2nd |null -> ? */ -x.badType; - - -/** @type {?Array.} only 2nd |null -> ? */ -x.wickedType; - - -/** @type {? string } null -> ? */ -x.nullWithSpace; - -spaceBeforeSemicolon = 10; -spaceBeforeParen = 10 + (5 * 2); -arrayNoSpace = [10]; -arrayExtraSpace[10] = 10; -spaceBeforeClose = ([10]); -spaceAfterStart = ([10]); -extraSpaceAfterPlus = 10 + 20; -extraSpaceBeforeOperator = x++; -extraSpaceBeforeOperator = x--; -extraSpaceBeforeComma = x(y, z); -missingSpaceBeforeOperator = x + y; -missingSpaceAfterOperator = x + y; -missingBothSpaces = x + y; -equalsSpacing = 10; -equalsSpacing = 10; -equalsSpacing = 10; -equalsSpacing = [10]; -reallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongName = 1000; - -'string should be single quotes'; - -// Regression test for interaction between space fixing and semicolon fixing - -// previously the fix for the missing space caused the function to be seen as -// a non-assigned function and then its semicolon was being stripped. -x = function() { -}; - - - -/** - * Missing a newline. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; -goog.inherits(x.y.z, a.b.c); - - - -/** - * Extra blank line. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; -goog.inherits(x.y.z, a.b.c); - - - -/** - * Perfect! - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; -goog.inherits(x.y.z, a.b.c); - -// Whitespace at end of comment. -var removeWhiteSpaceAtEndOfLine; - - -/** - * Whitespace at EOL (here and the line of code and the one below it). - * @type {string} - * @param {string} Description with whitespace at EOL. - */ -x = 10; - - -/** - * @type {number} - */ -foo.bar = 3; - - -/** - * @enum {boolean} - */ -bar.baz = true; - - -/** - * @extends {Object} - */ -bar.foo = x; - - -/** - * @type {function(string, boolean) : void} - */ -baz.bar = goog.nullFunction; - - -/** @inheritDoc */ -baz.baz = function() { -}; - -TR_Node.splitDomTreeAt(splitNode, clone, /** @type {Node} */ (quoteNode)); - -x = [1, 2, 3,]; -x = { - a: 1, -}; - -if (x) { -} - -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} -for (i = 0; i < 10; i++) { -} - -var x = 10; -var y = 100; - - -/** - * This is to test the ability to add or remove a = in type to mark optional - * parameters. - * @param {number=} firstArg Incorrect the name should start with opt_. Don't - * handle the fix (yet). - * @param {function(string=):number=} opt_function This should end with a =. - * @param {function(number)=} opt_otherFunc This should end with a =. - * @param {string=} opt_otherArg Incorrect this should be string=. - * @param {{string, number}=} opt_recordArg Incorrect this should - * be {string, number}=. - */ -function someFunction(firstArg, opt_function, opt_otherFunc, opt_otherArg, - opt_recordArg) { -} - - -/** - * This is to test the ability to add '...' in type with variable arguments. - * @param {number} firstArg First argument. - * @param {...string} var_args This should start with '...'. - */ -function varArgFunction(firstArg, var_args) { -} - - -/** - * This is to test the ability to add '...' in type with variable arguments. - * @param {number} firstArg First argument. - * @param {...{a, b}} var_args This should start with '...'. - */ -function varArgRecordTypeFunction(firstArg, var_args) { -} - -var indent = 'correct'; -indent = 'too far'; -if (indent) { - indent = 'too short'; -} -indent = function() { - return a + - b; -}; - - -/** - * Regression test, must insert whitespace before the 'b' when fixing - * indentation. Its different from below case of bug 3473113 as has spaces - * before parameter which was not working in part of the bug fix. - */ -indentWrongSpaces = function( - b) { -}; - - -/** - * Regression test, must insert whitespace before the 'b' when fixing - * indentation. - * @bug 3473113 - */ -indent = function( - b) { -}; - - -/** - * This is to test the ability to remove multiple extra lines before a top-level - * block. - */ -function someFunction() {} - - -/** - * This is to test the ability to add multiple extra lines before a top-level - * block. - */ -function someFunction() {} - - -// This is a comment. -/** - * This is to test that blank lines removed before a top level block skips any - * comments above the block. - */ -function someFunction() {} - - -// This is a comment. -/** - * This is to test that blank lines added before a top level block skips any - * comments above the block. - */ -function someFunction() {} - - -/** - * Parameters don't have proper spaces. - * @param {number} a - * @param {number} b - * @param {number} d - * @param {number} e - * @param {number} f - */ -function someFunction(a, b, d, e, f) { -} - -// File does not end with newline diff --git a/tools/closure_linter/closure_linter/testdata/goog_scope.js b/tools/closure_linter/closure_linter/testdata/goog_scope.js deleted file mode 100644 index aa655d8e6dfb02..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/goog_scope.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2011 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Tests provides/requires in the presence of goog.scope. - * There should be no errors for missing provides or requires. - * - * @author nicksantos@google.com (Nick Santos) - */ - -goog.provide('goog.something.Something'); - -goog.require('goog.util.Else'); - -goog.scope(function() { -var Else = goog.util.Else; -var something = goog.something; - -/** // WRONG_BLANK_LINE_COUNT - * This is a something. - * @constructor - */ -something.Something = function() { - /** - * This is an else. - * @type {Else} - */ - this.myElse = new Else(); - - /** @type {boolean} */ - this.private_ = false; // MISSING_PRIVATE, UNUSED_PRIVATE_MEMBER -}; - -/** // WRONG_BLANK_LINE_COUNT - * // +3: MISSING_PRIVATE - * Missing private. - */ -something.withTrailingUnderscore_ = 'should be declared @private'; - -/** // WRONG_BLANK_LINE_COUNT - * Does nothing. - */ -something.Something.prototype.noOp = function() {}; - - -/** - * Does something. - * Tests for included semicolon in function expression in goog.scope. - */ -something.Something.prototype.someOp = function() { -} // MISSING_SEMICOLON_AFTER_FUNCTION -}); // goog.scope diff --git a/tools/closure_linter/closure_linter/testdata/html_parse_error.html b/tools/closure_linter/closure_linter/testdata/html_parse_error.html deleted file mode 100644 index df61da10c7f6f2..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/html_parse_error.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - GJsLint HTML JavaScript extraction tests - - - Text outside the script tag should not be linted as JavaScript. - Stray closing brace: } - -
Some more non-JavaScript text with missing whitespace: (a+b).
- - diff --git a/tools/closure_linter/closure_linter/testdata/indentation.js b/tools/closure_linter/closure_linter/testdata/indentation.js deleted file mode 100644 index 10d2ad0174d5ff..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/indentation.js +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Test file for indentation. - * @author robbyw@google.com (Robert Walker) - */ - -goog.provide('goog.editor.SeamlessField'); -goog.provide('goog.something'); - -goog.require('goog.events.KeyCodes'); -goog.require('goog.userAgent'); - -// Some good indentation examples. - -var x = 10; -var y = 'some really really really really really really really long string', - z = 14; -if (x == 10) { - x = 12; -} -if (x == 10 || - x == 12) { - x = 14; -} -if (x == 14) { - if (z >= x) { - y = 'test'; - } -} -x = x + - 10 + ( - 14 - ); -something = - 5; -var arr = [ - 1, 2, 3]; -var arr2 = [ - 1, - 2, - 3]; -var obj = { - a: 10, - b: 20 -}; -callAFunction(10, [100, 200], - 300); -callAFunction([ - 100, - 200 -], -300); -callAFunction('abc' + - 'def' + - 'ghi'); - -x.reallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongName - .someMember = 10; - - -// confused on allowed indentation in continued function assignments vs overlong -// wrapped function calls. -some.sample(). // LINE_ENDS_WITH_DOT - then(function(response) { - return 1; - }); - - -/** - * Some function. - * @return {number} The number ten. - */ -goog.something.x = function() { - return 10 + - 20; -}; - - -/** - * Some function. - * @param {number} longParameterName1 Some number. - * @param {number} longParameterName2 Some number. - * @param {number} longParameterName3 Some number. - * @return {number} Sum number. - */ -goog.something.y = function(longParameterName1, longParameterName2, - longParameterName3) { - return longParameterName1 + longParameterName2 + longParameterName3; -}; - - -/** - * Some function. - * @param {number} longParameterName1 Some number. - * @param {number} longParameterName2 Some number. - * @param {number} longParameterName3 Some number. - * @return {number} Sum number. - */ -goog.something.z = function(longParameterName1, longParameterName2, - longParameterName3) { - return longParameterName1 + longParameterName2 + longParameterName3; -}; - -if (opt_rootTagName) { - doc.appendChild(doc.createNode(3, - opt_rootTagName, - opt_namespaceUri || '')); -} - - -/** - * For a while this errored because the function call parens were overriding - * the other opening paren. - */ -goog.something.q = function() { - goog.something.x(a.getStartNode(), - a.getStartOffset(), a.getEndNode(), a.getEndOffset()); -}; - -function doSomething() { - var titleElement = goog.something(x, // UNUSED_LOCAL_VARIABLE - y); -} - -switch (x) { - case 10: - y = 100; - break; - - // This should be allowed. - case 20: - if (y) { - z = 0; - } - break; - - // This should be allowed, - // even with mutliple lines. - case 30: - if (y) { - z = 0; - } - break; - - case SadThatYouSwitch - .onSomethingLikeThis: - z = 10; - - case 40: - z = 20; - - default: - break; -} - -// Description of if case. -if (x) { - -// Description of else case should be allowed at this indent. -// Multiple lines is ok. -} else { - -} - - -/** @inheritDoc */ -goog.editor.SeamlessField.prototype.setupMutationEventHandlersGecko = - function() { - var x = 10; - x++; -}; - - -// Regression test for '.' at the end confusing the indentation checker if it is -// not considered to be part of the identifier. -/** @inheritDoc */ -goog.editor.SeamlessField.prototype. - setupMutationEventHandlersGecko = function() { - // -2: LINE_ENDS_WITH_DOT - var x = 10; - x++; -}; - -var someReallyReallyLongVariableName = - y ? /veryVeryVeryVeryVeryVeryVeryVeryLongRegex1/gi : - /slightlyLessLongRegex2/gi; - -var somethingOrOther = z ? - a : - b; - -var z = x ? y : - 'bar'; - -var z = x ? - y : - a; - -var z = z ? - a ? b : c : - d ? e : f; - -var z = z ? - a ? b : - c : - d ? e : f; - -var z = z ? - a ? - b : - c : - d ? e : f; - -var z = z ? - a ? b : c : - d ? e : - f ? g : h; - -var z = z ? - a + - i ? - b + - j : c : - d ? e : - f ? g : h; - - -if (x) { - var block = - // some comment - // and some more comment - (e.keyCode == goog.events.KeyCodes.TAB && !this.dispatchBeforeTab_(e)) || - // #2: to block a Firefox-specific bug where Macs try to navigate - // back a page when you hit command+left arrow or comamnd-right arrow. - // See https://bugzilla.mozilla.org/show_bug.cgi?id=341886 - // get Firefox to fix this. - (goog.userAgent.GECKO && e.metaKey && - (e.keyCode == goog.events.KeyCodes.LEFT || - e.keyCode == goog.events.KeyCodes.RIGHT)); -} - -if (x) { -} - -var somethingElse = { - HAS_W3C_RANGES: goog.userAgent.GECKO || goog.userAgent.WEBKIT || - goog.userAgent.OPERA, - - // A reasonably placed comment. - SOME_KEY: goog.userAgent.IE -}; - -var x = { - ySomethingReallyReallyLong: - 'foo', - z: 'bar' -}; - -// Some bad indentation. - - var a = 10; // WRONG_INDENTATION -var b = 10, - c = 12; // WRONG_INDENTATION -x = x + - 10; // WRONG_INDENTATION -if (x == 14) { - x = 15; // WRONG_INDENTATION - x = 16; // WRONG_INDENTATION -} - -var longFunctionName = function(opt_element) { - return opt_element ? - new z(q(opt_element)) : 100; - // -1: WRONG_INDENTATION -}; - -longFunctionName(a, b, c, - d, e, f); // WRONG_INDENTATION -longFunctionName(a, b, - c, // WRONG_INDENTATION - d); // WRONG_INDENTATION - -x = a ? b : - c; // WRONG_INDENTATION -y = a ? - b : c; // WRONG_INDENTATION - -switch (x) { - case 10: - break; // WRONG_INDENTATION - case 20: // WRONG_INDENTATION - break; -default: // WRONG_INDENTATION - break; -} - -while (true) { - x = 10; // WRONG_INDENTATION - break; // WRONG_INDENTATION -} - -function foo() { - return entryUrlTemplate - .replace( - '${authorResourceId}', - this.sanitizer_.sanitize(authorResourceId)); -} - -return [new x( - 10)]; -return [ - new x(10)]; - -return [new x( - 10)]; // WRONG_INDENTATION -return [new x( - 10)]; // WRONG_INDENTATION - -return {x: y( - z)}; -return { - x: y(z) -}; - -return {x: y( - z)}; // WRONG_INDENTATION -return {x: y( - z)}; // WRONG_INDENTATION - -return /** @type {Window} */ (x( -'javascript:"' + encodeURI(loadingMessage) + '"')); // WRONG_INDENTATION - -x = { - y: function() {} -}; - -x = { - y: foo, - z: bar + - baz // WRONG_INDENTATION -}; - -x({ - a: b -}, -10); - -z = function(arr, f, val, opt_obj) { - x(arr, function(val, index) { - rval = f.call(opt_obj, rval, val, index, arr); - }); -}; - -var xyz = [100, - 200, - 300]; - -var def = [100, - 200]; // WRONG_INDENTATION - -var ghi = [100, - 200]; // WRONG_INDENTATION - -var abcdefg = ('a' + - 'b'); - -var x9 = z('7: ' + -x(x)); // WRONG_INDENTATION - -function abc() { - var z = d('div', // UNUSED_LOCAL_VARIABLE - { - a: 'b' - }); -} - -abcdefg('p', {x: 10}, - 'Para 1'); - -function bar1() { - return 3 + - 4; // WRONG_INDENTATION -} - -function bar2() { - return 3 + // WRONG_INDENTATION - 4; // WRONG_INDENTATION -} - -function bar3() { - return 3 + // WRONG_INDENTATION - 4; -} - -// Regression test for unfiled bug. Wrongly going into implied block after else -// when there was an explicit block (was an else if) caused false positive -// indentation errors. -if (true) { -} else if (doc.foo( - doc.getBar(baz))) { - var x = 3; -} - -// Regression tests for function indent + 4. -// (The first example is from the styleguide.) -if (veryLongFunctionNameA( - veryLongArgumentName) || - veryLongFunctionNameB( - veryLongArgumentName)) { - veryLongFunctionNameC(veryLongFunctionNameD( - veryLongFunctioNameE( - veryLongFunctionNameF))); -} - -if (outer(middle( - inner(first)))) {} -if (outer(middle( - inner(second)), - outer_second)) {} -if (nested.outer( - first)) {} -if (nested.outer(nested.middle( - first))) {} -if (nested - .outer(nested.middle( - first))) {} -if (nested.outer(first - .middle( - second), - third)) {} - -// goog.scope should not increase indentation. -goog.scope(function() { -var x = 5; -while (x > 0) { - --x; -} -}); // goog.scope - - -goog.scope(function() { // EXTRA_GOOG_SCOPE_USAGE -// +1: UNUSED_LOCAL_VARIABLE - var x = 5; // WRONG_INDENTATION -}); // goog.scope - -goog.scope(function() { // EXTRA_GOOG_SCOPE_USAGE -var x = 5; // UNUSED_LOCAL_VARIABLE -}); // MISSING_END_OF_SCOPE_COMMENT - -goog.scope(function() { // EXTRA_GOOG_SCOPE_USAGE -var x = 5; // UNUSED_LOCAL_VARIABLE -}); // malformed goog.scope comment // MALFORMED_END_OF_SCOPE_COMMENT diff --git a/tools/closure_linter/closure_linter/testdata/interface.js b/tools/closure_linter/closure_linter/testdata/interface.js deleted file mode 100644 index 7daeee3ca8bbca..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/interface.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Test file for interfaces. - * @author robbyw@google.com (Robert Walker) - */ - -goog.provide('sample.BadInterface'); -goog.provide('sample.GoodInterface'); - - - -/** - * Sample interface to demonstrate correct style. - * @interface - */ -sample.GoodInterface = function() { -}; - - -/** - * Legal methods can take parameters and have a return type. - * @param {string} param1 First parameter. - * @param {Object} param2 Second parameter. - * @return {number} Some return value. - */ -sample.GoodInterface.prototype.legalMethod = function(param1, param2) { -}; - - -/** - * Legal methods can also take no parameters and return nothing. - */ -sample.GoodInterface.prototype.legalMethod2 = function() { - // Comments should be allowed. -}; - - -/** - * Legal methods can also be omitted, even with params and return values. - * @param {string} param1 First parameter. - * @param {Object} param2 Second parameter. - * @return {number} Some return value. - */ -sample.GoodInterface.prototype.legalMethod3; - - -/** - * Legal methods can also be set to abstract, even with params and return - * values. - * @param {string} param1 First parameter. - * @param {Object} param2 Second parameter. - * @return {number} Some return value. - */ -sample.GoodInterface.prototype.legalMethod4 = goog.abstractMethod; - - - -/** - * Sample interface to demonstrate style errors. - * @param {string} a This is illegal. - * @interface - */ -sample.BadInterface = function(a) { // INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS - this.x = a; // INTERFACE_METHOD_CANNOT_HAVE_CODE -}; - - -/** - * It is illegal to include code in an interface method. - * @param {string} param1 First parameter. - * @param {Object} param2 Second parameter. - * @return {number} Some return value. - */ -sample.BadInterface.prototype.illegalMethod = function(param1, param2) { - return 10; // INTERFACE_METHOD_CANNOT_HAVE_CODE -}; diff --git a/tools/closure_linter/closure_linter/testdata/jsdoc.js b/tools/closure_linter/closure_linter/testdata/jsdoc.js deleted file mode 100644 index d62fd3c5fcb717..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/jsdoc.js +++ /dev/null @@ -1,1455 +0,0 @@ -// Copyright 2007 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Errors related to JsDoc. - * - * @author robbyw@google.com (Robby Walker) - * - * @author robbyw@google.com (Robby Walker) // EXTRA_SPACE, EXTRA_SPACE - * @author robbyw@google.com(Robby Walker) // MISSING_SPACE - * - * @author robbyw@google.com () // INVALID_AUTHOR_TAG_DESCRIPTION - * @author robbyw@google.com // INVALID_AUTHOR_TAG_DESCRIPTION - * - * @owner ajp@google.com (Andy Perelson) - * @badtag // INVALID_JSDOC_TAG - * @customtag This tag is passed as a flag in full_test.py - * @requires anotherCustomTagPassedInFromFullTestThatShouldAllowASingleWordLongerThan80Lines - * @requires firstWord, secondWordWhichShouldMakeThisLineTooLongSinceThereIsAFirstWord - * @wizmodule - * @wizModule // INVALID_JSDOC_TAG - */ -// -4: LINE_TOO_LONG - -goog.provide('MyClass'); -goog.provide('goog.NumberLike'); -goog.provide('goog.math.Vec2.sum'); - -goog.require('goog.array'); -goog.require('goog.color'); -goog.require('goog.dom.Range'); -goog.require('goog.math.Matrix'); -goog.require('goog.math.Vec2'); - - -/** - * Test the "no compilation should be done after annotation processing" tag. - * @nocompile - */ - - -/** - * @returns // INVALID_JSDOC_TAG - * @params // INVALID_JSDOC_TAG - * @defines // INVALID_JSDOC_TAG - * @nginject // INVALID_JSDOC_TAG - * @wizAction // INVALID_JSDOC_TAG - */ -function badTags() { -} - - -// +4: MISSING_JSDOC_TAG_DESCRIPTION -/** - * @license Description. - * @preserve Good tag, missing punctuation - * @preserve - */ -function goodTags() { - /** @preserveTry */ - try { - hexColor = goog.color.parse(value).hex; - } catch (ext) { - // Regression test. The preserveTry tag was incorrectly causing a warning - // for a missing period at the end of tag description. Parsed as - // flag: preserve, description: Try. - } -} - - -/** - * Some documentation goes here. - * - * @param {Object} object Good docs. - * @ngInject - * @wizaction - */ -function good(object) { -} - - -/** - * Some documentation goes here. - * @param {function(string, string) : string} f A function. - */ -function setConcatFunc(f) { -} - - -/** - * Some docs. - */ -function missingParam(object) { // MISSING_PARAMETER_DOCUMENTATION -} - - -/** - * @return {number} Hiya. - * @override - */ -function missingParamButInherit(object) { - return 3; -} - - -/** - * @inheritDoc - */ -function missingParamButInherit(object) { -} - - -/** - * @override - */ -function missingParamButOverride(object) { -} - - -// +2: UNNECESSARY_BRACES_AROUND_INHERIT_DOC -/** - * {@inheritDoc} - */ -function missingParamButInherit(object) { -} - - -/** - * Some docs. - * - * @param {Object} object Docs. - */ -function mismatchedParam(elem) { // WRONG_PARAMETER_DOCUMENTATION - /** @param {number} otherElem */ - function nestedFunction(elem) { // WRONG_PARAMETER_DOCUMENTATION - }; -} - - -/** - * @return {boolean} A boolean primitive. - */ -function goodReturn() { - return something; -} - - -/** - * @return {some.long.type.that.will.make.the.description.start.on.next.line} - * An object. - */ -function anotherGoodReturn() { - return something; -} - - -// +2: MISSING_JSDOC_TAG_TYPE -/** - * @return false. - */ -function missingReturnType() { - return something; -} - - -// +2: MISSING_SPACE -/** - * @return{type} - */ -function missingSpaceOnReturnType() { - return something; -} - - -// +2: MISSING_JSDOC_TAG_TYPE -/** - * @return - */ -function missingReturnType() { - return something; -} - -class.missingDocs = function() { // MISSING_MEMBER_DOCUMENTATION -}; - - -/** - * No return doc needed. - */ -function okMissingReturnDoc() { - return; -} - - -// +2: UNNECESSARY_RETURN_DOCUMENTATION -/** - * @return {number} Unnecessary return doc. - */ -function unnecessaryMissingReturnDoc() { -} - - -/** - * The "suppress" causes the compiler to ignore the 'debugger' statement. - * @suppress {checkDebuggerStatement} - */ -function checkDebuggerStatementWithSuppress() { - debugger; -} - - -/** - * Return doc is present, but the function doesn't have a 'return' statement. - * The "suppress" causes the compiler to ignore the error. - * @suppress {missingReturn} - * @return {string} - */ -function unnecessaryMissingReturnDocWithSuppress() { - if (false) { - return ''; - } else { - // Missing return statement in this branch. - } -} - - -// +3: MISSING_JSDOC_TAG_TYPE -// +2: UNNECESSARY_RETURN_DOCUMENTATION -/** - * @return - */ -function unnecessaryMissingReturnNoType() { -} - - -/** - * @return {undefined} Ok unnecessary return doc. - */ -function okUnnecessaryMissingReturnDoc() { -} - - -/** - * @return {*} Ok unnecessary return doc. - */ -function okUnnecessaryMissingReturnDoc2() { -} - - -/** - * @return {void} Ok unnecessary return doc. - */ -function okUnnecessaryMissingReturnDoc3() { -} - - -/** - * This function doesn't return anything, but it does contain the string return. - */ -function makeSureReturnTokenizesRight() { - fn(returnIsNotSomethingHappeningHere); -} - - -/** - * @return {number|undefined} Ok unnecessary return doc. - */ -function okUnnecessaryMissingReturnDoc3() { -} - - -/** - * @return {number} Ok unnecessary return doc. - */ -function okUnnecessaryReturnWithThrow() { - throw 'foo'; -} - - -/** @inheritDoc */ -function okNoReturnWithInheritDoc() { - return 10; -} - - -/** @override */ -function okNoReturnWithOverride() { - return 10; -} - - -/** - * No return doc. - */ // MISSING_RETURN_DOCUMENTATION -function badMissingReturnDoc() { - return 10; -} - - - -/** - * Constructor so we should not have a return jsdoc tag. - * @constructor - */ -function OkNoReturnWithConstructor() { - return this; -} - - -/** - * Type of array is known, so the cast is unnecessary. - * @suppress {unnecessaryCasts} - */ -function unnecessaryCastWithSuppress() { - var numberArray = /** @type {!Array.} */ ([]); - /** @type {number} */ (goog.array.peek(numberArray)); -} - - - -/** - * Make sure the 'unrestricted' annotation is accepted. - * @constructor @unrestricted - */ -function UnrestrictedClass() {} - - - -/** - * Check definition of fields in constructors. - * @constructor - */ -function AConstructor() { - /** - * A field. - * @type {string} - * @private - */ - this.isOk_ = 'ok'; - - // +5: MISSING_PRIVATE - /** - * Another field. - * @type {string} - */ - this.isBad_ = 'missing private'; - - /** - * This is ok, but a little weird. - * @type {number} - * @private - */ - var x = this.x_ = 10; - - // At first, this block mis-attributed the first typecast as a member doc, - // and therefore expected it to contain @private. - if (goog.math.Matrix.isValidArray(/** @type {Array} */ (m))) { - this.array_ = goog.array.clone(/** @type {Array.>} */ (m)); - } - - // Use the private and local variables we've defined so they don't generate a - // warning. - var y = [ - this.isOk_, - this.isBad_, - this.array_, - this.x_, - y, - x - ]; -} - - -/** - * @desc This message description is allowed. - */ -var MSG_YADDA_YADDA_YADDA = 'A great message!'; - - -/** - * @desc So is this one. - * @hidden - * @meaning Some unusual meaning. - */ -x.y.z.MSG_YADDA_YADDA_YADDA = 'A great message!'; - - -/** - * @desc But desc can only apply to messages. - */ -var x = 10; // INVALID_USE_OF_DESC_TAG - - -/** - * Same with hidden. - * @hidden - */ -var x = 10; // INVALID_USE_OF_DESC_TAG - - -/** - * Same with meaning. - * @meaning Some unusual meaning. - */ -var x = 10; // INVALID_USE_OF_DESC_TAG - - -// +9: MISSING_SPACE -// +9: MISSING_JSDOC_TAG_TYPE -// +10: OUT_OF_ORDER_JSDOC_TAG_TYPE -// +10: MISSING_JSDOC_TAG_TYPE, MISSING_SPACE -/** - * Lots of problems in this documentation. - * - * @param {Object} q params b & d are missing descriptions. - * @param {Object} a param d is missing a type (oh my). - * @param {Object}b - * @param d - * @param {Object} x param desc. - * @param z {type} Out of order type. - * @param{} y Empty type and missing space. - * @param {Object} omega mis-matched param. - */ -function manyProblems(a, b, c, d, x, z, y, alpha) { - // -1: MISSING_PARAMETER_DOCUMENTATION, EXTRA_PARAMETER_DOCUMENTATION - // -2: WRONG_PARAMETER_DOCUMENTATION -} - - -/** - * Good docs - * - * @param {really.really.really.really.really.really.really.long.type} good - * My param description. - * @param {really.really.really.really.really.really.really.really.long.type} - * okay My param description. - * @param - * {really.really.really.really.really.really.really.really.really.really.long.type} - * fine Wow that's a lot of wrapping. - */ -function wrappedParams(good, okay, fine) { -} - - -// +4: MISSING_JSDOC_TAG_TYPE -// +3: MISSING_JSDOC_PARAM_NAME -/** - * Really bad - * @param - */ -function reallyBadParam(a) { // MISSING_PARAMETER_DOCUMENTATION -} - - -/** - * Some docs. - * - * @private - */ -class.goodPrivate_ = function() { -}; - - -/** - * Some docs. - */ -class.missingPrivate_ = function() { // MISSING_PRIVATE -}; - - -/** - * Some docs. - * - * @private - */ -class.extraPrivate = function() { // EXTRA_PRIVATE -}; - - -/** - * Anything ending with two underscores is not treated as private. - */ -class.__iterator__ = function() { -}; - - -/** - * Some docs. - * @package - */ -class.goodPackage = function() { -}; - - -/** - * Some docs. - * @package - */ -class.badPackage_ = function() { // MISSING_PRIVATE -}; - - -/** - * Some docs. - * @protected - */ -class.goodProtected = function() { -}; - - -/** - * Some docs. - * @protected - */ -class.badProtected_ = function() { // MISSING_PRIVATE -}; - - -/** - * Example of a legacy name. - * @protected - * @suppress {underscore} - */ -class.dom_ = function() { - /** @suppress {with} */ - with ({}) {} -}; - - -/** - * Legacy names must be protected. - * @suppress {underscore} - */ -class.dom_ = function() { -}; - - -/** - * Allow compound suppression. - * @private - */ -class.dom_ = function() { - /** @suppress {visibility|with} */ - with ({}) {} -}; - - -/** - * Allow compound suppression. - * @private - */ -class.dom_ = function() { - /** @suppress {visibility,with} */ - with ({}) {} -}; - - -// +4: UNNECESSARY_SUPPRESS -/** - * Some docs. - * @private - * @suppress {underscore} - */ -class.unnecessarySuppress_ = function() { -}; - - -/** - * Some docs. - * @public - */ -class.goodProtected = function() { -}; - - -/** - * Some docs. - * @public - */ -class.badProtected_ = function() { // MISSING_PRIVATE -}; - - -/** - * Example of a legacy name. - * @public - * @suppress {underscore} - */ -class.dom_ = function() { -}; - - -// +5: JSDOC_PREFER_QUESTION_TO_PIPE_NULL -// +7: JSDOC_PREFER_QUESTION_TO_PIPE_NULL -/** - * Check JsDoc type annotations. - * @param {Object?} good A good one. - * @param {Object|null} bad A bad one. - * @param {Object|Element?} ok1 This is acceptable. - * @param {Object|Element|null} right The right way to do the above. - * @param {null|Object} bad2 Another bad one. - * @param {Object?|Element} ok2 Not good but acceptable. - * @param {Array.?} complicated A good one that was reported as - * bad. See bug 1154506. - */ -class.sampleFunction = function(good, bad, ok1, right, bad2, ok2, - complicated) { -}; - - -/** - * @return {Object?} A good return. - */ -class.goodReturn = function() { - return something; -}; - - -/** @type {Array.} // JSDOC_PREFER_QUESTION_TO_PIPE_NULL */ -class.badType; - - -/** - * For template types, the ?TYPE notation is not parsed correctly by the - * compiler, so don't warn here. - * @type {Array.} - * @template TYPE - */ -class.goodTemplateType; - - -// As the syntax may look ambivalent: The function returns just null. -/** @type {function():null|Object} */ -class.goodType; - - -/** @type {function():(null|Object)} // JSDOC_PREFER_QUESTION_TO_PIPE_NULL */ -class.badType; - - -// As the syntax may look ambivalent: The function returns just Object. -/** @type {function():Object|null} // JSDOC_PREFER_QUESTION_TO_PIPE_NULL */ -class.badType; - - -/** @type {(function():Object)|null} // JSDOC_PREFER_QUESTION_TO_PIPE_NULL */ -class.badType; - - -/** @type {function(null,Object)} */ -class.goodType; - - -/** @type {{a:null,b:Object}} */ -class.goodType; - - -// +2: JSDOC_PREFER_QUESTION_TO_PIPE_NULL -/** - * @return {Object|null} A bad return. - */ -class.badReturn = function() { - return something; -}; - - -/** - * @return {Object|Element?} An not so pretty return, but acceptable. - */ -class.uglyReturn = function() { - return something; -}; - - -/** - * @return {Object|Element|null} The right way to do the above. - */ -class.okReturn = function() { - return something; -}; - - -// +2: MISSING_SPACE, MISSING_SPACE -/** - * @return{mytype}Something. - */ -class.missingSpacesReturn = function() { - return something; -}; - - -/** - * A good type in the new notation. - * @type {Object?} - */ -class.otherGoodType = null; - - -/** - * A complex type that should allow both ? and |. - * @bug 1570763 - * @type {function(number?, Object|undefined):void} - */ -class.complexGoodType = goog.nullFunction; - - -/** - * A complex bad type that we can catch, though there are many we can't. - * Its acceptable. - * @type {Array.|string?} - */ -class.complexBadType = x || 'foo'; - - -/** - * A strange good type that caught a bad version of type checking from - * other.js, so I added it here too just because. - * @type {number|string|Object|Element|Array.|null} - */ -class.aStrangeGoodType = null; - - -/** - * A type that includes spaces. - * @type {function() : void} - */ -class.assignedFunc = goog.nullFunction; - - -// +4: JSDOC_PREFER_QUESTION_TO_PIPE_NULL -// +3: MISSING_BRACES_AROUND_TYPE -/** - * A bad type. - * @type Object|null - */ -class.badType = null; - - -// +3: JSDOC_PREFER_QUESTION_TO_PIPE_NULL -/** - * A bad type, in the new notation. - * @type {Object|null} - */ -class.badType = null; - - -/** - * An not pretty type, but acceptable. - * @type {Object|Element?} - */ -class.uglyType = null; - - -/** - * The right way to do the above. - * @type {Object|Element|null} - */ -class.okType = null; - - -/** - * @type {boolean} Is it okay to have a description here? - */ -class.maybeOkType = null; - - -/** - * A property whose type will be infered from the right hand side since it is - * constant. - * @const - */ -class.okWithoutType = 'stout'; - - -/** - * Const property without type and text in next line. b/10407058. - * @const - * TODO(user): Nothing to do, just for scenario. - */ -class.okWithoutType = 'string'; - - -/** - * Another constant property, but we should use the type tag if the type can't - * be inferred. - * @type {string} - * @const - */ -class.useTypeWithConst = functionWithUntypedReturnValue(); - - -/** - * Another constant property, but using type with const if the type can't - * be inferred. - * @const {string} - */ -class.useTypeWithConst = functionWithUntypedReturnValue(); - - -// +3: MISSING_BRACES_AROUND_TYPE -/** - * Constant property without proper type. - * @const string - */ -class.useImproperTypeWithConst = functionWithUntypedReturnValue(); - - -/** - * @define {boolean} A define. - */ -var COMPILED = false; - - -// +2: MISSING_JSDOC_TAG_TYPE -/** - * @define A define without type info. - */ -var UNTYPED_DEFINE = false; - - -// +4: MISSING_JSDOC_TAG_DESCRIPTION, MISSING_SPACE -/** - * A define without a description and missing a space. - * - * @define{boolean} - */ -var UNDESCRIBED_DEFINE = false; - - -// Test where to check for docs. -/** - * Docs for member object. - * @type {Object} - */ -x.objectContainingFunctionNeedsNoDocs = { - x: function(params, params) {} -}; - -if (test) { - x.functionInIfBlockNeedsDocs = function() { // MISSING_MEMBER_DOCUMENTATION - x.functionInFunctionNeedsNoDocs = function() { - }; - }; -} else { - x.functionInElseBlockNeedsDocs = function() { // MISSING_MEMBER_DOCUMENTATION - x.functionInFunctionNeedsNoDocs = function() { - }; - }; -} - - -/** - * Regression test. - * @param {goog.math.Vec2} a - * @param {goog.math.Vec2} b - * @return {goog.math.Vec2} The sum vector. - */ -goog.math.Vec2.sum = function(a, b) { - return new goog.math.Vec2(a.x + b.x, a.y + b.y); -}; - - -// +6: JSDOC_MISSING_OPTIONAL_PREFIX -// +8: JSDOC_MISSING_OPTIONAL_PREFIX -// +8: JSDOC_MISSING_OPTIONAL_TYPE -// +8: JSDOC_MISSING_OPTIONAL_TYPE -/** - * Optional parameters test. - * @param {number=} numberOptional The name should be prefixed by opt_. - * @param {function(number=)} funcOk Ok. - * @param {number} numberOk The type is ok. - * @param {function(string=):number=} funcOpt Param name need opt_ prefix. - * @param {string} opt_stringMissing The type miss an ending =. - * @param {function(number=)} opt_func The type miss an ending =. - * @param {string=} opt_ok The type is ok. - * @param {function(string=):number=} opt_funcOk Type is ok. - */ -goog.math.Vec2.aFunction = function( - numberOptional, funcOk, numberOk, funcOpt, opt_stringMissing, opt_func, - opt_ok, opt_funcOk) { -}; - - -/** - * Good documentation! - * - * @override - */ -class.goodOverrideDocs = function() { -}; - - -/** - * Test that flags embedded in docs don't trigger ends with invalid character - * error. - * @bug 2983692 - * @deprecated Please use the {@code @hidden} annotation. - */ -function goodEndChar() { -} - - -/** - * Test that previous case handles unballanced doc tags. - * @param {boolean} a Whether we should honor '{' characters in the string. - */ -function goodEndChar2(a) { -} - - -/** - * Regression test for braces in description invalidly being matched as types. - * This caused a false error for missing punctuation because the bad token - * caused us to incorrectly calculate the full description. - * @bug 1406513 - * @return {Object|undefined} A hash containing the attributes for the found url - * as in: {url: "page1.html", title: "First page"} - * or undefined if no match was found. - */ -x.z.a = function() { - return a; -}; - - -/** - * @bug 1492606 HTML parse error for JSDoc descriptions grashed gjslint. - * @param {string} description a long email or common name, e.g., - * "John Doe " or "Birthdays Calendar" - */ -function calendar(description) { -} - - -/** - * @bug 1492606 HTML parse error for JSDoc descriptions grashed gjslint. - * @param {string} description a long email or common name, e.g., - * "John Doe " or "Birthdays Calendar". - */ -function calendar(description) { -} - - -/** - * Regression test for invoked functions, this code used to report missing - * param and missing return errors. - * @type {number} - */ -x.y.z = (function(x) { - return x + 1; -})(); - - -/** - * Test for invoked function as part of an expression. It should not return - * an error for missing docs for x. - */ -goog.currentTime = something.Else || (function(x) { - //... -})(10); - - -/** - * @type boolean //MISSING_BRACES_AROUND_TYPE - */ -foo.bar = true; - - -/** - * @enum {null //MISSING_BRACES_AROUND_TYPE - */ -bar.foo = null; - - -/** - * @extends Object} //MISSING_BRACES_AROUND_TYPE - */ // JSDOC_DOES_NOT_PARSE -bar.baz = x; - - -/** @inheritDoc */ // INVALID_INHERIT_DOC_PRIVATE -x.privateFoo_ = function() { // MISSING_PRIVATE -}; - - -/** - * Does bar. - * @override // INVALID_OVERRIDE_PRIVATE - */ -x.privateBar_ = function() { // MISSING_PRIVATE -}; - - -/** - * Inherits private baz_ method (evil, wrong behavior, but we have no choice). - * @override - * @suppress {accessControls} - */ -x.prototype.privateBaz_ = function() { -}; - - -/** - * This looks like a function but it's a function call. - * @type {number} - */ -test.x = function() { - return 3; -}(); - - -/** - * Invalid reference to this. - */ // MISSING_JSDOC_TAG_THIS -test.x.y = function() { - var x = this.x; // UNUSED_LOCAL_VARIABLE -}; - - -/** - * Invalid write to this. - */ // MISSING_JSDOC_TAG_THIS -test.x.y = function() { - this.x = 10; -}; - - -/** - * Invalid standalone this. - */ // MISSING_JSDOC_TAG_THIS -test.x.y = function() { - some.func.call(this); -}; - - -/** - * Invalid reference to this. - */ // MISSING_JSDOC_TAG_THIS -function a() { - var x = this.x; // UNUSED_LOCAL_VARIABLE -} - - -/** - * Invalid write to this. - */ // MISSING_JSDOC_TAG_THIS -function b() { - this.x = 10; -} - - -/** - * Invalid standalone this. - */ // MISSING_JSDOC_TAG_THIS -function c() { - some.func.call(this); -} - - -/** - * Ok to do any in a prototype. - */ -test.prototype.x = function() { - var x = this.x; - this.y = x; - some.func.call(this); -}; - - -/** - * Ok to do any in a prototype that ends in a hex-like number. - */ -test.prototype.getColorX2 = function() { - var x = this.x; - this.y = x; - some.func.call(this); -}; - - -/** - * Ok to do any in a function with documented this usage. - * @this {test.x.y} Object bound to this via goog.bind. - */ -function a() { - var x = this.x; - this.y = x; - some.func.call(this); -} - - -/** - * Ok to do any in a function with documented this usage. - * @this {test.x.y} Object bound to this via goog.bind. - */ -test.x.y = function() { - var x = this.x; - this.y = x; - some.func.call(this); -}; - - -/** - * Regression test for bug 1220601. Wrapped function declarations shouldn't - * cause need for an (at)this flag, which I can't write out or it would get - * parsed as being here. - * @param {Event} e The event. - */ -detroit.commands.ChangeOwnerCommand - .prototype.handleDocumentStoreCompleteEvent = function(e) { - this.x = e.target; -}; - - - -/** - * Ok to do any in a constructor. - * @constructor - */ -test.x.y = function() { - this.y = x; - var x = this.y; // UNUSED_LOCAL_VARIABLE - some.func.call(this); -}; - -// Test that anonymous function doesn't throw an error. -window.setTimeout(function() { - var x = 10; // UNUSED_LOCAL_VARIABLE -}, 0); - - -/** - * @bug 1234567 - */ -function testGoodBug() { -} - - -/** - * @bug 1234567 Descriptions are allowed. - */ -function testGoodBugWithDescription() { -} - - -// +2: NO_BUG_NUMBER_AFTER_BUG_TAG -/** - * @bug Wrong - */ -function testBadBugNumber() { -} - - -// +2: NO_BUG_NUMBER_AFTER_BUG_TAG -/** - * @bug Wrong - */ -function testMissingBugNumber() { -} - - - -/** - * @interface - */ -function testInterface() { -} - - - -/** - * @implements {testInterface} - * @constructor - */ -function testImplements() { -} - - -/** - * Function that has an export jsdoc tag. - * @export - */ -function testExport() { -} - - -/** - * Declare and doc this member here, without assigning to it. - * @bug 1473402 - * @type {number} - */ -x.declareOnly; - -if (!someCondition) { - x.declareOnly = 10; -} - - -/** - * JsDoc describing array x.y as an array of function(arg). The missing - * semicolon caused the original bug. - * @type {Array.} - */ -x.y = [] // MISSING_SEMICOLON -x.y[0] = function(arg) {}; -x.y[1] = function(arg) {}; - - -/** - * Regression test for unfiled bug where descriptions didn't properly exclude - * the star-slash that must end doc comments. - * @return {Function} A factory method. - */ -x.y.foo = function() { - /** @return {goog.dom.Range} A range. */ - return function() { - return goog.dom.Range.createRangeFromNothing(); - }; -}; - - -// +4: INCORRECT_SUPPRESS_SYNTAX -// +4: INVALID_SUPPRESS_TYPE -/** - * Docs... - * @suppress - * @suppress {fake} - */ -class.x = 10; - - -/** - * These docs are OK. They used to not parse the identifier due to the use of - * array indices. - * @bug 1640846 - * @private - */ -window['goog']['forms']['Validation'].prototype.form_ = null; - - -/** - * Check JsDoc multiline type annotations. - * @param {string| - * number} multiline description. - */ -function testMultiline(multiline) { -} - - -/** - * Check JsDoc nosideeffects annotations. - * @nosideeffects - */ -function testNoSideEffects() { -} - - -/** - * @enum {google.visualization.DateFormat|google.visualization.NumberFormat| - * google.visualization.PatternFormat} - */ -MultiLineEnumTypeTest = { - FOO: 1, - BAR: 2, - BAZ: 3 -}; - - -/** - * @enum {google.visualization.DateFormat|google.visualization.NumberFormat|google.visualization.PatternFormat} - */ -AllowedLongLineEnum = { - CAT: 1, - DOG: 2, - RAT: 3 -}; - - -/** - * Typeless enum test - * @enum - */ -TypelessEnumTest = { - OK: 0, - CHECKING: 1, - DOWNLOADING: 2, - FAILURE: 3 -}; - -// Regression test for bug 1880803, shouldn't need to document assignments to -// prototype. -x.prototype = {}; - -y - .prototype = {}; - -x.y - .z.prototype = {}; - -x.myprototype = {}; // MISSING_MEMBER_DOCUMENTATION - -x.prototype.y = 5; // MISSING_MEMBER_DOCUMENTATION - -x.prototype - .y.z = {}; // MISSING_MEMBER_DOCUMENTATION - - -/** @typedef {(string|number)} */ -goog.NumberLike; - - -/** - * Something from the html5 externs file. - * @type {string} - * @implicitCast - */ -CanvasRenderingContext2D.prototype.fillStyle; - - - -/** - * Regression test. - * @bug 2994247 - * @inheritDoc - * @extends {Bar} - * @constructor - * @private - */ -Foo_ = function() { -}; - - -/** - * @param {function(this:T,...)} fn The function. - * @param {T} obj The object. - * @template T - */ -function bind(fn, obj) { -} - - - -/** - * @constructor - * @classTemplate T - */ -function MyClass() { -} - - -foo(/** @lends {T} */ ({foo: 'bar'})); - - - -/** - * @param {*} x . - * @constructor - * @struct - */ -function StructMaker(x) { this.x = x; } - -var structObjLit = /** @struct */ { x: 123 }; - - - -/** - * @param {*} x . - * @constructor - * @dict - */ -function DictMaker(x) { this['x'] = x; } - -var dictObjLit = /** @dict */ { x: 123 }; - - -/** - * @idGenerator - * @param {string} x . - * @return {string} . - */ -function makeId(x) { - return ''; -} - - -/** - * @consistentIdGenerator - * @param {string} x . - * @return {string} . - */ -function makeConsistentId(x) { - return ''; -} - - -/** - * @stableIdGenerator - * @param {string} x . - * @return {string} . - */ -function makeStableId(x) { - return ''; -} - - -/** - * Test to make sure defining object with object literal doest not produce - * doc warning for @this. - * Regression test for b/4073735. - */ -var Foo = function(); -Foo.prototype = { - /** - * @return {number} Never. - */ - method: function() { - return this.method(); - } -}; - -/** Regression tests for annotation types with spaces. */ - - -/** @enum {goog.events.Event} */ -var Bar; - - - -/** - * @constructor - * @implements {goog.dom.Range} - */ -var Foo = function() { - /** @final {goog.events.Event} */ - this.bar = null; -}; - -/* Regression tests for not ending block comments. Keep at end of file! **/ -/** - * When there are multiple asteriks. In the failure case we would get an - * error that the file ended mid comment, with no end comment token***/ -/** - * Was a separate bug 2950646 when the closing bit was on it's own line - * because the ending star was being put into a different token type: DOC_PREFIX - * rather than DOC_COMMENT. - **/ diff --git a/tools/closure_linter/closure_linter/testdata/limited_doc_checks.js b/tools/closure_linter/closure_linter/testdata/limited_doc_checks.js deleted file mode 100644 index 701cce9892be20..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/limited_doc_checks.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Test file for limited doc checks. - */ - - -/** - * Don't require documentation of parameters. - * @param {boolean} - * @param {boolean} c - * @param {boolean} d No check for punctuation - * @bug 3259564 - */ -x.y = function(a, b, c, d) { - return a; -}; diff --git a/tools/closure_linter/closure_linter/testdata/minimal.js b/tools/closure_linter/closure_linter/testdata/minimal.js deleted file mode 100644 index 6dbe7333f41d39..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/minimal.js +++ /dev/null @@ -1 +0,0 @@ -function f(x) {} // Regression test for old parsing bug. diff --git a/tools/closure_linter/closure_linter/testdata/not_strict.js b/tools/closure_linter/closure_linter/testdata/not_strict.js deleted file mode 100644 index f8ede3dc1d3e31..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/not_strict.js +++ /dev/null @@ -1,42 +0,0 @@ -/** // _WRONG_BLANK_LINE_COUNT - * @fileoverview This file has errors that could trigger both in strict and non - * strict mode. The errors beginning with _ should not be triggered when strict - * flag is false. - * // -1: _INVALID_AUTHOR_TAG_DESCRIPTION - */ - -/** // _WRONG_BLANK_LINE_COUNT - * A constructor with 1 line above it (BAD). - * // +1: MISSING_JSDOC_TAG_TYPE - * @param a A parameter. - * @privtae // INVALID_JSDOC_TAG - * @constructor - */ -function someFunction(a) { - /** +1: _MISSING_BRACES_AROUND_TYPE - * @type number - */ - this.a = 0; - someReallyReallyReallyReallyReallyReallyReallyReallyLongiName = quiteBigValue; // LINE_TOO_LONG - if (this.a == 0) { - // _WRONG_INDENTATION - return // MISSING_SEMICOLON - } -}; // ILLEGAL_SEMICOLON_AFTER_FUNCTION - - -// +1: _UNNECESSARY_BRACES_AROUND_INHERIT_DOC -/** {@inheritDoc} */ -function someFunction.prototype.toString() { -} - - -/** - * When not strict, there is no problem with optional markers in types. - * @param {string=} a A string. - * @param {string} aOk An other string. - * @param {number} opt_b An optional number. - * @param {number=} opt_bOk An other optional number. - */ -someFunction.optionalParams = function(a, aOk, opt_b, opt_bOk) { -}; diff --git a/tools/closure_linter/closure_linter/testdata/other.js b/tools/closure_linter/closure_linter/testdata/other.js deleted file mode 100644 index 1e424ce3f2cfa9..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/other.js +++ /dev/null @@ -1,459 +0,0 @@ -// Copyright 2007 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Miscellaneous style errors. - * - * @author robbyw@google.com (Robby Walker) - */ - -goog.provide('goog.dom'); - -goog.require('goog.events.EventHandler'); - -var this_is_a_really_long_line = 100000000000000000000000000000000000000000000000; // LINE_TOO_LONG - -// Declaration in multiple lines. -// Regression test for b/3009648 -var - a, - b = 10; - -// http://this.comment.should.be.allowed/because/it/is/a/URL/that/can't/be/broken/up - - -/** - * Types are allowed to be long even though they contain spaces. - * @type {function(ReallyReallyReallyReallyLongType, AnotherExtremelyLongType) : LongReturnType} - */ -x.z = 1000; - - -/** - * Params are also allowed to be long even though they contain spaces. - * @param {function(ReallyReallyReallyReallyLongType, AnotherExtremelyLongType) : LongReturnType} fn - * The function to call. - */ -x.z = function(fn) { -}; - - -/** - * Visibility tags are allowed to have type, therefore they allowed to be long. - * @private {function(ReallyReallyReallyReallyLongType, AnotherExtremelyLongType) : LongReturnType} - */ -x.z_ = 1000; - - -/** - * Visibility tags are allowed to have type, therefore they allowed to be long. - * @public {function(ReallyReallyReallyReallyLongType, AnotherExtremelyLongType) : LongReturnType} - */ -x.z = 1000; - - -/** - * Visibility tags are allowed to have type, therefore they allowed to be long. - * @protected {function(ReallyReallyReallyReallyLongType, AnotherExtremelyLongType) : LongReturnType} - */ -x.z = 1000; - - -/** - * Visibility tags are allowed to have type, therefore they allowed to be long. - * @package {function(ReallyReallyReallyReallyLongType,AnotherExtremelyLongType):LongReturnType} - */ -x.z = 1000; - -// +2: LINE_TOO_LONG -var x = - a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.a.b.c.d.tooLongEvenThoughNoSpaces; - -// +1: LINE_TOO_LONG -getSomeExtremelyLongNamedFunctionWowThisNameIsSoLongItIsAlmostUnbelievable().dispose(); - - -/** - * @param {number|string|Object|Element|Array.|null} aReallyReallyReallyStrangeParameter - * @param {number|string|Object|Element|goog.a.really.really.really.really.really.really.really.really.long.Type|null} shouldThisParameterWrap - * @return {goog.a.really.really.really.really.really.really.really.really.long.Type} - */ -x.y = function(aReallyReallyReallyStrangeParameter, shouldThisParameterWrap) { - return something; -}; - - -/** - * @type {goog.a.really.really.really.really.really.really.really.really.long.Type?} - */ -x.y = null; - -function doesEndWithSemicolon() { -}; // ILLEGAL_SEMICOLON_AFTER_FUNCTION - -function doesNotEndWithSemicolon() { -} - -doesEndWithSemicolon = function() { - // +1: UNUSED_LOCAL_VARIABLE - var shouldEndWithSemicolon = function() { - } // MISSING_SEMICOLON_AFTER_FUNCTION -}; - -doesNotEndWithSemicolon = function() { -} // MISSING_SEMICOLON_AFTER_FUNCTION - -doesEndWithSemicolon['100'] = function() { -}; - -doesNotEndWithSemicolon['100'] = function() { -} // MISSING_SEMICOLON_AFTER_FUNCTION - -if (some_flag) { - function doesEndWithSemicolon() { - }; // ILLEGAL_SEMICOLON_AFTER_FUNCTION - - function doesNotEndWithSemicolon() { - } - - doesEndWithSemicolon = function() { - }; - - doesNotEndWithSemicolon = function() { - } // MISSING_SEMICOLON_AFTER_FUNCTION -} - -// No semicolon for expressions that are immediately called. -var immediatelyCalledFunctionReturnValue = function() { -}(); - - -/** - * Regression test for function expressions treating semicolons wrong. - * @bug 1044052 - */ -goog.now = Date.now || function() { - //... -}; - - -/** - * Regression test for function expressions treating semicolons wrong. - * @bug 1044052 - */ -goog.now = Date.now || function() { - //... -} // MISSING_SEMICOLON_AFTER_FUNCTION - - -/** - * Function defined in ternary operator - * @bug 1413743 - * @param {string} id The ID of the element. - * @return {Element} The matching element. - */ -goog.dom.$ = document.getElementById ? - function(id) { - return document.getElementById(id); - } : - function(id) { - return document.all[id]; - }; - - -/** - * Test function in object literal needs no semicolon. - * @type {Object} - */ -x.y = { - /** - * @return {number} Doc the inner function too. - */ - a: function() { - return 10; - } -}; - -// Semicolon required at end of object literal. -var throwObjectLiteral = function() { - throw { - x: 0, - y: 1 - } // MISSING_SEMICOLON -}; - -var testRegex = /(\([^\)]*\))|(\[[^\]]*\])|({[^}]*})|(<[^&]*>)/g; -var testRegex2 = /abc/gimsx; - -var x = 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 - + 20; // LINE_STARTS_WITH_OPERATOR - -var x = 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + 100 + - -20; // unary minus is ok - -var x = z++ - + 20; // LINE_STARTS_WITH_OPERATOR - -var x = z. // LINE_ENDS_WITH_DOT - y(); - -// Regression test: This line was incorrectly not reporting an error -var marginHeight = x.layout.getSpacing_(elem, 'marginTop') - + x.layout.getSpacing_(elem, 'marginBottom'); -// -1: LINE_STARTS_WITH_OPERATOR - -// Regression test: This line was correctly reporting an error -x.layout.setHeight(elem, totalHeight - paddingHeight - borderHeight - - marginHeight); // LINE_STARTS_WITH_OPERATOR - -// Regression test: This line was incorrectly reporting spacing and binary -// operator errors -if (i == index) { -} -++i; - -var twoSemicolons = 10;; // REDUNDANT_SEMICOLON - -if (i == index) { -} else; // REDUNDANT_SEMICOLON -i++; - -do; // REDUNDANT_SEMICOLON -{ -} while (i == index); - -twoSemicolons = 10; -// A more interesting example of two semicolons - ; // EXTRA_SPACE, WRONG_INDENTATION, REDUNDANT_SEMICOLON - - -/** @bug 1598895 */ -for (;;) { - // Do nothing. -} - -for (var x = 0, foo = blah(), bar = {};; x = update(x)) { - // A ridiculous case that should probably never happen, but I suppose is - // valid. -} - -var x = "allow'd double quoted string"; -var x = "unnecessary double quotes string"; // UNNECESSARY_DOUBLE_QUOTED_STRING -// +1: MULTI_LINE_STRING, UNNECESSARY_DOUBLE_QUOTED_STRING, -var x = "multi-line unnecessary double quoted \ - string."; - - -// Regression test: incorrectly reported missing doc for variable used in global -// scope. -/** - * Whether the "Your browser isn't fully supported..." warning should be shown - * to the user; defaults to false. - * @type {boolean} - * @private - */ -init.browserWarning_ = false; - -init.browserWarning_ = true; - -if (someCondition) { - delete this.foo_[bar]; -} - -// Commas at the end of literals used to be forbidden. -x = [1, 2, 3,]; -x = [1, 2, 3, /* A comment */]; -x = [ - 1, - 2, - 3, -]; -x = { - a: 1, -}; - -// Make sure we don't screw up typing for Lvalues and think b:c is a type value -// pair. -x = a ? b : c = 34; -x = a ? b:c; // MISSING_SPACE, MISSING_SPACE -x = (a ? b:c = 34); // MISSING_SPACE, MISSING_SPACE - -if (x) { - x += 10; -}; // REDUNDANT_SEMICOLON - - -/** - * Bad assignment of array to prototype. - * @type {Array} - */ -x.prototype.badArray = []; // ILLEGAL_PROTOTYPE_MEMBER_VALUE - - -/** - * Bad assignment of object to prototype. - * @type {Object} - */ -x.prototype.badObject = {}; // ILLEGAL_PROTOTYPE_MEMBER_VALUE - - -/** - * Bad assignment of class instance to prototype. - * @type {goog.events.EventHandler} - */ -x.prototype.badInstance = new goog.events.EventHandler(); -// -1: ILLEGAL_PROTOTYPE_MEMBER_VALUE - -// Check that some basic structures cause no errors. -x = function() { - try { - } finally { - y = 10; - } -}; - -switch (x) { - case 10: - break; - case 20: - // Fallthrough. - case 30: - break; - case 40: { - break; - } - default: - break; -} - -do { - x += 10; -} while (x < 100); - -do { - x += 10; -} while (x < 100) // MISSING_SEMICOLON - -// Missing semicolon checks. -x = 10 // MISSING_SEMICOLON -x = someOtherVariable // MISSING_SEMICOLON -x = fnCall() // MISSING_SEMICOLON -x = {a: 10, b: 20} // MISSING_SEMICOLON -x = [10, 20, 30] // MISSING_SEMICOLON -x = (1 + 2) // MISSING_SEMICOLON -x = { - a: [ - 10, 20, (30 + - 40) - ] -} // MISSING_SEMICOLON -x = a - .b - .c(). // LINE_ENDS_WITH_DOT - d; - -// Test that blocks without braces don't generate incorrect semicolon and -// indentation errors. TODO: consider disallowing blocks without braces. -if (x) - y = 10; - -if (x) - y = 8 // MISSING_SEMICOLON - -// Regression test for bug 2973408, bad missing semi-colon error when else -// is not followed by an opening brace. -if (x) - y = 3; -else - z = 4; - -// We used to erroneously report a missing semicolon error. -if (x) -{ -} - -while (x) - y = 10; - -for (x = 0; x < 10; x++) - y += 10; - z += 10; // WRONG_INDENTATION - -var x = 100 // MISSING_SEMICOLON - -// Also regression test for bug 2973407 Parse error on nested ternary statments. -foo = bar ? baz ? 1 : 2 : 3 // MISSING_SEMICOLON -foo = bar ? 1 : baz ? 2 : 3; -bar ? 1 : baz ? 2 : bat ? 3 : 4; -bar ? 1 : baz ? bat ? 3 : 4 : baq ? 5 : 6; -foo = bar ? 1 : 2; - -foo = { - str: bar ? baz ? blah ? 1 : 2 : 3 : 4 -} // MISSING_SEMICOLON - - -// Regression tests for bug 2969408 GJsLint doesn't like labeled statements. -mainLoop: while (!y) { -} - -myLabel1: myLabel2: var x; - -for (var i = 0; i < n; i++) { - myLabel3: - while (true) { - break myLabel3; - } -} - -myLabelA : myLabelB : x > y ? 0 : 1; // EXTRA_SPACE, EXTRA_SPACE, EXTRA_SPACE - -// Regression test for bug 4269466. -var a = new Scheme({default: 0}); -switch (foo) { - default: - var a = new Scheme({default: 0}); - break; -} - - -/** @private Some text is allowed after tag */ -x.y_ = function() { -}; - - -/** @private Some text is allowed after tag but not the long oneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.*/ // LINE_TOO_LONG -x.y_ = function() { -}; - - -/** @private {number} Some text is allowed after tag */ -x.z_ = 200; - - -/** @private {number} Some text is allowed after tag but not the long oneeeeeeeeeeeeeeee. */ // LINE_TOO_LONG -x.z_ = 200; - -// Regression tests for b/16298424. -var z = function() {}.bind(); -window.alert(function() {}.bind()); -function() { -}.bind(); -var y = function() { -}.bind(); -var y = function() { - } - .bind(); - -/* comment not closed // FILE_MISSING_NEWLINE, FILE_IN_BLOCK \ No newline at end of file diff --git a/tools/closure_linter/closure_linter/testdata/provide_blank.js b/tools/closure_linter/closure_linter/testdata/provide_blank.js deleted file mode 100644 index a4e0716419e4af..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/provide_blank.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Checks that missing provides are reported at the first require - * when there are no other provides in the file. - */ - -goog.require('dummy.package.ClassName'); // MISSING_GOOG_PROVIDE - - - -/** - * @constructor - */ -dummy.Something = function() {}; - -var x = new dummy.package.ClassName(); diff --git a/tools/closure_linter/closure_linter/testdata/provide_extra.js b/tools/closure_linter/closure_linter/testdata/provide_extra.js deleted file mode 100644 index 3370950e3b2c41..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/provide_extra.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed 2to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Checks for extra goog.provides. - * - */ - -goog.provide(''); // EXTRA_GOOG_PROVIDE - -goog.provide('dummy.AnotherThingTest'); // ok since mentioned in setTestOnly -goog.provide('dummy.AnotherTrulyLongNamespaceToMakeItExceedEightyCharactersThingTest'); - -goog.provide('dummy.Something'); -goog.provide('dummy.Something'); // EXTRA_GOOG_PROVIDE -goog.provide('dummy.SomethingElse'); // EXTRA_GOOG_PROVIDE - -goog.provide('dummy.YetAnotherThingTest'); // EXTRA_GOOG_PROVIDE - -goog.setTestOnly('dummy.AnotherThingTest'); -goog.setTestOnly('dummy.AnotherTrulyLongNamespaceToMakeItExceedEightyCharactersThingTest'); - - - -/** - * @constructor - */ -dummy.Something = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/provide_missing.js b/tools/closure_linter/closure_linter/testdata/provide_missing.js deleted file mode 100644 index 42de489671113c..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/provide_missing.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2011 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// We are missing a provide of goog.something.Else. -// -15: MISSING_GOOG_PROVIDE - -/** - * @fileoverview Tests missing provides and the usage of the missing provide - * suppression annotation. - * - */ - - - -/** - * Constructor for Something. - * @constructor - * @suppress {missingProvide} - */ -goog.something.Something = function() {}; - - - -/** - * Constructor for Else. We should get an error about providing this, but not - * about the constructor for Something. - * @constructor - */ -goog.something.Else = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/require_alias.js b/tools/closure_linter/closure_linter/testdata/require_alias.js deleted file mode 100644 index 804b2ed1428684..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_alias.js +++ /dev/null @@ -1,14 +0,0 @@ -// We are missing a require of goog.sample.UsedType -goog.provide('goog.something.Else'); // +1: MISSING_GOOG_REQUIRE - - -goog.scope(function() { -var unused = goog.events.unused; // UNUSED_LOCAL_VARIABLE -var used = goog.events.used; // ALIAS_STMT_NEEDS_GOOG_REQUIRE -var UsedType = goog.sample.UsedType; -var other = goog.sample.other; - - -/** @type {used.UsedAlias|other.UsedAlias} */ -goog.something.Else = UsedType.create(); -}); // goog.scope diff --git a/tools/closure_linter/closure_linter/testdata/require_all_caps.js b/tools/closure_linter/closure_linter/testdata/require_all_caps.js deleted file mode 100644 index 49344f2c18b267..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_all_caps.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview A should come before B. - * - */ - -goog.provide('XX'); // GOOG_PROVIDES_NOT_ALPHABETIZED -goog.provide('ZZ'); -goog.provide('YY'); - -goog.require('dummy.AA'); // GOOG_REQUIRES_NOT_ALPHABETIZED -goog.require('dummy.CC'); -goog.require('dummy.BB'); - -dummy.AA(); -dummy.CC(); -dummy.BB(); diff --git a/tools/closure_linter/closure_linter/testdata/require_blank.js b/tools/closure_linter/closure_linter/testdata/require_blank.js deleted file mode 100644 index 060781ce7ca322..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_blank.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Checks that missing requires are reported just after the last - * provide when there are no other requires in the file. - */ - -goog.provide('dummy.Something'); // +1: MISSING_GOOG_REQUIRE - - - -/** - * @constructor - */ -dummy.Something = function() {}; - -var x = new dummy.package.ClassName(); diff --git a/tools/closure_linter/closure_linter/testdata/require_extra.js b/tools/closure_linter/closure_linter/testdata/require_extra.js deleted file mode 100644 index 3ee39c73a8a53a..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_extra.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Checks for extra goog.requires. - * - */ - -goog.require(''); // EXTRA_GOOG_REQUIRE -goog.require('dummy.Aa'); -goog.require('dummy.Aa.CONSTANT'); // EXTRA_GOOG_REQUIRE -goog.require('dummy.Aa.Enum'); // EXTRA_GOOG_REQUIRE -goog.require('dummy.Bb'); -goog.require('dummy.Ff'); // EXTRA_GOOG_REQUIRE -goog.require('dummy.Gg'); // EXTRA_GOOG_REQUIRE -goog.require('dummy.cc'); -goog.require('dummy.cc'); // EXTRA_GOOG_REQUIRE -goog.require('dummy.hh'); // EXTRA_GOOG_REQUIRE - -new dummy.Aa(); -dummy.Bb.someMethod(); -dummy.cc(); -var x = dummy.Aa.Enum.VALUE; -var y = dummy.Aa.CONSTANT; diff --git a/tools/closure_linter/closure_linter/testdata/require_function.js b/tools/closure_linter/closure_linter/testdata/require_function.js deleted file mode 100644 index 532bb67103157c..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_function.js +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Description of this file. - */ - -goog.require('goog.mobile.paging.getPage'); - - -goog.mobile.paging.getPage(); diff --git a/tools/closure_linter/closure_linter/testdata/require_function_missing.js b/tools/closure_linter/closure_linter/testdata/require_function_missing.js deleted file mode 100644 index 33bec21eab15c3..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_function_missing.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -14: MISSING_GOOG_REQUIRE - -/** - * @fileoverview Description of this file. - */ - - - -goog.mobile.paging.getPage(); -goog.mobile.paging.getOtherPage(); diff --git a/tools/closure_linter/closure_linter/testdata/require_function_through_both.js b/tools/closure_linter/closure_linter/testdata/require_function_through_both.js deleted file mode 100644 index d9525ec4e1467a..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_function_through_both.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Description of this file. - */ - -goog.require('goog.mobile.paging'); -goog.require('goog.mobile.paging.getPage'); - - -goog.mobile.paging.getPage(); diff --git a/tools/closure_linter/closure_linter/testdata/require_function_through_namespace.js b/tools/closure_linter/closure_linter/testdata/require_function_through_namespace.js deleted file mode 100644 index 55628fccfb34fd..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_function_through_namespace.js +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Description of this file. - */ - -goog.require('goog.mobile.paging'); - - -goog.mobile.paging.getPage(); diff --git a/tools/closure_linter/closure_linter/testdata/require_interface.js b/tools/closure_linter/closure_linter/testdata/require_interface.js deleted file mode 100644 index d6e83024b4b7ac..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_interface.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Contains a test to verify that interfaces implemented in a file - * are goog.require'd. - * - */ - -// We're missing a goog.require of goog.something.SomeInterface. -goog.provide('goog.something.SomeClass'); // +1: MISSING_GOOG_REQUIRE - - - -/** - * Constructor for SomeClass. - * @constructor - * @implements {goog.something.SomeInterface} - */ -goog.something.SomeClass = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/require_interface_alias.js b/tools/closure_linter/closure_linter/testdata/require_interface_alias.js deleted file mode 100644 index c71b29ca3c8d2f..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_interface_alias.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Contains a test to verify that aliased interfaces - * are goog.require'd. - */ - -// We're missing a goog.require of goog.something.SomeInterface. -goog.provide('goog.something.SomeClass'); // +1: MISSING_GOOG_REQUIRE - -goog.scope(function() { -var something = goog.something; - - - -/** - * Constructor for SomeClass. - * @constructor - * @implements {something.SomeInterface} - */ -something.SomeClass = function() {}; -}); // goog.scope diff --git a/tools/closure_linter/closure_linter/testdata/require_interface_base.js b/tools/closure_linter/closure_linter/testdata/require_interface_base.js deleted file mode 100644 index c8bb1f67a5ee8b..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_interface_base.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2011 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Contains a test to verify that parent interfaces - * implemented are goog.require'd. - * - */ - -// We're missing a goog.require of goog.something.BaseInterface. -goog.provide('goog.something.SomeInterface'); // +1: MISSING_GOOG_REQUIRE - - - -/** - * Constructor for SomeInterface. - * @interface - * @extends {goog.something.BaseInterface} - */ -goog.something.SomeInterface = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/require_lower_case.js b/tools/closure_linter/closure_linter/testdata/require_lower_case.js deleted file mode 100644 index c1fff4a3eda79c..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_lower_case.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview The B should come before the b. - * - */ - -goog.provide('x'); // GOOG_PROVIDES_NOT_ALPHABETIZED -goog.provide('X'); -goog.provide('Y'); - -goog.require('dummy.bb'); // GOOG_REQUIRES_NOT_ALPHABETIZED -goog.require('dummy.Bb'); -goog.require('dummy.Cc'); - -var x = dummy.bb.a(); -var y = dummy.Bb.a(); -var z = dummy.Cc.a(); diff --git a/tools/closure_linter/closure_linter/testdata/require_missing.js b/tools/closure_linter/closure_linter/testdata/require_missing.js deleted file mode 100644 index 3539c9489d65dc..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_missing.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2011 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Tests missing requires around the usage of the require - * suppression annotation. - * - */ - -// We are missing a require of goog.foo. -goog.provide('goog.something.Else'); // +1: MISSING_GOOG_REQUIRE - - - -/** - * Constructor for Else. - * @constructor - */ -goog.something.Else = function() { - /** @suppress {missingRequire} */ - this.control.createConstructorMock( - goog.foo.bar, 'Baz'); - - // Previous suppress should only be scoped to that statement. - this.control.createConstructorMock( - goog.foo.bar, 'Baz'); - - this.control.invoke(goog.foo.bar, 'Test'); -}; diff --git a/tools/closure_linter/closure_linter/testdata/require_numeric.js b/tools/closure_linter/closure_linter/testdata/require_numeric.js deleted file mode 100644 index 29d8377afaf566..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_numeric.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Numbers should come before letters. - * - */ - -goog.provide('xa'); // GOOG_PROVIDES_NOT_ALPHABETIZED -goog.provide('x1'); -goog.provide('xb'); - -goog.require('dummy.aa'); // GOOG_REQUIRES_NOT_ALPHABETIZED -goog.require('dummy.a1'); -goog.require('dummy.ab'); - -dummy.aa.a; -dummy.a1.a; -dummy.ab.a; diff --git a/tools/closure_linter/closure_linter/testdata/require_provide_blank.js b/tools/closure_linter/closure_linter/testdata/require_provide_blank.js deleted file mode 100644 index 0e0c188ca54270..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_provide_blank.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -14: MISSING_GOOG_PROVIDE -// -15: MISSING_GOOG_REQUIRE - -/** - * @fileoverview Checks that missing requires and provides are reported at the - * top of the file when there are no existing goog.requires or provides in the - * file. - */ - - - -/** - * @constructor - */ -dummy.Something = function() {}; - -var x = new dummy.package.ClassName(); diff --git a/tools/closure_linter/closure_linter/testdata/require_provide_missing.js b/tools/closure_linter/closure_linter/testdata/require_provide_missing.js deleted file mode 100644 index a56f4d00070819..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_provide_missing.js +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview The same code as require_provide_ok, but missing a provide - * and a require call. - * - */ - -goog.provide('goog.something'); // +1: MISSING_GOOG_PROVIDE -// Missing provide of goog.something.Else and goog.something.SomeTypeDef. - -goog.require('goog.Class'); -goog.require('goog.package'); // +1: MISSING_GOOG_REQUIRE -// Missing requires of goog.Class.Enum and goog.otherThing.Class.Enum. - - -var x = new goog.Class(); -goog.package.staticFunction(); - -var y = goog.Class.Enum.VALUE; - - -/** - * @typedef {string} - */ -goog.something.SomeTypeDef; - - -/** - * Private variable. - * @type {number} - * @private - */ -goog.something.private_ = 10; - - -/** - * Use private variables defined in this file so they don't cause a warning. - */ -goog.something.usePrivateVariables = function() { - var x = [ - goog.something.private_, - x - ]; -}; - - -/** - * Static function. - */ -goog.something.staticFunction = function() { -}; - - - -/** - * Constructor for Else. - * @constructor - */ -goog.something.Else = function() { - // Bug 1801608: Provide goog.otherThing.Class.Enum isn't missing. - var enum = goog.otherThing.Class.Enum; - goog.otherThing.Class.Enum = enum; -}; diff --git a/tools/closure_linter/closure_linter/testdata/require_provide_ok.js b/tools/closure_linter/closure_linter/testdata/require_provide_ok.js deleted file mode 100644 index 01ddafe490d977..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/require_provide_ok.js +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview There is nothing wrong w/ this javascript. - * - */ -goog.module('goog.super.long.DependencyNameThatForcesMethodDefinitionToSpanMultipleLinesFooBar'); -goog.provide('goog.something'); -goog.provide('goog.something.Else'); -goog.provide('goog.something.Else.Enum'); -/** @suppress {extraProvide} */ -goog.provide('goog.something.Extra'); -goog.provide('goog.something.SomeTypeDef'); -goog.provide('goog.somethingelse.someMethod'); -goog.provide('goog.super.long.DependencyNameThatForcesTheLineToBeOverEightyCharacters'); -goog.provide('notInClosurizedNamespacesSoNotExtra'); - -goog.require('dummy.foo'); -goog.require('dummy.foo.someSpecificallyRequiredMethod'); -goog.require('goog.Class'); -/** @suppress {extraRequire} */ -goog.require('goog.extra.require'); -goog.require('goog.package'); -goog.require('goog.package.ClassName'); -goog.require('goog.package.OtherClassName'); -/** @suppress {extraRequire} Legacy dependency on enum */ -goog.require('goog.package.OuterClassName.InnerClassName'); -goog.require('goog.super.long.DependencyNameThatForcesMethodDefinitionToSpanMultipleLinesFooBar'); -goog.require('goog.super.long.DependencyNameThatForcesTheLineToBeOverEightyCharacters2'); -goog.require('goog.super.long.DependencyNameThatForcesTheLineToBeOverEightyCharacters3'); -goog.require('notInClosurizedNamespacesSoNotExtra'); - -dummy.foo.someMethod(); -dummy.foo.someSpecificallyRequiredMethod(); - - -// Regression test for bug 3473189. Both of these 'goog.provide' tokens should -// be completely ignored by alphabetization checks. -if (typeof goog != 'undefined' && typeof goog.provide == 'function') { - goog.provide('goog.something.SomethingElse'); -} - - -var x = new goog.Class(); -goog.package.staticFunction(); - -var y = goog.Class.Enum.VALUE; - - -// This should not trigger a goog.require. -var somethingPrivate = goog.somethingPrivate.PrivateEnum_.VALUE; - - -/** - * This method is provided directly, instead of its namespace. - */ -goog.somethingelse.someMethod = function() {}; - - -/** - * Defining a private property on a required namespace should not trigger a - * provide of that namespace. Yes, people actually do this. - * @private - */ -goog.Class.privateProperty_ = 1; - - -/** - * @typedef {string} - */ -goog.something.SomeTypeDef; - - -/** - * @typedef {string} - * @private - */ -goog.something.SomePrivateTypeDef_; - - -/** - * Some variable that is declared but not initialized. - * @type {string|undefined} - * @private - */ -goog.something.somePrivateVariable_; - - -/** - * Private variable. - * @type {number} - * @private - */ -goog.something.private_ = 10; - - -/** - * Use private variables defined in this file so they don't cause a warning. - */ -goog.something.usePrivateVariables = function() { - var x = [ - goog.something.private_, - goog.Class.privateProperty_, - x - ]; -}; - - - -/** - * A really long class name to provide and usage of a really long class name to - * be required. - * @constructor - */ -goog.super.long.DependencyNameThatForcesTheLineToBeOverEightyCharacters = - function() { - var x = new goog.super.long. // LINE_ENDS_WITH_DOT - DependencyNameThatForcesTheLineToBeOverEightyCharacters2(); - var x = new goog.super.long - .DependencyNameThatForcesTheLineToBeOverEightyCharacters3(); - // Use x to avoid a warning. - var x = [x]; -}; - - -/** - * A really long class name to to force a method definition to be greater than - * 80 lines. We should be grabbing the whole identifier regardless of how many - * lines it is on. - */ -goog.super.long - .DependencyNameThatForcesMethodDefinitionToSpanMultipleLinesFooBar - .prototype.someMethod = function() { -}; - - -/** - * Static function. - */ -goog.something.staticFunction = function() { - // Tests that namespace usages are identified using 'namespace.' not just - // 'namespace'. - googSomething.property; - dummySomething.property; - goog.package.ClassName // A comment in between the identifier pieces. - .IDENTIFIER_SPLIT_OVER_MULTIPLE_LINES; - goog.package.OtherClassName.property = 1; - - // Test case where inner class needs to be required explicitly. - new goog.package.OuterClassName.InnerClassName(); - - // Don't just use goog.bar for missing namespace, hard coded to never require - // goog since it's never provided. - control.createConstructorMock( - /** @suppress {missingRequire} */ goog.foo.bar, 'Baz'); - - goog.require('goog.shouldBeIgnored'); -}; - - - -/** - * Constructor for Else. - * @constructor - */ -goog.something.Else = function() { - /** @suppress {missingRequire} */ - this.control.createConstructorMock(goog.foo.bar, 'Baz'); -}; - - -/** - * Enum attached to Else. Should not need to be provided explicitly, but - * should not generate an extra require warning either. - * @enum {number} - */ -goog.something.Else.Enum = { - 'key': 1 -}; - - -/** - * Sample of a typedef. This should not need a provide as it is an inner - * element like an enum. - * - * @typedef {{val1: string, val2: boolean, val3: number}} - */ -goog.something.Else.Typedef; - - - -/** - * Constructor for SomethingElse. - * @constructor - */ -goog.something.SomethingElse = function() {}; - - -/** - * @suppress {missingProvide} - */ -goog.suppress.someMethod = function() {}; diff --git a/tools/closure_linter/closure_linter/testdata/semicolon_missing.js b/tools/closure_linter/closure_linter/testdata/semicolon_missing.js deleted file mode 100644 index 5601db8decf289..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/semicolon_missing.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * @fileoverview This is for regression testing of scenario where semicolon is - * missing at EOF. b/10801776. - */ - -goog.provide('dummy.foo.DATA'); - -/** - * @type {string} - * @const - * - * For repeating the bug blank comment line above this is needed. - */ - -// +3: MISSING_SEMICOLON -dummy.foo.DATA = - 'SFSDFSDdfgdfgdftreterterterterterggsdfsrrwerwerwsfwerwerwere55454ss' + - 'SFSDFSDdfgdfgdftretertertertertergg' diff --git a/tools/closure_linter/closure_linter/testdata/simple.html b/tools/closure_linter/closure_linter/testdata/simple.html deleted file mode 100644 index 42ebab97d0f575..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/simple.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - GJsLint HTML JavaScript extraction tests - - - - - - - diff --git a/tools/closure_linter/closure_linter/testdata/spaces.js b/tools/closure_linter/closure_linter/testdata/spaces.js deleted file mode 100644 index 85a36e53bfe6d2..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/spaces.js +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2007 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Errors relating to whitespace. - * - * @author robbyw@google.com (Robby Walker) - */ - -if(needs_space) { // MISSING_SPACE -} - -if ( too_much_space) { // EXTRA_SPACE -} - -if (different_extra_space ) { // EXTRA_SPACE -} - -switch(needs_space) { // MISSING_SPACE -} - -var x = 'if(not_an_error)'; - -var y = afjkljkl + ajklasdflj + ajkadfjkasdfklj + aadskfasdjklf + jkasdfa + ( - kasdfkjlasdfjkl / jklasdfjklasdfjkl); - -x = 5+ 8; // MISSING_SPACE -x = 5 +8; // MISSING_SPACE -x= 5; // MISSING_SPACE -x = 6; // EXTRA_SPACE -x = 7; // EXTRA_SPACE -x = 6 + 2; // EXTRA_SPACE -x += 10; - -throw Error('Selector not supported yet('+ opt_selector + ')'); // MISSING_SPACE -throw Error('Selector not supported yet(' +opt_selector + ')'); // MISSING_SPACE -throw Error( - 'Selector not supported yet' + - '(' +(opt_selector ? 'foo' : 'bar') + ')'); // MISSING_SPACE - -x++; -x ++; // EXTRA_SPACE -x++ ; // EXTRA_SPACE -y = a + ++b; -for (var i = 0; i < 10; ++i) { -} - -// We omit the update section of the for loop to test that a space is allowed -// in this special case. -for (var part; part = parts.shift(); ) { -} - -if (x == y) { -} - -x = 10; // no error here -x = -1; -x++; -++x; - -x = bool ? -1 : -1; - -x = {a: 10}; -x = {a:10}; // MISSING_SPACE - -x = !!y; - -x >>= 0; -x <<= 10; - -x[100] = 10; -x[ 100] = 10; // EXTRA_SPACE -x[100 ] = 10; // EXTRA_SPACE -x [100] = 10; // EXTRA_SPACE -x[10]= 5; // MISSING_SPACE -var x = []; -x = [[]]; -x = [[x]]; -x = [[[x, y]]]; -var craziness = ([1, 2, 3])[1]; -var crazinessError = ([1, 2, 3]) [1]; // EXTRA_SPACE -var multiArray = x[1][2][3][4]; -var multiArrayError = x[1] [2][3][4]; // EXTRA_SPACE - -array[aReallyLooooooooooooooooooooooooooooongIndex1][ - anotherVeryLoooooooooooooooooooooooooooooooooooongIndex -] = 10; - -if (x) { - array[aReallyLooooooooooooooooooooooooooooongIndex1][ - anotherVeryLoooooooooooooooooooooooooooooooooooongIndex - ] = 10; -} - - -/** - * Docs. - * @param {Number} x desc. - * @return {boolean} Some boolean value. - */ -function functionName( x) { // EXTRA_SPACE - return !!x; -} - - -/** - * Docs. - * @param {Number} x desc. - */ -function functionName(x ) { // EXTRA_SPACE - return; -} - - -/** - * Docs. - * @param {Number} x desc. - * @param {Number} y desc. - */ -function functionName(x,y) { // MISSING_SPACE -} - - -/** - * Docs. - * @param {Number} x desc. - * @param {Number} y desc. - */ -function functionName(x, y) { -} - - -/** - * Docs. - */ -function functionName() { // EXTRA_SPACE -} - - -/** - * Docs. - */ -function functionName(){ // MISSING_SPACE -} - -functionName (); // EXTRA_SPACE - - -/** - * Docs. - */ -function functionName () { // EXTRA_SPACE -} - - -/** - * Docs. - */ -var foo = function () { // EXTRA_SPACE -}; - - - -/** - * Missing a newline. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -};goog.inherits(x.y.z, a.b.c); // MISSING_LINE - - - -/** - * Extra space. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; - goog.inherits(x.y.z, a.b.c); // WRONG_INDENTATION - - - -/** - * Extra blank line. - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; - -goog.inherits(x.y.z, a.b.c); // -1: EXTRA_LINE - - - -/** - * Perfect! - * @constructor - * @extends {a.b.c} - */ -x.y.z = function() { -}; -goog.inherits(x.y.z, a.b.c); - -if (flag) { - /** - * Also ok! - * @constructor - * @extends {a.b.c} - */ - x.y.z = function() { - }; - goog.inherits(x.y.z, a.b.c); -} - - -/** - * Docs. - */ -x.finally = function() { -}; - -x.finally(); -x - .finally(); -x.finally (); // EXTRA_SPACE -x - .finally (); // EXTRA_SPACE -try { -} finally (e) { -} -try { -} finally(e) { // MISSING_SPACE -} - -functionName(x , y); // EXTRA_SPACE -functionName(x,y); // MISSING_SPACE -functionName(x, y); - -var really_really_really_really_really_really_really_really_really_long_name = - 2; - -var current = arr[cursorRead++]; - -var x = -(y + z); - -// Tab before + -var foo + 3; // ILLEGAL_TAB -if (something) { - var x = 4; // ILLEGAL_TAB -} - -// +1: ILLEGAL_TAB -// Tab <-- in a comment. - - -// +3: ILLEGAL_TAB -// +3: ILLEGAL_TAB -/** - * An inline flag with a tab {@code asdfasd}. - * @return {string} Illegal <-- tab in a doc description. - */ -function x() { - return ''; -} - - -// +2: ILLEGAL_TAB -/** - * @type {tabBeforeMe} - */ - -// +1: EXTRA_SPACE -var whitespaceAtEndOfLine; - -// +1: EXTRA_SPACE -// Whitespace at end of comment. - - -// +4: EXTRA_SPACE -// +4: EXTRA_SPACE -// +4: EXTRA_SPACE -// +4: EXTRA_SPACE -/* - * Whitespace at EOL. - * @type {string} - * @param {string} Description with whitespace at EOL. - */ -x = 10; - - -/** - * @param {?{foo, bar: number}} x This is a valid annotation. - * @return {{baz}} This is also a valid annotation. - */ -function recordTypeFunction(x) { - return x; -} - -if (y) { - // Colons are difficult. - y = x ? 1 : 2; - y = x ? 1: 2; // MISSING_SPACE - - x = { - b: 'Good', - d : 'Space before colon is bad', // EXTRA_SPACE - f: abc ? def : ghi // These colons should be treated differently - }; - - x = {language: langCode}; // EXTRA_SPACE -} - -// 1094445 - should produce missing space error before +. -// +1: MISSING_SPACE -throw Error('Selector not supported yet ('+ opt_selector + ')'); - -// This code is ok. -for (i = 0; i < len; ++i) { -} - -for (i = 0;i < 10; i++) { // MISSING_SPACE -} -for (i = 0; i < 10;i++) { // MISSING_SPACE -} -for ( i = 0; i < 10; i++) { // EXTRA_SPACE -} -for (i = 0 ; i < 10; i++) { // EXTRA_SPACE -} -for (i = 0; i < 10 ; i++) { // EXTRA_SPACE -} -for (i = 0; i < 10; i++ ) { // EXTRA_SPACE -} -for (i = 0; i < 10; i++) { // EXTRA_SPACE -} -for (i = 0; i < 10; i++) { // EXTRA_SPACE -} -for (i = 0 ;i < 10; i++) { // EXTRA_SPACE, MISSING_SPACE -} - -// Regression test for bug 3508480, parse error when tab as last token. -// +1: ILLEGAL_TAB, EXTRA_SPACE diff --git a/tools/closure_linter/closure_linter/testdata/tokenizer.js b/tools/closure_linter/closure_linter/testdata/tokenizer.js deleted file mode 100644 index 1fbcf4bd410a2a..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/tokenizer.js +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Errors relating to tokenizing. - * - * @author robbyw@google.com (Robby Walker) - */ - -// Regression test: if regular expressions parse incorrectly this will emit an -// error such as: Missing space after '/' -x = /[^\']/; // and all the other chars - -// Regression test: if regular expressions parse incorrectly this will emit an -// error such as: Missing space before + -var regExp = fromStart ? / ^[\t\r\n]+/ : /[ \t\r\n]+$/; - -// Regression test for bug 1032312: test for correct parsing of multiline -// strings -// +2: MULTI_LINE_STRING -var RG_MONTH_EVENT_TEMPLATE_SINGLE_QUOTE = new Template( - '\ -
>>' and '>>>=' that weren't -// recognized as operators. -a -= b; a -= c; a ^= c >>> 13; a >>>= 1; - -// Regression test as xor was not allowed on the end of a line. -x = 1000 ^ - 45; - -// Regression test for proper number parsing. If parsed incorrectly, some of -// these notations can lead to missing spaces errors. -var x = 1e-6 + 1e+6 + 0. + .5 + 0.5 + 0.e-6 + .5e-6 + 0.5e-6 + 0x123abc + - 0X1Ab3 + 1E7; - -// Regression test for keyword parsing - making sure the fact that the "do" -// keyword is a part of the identifier below doesn't break anything. -this.undoRedoManager_.undo(); - -// Regression test for regex as object value not matching. -x = {x: /./}; - -// Regression test for regex as last array element not matching. -x = [/./]; - -// Syntax tests for ES6: -x = x => x; diff --git a/tools/closure_linter/closure_linter/testdata/unparseable.js b/tools/closure_linter/closure_linter/testdata/unparseable.js deleted file mode 100644 index e8426142869810..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/unparseable.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2008 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - - - -/** - * Constructs and initializes a new good object. - * @constructor - */ -goog.good = function() { -}; - - -/** - * Makes this good object go bad. - * @param {number} badnessLevel How bad this object is going. - */ -goog.good.prototype.goBad = function() { // EXTRA_PARAMETER_DOCUMENTATION -}; - -if (x) - // Cannot parse ending block because beginning block is missing. -} // FILE_DOES_NOT_PARSE - - -/** - * Unecessary return documentation error is not reported because file checking - * stopped at token causing parse error. - * - * @return {boolean} Whether reform was sucessful. - */ -goog.good.prototype.reform = function() { -}; diff --git a/tools/closure_linter/closure_linter/testdata/unused_local_variables.js b/tools/closure_linter/closure_linter/testdata/unused_local_variables.js deleted file mode 100644 index e9e51a1164d92d..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/unused_local_variables.js +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2013 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Checks that unused local variables result in an error. - */ - -goog.provide('dummy.Something'); - - - -/** - * @constructor - */ -dummy.Something = function() { - // This variable isn't really used, but we can't tell for sure. - var usedVariable = []; - usedVariable.length = 1; - - var variableUsedInAClosure = []; - var functionUsedByInvoking = function() { - variableUsedInAClosure[1] = 'abc'; - }; - functionUsedByInvoking(); - - var variableUsedTwoLevelsDeep = []; - var firstLevelFunction = function() { - function() { - variableUsedTwoLevelsDeep.append(1); - } - }; - firstLevelFunction(); - - // This variable isn't being declared so is unchecked. - undeclaredLocal = 1; - - var unusedVariable; - - // Check that using a variable as member name doesn't trigger - // usage. - this.unusedVariable = 0; - this.unusedVariable = this.unusedVariable + 1; - - // Check that declaring a variable twice doesn't trigger - // usage. - var unusedVariable; // UNUSED_LOCAL_VARIABLE - - var unusedVariableWithReassignment = []; // UNUSED_LOCAL_VARIABLE - unusedVariableWithReassignment = 'a'; - - var unusedFunction = function() {}; // UNUSED_LOCAL_VARIABLE - - var unusedHiddenVariable = 1; // UNUSED_LOCAL_VARIABLE - firstLevelFunction = function() { - // This variable is actually used in the function below, but hides the outer - // variable with the same name. - var unusedHiddenVariable = 1; - function() { - delete unusedHiddenVariable; - } - }; -}; - - -goog.scope(function() { -var unusedAlias = dummy.Something; // UNUSED_LOCAL_VARIABLE -var UsedTypeAlias = dummy.Something; -var AnotherUsedTypeAlias = dummy.Something; - - -/** @protected {AnotherUsedTypeAlias.Something|UsedTypeAlias} */ -var usedAlias = dummy.Something; -new usedAlias(); -}); // goog.scope - -// Unused top level variables are not checked. -var unusedTopLevelVariable; diff --git a/tools/closure_linter/closure_linter/testdata/unused_private_members.js b/tools/closure_linter/closure_linter/testdata/unused_private_members.js deleted file mode 100644 index 76c0865bcc5540..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/unused_private_members.js +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2010 The Closure Linter Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Checks that an unused private members result in an error. - */ - -goog.provide('dummy.Something'); - - - -/** - * @constructor - */ -dummy.Something = function() { - /** - * @type {number} - * @private - */ - this.normalVariable_ = 1; - - // +5: UNUSED_PRIVATE_MEMBER - /** - * @type {number} - * @private - */ - this.unusedVariable_ = 1; - - /** - * @type {number} - * @private - * @suppress {unusedPrivateMembers} - */ - this.suppressedUnusedVariable_ = 1; -}; - - -/** - * @type {number} - * @private - */ -dummy.Something.NORMAL_CONSTANT_ = 1; - - -// +5: UNUSED_PRIVATE_MEMBER -/** - * @type {number} - * @private - */ -dummy.Something.UNUSED_CONSTANT_ = 1; - - -/** - * @type {number} - * @private - * @suppress {unusedPrivateMembers} - */ -dummy.Something.SUPPRESSED_UNUSED_CONSTANT_ = 1; - - -/** - * @type {number} - * @private - */ -dummy.Something.normalStaticVariable_ = 1; - - -// +5: UNUSED_PRIVATE_MEMBER -/** - * @type {number} - * @private - */ -dummy.Something.unusedStaticVariable_ = 1; - - -/** - * @type {number} - * @private - * @suppress {unusedPrivateMembers} - */ -dummy.Something.suppressedUnusedStaticVariable_ = 1; - - -/** - * @type {number} - * @private - */ -dummy.Something.prototype.normalVariableOnPrototype_ = 1; - - -// +5: UNUSED_PRIVATE_MEMBER -/** - * @type {number} - * @private - */ -dummy.Something.prototype.unusedVariableOnPrototype_ = 1; - - -/** - * @type {number} - * @private - * @suppress {unusedPrivateMembers} - */ -dummy.Something.prototype.suppressedUnusedVariableOnPrototype_ = 1; - - -/** - * Check edge cases that should not be reported. - */ -dummy.Something.prototype.checkFalsePositives = function() { - this.__iterator__ = 1; - this.normalVariable_.unknownChainedVariable_ = 1; - othernamespace.unusedVariable_ = 1; - - this.element_ = 1; - this.element_.modifyPublicMember = 1; - - /** @suppress {underscore} */ - this.suppressedUnderscore_ = true; -}; - - -/** - * Use all the normal variables. - */ -dummy.Something.prototype.useAllTheThings = function() { - var x = [ - dummy.Something.NORMAL_CONSTANT_, - this.normalStaticVariable_, - this.normalVariable_, - this.normalVariableOnPrototype_, - dummy.Something.normalStaticMethod_(), - this.normalMethod_(), - x - ]; -}; - - -// +5: UNUSED_PRIVATE_MEMBER -/** - * Unused static method. - * @private - */ -dummy.Something.unusedStaticMethod_ = function() { - // Do nothing. -}; - - -/** - * Unused static method. - * @private - * @suppress {unusedPrivateMembers} - */ -dummy.Something.suppressedUnusedStaticMethod_ = function() { - // Do nothing. -}; - - -/** - * Normal static method. - * @private - */ -dummy.Something.normalStaticMethod_ = function() { - // Do nothing. -}; - - -// +5: UNUSED_PRIVATE_MEMBER -/** - * Unused non-static method. - * @private - */ -dummy.Something.prototype.unusedMethod_ = function() { - // Do nothing. -}; - - -/** - * Unused non-static method that is suppressed. - * @private - * @suppress {unusedPrivateMembers} - */ -dummy.Something.prototype.suppressedUnusedMethod_ = function() { - // Do nothing. -}; - - -/** - * Normal non-static method. - * @private - */ -dummy.Something.prototype.normalMethod_ = function() { - // Do nothing. -}; diff --git a/tools/closure_linter/closure_linter/testdata/utf8.html b/tools/closure_linter/closure_linter/testdata/utf8.html deleted file mode 100644 index 29517d09416422..00000000000000 --- a/tools/closure_linter/closure_linter/testdata/utf8.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - diff --git a/tools/closure_linter/closure_linter/testutil.py b/tools/closure_linter/closure_linter/testutil.py deleted file mode 100644 index f7084ee37b0683..00000000000000 --- a/tools/closure_linter/closure_linter/testutil.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Utility functions for testing gjslint components.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import StringIO - -from closure_linter import ecmametadatapass -from closure_linter import javascriptstatetracker -from closure_linter import javascripttokenizer - - -def TokenizeSource(source): - """Convert a source into a string of tokens. - - Args: - source: A source file as a string or file-like object (iterates lines). - - Returns: - The first token of the resulting token stream. - """ - - if isinstance(source, basestring): - source = StringIO.StringIO(source) - - tokenizer = javascripttokenizer.JavaScriptTokenizer() - return tokenizer.TokenizeFile(source) - - -def TokenizeSourceAndRunEcmaPass(source): - """Tokenize a source and run the EcmaMetaDataPass on it. - - Args: - source: A source file as a string or file-like object (iterates lines). - - Returns: - The first token of the resulting token stream. - """ - start_token = TokenizeSource(source) - ecma_pass = ecmametadatapass.EcmaMetaDataPass() - ecma_pass.Process(start_token) - return start_token - - -def ParseFunctionsAndComments(source, error_handler=None): - """Run the tokenizer and tracker and return comments and functions found. - - Args: - source: A source file as a string or file-like object (iterates lines). - error_handler: An error handler. - - Returns: - The functions and comments as a tuple. - """ - start_token = TokenizeSourceAndRunEcmaPass(source) - - tracker = javascriptstatetracker.JavaScriptStateTracker() - if error_handler is not None: - tracker.DocFlagPass(start_token, error_handler) - - functions = [] - comments = [] - for token in start_token: - tracker.HandleToken(token, tracker.GetLastNonSpaceToken()) - - function = tracker.GetFunction() - if function and function not in functions: - functions.append(function) - - comment = tracker.GetDocComment() - if comment and comment not in comments: - comments.append(comment) - - tracker.HandleAfterToken(token) - - return functions, comments diff --git a/tools/closure_linter/closure_linter/tokenutil.py b/tools/closure_linter/closure_linter/tokenutil.py deleted file mode 100755 index 11e3ccc68bbe06..00000000000000 --- a/tools/closure_linter/closure_linter/tokenutil.py +++ /dev/null @@ -1,697 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Token utility functions.""" - -__author__ = ('robbyw@google.com (Robert Walker)', - 'ajp@google.com (Andy Perelson)') - -import copy -import StringIO - -from closure_linter.common import tokens -from closure_linter.javascripttokens import JavaScriptToken -from closure_linter.javascripttokens import JavaScriptTokenType - -# Shorthand -Type = tokens.TokenType - - -def GetFirstTokenInSameLine(token): - """Returns the first token in the same line as token. - - Args: - token: Any token in the line. - - Returns: - The first token in the same line as token. - """ - while not token.IsFirstInLine(): - token = token.previous - return token - - -def GetFirstTokenInPreviousLine(token): - """Returns the first token in the previous line as token. - - Args: - token: Any token in the line. - - Returns: - The first token in the previous line as token, or None if token is on the - first line. - """ - first_in_line = GetFirstTokenInSameLine(token) - if first_in_line.previous: - return GetFirstTokenInSameLine(first_in_line.previous) - - return None - - -def GetLastTokenInSameLine(token): - """Returns the last token in the same line as token. - - Args: - token: Any token in the line. - - Returns: - The last token in the same line as token. - """ - while not token.IsLastInLine(): - token = token.next - return token - - -def GetAllTokensInSameLine(token): - """Returns all tokens in the same line as the given token. - - Args: - token: Any token in the line. - - Returns: - All tokens on the same line as the given token. - """ - first_token = GetFirstTokenInSameLine(token) - last_token = GetLastTokenInSameLine(token) - - tokens_in_line = [] - while first_token != last_token: - tokens_in_line.append(first_token) - first_token = first_token.next - tokens_in_line.append(last_token) - - return tokens_in_line - - -def CustomSearch(start_token, func, end_func=None, distance=None, - reverse=False): - """Returns the first token where func is True within distance of this token. - - Args: - start_token: The token to start searching from - func: The function to call to test a token for applicability - end_func: The function to call to test a token to determine whether to abort - the search. - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token matching func within distance of this token, or None if no - such token is found. - """ - token = start_token - if reverse: - while token and (distance is None or distance > 0): - previous = token.previous - if previous: - if func(previous): - return previous - if end_func and end_func(previous): - return None - - token = previous - if distance is not None: - distance -= 1 - - else: - while token and (distance is None or distance > 0): - next_token = token.next - if next_token: - if func(next_token): - return next_token - if end_func and end_func(next_token): - return None - - token = next_token - if distance is not None: - distance -= 1 - - return None - - -def Search(start_token, token_types, distance=None, reverse=False): - """Returns the first token of type in token_types within distance. - - Args: - start_token: The token to start searching from - token_types: The allowable types of the token being searched for - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token of any type in token_types within distance of this token, or - None if no such token is found. - """ - return CustomSearch(start_token, lambda token: token.IsAnyType(token_types), - None, distance, reverse) - - -def SearchExcept(start_token, token_types, distance=None, reverse=False): - """Returns the first token not of any type in token_types within distance. - - Args: - start_token: The token to start searching from - token_types: The unallowable types of the token being searched for - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token of any type in token_types within distance of this token, or - None if no such token is found. - """ - return CustomSearch(start_token, - lambda token: not token.IsAnyType(token_types), - None, distance, reverse) - - -def SearchUntil(start_token, token_types, end_types, distance=None, - reverse=False): - """Returns the first token of type in token_types before a token of end_type. - - Args: - start_token: The token to start searching from. - token_types: The allowable types of the token being searched for. - end_types: Types of tokens to abort search if we find. - distance: The number of tokens to look through before failing search. Must - be positive. If unspecified, will search until the end of the token - chain - reverse: When true, search the tokens before this one instead of the tokens - after it - - Returns: - The first token of any type in token_types within distance of this token - before any tokens of type in end_type, or None if no such token is found. - """ - return CustomSearch(start_token, lambda token: token.IsAnyType(token_types), - lambda token: token.IsAnyType(end_types), - distance, reverse) - - -def DeleteToken(token): - """Deletes the given token from the linked list. - - Args: - token: The token to delete - """ - # When deleting a token, we do not update the deleted token itself to make - # sure the previous and next pointers are still pointing to tokens which are - # not deleted. Also it is very hard to keep track of all previously deleted - # tokens to update them when their pointers become invalid. So we add this - # flag that any token linked list iteration logic can skip deleted node safely - # when its current token is deleted. - token.is_deleted = True - if token.previous: - token.previous.next = token.next - - if token.next: - token.next.previous = token.previous - - following_token = token.next - while following_token and following_token.metadata.last_code == token: - following_token.metadata.last_code = token.metadata.last_code - following_token = following_token.next - - -def DeleteTokens(token, token_count): - """Deletes the given number of tokens starting with the given token. - - Args: - token: The token to start deleting at. - token_count: The total number of tokens to delete. - """ - for i in xrange(1, token_count): - DeleteToken(token.next) - DeleteToken(token) - - -def InsertTokenBefore(new_token, token): - """Insert new_token before token. - - Args: - new_token: A token to be added to the stream - token: A token already in the stream - """ - new_token.next = token - new_token.previous = token.previous - - new_token.metadata = copy.copy(token.metadata) - - if new_token.IsCode(): - old_last_code = token.metadata.last_code - following_token = token - while (following_token and - following_token.metadata.last_code == old_last_code): - following_token.metadata.last_code = new_token - following_token = following_token.next - - token.previous = new_token - if new_token.previous: - new_token.previous.next = new_token - - if new_token.start_index is None: - if new_token.line_number == token.line_number: - new_token.start_index = token.start_index - else: - previous_token = new_token.previous - if previous_token: - new_token.start_index = (previous_token.start_index + - len(previous_token.string)) - else: - new_token.start_index = 0 - - iterator = new_token.next - while iterator and iterator.line_number == new_token.line_number: - iterator.start_index += len(new_token.string) - iterator = iterator.next - - -def InsertTokenAfter(new_token, token): - """Insert new_token after token. - - Args: - new_token: A token to be added to the stream - token: A token already in the stream - """ - new_token.previous = token - new_token.next = token.next - - new_token.metadata = copy.copy(token.metadata) - - if token.IsCode(): - new_token.metadata.last_code = token - - if new_token.IsCode(): - following_token = token.next - while following_token and following_token.metadata.last_code == token: - following_token.metadata.last_code = new_token - following_token = following_token.next - - token.next = new_token - if new_token.next: - new_token.next.previous = new_token - - if new_token.start_index is None: - if new_token.line_number == token.line_number: - new_token.start_index = token.start_index + len(token.string) - else: - new_token.start_index = 0 - - iterator = new_token.next - while iterator and iterator.line_number == new_token.line_number: - iterator.start_index += len(new_token.string) - iterator = iterator.next - - -def InsertTokensAfter(new_tokens, token): - """Insert multiple tokens after token. - - Args: - new_tokens: An array of tokens to be added to the stream - token: A token already in the stream - """ - # TODO(user): It would be nicer to have InsertTokenAfter defer to here - # instead of vice-versa. - current_token = token - for new_token in new_tokens: - InsertTokenAfter(new_token, current_token) - current_token = new_token - - -def InsertSpaceTokenAfter(token): - """Inserts a space token after the given token. - - Args: - token: The token to insert a space token after - - Returns: - A single space token - """ - space_token = JavaScriptToken(' ', Type.WHITESPACE, token.line, - token.line_number) - InsertTokenAfter(space_token, token) - - -def InsertBlankLineAfter(token): - """Inserts a blank line after the given token. - - Args: - token: The token to insert a blank line after - - Returns: - A single space token - """ - blank_token = JavaScriptToken('', Type.BLANK_LINE, '', - token.line_number + 1) - InsertLineAfter(token, [blank_token]) - - -def InsertLineAfter(token, new_tokens): - """Inserts a new line consisting of new_tokens after the given token. - - Args: - token: The token to insert after. - new_tokens: The tokens that will make up the new line. - """ - insert_location = token - for new_token in new_tokens: - InsertTokenAfter(new_token, insert_location) - insert_location = new_token - - # Update all subsequent line numbers. - next_token = new_tokens[-1].next - while next_token: - next_token.line_number += 1 - next_token = next_token.next - - -def SplitToken(token, position): - """Splits the token into two tokens at position. - - Args: - token: The token to split - position: The position to split at. Will be the beginning of second token. - - Returns: - The new second token. - """ - new_string = token.string[position:] - token.string = token.string[:position] - - new_token = JavaScriptToken(new_string, token.type, token.line, - token.line_number) - InsertTokenAfter(new_token, token) - - return new_token - - -def Compare(token1, token2): - """Compares two tokens and determines their relative order. - - Args: - token1: The first token to compare. - token2: The second token to compare. - - Returns: - A negative integer, zero, or a positive integer as the first token is - before, equal, or after the second in the token stream. - """ - if token2.line_number != token1.line_number: - return token1.line_number - token2.line_number - else: - return token1.start_index - token2.start_index - - -def GoogScopeOrNoneFromStartBlock(token): - """Determines if the given START_BLOCK is part of a goog.scope statement. - - Args: - token: A token of type START_BLOCK. - - Returns: - The goog.scope function call token, or None if such call doesn't exist. - """ - if token.type != JavaScriptTokenType.START_BLOCK: - return None - - # Search for a goog.scope statement, which will be 5 tokens before the - # block. Illustration of the tokens found prior to the start block: - # goog.scope(function() { - # 5 4 3 21 ^ - - maybe_goog_scope = token - for unused_i in xrange(5): - maybe_goog_scope = (maybe_goog_scope.previous if maybe_goog_scope and - maybe_goog_scope.previous else None) - if maybe_goog_scope and maybe_goog_scope.string == 'goog.scope': - return maybe_goog_scope - - -def GetTokenRange(start_token, end_token): - """Returns a list of tokens between the two given, inclusive. - - Args: - start_token: Start token in the range. - end_token: End token in the range. - - Returns: - A list of tokens, in order, from start_token to end_token (including start - and end). Returns none if the tokens do not describe a valid range. - """ - - token_range = [] - token = start_token - - while token: - token_range.append(token) - - if token == end_token: - return token_range - - token = token.next - - -def TokensToString(token_iterable): - """Convert a number of tokens into a string. - - Newlines will be inserted whenever the line_number of two neighboring - strings differ. - - Args: - token_iterable: The tokens to turn to a string. - - Returns: - A string representation of the given tokens. - """ - - buf = StringIO.StringIO() - token_list = list(token_iterable) - if not token_list: - return '' - - line_number = token_list[0].line_number - - for token in token_list: - - while line_number < token.line_number: - line_number += 1 - buf.write('\n') - - if line_number > token.line_number: - line_number = token.line_number - buf.write('\n') - - buf.write(token.string) - - return buf.getvalue() - - -def GetPreviousCodeToken(token): - """Returns the code token before the specified token. - - Args: - token: A token. - - Returns: - The code token before the specified token or None if no such token - exists. - """ - - return CustomSearch( - token, - lambda t: t and t.type not in JavaScriptTokenType.NON_CODE_TYPES, - reverse=True) - - -def GetNextCodeToken(token): - """Returns the next code token after the specified token. - - Args: - token: A token. - - Returns: - The next code token after the specified token or None if no such token - exists. - """ - - return CustomSearch( - token, - lambda t: t and t.type not in JavaScriptTokenType.NON_CODE_TYPES, - reverse=False) - - -def GetIdentifierStart(token): - """Returns the first token in an identifier. - - Given a token which is part of an identifier, returns the token at the start - of the identifier. - - Args: - token: A token which is part of an identifier. - - Returns: - The token at the start of the identifier or None if the identifier was not - of the form 'a.b.c' (e.g. "['a']['b'].c"). - """ - - start_token = token - previous_code_token = GetPreviousCodeToken(token) - - while (previous_code_token and ( - previous_code_token.IsType(JavaScriptTokenType.IDENTIFIER) or - IsDot(previous_code_token))): - start_token = previous_code_token - previous_code_token = GetPreviousCodeToken(previous_code_token) - - if IsDot(start_token): - return None - - return start_token - - -def GetIdentifierForToken(token): - """Get the symbol specified by a token. - - Given a token, this function additionally concatenates any parts of an - identifying symbol being identified that are split by whitespace or a - newline. - - The function will return None if the token is not the first token of an - identifier. - - Args: - token: The first token of a symbol. - - Returns: - The whole symbol, as a string. - """ - - # Search backward to determine if this token is the first token of the - # identifier. If it is not the first token, return None to signal that this - # token should be ignored. - prev_token = token.previous - while prev_token: - if (prev_token.IsType(JavaScriptTokenType.IDENTIFIER) or - IsDot(prev_token)): - return None - - if (prev_token.IsType(tokens.TokenType.WHITESPACE) or - prev_token.IsAnyType(JavaScriptTokenType.COMMENT_TYPES)): - prev_token = prev_token.previous - else: - break - - # A "function foo()" declaration. - if token.type is JavaScriptTokenType.FUNCTION_NAME: - return token.string - - # A "var foo" declaration (if the previous token is 'var') - previous_code_token = GetPreviousCodeToken(token) - - if previous_code_token and previous_code_token.IsKeyword('var'): - return token.string - - # Otherwise, this is potentially a namespaced (goog.foo.bar) identifier that - # could span multiple lines or be broken up by whitespace. We need - # to concatenate. - identifier_types = set([ - JavaScriptTokenType.IDENTIFIER, - JavaScriptTokenType.SIMPLE_LVALUE - ]) - - assert token.type in identifier_types - - # Start with the first token - symbol_tokens = [token] - - if token.next: - for t in token.next: - last_symbol_token = symbol_tokens[-1] - - # A dot is part of the previous symbol. - if IsDot(t): - symbol_tokens.append(t) - continue - - # An identifier is part of the previous symbol if the previous one was a - # dot. - if t.type in identifier_types: - if IsDot(last_symbol_token): - symbol_tokens.append(t) - continue - else: - break - - # Skip any whitespace - if t.type in JavaScriptTokenType.NON_CODE_TYPES: - continue - - # This is the end of the identifier. Stop iterating. - break - - if symbol_tokens: - return ''.join([t.string for t in symbol_tokens]) - - -def GetStringAfterToken(token): - """Get string after token. - - Args: - token: Search will be done after this token. - - Returns: - String if found after token else None (empty string will also - return None). - - Search until end of string as in case of empty string Type.STRING_TEXT is not - present/found and don't want to return next string. - E.g. - a = ''; - b = 'test'; - When searching for string after 'a' if search is not limited by end of string - then it will return 'test' which is not desirable as there is a empty string - before that. - - This will return None for cases where string is empty or no string found - as in both cases there is no Type.STRING_TEXT. - """ - string_token = SearchUntil(token, JavaScriptTokenType.STRING_TEXT, - [JavaScriptTokenType.SINGLE_QUOTE_STRING_END, - JavaScriptTokenType.DOUBLE_QUOTE_STRING_END]) - if string_token: - return string_token.string - else: - return None - - -def IsDot(token): - """Whether the token represents a "dot" operator (foo.bar).""" - return token.type is JavaScriptTokenType.OPERATOR and token.string == '.' - - -def IsIdentifierOrDot(token): - """Whether the token is either an identifier or a '.'.""" - return (token.type in [JavaScriptTokenType.IDENTIFIER, - JavaScriptTokenType.SIMPLE_LVALUE] or - IsDot(token)) diff --git a/tools/closure_linter/closure_linter/tokenutil_test.py b/tools/closure_linter/closure_linter/tokenutil_test.py deleted file mode 100644 index c7d3854776bd48..00000000000000 --- a/tools/closure_linter/closure_linter/tokenutil_test.py +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2012 The Closure Linter Authors. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests for the scopeutil module.""" - -# Allow non-Google copyright -# pylint: disable=g-bad-file-header - -__author__ = ('nnaze@google.com (Nathan Naze)') - -import unittest as googletest - -from closure_linter import ecmametadatapass -from closure_linter import javascripttokens -from closure_linter import testutil -from closure_linter import tokenutil - - -class FakeToken(object): - pass - - -class TokenUtilTest(googletest.TestCase): - - def testGetTokenRange(self): - - a = FakeToken() - b = FakeToken() - c = FakeToken() - d = FakeToken() - e = FakeToken() - - a.next = b - b.next = c - c.next = d - - self.assertEquals([a, b, c, d], tokenutil.GetTokenRange(a, d)) - - # This is an error as e does not come after a in the token chain. - self.assertRaises(Exception, lambda: tokenutil.GetTokenRange(a, e)) - - def testTokensToString(self): - - a = FakeToken() - b = FakeToken() - c = FakeToken() - d = FakeToken() - e = FakeToken() - - a.string = 'aaa' - b.string = 'bbb' - c.string = 'ccc' - d.string = 'ddd' - e.string = 'eee' - - a.line_number = 5 - b.line_number = 6 - c.line_number = 6 - d.line_number = 10 - e.line_number = 11 - - self.assertEquals( - 'aaa\nbbbccc\n\n\n\nddd\neee', - tokenutil.TokensToString([a, b, c, d, e])) - - self.assertEquals( - 'ddd\neee\naaa\nbbbccc', - tokenutil.TokensToString([d, e, a, b, c]), - 'Neighboring tokens not in line_number order should have a newline ' - 'between them.') - - def testGetPreviousCodeToken(self): - - tokens = testutil.TokenizeSource(""" -start1. // comment - /* another comment */ - end1 -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - None, - tokenutil.GetPreviousCodeToken(_GetTokenStartingWith('start1'))) - - self.assertEquals( - '.', - tokenutil.GetPreviousCodeToken(_GetTokenStartingWith('end1')).string) - - self.assertEquals( - 'start1', - tokenutil.GetPreviousCodeToken(_GetTokenStartingWith('.')).string) - - def testGetNextCodeToken(self): - - tokens = testutil.TokenizeSource(""" -start1. // comment - /* another comment */ - end1 -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - '.', - tokenutil.GetNextCodeToken(_GetTokenStartingWith('start1')).string) - - self.assertEquals( - 'end1', - tokenutil.GetNextCodeToken(_GetTokenStartingWith('.')).string) - - self.assertEquals( - None, - tokenutil.GetNextCodeToken(_GetTokenStartingWith('end1'))) - - def testGetIdentifierStart(self): - - tokens = testutil.TokenizeSource(""" -start1 . // comment - prototype. /* another comment */ - end1 - -['edge'][case].prototype. - end2 = function() {} -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - 'start1', - tokenutil.GetIdentifierStart(_GetTokenStartingWith('end1')).string) - - self.assertEquals( - 'start1', - tokenutil.GetIdentifierStart(_GetTokenStartingWith('start1')).string) - - self.assertEquals( - None, - tokenutil.GetIdentifierStart(_GetTokenStartingWith('end2'))) - - def testInsertTokenBefore(self): - - self.AssertInsertTokenAfterBefore(False) - - def testInsertTokenAfter(self): - - self.AssertInsertTokenAfterBefore(True) - - def AssertInsertTokenAfterBefore(self, after): - - new_token = javascripttokens.JavaScriptToken( - 'a', javascripttokens.JavaScriptTokenType.IDENTIFIER, 1, 1) - - existing_token1 = javascripttokens.JavaScriptToken( - 'var', javascripttokens.JavaScriptTokenType.KEYWORD, 1, 1) - existing_token1.start_index = 0 - existing_token1.metadata = ecmametadatapass.EcmaMetaData() - - existing_token2 = javascripttokens.JavaScriptToken( - ' ', javascripttokens.JavaScriptTokenType.WHITESPACE, 1, 1) - existing_token2.start_index = 3 - existing_token2.metadata = ecmametadatapass.EcmaMetaData() - existing_token2.metadata.last_code = existing_token1 - - existing_token1.next = existing_token2 - existing_token2.previous = existing_token1 - - if after: - tokenutil.InsertTokenAfter(new_token, existing_token1) - else: - tokenutil.InsertTokenBefore(new_token, existing_token2) - - self.assertEquals(existing_token1, new_token.previous) - self.assertEquals(existing_token2, new_token.next) - - self.assertEquals(new_token, existing_token1.next) - self.assertEquals(new_token, existing_token2.previous) - - self.assertEquals(existing_token1, new_token.metadata.last_code) - self.assertEquals(new_token, existing_token2.metadata.last_code) - - self.assertEquals(0, existing_token1.start_index) - self.assertEquals(3, new_token.start_index) - self.assertEquals(4, existing_token2.start_index) - - def testGetIdentifierForToken(self): - - tokens = testutil.TokenizeSource(""" -start1.abc.def.prototype. - onContinuedLine - -(start2.abc.def - .hij.klm - .nop) - -start3.abc.def - .hij = function() {}; - -// An absurd multi-liner. -start4.abc.def. - hij. - klm = function() {}; - -start5 . aaa . bbb . ccc - shouldntBePartOfThePreviousSymbol - -start6.abc.def ghi.shouldntBePartOfThePreviousSymbol - -var start7 = 42; - -function start8() { - -} - -start9.abc. // why is there a comment here? - def /* another comment */ - shouldntBePart - -start10.abc // why is there a comment here? - .def /* another comment */ - shouldntBePart - -start11.abc. middle1.shouldNotBeIdentifier -""") - - def _GetTokenStartingWith(token_starts_with): - for t in tokens: - if t.string.startswith(token_starts_with): - return t - - self.assertEquals( - 'start1.abc.def.prototype.onContinuedLine', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start1'))) - - self.assertEquals( - 'start2.abc.def.hij.klm.nop', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start2'))) - - self.assertEquals( - 'start3.abc.def.hij', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start3'))) - - self.assertEquals( - 'start4.abc.def.hij.klm', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start4'))) - - self.assertEquals( - 'start5.aaa.bbb.ccc', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start5'))) - - self.assertEquals( - 'start6.abc.def', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start6'))) - - self.assertEquals( - 'start7', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start7'))) - - self.assertEquals( - 'start8', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start8'))) - - self.assertEquals( - 'start9.abc.def', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start9'))) - - self.assertEquals( - 'start10.abc.def', - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('start10'))) - - self.assertIsNone( - tokenutil.GetIdentifierForToken(_GetTokenStartingWith('middle1'))) - - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/closure_linter/typeannotation.py b/tools/closure_linter/closure_linter/typeannotation.py deleted file mode 100644 index 00604c13a7b31b..00000000000000 --- a/tools/closure_linter/closure_linter/typeannotation.py +++ /dev/null @@ -1,401 +0,0 @@ -#!/usr/bin/env python -#*-* coding: utf-8 -"""Closure typeannotation parsing and utilities.""" - - - -from closure_linter import errors -from closure_linter import javascripttokens -from closure_linter.common import error - -# Shorthand -TYPE = javascripttokens.JavaScriptTokenType - - -class TypeAnnotation(object): - """Represents a structured view of a closure type annotation. - - Attribute: - identifier: The name of the type. - key_type: The name part before a colon. - sub_types: The list of sub_types used e.g. for Array.<…> - or_null: The '?' annotation - not_null: The '!' annotation - type_group: If this a a grouping (a|b), but does not include function(a). - return_type: The return type of a function definition. - alias: The actual type set by closurizednamespaceinfo if the identifier uses - an alias to shorten the name. - tokens: An ordered list of tokens used for this type. May contain - TypeAnnotation instances for sub_types, key_type or return_type. - """ - - IMPLICIT_TYPE_GROUP = 2 - - NULLABILITY_UNKNOWN = 2 - - # Frequently used known non-nullable types. - NON_NULLABLE = frozenset([ - 'boolean', 'function', 'number', 'string', 'undefined']) - # Frequently used known nullable types. - NULLABLE_TYPE_WHITELIST = frozenset([ - 'Array', 'Document', 'Element', 'Function', 'Node', 'NodeList', - 'Object']) - - def __init__(self): - self.identifier = '' - self.sub_types = [] - self.or_null = False - self.not_null = False - self.type_group = False - self.alias = None - self.key_type = None - self.record_type = False - self.opt_arg = False - self.return_type = None - self.tokens = [] - - def IsFunction(self): - """Determines whether this is a function definition.""" - return self.identifier == 'function' - - def IsConstructor(self): - """Determines whether this is a function definition for a constructor.""" - key_type = self.sub_types and self.sub_types[0].key_type - return self.IsFunction() and key_type.identifier == 'new' - - def IsRecordType(self): - """Returns True if this type is a record type.""" - return (self.record_type or - bool([t for t in self.sub_types if t.IsRecordType()])) - - def IsVarArgsType(self): - """Determines if the type is a var_args type, i.e. starts with '...'.""" - return self.identifier.startswith('...') or ( - self.type_group == TypeAnnotation.IMPLICIT_TYPE_GROUP and - self.sub_types[0].identifier.startswith('...')) - - def IsEmpty(self): - """Returns True if the type is empty.""" - return not self.tokens - - def IsUnknownType(self): - """Returns True if this is the unknown type {?}.""" - return (self.or_null - and not self.identifier - and not self.sub_types - and not self.return_type) - - def Append(self, item): - """Adds a sub_type to this type and finalizes it. - - Args: - item: The TypeAnnotation item to append. - """ - # item is a TypeAnnotation instance, so pylint: disable=protected-access - self.sub_types.append(item._Finalize(self)) - - def __repr__(self): - """Reconstructs the type definition.""" - append = '' - if self.sub_types: - separator = (',' if not self.type_group else '|') - if self.identifier == 'function': - surround = '(%s)' - else: - surround = {False: '{%s}' if self.record_type else '<%s>', - True: '(%s)', - self.IMPLICIT_TYPE_GROUP: '%s'}[self.type_group] - append = surround % separator.join([repr(t) for t in self.sub_types]) - if self.return_type: - append += ':%s' % repr(self.return_type) - append += '=' if self.opt_arg else '' - prefix = '' + ('?' if self.or_null else '') + ('!' if self.not_null else '') - keyword = '%s:' % repr(self.key_type) if self.key_type else '' - return keyword + prefix + '%s' % (self.alias or self.identifier) + append - - def ToString(self): - """Concats the type's tokens to form a string again.""" - ret = [] - for token in self.tokens: - if not isinstance(token, TypeAnnotation): - ret.append(token.string) - else: - ret.append(token.ToString()) - return ''.join(ret) - - def Dump(self, indent=''): - """Dumps this type's structure for debugging purposes.""" - result = [] - for t in self.tokens: - if isinstance(t, TypeAnnotation): - result.append(indent + str(t) + ' =>\n' + t.Dump(indent + ' ')) - else: - result.append(indent + str(t)) - return '\n'.join(result) - - def IterIdentifiers(self): - """Iterates over all identifiers in this type and its subtypes.""" - if self.identifier: - yield self.identifier - for subtype in self.IterTypes(): - for identifier in subtype.IterIdentifiers(): - yield identifier - - def IterTypeGroup(self): - """Iterates over all types in the type group including self. - - Yields: - If this is a implicit or manual type-group: all sub_types. - Otherwise: self - E.g. for @type {Foo.} this will yield only Foo., - for @type {Foo|(Bar|Sample)} this will yield Foo, Bar and Sample. - - """ - if self.type_group: - for sub_type in self.sub_types: - for sub_type in sub_type.IterTypeGroup(): - yield sub_type - else: - yield self - - def IterTypes(self): - """Iterates over each subtype as well as return and key types.""" - if self.return_type: - yield self.return_type - - if self.key_type: - yield self.key_type - - for sub_type in self.sub_types: - yield sub_type - - def GetNullability(self, modifiers=True): - """Computes whether the type may be null. - - Args: - modifiers: Whether the modifiers ? and ! should be considered in the - evaluation. - Returns: - True if the type allows null, False if the type is strictly non nullable - and NULLABILITY_UNKNOWN if the nullability cannot be determined. - """ - - # Explicitly marked nullable types or 'null' are nullable. - if (modifiers and self.or_null) or self.identifier == 'null': - return True - - # Explicitly marked non-nullable types or non-nullable base types: - if ((modifiers and self.not_null) or self.record_type - or self.identifier in self.NON_NULLABLE): - return False - - # A type group is nullable if any of its elements are nullable. - if self.type_group: - maybe_nullable = False - for sub_type in self.sub_types: - nullability = sub_type.GetNullability() - if nullability == self.NULLABILITY_UNKNOWN: - maybe_nullable = nullability - elif nullability: - return True - return maybe_nullable - - # Whitelisted types are nullable. - if self.identifier.rstrip('.') in self.NULLABLE_TYPE_WHITELIST: - return True - - # All other types are unknown (most should be nullable, but - # enums are not and typedefs might not be). - return self.NULLABILITY_UNKNOWN - - def WillAlwaysBeNullable(self): - """Computes whether the ! flag is illegal for this type. - - This is the case if this type or any of the subtypes is marked as - explicitly nullable. - - Returns: - True if the ! flag would be illegal. - """ - if self.or_null or self.identifier == 'null': - return True - - if self.type_group: - return bool([t for t in self.sub_types if t.WillAlwaysBeNullable()]) - - return False - - def _Finalize(self, parent): - """Fixes some parsing issues once the TypeAnnotation is complete.""" - - # Normalize functions whose definition ended up in the key type because - # they defined a return type after a colon. - if self.key_type and self.key_type.identifier == 'function': - current = self.key_type - current.return_type = self - self.key_type = None - # opt_arg never refers to the return type but to the function itself. - current.opt_arg = self.opt_arg - self.opt_arg = False - return current - - # If a typedef just specified the key, it will not end up in the key type. - if parent.record_type and not self.key_type: - current = TypeAnnotation() - current.key_type = self - current.tokens.append(self) - return current - return self - - def FirstToken(self): - """Returns the first token used in this type or any of its subtypes.""" - first = self.tokens[0] - return first.FirstToken() if isinstance(first, TypeAnnotation) else first - - -def Parse(token, token_end, error_handler): - """Parses a type annotation and returns a TypeAnnotation object.""" - return TypeAnnotationParser(error_handler).Parse(token.next, token_end) - - -class TypeAnnotationParser(object): - """A parser for type annotations constructing the TypeAnnotation object.""" - - def __init__(self, error_handler): - self._stack = [] - self._error_handler = error_handler - self._closing_error = False - - def Parse(self, token, token_end): - """Parses a type annotation and returns a TypeAnnotation object.""" - root = TypeAnnotation() - self._stack.append(root) - current = TypeAnnotation() - root.tokens.append(current) - - while token and token != token_end: - if token.type in (TYPE.DOC_TYPE_START_BLOCK, TYPE.DOC_START_BRACE): - if token.string == '(': - if (current.identifier and - current.identifier not in ['function', '...']): - self.Error(token, - 'Invalid identifier for (): "%s"' % current.identifier) - current.type_group = current.identifier != 'function' - elif token.string == '{': - current.record_type = True - current.tokens.append(token) - self._stack.append(current) - current = TypeAnnotation() - self._stack[-1].tokens.append(current) - - elif token.type in (TYPE.DOC_TYPE_END_BLOCK, TYPE.DOC_END_BRACE): - prev = self._stack.pop() - prev.Append(current) - current = prev - - # If an implicit type group was created, close it as well. - if prev.type_group == TypeAnnotation.IMPLICIT_TYPE_GROUP: - prev = self._stack.pop() - prev.Append(current) - current = prev - current.tokens.append(token) - - elif token.type == TYPE.DOC_TYPE_MODIFIER: - if token.string == '!': - current.tokens.append(token) - current.not_null = True - elif token.string == '?': - current.tokens.append(token) - current.or_null = True - elif token.string == ':': - current.tokens.append(token) - prev = current - current = TypeAnnotation() - prev.tokens.append(current) - current.key_type = prev - elif token.string == '=': - # For implicit type groups the '=' refers to the parent. - try: - if self._stack[-1].type_group == TypeAnnotation.IMPLICIT_TYPE_GROUP: - self._stack[-1].tokens.append(token) - self._stack[-1].opt_arg = True - else: - current.tokens.append(token) - current.opt_arg = True - except IndexError: - self.ClosingError(token) - elif token.string == '|': - # If a type group has explicitly been opened do a normal append. - # Otherwise we have to open the type group and move the current - # type into it, before appending - if not self._stack[-1].type_group: - type_group = TypeAnnotation() - if current.key_type and current.key_type.identifier != 'function': - type_group.key_type = current.key_type - current.key_type = None - type_group.type_group = TypeAnnotation.IMPLICIT_TYPE_GROUP - # Fix the token order - prev = self._stack[-1].tokens.pop() - self._stack[-1].tokens.append(type_group) - type_group.tokens.append(prev) - self._stack.append(type_group) - self._stack[-1].tokens.append(token) - self.Append(current, error_token=token) - current = TypeAnnotation() - self._stack[-1].tokens.append(current) - elif token.string == ',': - self.Append(current, error_token=token) - current = TypeAnnotation() - self._stack[-1].tokens.append(token) - self._stack[-1].tokens.append(current) - else: - current.tokens.append(token) - self.Error(token, 'Invalid token') - - elif token.type == TYPE.COMMENT: - current.tokens.append(token) - current.identifier += token.string.strip() - - elif token.type in [TYPE.DOC_PREFIX, TYPE.WHITESPACE]: - current.tokens.append(token) - - else: - current.tokens.append(token) - self.Error(token, 'Unexpected token') - - token = token.next - - self.Append(current, error_token=token) - try: - ret = self._stack.pop() - except IndexError: - self.ClosingError(token) - # The type is screwed up, but let's return something. - return current - - if self._stack and (len(self._stack) != 1 or - ret.type_group != TypeAnnotation.IMPLICIT_TYPE_GROUP): - self.Error(token, 'Too many opening items.') - - return ret if len(ret.sub_types) > 1 else ret.sub_types[0] - - def Append(self, type_obj, error_token): - """Appends a new TypeAnnotation object to the current parent.""" - if self._stack: - self._stack[-1].Append(type_obj) - else: - self.ClosingError(error_token) - - def ClosingError(self, token): - """Reports an error about too many closing items, but only once.""" - if not self._closing_error: - self._closing_error = True - self.Error(token, 'Too many closing items.') - - def Error(self, token, message): - """Calls the error_handler to post an error message.""" - if self._error_handler: - self._error_handler.HandleError(error.Error( - errors.JSDOC_DOES_NOT_PARSE, - 'Error parsing jsdoc type at token "%s" (column: %d): %s' % - (token.string, token.start_index, message), token)) diff --git a/tools/closure_linter/closure_linter/typeannotation_test.py b/tools/closure_linter/closure_linter/typeannotation_test.py deleted file mode 100755 index da9dfa369f0bc8..00000000000000 --- a/tools/closure_linter/closure_linter/typeannotation_test.py +++ /dev/null @@ -1,232 +0,0 @@ -#!/usr/bin/env python -"""Unit tests for the typeannotation module.""" - - - - -import unittest as googletest - -from closure_linter import testutil -from closure_linter.common import erroraccumulator - -CRAZY_TYPE = ('Array.))>') - - -class TypeErrorException(Exception): - """Exception for TypeErrors.""" - - def __init__(self, errors): - super(TypeErrorException, self).__init__() - self.errors = errors - - -class TypeParserTest(googletest.TestCase): - """Tests for typeannotation parsing.""" - - def _ParseComment(self, script): - """Parse a script that contains one comment and return it.""" - accumulator = erroraccumulator.ErrorAccumulator() - _, comments = testutil.ParseFunctionsAndComments(script, accumulator) - if accumulator.GetErrors(): - raise TypeErrorException(accumulator.GetErrors()) - self.assertEquals(1, len(comments)) - return comments[0] - - def _ParseType(self, type_str): - """Creates a comment to parse and returns the parsed type.""" - comment = self._ParseComment('/** @type {%s} **/' % type_str) - return comment.GetDocFlags()[0].jstype - - def assertProperReconstruction(self, type_str, matching_str=None): - """Parses the type and asserts the its repr matches the type. - - If matching_str is specified, it will assert that the repr matches this - string instead. - - Args: - type_str: The type string to parse. - matching_str: A string the __repr__ of the parsed type should match. - Returns: - The parsed js_type. - """ - parsed_type = self._ParseType(type_str) - # Use listEqual assertion to more easily identify the difference - self.assertListEqual(list(matching_str or type_str), - list(repr(parsed_type))) - self.assertEquals(matching_str or type_str, repr(parsed_type)) - - # Newlines will be inserted by the file writer. - self.assertEquals(type_str.replace('\n', ''), parsed_type.ToString()) - return parsed_type - - def assertNullable(self, type_str, nullable=True): - parsed_type = self.assertProperReconstruction(type_str) - self.assertEquals(nullable, parsed_type.GetNullability(), - '"%s" should %sbe nullable' % - (type_str, 'not ' if nullable else '')) - - def assertNotNullable(self, type_str): - return self.assertNullable(type_str, nullable=False) - - def testReconstruction(self): - self.assertProperReconstruction('*') - self.assertProperReconstruction('number') - self.assertProperReconstruction('(((number)))') - self.assertProperReconstruction('!number') - self.assertProperReconstruction('?!number') - self.assertProperReconstruction('number=') - self.assertProperReconstruction('number=!?', '?!number=') - self.assertProperReconstruction('number|?string') - self.assertProperReconstruction('(number|string)') - self.assertProperReconstruction('?(number|string)') - self.assertProperReconstruction('Object.') - self.assertProperReconstruction('function(new:Object)') - self.assertProperReconstruction('function(new:Object):number') - self.assertProperReconstruction('function(new:Object,Element):number') - self.assertProperReconstruction('function(this:T,...)') - self.assertProperReconstruction('{a:?number}') - self.assertProperReconstruction('{a:?number,b:(number|string)}') - self.assertProperReconstruction('{c:{nested_element:*}|undefined}') - self.assertProperReconstruction('{handleEvent:function(?):?}') - self.assertProperReconstruction('function():?|null') - self.assertProperReconstruction('null|function():?|bar') - - def testOptargs(self): - self.assertProperReconstruction('number=') - self.assertProperReconstruction('number|string=') - self.assertProperReconstruction('(number|string)=') - self.assertProperReconstruction('(number|string=)') - self.assertProperReconstruction('(number=|string)') - self.assertProperReconstruction('function(...):number=') - - def testIndepth(self): - # Do an deeper check of the crazy identifier - crazy = self.assertProperReconstruction(CRAZY_TYPE) - self.assertEquals('Array.', crazy.identifier) - self.assertEquals(1, len(crazy.sub_types)) - func1 = crazy.sub_types[0] - func2 = func1.return_type - self.assertEquals('function', func1.identifier) - self.assertEquals('function', func2.identifier) - self.assertEquals(3, len(func1.sub_types)) - self.assertEquals(1, len(func2.sub_types)) - self.assertEquals('Object.', func2.sub_types[0].sub_types[0].identifier) - - def testIterIdentifiers(self): - nested_identifiers = self._ParseType('(a|{b:(c|function(new:d):e)})') - for identifier in ('a', 'b', 'c', 'd', 'e'): - self.assertIn(identifier, nested_identifiers.IterIdentifiers()) - - def testIsEmpty(self): - self.assertTrue(self._ParseType('').IsEmpty()) - self.assertFalse(self._ParseType('?').IsEmpty()) - self.assertFalse(self._ParseType('!').IsEmpty()) - self.assertFalse(self._ParseType('').IsEmpty()) - - def testIsConstructor(self): - self.assertFalse(self._ParseType('').IsConstructor()) - self.assertFalse(self._ParseType('Array.').IsConstructor()) - self.assertTrue(self._ParseType('function(new:T)').IsConstructor()) - - def testIsVarArgsType(self): - self.assertTrue(self._ParseType('...number').IsVarArgsType()) - self.assertTrue(self._ParseType('...Object|Array').IsVarArgsType()) - self.assertTrue(self._ParseType('...(Object|Array)').IsVarArgsType()) - self.assertFalse(self._ParseType('Object|...Array').IsVarArgsType()) - self.assertFalse(self._ParseType('(...Object|Array)').IsVarArgsType()) - - def testIsUnknownType(self): - self.assertTrue(self._ParseType('?').IsUnknownType()) - self.assertTrue(self._ParseType('Foo.').sub_types[0].IsUnknownType()) - self.assertFalse(self._ParseType('?|!').IsUnknownType()) - self.assertTrue(self._ParseType('?|!').sub_types[0].IsUnknownType()) - self.assertFalse(self._ParseType('!').IsUnknownType()) - - long_type = 'function():?|{handleEvent:function(?=):?,sample:?}|?=' - record = self._ParseType(long_type) - # First check that there's not just one type with 3 return types, but three - # top-level types. - self.assertEquals(3, len(record.sub_types)) - - # Now extract all unknown type instances and verify that they really are. - handle_event, sample = record.sub_types[1].sub_types - for i, sub_type in enumerate([ - record.sub_types[0].return_type, - handle_event.return_type, - handle_event.sub_types[0], - sample, - record.sub_types[2]]): - self.assertTrue(sub_type.IsUnknownType(), - 'Type %d should be the unknown type: %s\n%s' % ( - i, sub_type.tokens, record.Dump())) - - def testTypedefNames(self): - easy = self._ParseType('{a}') - self.assertTrue(easy.record_type) - - easy = self.assertProperReconstruction('{a}', '{a:}').sub_types[0] - self.assertEquals('a', easy.key_type.identifier) - self.assertEquals('', easy.identifier) - - easy = self.assertProperReconstruction('{a:b}').sub_types[0] - self.assertEquals('a', easy.key_type.identifier) - self.assertEquals('b', easy.identifier) - - def assertTypeError(self, type_str): - """Asserts that parsing the given type raises a linter error.""" - self.assertRaises(TypeErrorException, self._ParseType, type_str) - - def testParseBadTypes(self): - """Tests that several errors in types don't break the parser.""" - self.assertTypeError('<') - self.assertTypeError('>') - self.assertTypeError('Foo.=') - self.assertTypeError('Foo.>=') - self.assertTypeError('(') - self.assertTypeError(')') - self.assertTypeError('Foo.') - self._ParseType(':') - self._ParseType(':foo') - self.assertTypeError(':)foo') - self.assertTypeError('(a|{b:(c|function(new:d):e') - - def testNullable(self): - self.assertNullable('null') - self.assertNullable('Object') - self.assertNullable('?string') - self.assertNullable('?number') - - self.assertNotNullable('string') - self.assertNotNullable('number') - self.assertNotNullable('boolean') - self.assertNotNullable('function(Object)') - self.assertNotNullable('function(Object):Object') - self.assertNotNullable('function(?Object):?Object') - self.assertNotNullable('!Object') - - self.assertNotNullable('boolean|string') - self.assertNotNullable('(boolean|string)') - - self.assertNullable('(boolean|string|null)') - self.assertNullable('(?boolean)') - self.assertNullable('?(boolean)') - - self.assertNullable('(boolean|Object)') - self.assertNotNullable('(boolean|(string|{a:}))') - - def testSpaces(self): - """Tests that spaces don't change the outcome.""" - type_str = (' A < b | ( c | ? ! d e f ) > | ' - 'function ( x : . . . ) : { y : z = } ') - two_spaces = type_str.replace(' ', ' ') - no_spaces = type_str.replace(' ', '') - newlines = type_str.replace(' ', '\n * ') - self.assertProperReconstruction(no_spaces) - self.assertProperReconstruction(type_str, no_spaces) - self.assertProperReconstruction(two_spaces, no_spaces) - self.assertProperReconstruction(newlines, no_spaces) - -if __name__ == '__main__': - googletest.main() diff --git a/tools/closure_linter/dist/closure_linter-2.3.17-py2.7.egg b/tools/closure_linter/dist/closure_linter-2.3.17-py2.7.egg deleted file mode 100644 index e9a847ca28b842..00000000000000 Binary files a/tools/closure_linter/dist/closure_linter-2.3.17-py2.7.egg and /dev/null differ diff --git a/tools/closure_linter/setup.py b/tools/closure_linter/setup.py deleted file mode 100755 index d320b65d1791fd..00000000000000 --- a/tools/closure_linter/setup.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 The Closure Linter Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS-IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -try: - from setuptools import setup -except ImportError: - from distutils.core import setup - -setup(name='closure_linter', - version='2.3.17', - description='Closure Linter', - license='Apache', - author='The Closure Linter Authors', - author_email='opensource@google.com', - url='http://code.google.com/p/closure-linter', - install_requires=['python-gflags'], - package_dir={'closure_linter': 'closure_linter'}, - packages=['closure_linter', 'closure_linter.common'], - entry_points = { - 'console_scripts': [ - 'gjslint = closure_linter.gjslint:main', - 'fixjsstyle = closure_linter.fixjsstyle:main' - ] - } -) diff --git a/tools/eslint/LICENSE b/tools/eslint/LICENSE new file mode 100644 index 00000000000000..3f7b4baaa16466 --- /dev/null +++ b/tools/eslint/LICENSE @@ -0,0 +1,20 @@ +ESLint +Copyright (c) 2013 Nicholas C. Zakas. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/README.md b/tools/eslint/README.md new file mode 100644 index 00000000000000..f2f75acf19c588 --- /dev/null +++ b/tools/eslint/README.md @@ -0,0 +1,79 @@ +[![NPM version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![Downloads][downloads-image]][downloads-url] +[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=282608)](https://www.bountysource.com/trackers/282608-eslint?utm_source=282608&utm_medium=shield&utm_campaign=TRACKER_BADGE) + +# ESLint + +[Website](http://eslint.org) | [Configuring](http://eslint.org/docs/user-guide/configuring) | [Rules](http://eslint.org/docs/rules/) | [Contributing](http://eslint.org/docs/developer-guide/contributing) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) + +ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: + +* ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. +* ESLint uses an AST to evaluate patterns in code. +* ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. + +## Installation + +You can install ESLint using npm: + + npm install -g eslint + +## Usage + + eslint test.js test2.js + +## Frequently Asked Questions + +### Why don't you like JSHint??? + +I do like JSHint. And I like Anton and Rick. Neither of those were deciding factors in creating this tool. The fact is that I've had a dire need for a JavaScript tool with pluggable linting rules. I had hoped JSHint would be able to do this, however after chatting with Anton, I found that the planned plugin infrastructure wasn't going to suit my purpose. + +### I'm not giving up JSHint for this! + +That's not really a question, but I got it. I'm not trying to convince you that ESLint is better than JSHint. The only thing I know is that ESLint is better than JSHint for what I'm doing. In the off chance you're doing something similar, it might be better for you. Otherwise, keep using JSHint, I'm certainly not going to tell you to stop using it. + +### How does ESLint performance compare to JSHint? + +ESLint is slower than JSHint, usually 2-3x slower on a single file. This is because ESLint uses Espree to construct an AST before it can evaluate your code whereas JSHint evaluates your code as it's being parsed. The speed is also based on the number of rules you enable; the more rules you enable, the slower the process. + +Despite being slower, we believe that ESLint is fast enough to replace JSHint without causing significant pain. + +### Is ESLint just linting or does it also check style? + +ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use it for both. + +### Who is using ESLint? + +The following projects are using ESLint to validate their JavaScript: + +* [Drupal](https://www.drupal.org/node/2274223) +* [Esprima](https://github.com/ariya/esprima) +* [WebKit](https://bugs.webkit.org/show_bug.cgi?id=125048) + +In addition, the following companies are using ESLint internally to validate their JavaScript: + +* [Box](https://box.com) +* [CustomInk](https://customink.com) +* [Fitbit](http://www.fitbit.com) +* [HolidayCheck](http://holidaycheck.de) +* [the native web](http://www.thenativeweb.io) + +### What about ECMAScript 6 support? + +We are implementing ECMAScript 6 support piece-by-piece starting with version 0.12.0. You'll be able to opt-in to any ECMAScript 6 feature you want to use. + +### Where to ask for help? + +Join our [Mailing List](https://groups.google.com/group/eslint) + + +[npm-image]: https://img.shields.io/npm/v/eslint.svg?style=flat-square +[npm-url]: https://npmjs.org/package/eslint +[travis-image]: https://img.shields.io/travis/eslint/eslint/master.svg?style=flat-square +[travis-url]: https://travis-ci.org/eslint/eslint +[coveralls-image]: https://img.shields.io/coveralls/eslint/eslint/master.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/eslint/eslint?branch=master +[downloads-image]: http://img.shields.io/npm/dm/eslint.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/eslint diff --git a/tools/eslint/bin/eslint.js b/tools/eslint/bin/eslint.js new file mode 100755 index 00000000000000..0188c2e600022f --- /dev/null +++ b/tools/eslint/bin/eslint.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node +var concat = require("concat-stream"), + cli = require("../lib/cli"); + +var exitCode = 0, + useStdIn = (process.argv.indexOf("--stdin") > -1); + +if (useStdIn) { + process.stdin.pipe(concat({ encoding: "string" }, function(text) { + try { + exitCode = cli.execute(process.argv, text); + } catch (ex) { + console.error(ex.message); + console.error(ex.stack); + exitCode = 1; + } + })); +} else { + exitCode = cli.execute(process.argv); +} + +/* + * Wait for the stdout buffer to drain. + * See https://github.com/eslint/eslint/issues/317 + */ +process.on("exit", function() { + process.exit(exitCode); +}); diff --git a/tools/eslint/conf/environments.js b/tools/eslint/conf/environments.js new file mode 100644 index 00000000000000..f59b852f946876 --- /dev/null +++ b/tools/eslint/conf/environments.js @@ -0,0 +1,78 @@ +/** + * @fileoverview Defines environment settings and globals. + * @author Elan Shanker + * @copyright 2014 Elan Shanker. All rights reserved. + */ +"use strict"; + +var globals = require("globals"); + +module.exports = { + builtin: globals.builtin, + browser: { + globals: globals.browser + }, + node: { + globals: globals.node, + ecmaFeatures: { + globalReturn: true + }, + rules: { + "no-catch-shadow": 0, + "no-console": 0, + "no-mixed-requires": 2, + "no-new-require": 2, + "no-path-concat": 2, + "no-process-exit": 2, + "global-strict": [0, "always"], + "handle-callback-err": [2, "err"] + } + }, + amd: { + globals: globals.amd + }, + mocha: { + globals: globals.mocha + }, + jasmine: { + globals: globals.jasmine + }, + phantomjs: { + globals: globals.phantom + }, + jquery: { + globals: globals.jquery + }, + prototypejs: { + globals: globals.prototypejs + }, + shelljs: { + globals: globals.shelljs + }, + meteor: { + globals: globals.meteor + }, + es6: { + ecmaFeatures: { + arrowFunctions: true, + blockBindings: true, + regexUFlag: true, + regexYFlag: true, + templateStrings: true, + binaryLiterals: true, + octalLiterals: true, + unicodeCodePointEscapes: true, + superInFunctions: true, + defaultParams: true, + restParams: true, + forOf: true, + objectLiteralComputedProperties: true, + objectLiteralShorthandMethods: true, + objectLiteralShorthandProperties: true, + objectLiteralDuplicateProperties: true, + generators: true, + destructuring: true, + classes: true + } + } +}; diff --git a/tools/eslint/conf/eslint.json b/tools/eslint/conf/eslint.json new file mode 100644 index 00000000000000..dc92cc143d236a --- /dev/null +++ b/tools/eslint/conf/eslint.json @@ -0,0 +1,172 @@ +{ + "ecmaFeatures": {}, + "parser": "espree", + "env": { + "browser": false, + "node": false, + "amd": false, + "mocha": false, + "jasmine": false + }, + + "rules": { + "no-alert": 2, + "no-array-constructor": 2, + "no-bitwise": 0, + "no-caller": 2, + "no-catch-shadow": 2, + "no-comma-dangle": 0, + "no-cond-assign": 2, + "no-console": 2, + "no-constant-condition": 2, + "no-continue": 0, + "no-control-regex": 2, + "no-debugger": 2, + "no-delete-var": 2, + "no-div-regex": 0, + "no-dupe-keys": 2, + "no-dupe-args": 2, + "no-duplicate-case": 2, + "no-else-return": 0, + "no-empty": 2, + "no-empty-class": 2, + "no-empty-label": 2, + "no-eq-null": 0, + "no-eval": 2, + "no-ex-assign": 2, + "no-extend-native": 2, + "no-extra-bind": 2, + "no-extra-boolean-cast": 2, + "no-extra-parens": 0, + "no-extra-semi": 2, + "no-extra-strict": 2, + "no-fallthrough": 2, + "no-floating-decimal": 0, + "no-func-assign": 2, + "no-implied-eval": 2, + "no-inline-comments": 0, + "no-inner-declarations": [2, "functions"], + "no-invalid-regexp": 2, + "no-irregular-whitespace": 2, + "no-iterator": 2, + "no-label-var": 2, + "no-labels": 2, + "no-lone-blocks": 2, + "no-lonely-if": 0, + "no-loop-func": 2, + "no-mixed-requires": [0, false], + "no-mixed-spaces-and-tabs": [2, false], + "no-multi-spaces": 2, + "no-multi-str": 2, + "no-multiple-empty-lines": [0, {"max": 2}], + "no-native-reassign": 2, + "no-negated-in-lhs": 2, + "no-nested-ternary": 0, + "no-new": 2, + "no-new-func": 2, + "no-new-object": 2, + "no-new-require": 0, + "no-new-wrappers": 2, + "no-obj-calls": 2, + "no-octal": 2, + "no-octal-escape": 2, + "no-param-reassign": 0, + "no-path-concat": 0, + "no-plusplus": 0, + "no-process-env": 0, + "no-process-exit": 2, + "no-proto": 2, + "no-redeclare": 2, + "no-regex-spaces": 2, + "no-reserved-keys": 0, + "no-restricted-modules": 0, + "no-return-assign": 2, + "no-script-url": 2, + "no-self-compare": 0, + "no-sequences": 2, + "no-shadow": 2, + "no-shadow-restricted-names": 2, + "no-space-before-semi": 0, + "no-spaced-func": 2, + "no-sparse-arrays": 2, + "no-sync": 0, + "no-ternary": 0, + "no-trailing-spaces": 2, + "no-throw-literal": 0, + "no-undef": 2, + "no-undef-init": 2, + "no-undefined": 0, + "no-underscore-dangle": 2, + "no-unreachable": 2, + "no-unused-expressions": 2, + "no-unused-vars": [2, {"vars": "all", "args": "after-used"}], + "no-use-before-define": 2, + "no-void": 0, + "no-var": 0, + "no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }], + "no-with": 2, + "no-wrap-func": 2, + + "block-scoped-var": 0, + "brace-style": [0, "1tbs"], + "camelcase": 2, + "comma-dangle": [2, "never"], + "comma-spacing": 2, + "comma-style": 0, + "complexity": [0, 11], + "consistent-return": 2, + "consistent-this": [0, "that"], + "curly": [2, "all"], + "default-case": 0, + "dot-notation": [2, { "allowKeywords": true }], + "eol-last": 2, + "eqeqeq": 2, + "func-names": 0, + "func-style": [0, "declaration"], + "generator-star": 0, + "generator-star-spacing": 0, + "global-strict": [2, "never"], + "guard-for-in": 0, + "handle-callback-err": 0, + "indent": 0, + "key-spacing": [2, { "beforeColon": false, "afterColon": true }], + "max-depth": [0, 4], + "max-len": [0, 80, 4], + "max-nested-callbacks": [0, 2], + "max-params": [0, 3], + "max-statements": [0, 10], + "new-cap": 2, + "new-parens": 2, + "newline-after-var": 0, + "object-shorthand": 0, + "one-var": 0, + "operator-assignment": [0, "always"], + "operator-linebreak": 0, + "padded-blocks": 0, + "quote-props": 0, + "quotes": [2, "double"], + "radix": 0, + "semi": 2, + "semi-spacing": [2, {"before": false, "after": true}], + "sort-vars": 0, + "space-after-function-name": [0, "never"], + "space-after-keywords": [0, "always"], + "space-before-blocks": [0, "always"], + "space-before-function-paren": [0, "always"], + "space-before-function-parentheses": [0, "always"], + "space-in-brackets": [0, "never"], + "space-in-parens": [0, "never"], + "space-infix-ops": 2, + "space-return-throw-case": 2, + "space-unary-ops": [2, { "words": true, "nonwords": false }], + "spaced-line-comment": [0, "always"], + "strict": 2, + "use-isnan": 2, + "valid-jsdoc": 0, + "valid-typeof": 2, + "vars-on-top": 0, + "wrap-iife": 0, + "wrap-regex": 0, + "yoda": [2, "never"] + } +} diff --git a/tools/eslint/lib/api.js b/tools/eslint/lib/api.js new file mode 100644 index 00000000000000..aafad533c2f258 --- /dev/null +++ b/tools/eslint/lib/api.js @@ -0,0 +1,12 @@ +/** + * @fileoverview Expose out ESLint and CLI to require. + * @author Ian Christian Myers + */ + +"use strict"; + +module.exports = { + linter: require("./eslint"), + cli: require("./cli"), + CLIEngine: require("./cli-engine") +}; diff --git a/tools/eslint/lib/cli-engine.js b/tools/eslint/lib/cli-engine.js new file mode 100644 index 00000000000000..29863fadd5d1e8 --- /dev/null +++ b/tools/eslint/lib/cli-engine.js @@ -0,0 +1,423 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + */ + +"use strict"; + +/* + * The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + path = require("path"), + + assign = require("object-assign"), + debug = require("debug"), + + rules = require("./rules"), + eslint = require("./eslint"), + traverse = require("./util/traverse"), + IgnoredPaths = require("./ignored-paths"), + Config = require("./config"), + util = require("./util"); + +//------------------------------------------------------------------------------ +// Typedefs +//------------------------------------------------------------------------------ + +/** + * The options to configure a CLI engine with. + * @typedef {Object} CLIEngineOptions + * @property {string} configFile The configuration file to use. + * @property {boolean} reset True disables all default rules and environments. + * @property {boolean|object} baseConfig Base config object. False disables all default rules and environments. + * @property {boolean} ignore False disables use of .eslintignore. + * @property {string[]} rulePaths An array of directories to load custom rules from. + * @property {boolean} useEslintrc False disables looking for .eslintrc + * @property {string[]} envs An array of environments to load. + * @property {string[]} globals An array of global variables to declare. + * @property {string[]} extensions An array of file extensions to check. + * @property {Object} rules An object of rules to use. + * @property {string} ignorePath The ignore file to use instead of .eslintignore. + */ + +/** + * A linting warning or error. + * @typedef {Object} LintMessage + * @property {string} message The message to display to the user. + */ + +/** + * A linting result. + * @typedef {Object} LintResult + * @property {string} filePath The path to the file that was linted. + * @property {LintMessage[]} messages All of the messages for the result. + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + + +var defaultOptions = { + configFile: null, + reset: false, + baseConfig: require(path.resolve(__dirname, "..", "conf", "eslint.json")), + rulePaths: [], + useEslintrc: true, + envs: [], + globals: [], + rules: {}, + extensions: [".js"], + ignore: true, + ignorePath: null + }, + loadedPlugins = Object.create(null); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +debug = debug("eslint:cli-engine"); + +/** + * Load the given plugins if they are not loaded already. + * @param {string[]} pluginNames An array of plugin names which should be loaded. + * @returns {void} + */ +function loadPlugins(pluginNames) { + if (pluginNames) { + pluginNames.forEach(function (pluginName) { + var pluginNamespace = util.getNamespace(pluginName), + pluginNameWithoutNamespace = util.removeNameSpace(pluginName), + pluginNameWithoutPrefix = util.removePluginPrefix(pluginNameWithoutNamespace), + plugin; + + if (!loadedPlugins[pluginNameWithoutPrefix]) { + debug("Load plugin " + pluginNameWithoutPrefix); + + plugin = require(pluginNamespace + util.PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix); + // if this plugin has rules, import them + if (plugin.rules) { + rules.import(plugin.rules, pluginNameWithoutPrefix); + } + + loadedPlugins[pluginNameWithoutPrefix] = plugin; + } + }); + } +} + +/** + * It will calculate the error and warning count for collection of messages per file + * @param {Object[]} messages - Collection of messages + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerFile(messages) { + return messages.reduce(function(stat, message) { + if (message.fatal || message.severity === 2) { + stat.errorCount++; + } else { + stat.warningCount++; + } + return stat; + }, { + errorCount: 0, + warningCount: 0 + }); +} + +/** + * It will calculate the error and warning count for collection of results from all files + * @param {Object[]} results - Collection of messages from all the files + * @returns {Object} Contains the stats + * @private + */ +function calculateStatsPerRun(results) { + return results.reduce(function(stat, result) { + stat.errorCount += result.errorCount; + stat.warningCount += result.warningCount; + return stat; + }, { + errorCount: 0, + warningCount: 0 + }); +} + +/** + * Processes an individual file using ESLint. Files used here are known to + * exist, so no need to check that here. + * @param {string} filename The filename of the file being checked. + * @param {Object} configHelper The configuration options for ESLint. + * @returns {Result} The results for linting on this file. + * @private + */ +function processFile(filename, configHelper) { + + // clear all existing settings for a new file + eslint.reset(); + + var filePath = path.resolve(filename), + config, + text, + messages, + stats, + fileExtension = path.extname(filename), + processor; + + debug("Linting " + filePath); + config = configHelper.getConfig(filePath); + loadPlugins(config.plugins); + text = fs.readFileSync(path.resolve(filename), "utf8"); + + for (var plugin in loadedPlugins) { + if (loadedPlugins[plugin].processors && Object.keys(loadedPlugins[plugin].processors).indexOf(fileExtension) >= 0) { + processor = loadedPlugins[plugin].processors[fileExtension]; + break; + } + } + + if (processor) { + var parsedBlocks = processor.preprocess(text, filename); + var unprocessedMessages = []; + parsedBlocks.forEach(function(block) { + unprocessedMessages.push(eslint.verify(block, config, filename)); + }); + messages = processor.postprocess(unprocessedMessages, filename); + } else { + messages = eslint.verify(text, config, filename); + } + + stats = calculateStatsPerFile(messages); + + return { + filePath: filename, + messages: messages, + errorCount: stats.errorCount, + warningCount: stats.warningCount + }; +} + +/** + * Processes an source code using ESLint. + * @param {string} text The source code to check. + * @param {Object} configHelper The configuration options for ESLint. + * @param {string} filename An optional string representing the texts filename. + * @returns {Result} The results for linting on this text. + * @private + */ +function processText(text, configHelper, filename) { + + // clear all existing settings for a new file + eslint.reset(); + + var config, + messages, + stats; + + filename = filename || ""; + debug("Linting " + filename); + config = configHelper.getConfig(); + loadPlugins(config.plugins); + messages = eslint.verify(text, config, filename); + + stats = calculateStatsPerFile(messages); + + return { + filePath: filename, + messages: messages, + errorCount: stats.errorCount, + warningCount: stats.warningCount + }; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Creates a new instance of the core CLI engine. + * @param {CLIEngineOptions} options The options for this instance. + * @constructor + */ +function CLIEngine(options) { + + /** + * Stored options for this instance + * @type {Object} + */ + this.options = assign(Object.create(defaultOptions), options || {}); + + // load in additional rules + if (this.options.rulePaths) { + this.options.rulePaths.forEach(function(rulesdir) { + debug("Loading rules from " + rulesdir); + rules.load(rulesdir); + }); + } + + loadPlugins(this.options.plugins); +} + +CLIEngine.prototype = { + + constructor: CLIEngine, + + /** + * Executes the current configuration on an array of file and directory names. + * @param {string[]} files An array of file and directory names. + * @returns {Object} The results for all files that were linted. + */ + executeOnFiles: function(files) { + + var results = [], + processed = [], + options = this.options, + configHelper = new Config(options), + ignoredPaths = IgnoredPaths.load(options), + exclude = ignoredPaths.contains.bind(ignoredPaths), + stats; + + traverse({ + files: files, + extensions: options.extensions, + exclude: options.ignore ? exclude : false + }, function(filename) { + + debug("Processing " + filename); + + processed.push(filename); + results.push(processFile(filename, configHelper)); + }); + + // only warn for files explicitly passed on the command line + if (options.ignore) { + files.forEach(function(file) { + if (fs.statSync(path.resolve(file)).isFile() && processed.indexOf(file) === -1) { + results.push({ + filePath: file, + messages: [ + { + fatal: false, + severity: 1, + message: "File ignored because of your .eslintignore file. Use --no-ignore to override." + } + ], + errorCount: 0, + warningCount: 1 + }); + } + }); + } + + stats = calculateStatsPerRun(results); + + return { + results: results, + errorCount: stats.errorCount, + warningCount: stats.warningCount + }; + }, + + /** + * Executes the current configuration on text. + * @param {string} text A string of JavaScript code to lint. + * @param {string} filename An optional string representing the texts filename. + * @returns {Object} The results for the linting. + */ + executeOnText: function(text, filename) { + + var configHelper = new Config(this.options), + results = [], + stats; + + results.push(processText(text, configHelper, filename)); + stats = calculateStatsPerRun(results); + + return { + results: results, + errorCount: stats.errorCount, + warningCount: stats.warningCount + }; + }, + + /** + * Returns a configuration object for the given file based on the CLI options. + * This is the same logic used by the ESLint CLI executable to determine + * configuration for each file it processes. + * @param {string} filePath The path of the file to retrieve a config object for. + * @returns {Object} A configuration object for the file. + */ + getConfigForFile: function(filePath) { + var configHelper = new Config(this.options); + return configHelper.getConfig(filePath); + }, + + /** + * Checks if a given path is ignored by ESLint. + * @param {string} filePath The path of the file to check. + * @returns {boolean} Whether or not the given path is ignored. + */ + isPathIgnored: function (filePath) { + var ignoredPaths; + + if (this.options.ignore) { + ignoredPaths = IgnoredPaths.load(this.options); + return ignoredPaths.contains(filePath); + } + + return false; + }, + + /** + * Returns the formatter representing the given format or null if no formatter + * with the given name can be found. + * @param {string} [format] The name of the format to load or the path to a + * custom formatter. + * @returns {Function} The formatter function or null if not found. + */ + getFormatter: function(format) { + + var formatterPath; + + // default is stylish + format = format || "stylish"; + + // only strings are valid formatters + if (typeof format === "string") { + + // replace \ with / for Windows compatibility + format = format.replace(/\\/g, "/"); + + // if there's a slash, then it's a file + if (format.indexOf("/") > -1) { + formatterPath = path.resolve(process.cwd(), format); + } else { + formatterPath = "./formatters/" + format; + } + + try { + return require(formatterPath); + } catch (ex) { + return null; + } + + } else { + return null; + } + + + } + +}; + +module.exports = CLIEngine; diff --git a/tools/eslint/lib/cli.js b/tools/eslint/lib/cli.js new file mode 100644 index 00000000000000..72afc98167cc5c --- /dev/null +++ b/tools/eslint/lib/cli.js @@ -0,0 +1,195 @@ +/** + * @fileoverview Main CLI object. + * @author Nicholas C. Zakas + */ + +"use strict"; + +/* + * The CLI object should *not* call process.exit() directly. It should only return + * exit codes. This allows other programs to use the CLI object and still control + * when the program exits. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + path = require("path"), + + debug = require("debug"), + + options = require("./options"), + CLIEngine = require("./cli-engine"), + mkdirp = require("mkdirp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +debug = debug("eslint:cli"); + +/** + * Translates the CLI options into the options expected by the CLIEngine. + * @param {Object} cliOptions The CLI options to translate. + * @returns {CLIEngineOptions} The options object for the CLIEngine. + * @private + */ +function translateOptions(cliOptions) { + return { + envs: cliOptions.env, + extensions: cliOptions.ext, + rules: cliOptions.rule, + plugins: cliOptions.plugin, + globals: cliOptions.global, + ignore: cliOptions.ignore, + ignorePath: cliOptions.ignorePath, + configFile: cliOptions.config, + rulePaths: cliOptions.rulesdir, + reset: cliOptions.reset, + useEslintrc: cliOptions.eslintrc + }; +} + +/** + * Outputs the results of the linting. + * @param {CLIEngine} engine The CLIEngine to use. + * @param {LintResult[]} results The results to print. + * @param {string} format The name of the formatter to use or the path to the formatter. + * @param {string} outputFile The path for the output file. + * @returns {boolean} True if the printing succeeds, false if not. + * @private + */ +function printResults(engine, results, format, outputFile) { + var formatter, + output, + filePath; + + formatter = engine.getFormatter(format); + if (!formatter) { + console.error("Could not find formatter '%s'.", format); + return false; + } + + output = formatter(results); + + if (output) { + if (outputFile) { + filePath = path.resolve(process.cwd(), outputFile); + + if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) { + console.error("Cannot write to output file path, it is a directory: %s", outputFile); + return false; + } + + try { + mkdirp.sync(path.dirname(filePath)); + fs.writeFileSync(filePath, output); + } catch (ex) { + console.error("There was a problem writing the output file:\n%s", ex); + return false; + } + } else { + console.log(output); + } + } + + return true; + +} + +/** + * Checks if the given message is an error message. + * @param {object} message The message to check. + * @returns {boolean} Whether or not the message is an error message. + */ +function isErrorMessage(message) { + return message.severity === 2; +} + +/** + * Returns results that only contains errors. + * @param {LintResult[]} results The results to filter. + * @returns {LintResult[]} The filtered results. + */ +function getErrorResults(results) { + var filtered = []; + + results.forEach(function (result) { + var filteredMessages = result.messages.filter(isErrorMessage); + + if (filteredMessages.length > 0) { + filtered.push({ + filePath: result.filePath, + messages: filteredMessages + }); + } + }); + + return filtered; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as + * for other Node.js programs to effectively run the CLI. + */ +var cli = { + + /** + * Executes the CLI based on an array of arguments that is passed in. + * @param {string|Array|Object} args The arguments to process. + * @param {string} [text] The text to lint (used for TTY). + * @returns {int} The exit code for the operation. + */ + execute: function(args, text) { + + var currentOptions, + files, + result, + engine; + + try { + currentOptions = options.parse(args); + } catch (error) { + console.error(error.message); + return 1; + } + + files = currentOptions._; + + if (currentOptions.version) { // version from package.json + + console.log("v" + require("../package.json").version); + + } else if (currentOptions.help || (!files.length && !text)) { + + console.log(options.generateHelp()); + + } else { + + engine = new CLIEngine(translateOptions(currentOptions)); + debug("Running on " + (text ? "text" : "files")); + + result = text ? engine.executeOnText(text, currentOptions.stdinFilename) : engine.executeOnFiles(files); + if (currentOptions.quiet) { + result.results = getErrorResults(result.results); + } + + if (printResults(engine, result.results, currentOptions.format, currentOptions.outputFile)) { + return result.errorCount ? 1 : 0; + } else { + return 1; + } + + } + + return 0; + } +}; + +module.exports = cli; diff --git a/tools/eslint/lib/config.js b/tools/eslint/lib/config.js new file mode 100644 index 00000000000000..3955a048f684ed --- /dev/null +++ b/tools/eslint/lib/config.js @@ -0,0 +1,360 @@ +/** + * @fileoverview Responsible for loading config files + * @author Seth McLaughlin + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2013 Seth McLaughlin. All rights reserved. + * @copyright 2014 Michael McLaughlin. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + path = require("path"), + environments = require("../conf/environments"), + util = require("./util"), + FileFinder = require("./file-finder"), + stripComments = require("strip-json-comments"), + assign = require("object-assign"), + debug = require("debug"), + yaml = require("js-yaml"), + userHome = require("user-home"); + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var LOCAL_CONFIG_FILENAME = ".eslintrc", + PACKAGE_CONFIG_FILENAME = "package.json", + PACKAGE_CONFIG_FIELD_NAME = "eslintConfig", + PERSONAL_CONFIG_PATH = userHome ? path.join(userHome, LOCAL_CONFIG_FILENAME) : null; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +var loadedPlugins = Object.create(null); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +debug = debug("eslint:config"); + +/** + * Load and parse a JSON config object from a file. + * @param {string} filePath the path to the JSON config file + * @returns {Object} the parsed config object (empty object if there was a parse error) + */ +function loadConfig(filePath) { + var config = {}; + + if (filePath) { + try { + config = yaml.safeLoad(stripComments(fs.readFileSync(filePath, "utf8"))) || {}; + } catch (e) { + debug("Error reading YAML file: " + filePath); + e.message = "Cannot read config file: " + filePath + "\nError: " + e.message; + throw e; + } + } + + return config; +} + +/** + * Load configuration for all plugins provided. + * @param {string[]} pluginNames An array of plugin names which should be loaded. + * @returns {Object} all plugin configurations merged together + */ +function getPluginsConfig(pluginNames) { + var pluginConfig = {}; + + if (pluginNames) { + pluginNames.forEach(function (pluginName) { + var pluginNamespace = util.getNamespace(pluginName), + pluginNameWithoutNamespace = util.removeNameSpace(pluginName), + pluginNameWithoutPrefix = util.removePluginPrefix(pluginNameWithoutNamespace), + plugin = {}, + rules = {}; + + if (!loadedPlugins[pluginNameWithoutPrefix]) { + try { + plugin = require(pluginNamespace + util.PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix); + loadedPlugins[pluginNameWithoutPrefix] = plugin; + } catch(err) { + debug("Failed to load plugin configuration for " + pluginNameWithoutPrefix + ". Proceeding without it."); + plugin = { rulesConfig: {}}; + } + } else { + plugin = loadedPlugins[pluginNameWithoutPrefix]; + } + + if (!plugin.rulesConfig) { + plugin.rulesConfig = {}; + } + + Object.keys(plugin.rulesConfig).forEach(function(item) { + rules[pluginNameWithoutPrefix + "/" + item] = plugin.rulesConfig[item]; + }); + + pluginConfig = util.mergeConfigs(pluginConfig, rules); + }); + } + + return {rules: pluginConfig}; +} + +/** + * Get personal config object from ~/.eslintrc. + * @returns {Object} the personal config object (empty object if there is no personal config) + * @private + */ +function getPersonalConfig() { + var config = {}; + + if (PERSONAL_CONFIG_PATH && fs.existsSync(PERSONAL_CONFIG_PATH)) { + debug("Using personal config"); + config = loadConfig(PERSONAL_CONFIG_PATH); + } + + return config; +} + +/** + * Get a local config object. + * @param {Object} thisConfig A Config object. + * @param {string} directory The directory to start looking in for a local config file. + * @returns {Object} The local config object, or an empty object if there is no local config. + */ +function getLocalConfig(thisConfig, directory) { + var found, + i, + localConfig, + localConfigFile, + config = {}, + localConfigFiles = thisConfig.findLocalConfigFiles(directory), + numFiles = localConfigFiles.length; + + for (i = 0; i < numFiles; i++) { + + localConfigFile = localConfigFiles[i]; + + // Don't consider the personal config file in the home directory. + if (localConfigFile === PERSONAL_CONFIG_PATH) { + continue; + } + + localConfig = loadConfig(localConfigFile); + + if (path.basename(localConfigFile) !== LOCAL_CONFIG_FILENAME) { + + // Don't consider a local config file found if the package.json doesn't have the eslintConfig field. + if (!localConfig.hasOwnProperty(PACKAGE_CONFIG_FIELD_NAME)) { + continue; + } + localConfig = localConfig[PACKAGE_CONFIG_FIELD_NAME] || {}; + } + + found = true; + debug("Using " + localConfigFile); + config = util.mergeConfigs(localConfig, config); + } + + // Use the personal config file if there are no other local config files found. + return found ? config : util.mergeConfigs(config, getPersonalConfig()); +} + +/** + * Creates an environment config based on the specified environments. + * @param {Object} envs The environment settings. + * @param {boolean} reset The value of the command line reset option. If true, + * rules are not automatically merged into the config. + * @returns {Object} A configuration object with the appropriate rules and globals + * set. + * @private + */ +function createEnvironmentConfig(envs, reset) { + + var envConfig = { + globals: {}, + env: envs || {}, + rules: {}, + ecmaFeatures: {} + }; + + if (envs) { + Object.keys(envs).filter(function (name) { + return envs[name]; + }).forEach(function(name) { + var environment = environments[name]; + + if (environment) { + + if (!reset && environment.rules) { + assign(envConfig.rules, environment.rules); + } + + if (environment.globals) { + assign(envConfig.globals, environment.globals); + } + + if (environment.ecmaFeatures) { + assign(envConfig.ecmaFeatures, environment.ecmaFeatures); + } + } + }); + } + + return envConfig; +} + +//------------------------------------------------------------------------------ +// API +//------------------------------------------------------------------------------ + +/** + * Config + * @constructor + * @class Config + * @param {Object} options Options to be passed in + * @param {string} [cwd] current working directory. Defaults to process.cwd() + */ +function Config(options) { + var useConfig; + + options = options || {}; + + this.ignore = options.ignore; + this.ignorePath = options.ignorePath; + this.cache = {}; + + if (options.reset || options.baseConfig === false) { + // If `options.reset` is truthy or `options.baseConfig` is set to `false`, + // disable all default rules and environments + this.baseConfig = { rules: {} }; + } else { + // If `options.baseConfig` is an object, just use it, + // otherwise use default base config from `conf/eslint.json` + this.baseConfig = options.baseConfig || + require(path.resolve(__dirname, "..", "conf", "eslint.json")); + } + + this.baseConfig.format = options.format; + this.useEslintrc = (options.useEslintrc !== false); + + this.env = (options.envs || []).reduce(function (envs, name) { + envs[name] = true; + return envs; + }, {}); + + this.globals = (options.globals || []).reduce(function (globals, def) { + // Default "foo" to false and handle "foo:false" and "foo:true" + var parts = def.split(":"); + globals[parts[0]] = (parts.length > 1 && parts[1] === "true"); + return globals; + }, {}); + + useConfig = options.configFile; + this.options = options; + + if (useConfig) { + debug("Using command line config " + useConfig); + this.useSpecificConfig = loadConfig(path.resolve(process.cwd(), useConfig)); + } +} + +/** + * Build a config object merging the base config (conf/eslint.json), the + * environments config (conf/environments.js) and eventually the user config. + * @param {string} filePath a file in whose directory we start looking for a local config + * @returns {Object} config object + */ +Config.prototype.getConfig = function (filePath) { + var config, + userConfig, + directory = filePath ? path.dirname(filePath) : process.cwd(), + pluginConfig; + + debug("Constructing config for " + (filePath ? filePath : "text")); + + config = this.cache[directory]; + + if (config) { + debug("Using config from cache"); + return config; + } + + // Step 1: Determine user-specified config from .eslintrc and package.json files + if (this.useEslintrc) { + debug("Using .eslintrc and package.json files"); + userConfig = getLocalConfig(this, directory); + } else { + debug("Not using .eslintrc or package.json files"); + userConfig = {}; + } + + // Step 2: Create a copy of the baseConfig + config = util.mergeConfigs({}, this.baseConfig); + + // Step 3: Merge in environment-specific globals and rules from .eslintrc files + config = util.mergeConfigs(config, createEnvironmentConfig(userConfig.env, this.options.reset)); + + // Step 4: Merge in the user-specified configuration from .eslintrc and package.json + config = util.mergeConfigs(config, userConfig); + + // Step 5: Merge in command line config file + if (this.useSpecificConfig) { + debug("Merging command line config file"); + + if (this.useSpecificConfig.env) { + config = util.mergeConfigs(config, createEnvironmentConfig(this.useSpecificConfig.env, this.options.reset)); + } + + config = util.mergeConfigs(config, this.useSpecificConfig); + } + + // Step 6: Merge in command line environments + if (this.env) { + debug("Merging command line environment settings"); + config = util.mergeConfigs(config, createEnvironmentConfig(this.env, this.options.reset)); + } + + // Step 7: Merge in command line rules + if (this.options.rules) { + debug("Merging command line rules"); + config = util.mergeConfigs(config, { rules: this.options.rules }); + } + + // Step 8: Merge in command line globals + config = util.mergeConfigs(config, { globals: this.globals }); + + + // Step 9: Merge in plugin specific rules in reverse + if (config.plugins) { + pluginConfig = getPluginsConfig(config.plugins); + config = util.mergeConfigs(pluginConfig, config); + } + + this.cache[directory] = config; + + return config; +}; + +/** + * Find local config files from directory and parent directories. + * @param {string} directory The directory to start searching from. + * @returns {string[]} The paths of local config files found. + */ +Config.prototype.findLocalConfigFiles = function (directory) { + + if (!this.localConfigFinder) { + this.localConfigFinder = new FileFinder(LOCAL_CONFIG_FILENAME, PACKAGE_CONFIG_FILENAME); + } + + return this.localConfigFinder.findAllInDirectoryAndParents(directory); +}; + +module.exports = Config; diff --git a/tools/eslint/lib/eslint.js b/tools/eslint/lib/eslint.js new file mode 100644 index 00000000000000..0a3e39192b1e1a --- /dev/null +++ b/tools/eslint/lib/eslint.js @@ -0,0 +1,1059 @@ +/** + * @fileoverview Main ESLint object. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var estraverse = require("estraverse-fb"), + escope = require("escope"), + environments = require("../conf/environments"), + assign = require("object-assign"), + rules = require("./rules"), + util = require("./util"), + RuleContext = require("./rule-context"), + timing = require("./timing"), + createTokenStore = require("./token-store.js"), + EventEmitter = require("events").EventEmitter, + escapeRegExp = require("escape-string-regexp"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// TODO: Remove when estraverse is updated +estraverse.Syntax.Super = "Super"; +estraverse.VisitorKeys.Super = []; + +/** + * Parses a list of "name:boolean_value" or/and "name" options divided by comma or + * whitespace. + * @param {string} string The string to parse. + * @returns {Object} Result map object of names and boolean values + */ +function parseBooleanConfig(string) { + var items = {}; + // Collapse whitespace around : to make parsing easier + string = string.replace(/\s*:\s*/g, ":"); + // Collapse whitespace around , + string = string.replace(/\s*,\s*/g, ","); + string.split(/\s|,+/).forEach(function(name) { + if (!name) { + return; + } + var pos = name.indexOf(":"), + value; + if (pos !== -1) { + value = name.substring(pos + 1, name.length); + name = name.substring(0, pos); + } + + items[name] = (value === "true"); + + }); + return items; +} + +/** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @param {Object} location Start line and column of comments for potential error message. + * @param {Object[]} messages The messages queue for potential error message. + * @returns {Object} Result map object + */ +function parseJsonConfig(string, location, messages) { + var items = {}; + string = string.replace(/([a-zA-Z0-9\-\/]+):/g, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/, "$1,"); + try { + items = JSON.parse("{" + string + "}"); + } catch(ex) { + + messages.push({ + fatal: true, + severity: 2, + message: "Failed to parse JSON from '" + string + "': " + ex.message, + line: location.start.line, + column: location.start.column + }); + + } + + return items; +} + +/** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {Object} Result map of values and true values + */ +function parseListConfig(string) { + var items = {}; + // Collapse whitespace around , + string = string.replace(/\s*,\s*/g, ","); + string.split(/,+/).forEach(function(name) { + name = name.trim(); + if (!name) { + return; + } + items[name] = true; + }); + return items; +} + +/** + * @param {Scope} scope The scope object to check. + * @param {string} name The name of the variable to look up. + * @returns {Variable} The variable object if found or null if not. + */ +function getVariable(scope, name) { + var variable = null; + scope.variables.some(function(v) { + if (v.name === name) { + variable = v; + return true; + } else { + return false; + } + + }); + return variable; +} + +/** + * Ensures that variables representing built-in properties of the Global Object, + * and any globals declared by special block comments, are present in the global + * scope. + * @param {ASTNode} program The top node of the AST. + * @param {Scope} globalScope The global scope. + * @param {Object} config The existing configuration data. + * @returns {void} + */ +function addDeclaredGlobals(program, globalScope, config) { + var declaredGlobals = {}, + explicitGlobals = {}, + builtin = environments.builtin; + + assign(declaredGlobals, builtin); + + Object.keys(config.env).forEach(function (name) { + if (config.env[name]) { + var environmentGlobals = environments[name] && environments[name].globals; + if (environmentGlobals) { + assign(declaredGlobals, environmentGlobals); + } + } + }); + + assign(declaredGlobals, config.globals); + assign(explicitGlobals, config.astGlobals); + + Object.keys(declaredGlobals).forEach(function(name) { + var variable = getVariable(globalScope, name); + if (!variable) { + variable = new escope.Variable(name, globalScope); + variable.eslintExplicitGlobal = false; + globalScope.variables.push(variable); + } + variable.writeable = declaredGlobals[name]; + }); + + Object.keys(explicitGlobals).forEach(function(name) { + var variable = getVariable(globalScope, name); + if (!variable) { + variable = new escope.Variable(name, globalScope); + variable.eslintExplicitGlobal = true; + globalScope.variables.push(variable); + } + variable.writeable = explicitGlobals[name]; + }); +} + +/** + * Add data to reporting configuration to disable reporting for list of rules + * starting from start location + * @param {Object[]} reportingConfig Current reporting configuration + * @param {Object} start Position to start + * @param {string[]} rulesToDisable List of rules + * @returns {void} + */ +function disableReporting(reportingConfig, start, rulesToDisable) { + + if (rulesToDisable.length) { + rulesToDisable.forEach(function(rule) { + reportingConfig.push({ + start: start, + end: null, + rule: rule + }); + }); + } else { + reportingConfig.push({ + start: start, + end: null, + rule: null + }); + } +} + +/** + * Add data to reporting configuration to enable reporting for list of rules + * starting from start location + * @param {Object[]} reportingConfig Current reporting configuration + * @param {Object} start Position to start + * @param {string[]} rulesToEnable List of rules + * @returns {void} + */ +function enableReporting(reportingConfig, start, rulesToEnable) { + var i; + + if (rulesToEnable.length) { + rulesToEnable.forEach(function(rule) { + for (i = reportingConfig.length - 1; i >= 0; i--) { + if (!reportingConfig[i].end && reportingConfig[i].rule === rule ) { + reportingConfig[i].end = start; + break; + } + } + }); + } else { + // find all previous disabled locations if they was started as list of rules + var prevStart; + for (i = reportingConfig.length - 1; i >= 0; i--) { + if (prevStart && prevStart !== reportingConfig[i].start) { + break; + } + + if (!reportingConfig[i].end) { + reportingConfig[i].end = start; + prevStart = reportingConfig[i].start; + } + } + } +} + +/** + * Parses comments in file to extract file-specific config of rules, globals + * and environments and merges them with global config; also code blocks + * where reporting is disabled or enabled and merges them with reporting config. + * @param {ASTNode} ast The top node of the AST. + * @param {Object} config The existing configuration data. + * @param {Object[]} reportingConfig The existing reporting configuration data. + * @param {Object[]} messages The messages queue. + * @returns {void} + */ +function modifyConfigsFromComments(ast, config, reportingConfig, messages) { + + var commentConfig = { + astGlobals: {}, + rules: {}, + env: {} + }; + var commentRules = {}; + + ast.comments.forEach(function(comment) { + + var value = comment.value.trim(); + var match = /^(eslint-\w+|eslint-\w+-\w+|eslint|globals?)(\s|$)/.exec(value); + + if (match) { + value = value.substring(match.index + match[1].length); + + if (comment.type === "Block") { + switch (match[1]) { + case "globals": + case "global": + assign(commentConfig.astGlobals, parseBooleanConfig(value)); + break; + + case "eslint-env": + assign(commentConfig.env, parseListConfig(value)); + break; + + case "eslint-disable": + disableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value))); + break; + + case "eslint-enable": + enableReporting(reportingConfig, comment.loc.start, Object.keys(parseListConfig(value))); + break; + + case "eslint": + var items = parseJsonConfig(value, comment.loc, messages); + Object.keys(items).forEach(function(name) { + var ruleValue = items[name]; + if (typeof ruleValue === "number" || (Array.isArray(ruleValue) && typeof ruleValue[0] === "number")) { + commentRules[name] = ruleValue; + } + }); + break; + + // no default + } + } else { + // comment.type === "Line" + if (match[1] === "eslint-disable-line") { + disableReporting(reportingConfig, { "line": comment.loc.start.line, "column": 0 }, Object.keys(parseListConfig(value))); + enableReporting(reportingConfig, comment.loc.end, Object.keys(parseListConfig(value))); + } + } + } + }); + + // apply environment rules before user rules + Object.keys(commentConfig.env).forEach(function (name) { + var environmentRules = environments[name] && environments[name].rules; + if (commentConfig.env[name] && environmentRules) { + assign(commentConfig.rules, environmentRules); + } + }); + assign(commentConfig.rules, commentRules); + + util.mergeConfigs(config, commentConfig); +} + +/** + * Check if message of rule with ruleId should be ignored in location + * @param {Object[]} reportingConfig Collection of ignore records + * @param {string} ruleId Id of rule + * @param {Object} location Location of message + * @returns {boolean} True if message should be ignored, false otherwise + */ +function isDisabledByReportingConfig(reportingConfig, ruleId, location) { + + for (var i = 0, c = reportingConfig.length; i < c; i++) { + + var ignore = reportingConfig[i]; + if ((!ignore.rule || ignore.rule === ruleId) && + (location.line > ignore.start.line || (location.line === ignore.start.line && location.column >= ignore.start.column)) && + (!ignore.end || (location.line < ignore.end.line || (location.line === ignore.end.line && location.column <= ignore.end.column)))) { + return true; + } + } + + return false; +} + +/** + * Process initial config to make it safe to extend by file comment config + * @param {Object} config Initial config + * @returns {Object} Processed config + */ +function prepareConfig(config) { + + config.globals = config.globals || config.global || {}; + delete config.global; + + var copiedRules = {}, + ecmaFeatures = {}, + preparedConfig; + + if (typeof config.rules === "object") { + Object.keys(config.rules).forEach(function(k) { + var rule = config.rules[k]; + if (rule === null) { + throw new Error("Invalid config for rule '" + k + "'\."); + } + if (Array.isArray(rule)) { + copiedRules[k] = rule.slice(); + } else { + copiedRules[k] = rule; + } + }); + } + + // merge in environment ecmaFeatures + if (typeof config.env === "object") { + Object.keys(config.env).forEach(function(env) { + if (config.env[env] && environments[env].ecmaFeatures) { + assign(ecmaFeatures, environments[env].ecmaFeatures); + } + }); + } + + preparedConfig = { + rules: copiedRules, + parser: config.parser || "espree", + globals: util.mergeConfigs({}, config.globals), + env: util.mergeConfigs({}, config.env || {}), + settings: util.mergeConfigs({}, config.settings || {}), + ecmaFeatures: util.mergeConfigs(ecmaFeatures, config.ecmaFeatures || {}) + }; + + // can't have global return inside of modules + if (preparedConfig.ecmaFeatures.modules) { + preparedConfig.ecmaFeatures.globalReturn = false; + } + + return preparedConfig; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object that is responsible for verifying JavaScript text + * @name eslint + */ +module.exports = (function() { + + var api = Object.create(new EventEmitter()), + messages = [], + currentText = null, + currentTextLines = [], + currentConfig = null, + currentTokens = null, + currentScopes = null, + scopeMap = null, + scopeManager = null, + currentFilename = null, + controller = null, + reportingConfig = [], + commentLocsEnter = [], + commentLocsExit = [], + currentAST = null; + + /** + * Parses text into an AST. Moved out here because the try-catch prevents + * optimization of functions, so it's best to keep the try-catch as isolated + * as possible + * @param {string} text The text to parse. + * @param {Object} config The ESLint configuration object. + * @returns {ASTNode} The AST if successful or null if not. + * @private + */ + function parse(text, config) { + + var parser; + + try { + parser = require(config.parser); + } catch (ex) { + messages.push({ + fatal: true, + severity: 2, + message: ex.message, + line: 0, + column: 0 + }); + + return null; + } + + /* + * Check for parsing errors first. If there's a parsing error, nothing + * else can happen. However, a parsing error does not throw an error + * from this method - it's just considered a fatal error message, a + * problem that ESLint identified just like any other. + */ + try { + return parser.parse(text, { + loc: true, + range: true, + raw: true, + tokens: true, + comment: true, + attachComment: true, + ecmaFeatures: config.ecmaFeatures + }); + } catch (ex) { + + messages.push({ + fatal: true, + severity: 2, + + // messages come as "Line X: Unexpected token foo", so strip off leading part + message: ex.message.substring(ex.message.indexOf(":") + 1).trim(), + + line: ex.lineNumber, + column: ex.column + }); + + return null; + } + } + + /** + * Check collection of comments to prevent double event for comment as + * leading and trailing, then emit event if passing + * @param {ASTNode[]} comments Collection of comment nodes + * @param {Object[]} locs List of locations of previous comment nodes + * @param {string} eventName Event name postfix + * @returns {void} + */ + function emitComments(comments, locs, eventName) { + + if (comments.length) { + comments.forEach(function(node) { + if (locs.indexOf(node.loc) >= 0) { + locs.splice(locs.indexOf(node.loc), 1); + } else { + locs.push(node.loc); + api.emit(node.type + eventName, node); + } + }); + } + } + + /** + * Shortcut to check and emit enter of comment nodes + * @param {ASTNode[]} comments Collection of comment nodes + * @returns {void} + */ + function emitCommentsEnter(comments) { + emitComments(comments, commentLocsEnter, "Comment"); + } + + /** + * Shortcut to check and emit exit of comment nodes + * @param {ASTNode[]} comments Collection of comment nodes + * @returns {void} + */ + function emitCommentsExit(comments) { + emitComments(comments, commentLocsExit, "Comment:exit"); + } + + /** + * Get the severity level of a rule (0 - none, 1 - warning, 2 - error) + * Returns 0 if the rule config is not valid (an Array or a number) + * @param {Array|number} ruleConfig rule configuration + * @returns {number} 0, 1, or 2, indicating rule severity + */ + function getRuleSeverity(ruleConfig) { + if (typeof ruleConfig === "number") { + return ruleConfig; + } else if (Array.isArray(ruleConfig)) { + return ruleConfig[0]; + } else { + return 0; + } + } + + /** + * Get the options for a rule (not including severity), if any + * @param {Array|number} ruleConfig rule configuration + * @returns {Array} of rule options, empty Array if none + */ + function getRuleOptions(ruleConfig) { + if (Array.isArray(ruleConfig)) { + return ruleConfig.slice(1); + } else { + return []; + } + } + + // set unlimited listeners (see https://github.com/eslint/eslint/issues/524) + api.setMaxListeners(0); + + /** + * Resets the internal state of the object. + * @returns {void} + */ + api.reset = function() { + this.removeAllListeners(); + messages = []; + currentAST = null; + currentConfig = null; + currentText = null; + currentTextLines = []; + currentTokens = null; + currentScopes = null; + scopeMap = null; + scopeManager = null; + controller = null; + reportingConfig = []; + commentLocsEnter = []; + commentLocsExit = []; + }; + + /** + * Verifies the text against the rules specified by the second argument. + * @param {string} text The JavaScript text to verify. + * @param {Object} config An object whose keys specify the rules to use. + * @param {string=} filename The optional filename of the file being checked. + * If this is not set, the filename will default to '' in the rule context. + * @param {boolean=} saveState Indicates if the state from the last run should be saved. + * Mostly useful for testing purposes. + * @returns {Object[]} The results as an array of messages or null if no messages. + */ + api.verify = function(text, config, filename, saveState) { + + var ast, + shebang, + ecmaFeatures, + ecmaVersion; + + // set the current parsed filename + currentFilename = filename; + + if (!saveState) { + this.reset(); + } + + // there's no input, just exit here + if (text.trim().length === 0) { + currentText = text; + return messages; + } + + // process initial config to make it safe to extend + config = prepareConfig(config || {}); + + ast = parse(text.replace(/^#!([^\r\n]+)/, function(match, captured) { + shebang = captured; + return "//" + captured; + }), config); + + // if espree failed to parse the file, there's no sense in setting up rules + if (ast) { + + currentAST = ast; + + // parse global comments and modify config + modifyConfigsFromComments(ast, config, reportingConfig, messages); + + // enable appropriate rules + Object.keys(config.rules).filter(function(key) { + return getRuleSeverity(config.rules[key]) > 0; + }).forEach(function(key) { + + var ruleCreator = rules.get(key), + severity = getRuleSeverity(config.rules[key]), + options = getRuleOptions(config.rules[key]), + rule; + + if (ruleCreator) { + try { + rule = ruleCreator(new RuleContext( + key, api, severity, options, + config.settings, config.ecmaFeatures + )); + + // add all the node types as listeners + Object.keys(rule).forEach(function(nodeType) { + api.on(nodeType, timing.enabled + ? timing.time(key, rule[nodeType]) + : rule[nodeType] + ); + }); + } catch(ex) { + ex.message = "Error while loading rule '" + key + "': " + ex.message; + throw ex; + } + + } else { + throw new Error("Definition for rule '" + key + "' was not found."); + } + }); + + // save config so rules can access as necessary + currentConfig = config; + currentText = text; + controller = new estraverse.Controller(); + + ecmaFeatures = currentConfig.ecmaFeatures; + ecmaVersion = (ecmaFeatures.blockBindings || ecmaFeatures.classes || + ecmaFeatures.modules || ecmaFeatures.defaultParams || + ecmaFeatures.destructuring) ? 6 : 5; + + + // gather data that may be needed by the rules + scopeManager = escope.analyze(ast, { + ignoreEval: true, + nodejsScope: ecmaFeatures.globalReturn, + ecmaVersion: ecmaVersion, + sourceType: ecmaFeatures.modules ? "module" : "script" + }); + currentScopes = scopeManager.scopes; + + /* + * Index the scopes by the start range of their block for efficient + * lookup in getScope. + */ + scopeMap = []; + currentScopes.forEach(function (scope, index) { + var range = scope.block.range[0]; + + // Sometimes two scopes are returned for a given node. This is + // handled later in a known way, so just don't overwrite here. + if (!scopeMap[range]) { + scopeMap[range] = index; + } + }); + + /* + * Split text here into array of lines so + * it's not being done repeatedly + * by individual rules. + */ + currentTextLines = currentText.split(/\r\n|\r|\n|\u2028|\u2029/g); + + // Freezing so array isn't accidentally changed by a rule. + Object.freeze(currentTextLines); + + currentTokens = createTokenStore(ast.tokens); + Object.keys(currentTokens).forEach(function(method) { + api[method] = currentTokens[method]; + }); + + // augment global scope with declared global variables + addDeclaredGlobals(ast, currentScopes[0], currentConfig); + + // remove shebang comments + if (shebang && ast.comments.length && ast.comments[0].value === shebang) { + ast.comments.splice(0, 1); + + if (ast.body.length && ast.body[0].leadingComments && ast.body[0].leadingComments[0].value === shebang) { + ast.body[0].leadingComments.splice(0, 1); + } + } + + /* + * Each node has a type property. Whenever a particular type of node is found, + * an event is fired. This allows any listeners to automatically be informed + * that this type of node has been found and react accordingly. + */ + controller.traverse(ast, { + enter: function(node, parent) { + + var comments = api.getComments(node); + + emitCommentsEnter(comments.leading); + node.parent = parent; + api.emit(node.type, node); + emitCommentsEnter(comments.trailing); + }, + leave: function(node) { + + var comments = api.getComments(node); + + emitCommentsExit(comments.trailing); + api.emit(node.type + ":exit", node); + emitCommentsExit(comments.leading); + } + }); + + } + + // sort by line and column + messages.sort(function(a, b) { + var lineDiff = a.line - b.line; + + if (lineDiff === 0) { + return a.column - b.column; + } else { + return lineDiff; + } + }); + + return messages; + }; + + /** + * Reports a message from one of the rules. + * @param {string} ruleId The ID of the rule causing the message. + * @param {number} severity The severity level of the rule as configured. + * @param {ASTNode} node The AST node that the message relates to. + * @param {Object=} location An object containing the error line and column + * numbers. If location is not provided the node's start location will + * be used. + * @param {string} message The actual message. + * @param {Object} opts Optional template data which produces a formatted message + * with symbols being replaced by this object's values. + * @returns {void} + */ + api.report = function(ruleId, severity, node, location, message, opts) { + + if (typeof location === "string") { + opts = message; + message = location; + location = node.loc.start; + } + + Object.keys(opts || {}).forEach(function (key) { + var rx = new RegExp("{{" + escapeRegExp(key) + "}}", "g"); + message = message.replace(rx, opts[key]); + }); + + if (isDisabledByReportingConfig(reportingConfig, ruleId, location)) { + return; + } + + messages.push({ + ruleId: ruleId, + severity: severity, + message: message, + line: location.line, + column: location.column, + nodeType: node.type, + source: currentTextLines[location.line - 1] || "" + }); + }; + + /** + * Gets the source code for the given node. + * @param {ASTNode=} node The AST node to get the text for. + * @param {int=} beforeCount The number of characters before the node to retrieve. + * @param {int=} afterCount The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + */ + api.getSource = function(node, beforeCount, afterCount) { + if (node) { + return (currentText !== null) ? currentText.slice(Math.max(node.range[0] - (beforeCount || 0), 0), + node.range[1] + (afterCount || 0)) : null; + } else { + return currentText; + } + + }; + + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + */ + api.getSourceLines = function() { + return currentTextLines; + }; + + /** + * Retrieves an array containing all comments in the source code. + * @returns {ASTNode[]} An array of comment nodes. + */ + api.getAllComments = function() { + return currentAST.comments; + }; + + /** + * Gets all comments for the given node. + * @param {ASTNode} node The AST node to get the comments for. + * @returns {Object} The list of comments indexed by their position. + */ + api.getComments = function(node) { + + var leadingComments = node.leadingComments || [], + trailingComments = node.trailingComments || []; + + /* + * espree adds a "comments" array on Program nodes rather than + * leadingComments/trailingComments. Comments are only left in the + * Program node comments array if there is no executable code. + */ + if (node.type === "Program") { + if (node.body.length === 0) { + leadingComments = node.comments; + } + } + + return { + leading: leadingComments, + trailing: trailingComments + }; + }; + + /** + * Retrieves the JSDoc comment for a given node. + * @param {ASTNode} node The AST node to get the comment for. + * @returns {ASTNode} The BlockComment node containing the JSDoc for the + * given node or null if not found. + */ + api.getJSDocComment = function(node) { + + var parent = node.parent, + line = node.loc.start.line; + + /** + * Finds a JSDoc comment node in an array of comment nodes. + * @param {ASTNode[]} comments The array of comment nodes to search. + * @returns {ASTNode} The node if found, null if not. + * @private + */ + function findJSDocComment(comments) { + + if (comments) { + for (var i = comments.length - 1; i >= 0; i--) { + if (comments[i].type === "Block" && comments[i].value.charAt(0) === "*") { + + if (line - comments[i].loc.end.line <= 1) { + return comments[i]; + } else { + break; + } + } + } + } + + return null; + } + + switch (node.type) { + case "FunctionDeclaration": + return findJSDocComment(node.leadingComments); + + case "ArrowFunctionExpression": + case "FunctionExpression": + + if (parent.type !== "CallExpression" || parent.callee !== node) { + while (parent && !parent.leadingComments && !/Function/.test(parent.type)) { + parent = parent.parent; + } + + return parent && (parent.type !== "FunctionDeclaration") ? findJSDocComment(parent.leadingComments) : null; + } + + // falls through + + default: + return null; + } + }; + + /** + * Gets nodes that are ancestors of current node. + * @returns {ASTNode[]} Array of objects representing ancestors. + */ + api.getAncestors = function() { + return controller.parents(); + }; + + /** + * Gets the deepest node containing a range index. + * @param {int} index Range index of the desired node. + * @returns {ASTNode} [description] + */ + api.getNodeByRangeIndex = function(index) { + var result = null; + + estraverse.traverse(controller.root, { + enter: function (node) { + if (node.range[0] <= index && index < node.range[1]) { + result = node; + } else { + this.skip(); + } + }, + leave: function (node) { + if (node === result) { + this.break(); + } + } + }); + + return result; + }; + + /** + * Gets the scope for the current node. + * @returns {Object} An object representing the current node's scope. + */ + api.getScope = function() { + var parents = controller.parents(), + scope = currentScopes[0]; + + // Don't do this for Program nodes - they have no parents + if (parents.length) { + + // if current node is function declaration, add it to the list + var current = controller.current(); + if (["FunctionDeclaration", "FunctionExpression", + "ArrowFunctionExpression"].indexOf(current.type) >= 0) { + parents.push(current); + } + + // Ascend the current node's parents + for (var i = parents.length - 1; i >= 0; --i) { + + scope = scopeManager.acquire(parents[i]); + if (scope) { + if (scope.type === "function-expression-name") { + return scope.childScopes[0]; + } else { + return scope; + } + } + + } + + } + + return currentScopes[0]; + }; + + /** + * Record that a particular variable has been used in code + * @param {string} name The name of the variable to mark as used + * @returns {boolean} True if the variable was found and marked as used, + * false if not. + */ + api.markVariableAsUsed = function(name) { + var scope = this.getScope(), + specialScope = currentConfig.ecmaFeatures.globalReturn || currentConfig.ecmaFeatures.modules, + variables, + i, + len; + + // Special Node.js scope means we need to start one level deeper + if (scope.type === "global" && specialScope) { + scope = scope.childScopes[0]; + } + + do { + variables = scope.variables; + for (i = 0, len = variables.length; i < len; i++) { + if (variables[i].name === name) { + variables[i].eslintUsed = true; + return true; + } + } + } while ( (scope = scope.upper) ); + + return false; + }; + + /** + * Gets the filename for the currently parsed source. + * @returns {string} The filename associated with the source being parsed. + * Defaults to "" if no filename info is present. + */ + api.getFilename = function() { + if (typeof currentFilename === "string") { + return currentFilename; + } else { + return ""; + } + }; + + /** + * Defines a new linting rule. + * @param {string} ruleId A unique rule identifier + * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers + * @returns {void} + */ + var defineRule = api.defineRule = function(ruleId, ruleModule) { + rules.define(ruleId, ruleModule); + }; + + /** + * Defines many new linting rules. + * @param {object} rulesToDefine map from unique rule identifier to rule + * @returns {void} + */ + api.defineRules = function(rulesToDefine) { + Object.getOwnPropertyNames(rulesToDefine).forEach(function(ruleId) { + defineRule(ruleId, rulesToDefine[ruleId]); + }); + }; + + /** + * Gets the default eslint configuration. + * @returns {Object} Object mapping rule IDs to their default configurations + */ + api.defaults = function() { + return require("../conf/eslint.json"); + }; + + return api; + +}()); diff --git a/tools/eslint/lib/file-finder.js b/tools/eslint/lib/file-finder.js new file mode 100644 index 00000000000000..3cdf9150fd765e --- /dev/null +++ b/tools/eslint/lib/file-finder.js @@ -0,0 +1,167 @@ +/** + * @fileoverview Util class to find config files. + * @author Aliaksei Shytkin + * @copyright 2014 Michael McLaughlin. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + path = require("path"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the entries for a directory. Including a try-catch may be detrimental to + * function performance, so move it out here a separate function. + * @param {string} directory The directory to search in. + * @returns {string[]} The entries in the directory or an empty array on error. + * @private + */ +function getDirectoryEntries(directory) { + try { + return fs.readdirSync(directory); + } catch (ex) { + return []; + } +} + +//------------------------------------------------------------------------------ +// API +//------------------------------------------------------------------------------ + +/** + * FileFinder + * @constructor + * @param {...string} arguments The basename(s) of the file(s) to find. + */ +function FileFinder() { + this.fileNames = Array.prototype.slice.call(arguments); + this.cache = {}; +} + +/** + * Find one instance of a specified file name in directory or in a parent directory. + * Cache the results. + * Does not check if a matching directory entry is a file, and intentionally + * only searches for the first file name in this.fileNames. + * Is currently used by lib/ignored_paths.js to find an .eslintignore file. + * @param {string} directory The directory to start the search from. + * @returns {string} Path of the file found, or an empty string if not found. + */ +FileFinder.prototype.findInDirectoryOrParents = function (directory) { + var cache = this.cache, + child, + dirs, + filePath, + i, + name, + searched; + + if (!directory) { + directory = process.cwd(); + } + + if (cache.hasOwnProperty(directory)) { + return cache[directory]; + } + + dirs = []; + searched = 0; + name = this.fileNames[0]; + + while (directory !== child) { + dirs[searched++] = directory; + + if (getDirectoryEntries(directory).indexOf(name) !== -1) { + filePath = path.resolve(directory, name); + break; + } + + child = directory; + + // Assign parent directory to directory. + directory = path.dirname(directory); + } + + for (i = 0; i < searched; i++) { + cache[dirs[i]] = filePath; + } + + return filePath || String(); +}; + +/** + * Find all instances of files with the specified file names, in directory and + * parent directories. Cache the results. + * Does not check if a matching directory entry is a file. + * Searches for all the file names in this.fileNames. + * Is currently used by lib/config.js to find .eslintrc and package.json files. + * @param {string} directory The directory to start the search from. + * @returns {string[]} The file paths found. + */ +FileFinder.prototype.findAllInDirectoryAndParents = function (directory) { + var cache = this.cache, + child, + dirs, + name, + fileNames, + fileNamesCount, + filePath, + i, + j, + searched; + + if (!directory) { + directory = process.cwd(); + } + + if (cache.hasOwnProperty(directory)) { + return cache[directory]; + } + + dirs = []; + searched = 0; + fileNames = this.fileNames; + fileNamesCount = fileNames.length; + + do { + dirs[searched++] = directory; + cache[directory] = []; + + for (i = 0; i < fileNamesCount; i++) { + name = fileNames[i]; + + if (getDirectoryEntries(directory).indexOf(name) !== -1) { + filePath = path.resolve(directory, name); + + // Add the file path to the cache of each directory searched. + for (j = 0; j < searched; j++) { + cache[dirs[j]].push(filePath); + } + } + } + child = directory; + + // Assign parent directory to directory. + directory = path.dirname(directory); + + if (directory === child) { + return cache[dirs[0]]; + } + } while (!cache.hasOwnProperty(directory)); + + // Add what has been cached previously to the cache of each directory searched. + for (i = 0; i < searched; i++) { + dirs.push.apply(cache[dirs[i]], cache[directory]); + } + + return cache[dirs[0]]; +}; + +module.exports = FileFinder; diff --git a/tools/eslint/lib/formatters/checkstyle.js b/tools/eslint/lib/formatters/checkstyle.js new file mode 100644 index 00000000000000..5e98c8b1312b6d --- /dev/null +++ b/tools/eslint/lib/formatters/checkstyle.js @@ -0,0 +1,68 @@ +/** + * @fileoverview CheckStyle XML reporter + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "error"; + } else { + return "warning"; + } +} + +function xmlEscape(s) { + return ("" + s).replace(/[<>&"']/g, function(c) { + switch (c) { + case "<": + return "<"; + case ">": + return ">"; + case "&": + return "&"; + case "\"": + return """; + case "'": + return "'"; + // no default + } + }); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + var output = ""; + + output += ""; + output += ""; + + results.forEach(function(result) { + var messages = result.messages; + + output += ""; + + messages.forEach(function(message) { + output += ""; + }); + + output += ""; + + }); + + output += ""; + + return output; +}; diff --git a/tools/eslint/lib/formatters/compact.js b/tools/eslint/lib/formatters/compact.js new file mode 100644 index 00000000000000..b7c2fc7e25f4cf --- /dev/null +++ b/tools/eslint/lib/formatters/compact.js @@ -0,0 +1,53 @@ +/** + * @fileoverview Compact reporter + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "Error"; + } else { + return "Warning"; + } +} + + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + var output = "", + total = 0; + + results.forEach(function(result) { + + var messages = result.messages; + total += messages.length; + + messages.forEach(function(message) { + + output += result.filePath + ": "; + output += "line " + (message.line || 0); + output += ", col " + (message.column || 0); + output += ", " + getMessageType(message); + output += " - " + message.message; + output += message.ruleId ? " (" + message.ruleId + ")" : ""; + output += "\n"; + + }); + + }); + + if (total > 0) { + output += "\n" + total + " problem" + (total !== 1 ? "s" : ""); + } + + return output; +}; diff --git a/tools/eslint/lib/formatters/jslint-xml.js b/tools/eslint/lib/formatters/jslint-xml.js new file mode 100644 index 00000000000000..26aa2de0b5b8ec --- /dev/null +++ b/tools/eslint/lib/formatters/jslint-xml.js @@ -0,0 +1,40 @@ +/** + * @fileoverview JSLint XML reporter + * @author Ian Christian Myers + */ +"use strict"; + +var xmlescape = require("xml-escape"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + var output = ""; + + output += ""; + output += ""; + + results.forEach(function(result) { + var messages = result.messages; + + output += ""; + + messages.forEach(function(message) { + output += ""; + }); + + output += ""; + + }); + + output += ""; + + return output; +}; diff --git a/tools/eslint/lib/formatters/junit.js b/tools/eslint/lib/formatters/junit.js new file mode 100644 index 00000000000000..7ee94135f6a84f --- /dev/null +++ b/tools/eslint/lib/formatters/junit.js @@ -0,0 +1,63 @@ +/** + * @fileoverview jUnit Reporter + * @author Jamund Ferguson + */ +"use strict"; + +var xmlescape = require("xml-escape"); + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "Error"; + } else { + return "Warning"; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + var output = ""; + + output += "\n"; + output += "\n"; + + results.forEach(function(result) { + + var messages = result.messages; + + if (messages.length) { + output += "\n"; + } + + messages.forEach(function(message) { + var type = message.fatal ? "error" : "failure"; + output += ""; + output += "<" + type + " message=\"" + xmlescape(message.message || "") + "\">"; + output += ""; + output += ""; + output += "\n"; + }); + + if (messages.length) { + output += "\n"; + } + + }); + + output += "\n"; + + return output; +}; diff --git a/tools/eslint/lib/formatters/stylish.js b/tools/eslint/lib/formatters/stylish.js new file mode 100644 index 00000000000000..59e01d0b3ef563 --- /dev/null +++ b/tools/eslint/lib/formatters/stylish.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Stylish reporter + * @author Sindre Sorhus + */ +"use strict"; + +var chalk = require("chalk"), + table = require("text-table"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Given a word and a count, append an s if count is not one. + * @param {string} word A word in its singular form. + * @param {int} count A number controlling whether word should be pluralized. + * @returns {string} The original word with an s on the end if count is not one. + */ +function pluralize(word, count) { + return (count === 1 ? word : word + "s"); +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + + var output = "\n", + total = 0, + errors = 0, + warnings = 0, + summaryColor = "yellow"; + + results.forEach(function(result) { + var messages = result.messages; + + if (messages.length === 0) { + return; + } + + total += messages.length; + output += chalk.underline(result.filePath) + "\n"; + + output += table( + messages.map(function(message) { + var messageType; + + if (message.fatal || message.severity === 2) { + messageType = chalk.red("error"); + summaryColor = "red"; + errors++; + } else { + messageType = chalk.yellow("warning"); + warnings++; + } + + return [ + "", + message.line || 0, + message.column || 0, + messageType, + message.message.replace(/\.$/, ""), + chalk.gray(message.ruleId || "") + ]; + }), + { + align: ["", "r", "l"], + stringLength: function(str) { + return chalk.stripColor(str).length; + } + } + ).split("\n").map(function(el) { + return el.replace(/(\d+)\s+(\d+)/, function(m, p1, p2) { + return chalk.gray(p1 + ":" + p2); + }); + }).join("\n") + "\n\n"; + }); + + if (total > 0) { + output += chalk[summaryColor].bold([ + "\u2716 ", total, pluralize(" problem", total), + " (", errors, pluralize(" error", errors), ", ", + warnings, pluralize(" warning", warnings), ")\n" + ].join("")); + } + + return total > 0 ? output : ""; +}; diff --git a/tools/eslint/lib/formatters/tap.js b/tools/eslint/lib/formatters/tap.js new file mode 100644 index 00000000000000..b9f4cd66b9a549 --- /dev/null +++ b/tools/eslint/lib/formatters/tap.js @@ -0,0 +1,90 @@ +/** + * @fileoverview TAP reporter + * @author Jonathan Kingston + */ +"use strict"; + +var yaml = require("js-yaml"); + +//------------------------------------------------------------------------------ +// Helper Functions +//------------------------------------------------------------------------------ + +/** + * Returns a canonical error level string based upon the error message passed in. + * @param {object} message Individual error message provided by eslint + * @returns {String} Error level string + */ +function getMessageType(message) { + if (message.fatal || message.severity === 2) { + return "error"; + } else { + return "warning"; + } +} + +/** + * Takes in a JavaScript object and outputs a TAP diagnostics string + * @param {object} diagnostic JavaScript object to be embedded as YAML into output. + * @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant + */ +function outputDiagnostics(diagnostic) { + var prefix = " "; + var output = prefix + "---\n"; + output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix); + output += "...\n"; + return output; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +module.exports = function(results) { + var output = "TAP version 13\n1.." + results.length + "\n"; + + results.forEach(function(result, id) { + var messages = result.messages; + var testResult = "ok"; + var diagnostics = {}; + + if (messages.length > 0) { + testResult = "not ok"; + + messages.forEach(function(message) { + var diagnostic = { + message: message.message, + severity: getMessageType(message), + data: { + line: message.line || 0, + column: message.column || 0, + ruleId: message.ruleId || "" + } + }; + + // If we have multiple messages place them under a messages key + // The first error will be logged as message key + // This is to adhere to TAP 13 loosely defined specification of having a message key + if ("message" in diagnostics) { + if ("messages" in diagnostics) { + diagnostics.messages.push(diagnostic); + } else { + diagnostics.messages = [diagnostic]; + } + } else { + diagnostics = diagnostic; + } + }); + } + + output += testResult + " " + (id + 1) + " - " + result.filePath + "\n"; + + // If we have an error include diagnostics + if (messages.length > 0) { + output += outputDiagnostics(diagnostics); + } + + }); + + return output; +}; diff --git a/tools/eslint/lib/ignored-paths.js b/tools/eslint/lib/ignored-paths.js new file mode 100644 index 00000000000000..3d2bd9b44cd47b --- /dev/null +++ b/tools/eslint/lib/ignored-paths.js @@ -0,0 +1,133 @@ +/** + * @fileoverview Responsible for loading ignore config files and managing ignore patterns + * @author Jonathan Rajavuori + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + debug = require("debug"), + minimatch = require("minimatch"), + FileFinder = require("./file-finder"); + +debug = debug("eslint:ignored-paths"); + + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var ESLINT_IGNORE_FILENAME = ".eslintignore"; + + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Load and parse ignore patterns from the file at the given path + * @param {string} filepath Path to the ignore file. + * @returns {string[]} An array of ignore patterns or an empty array if no ignore file. + */ +function loadIgnoreFile(filepath) { + var ignorePatterns = []; + + function nonEmpty(line) { + return line.trim() !== "" && line[0] !== "#"; + } + + if (filepath) { + try { + ignorePatterns = fs.readFileSync(filepath, "utf8").split(/\r?\n/).filter(nonEmpty); + } catch (e) { + e.message = "Cannot read ignore file: " + filepath + "\nError: " + e.message; + throw e; + } + } + + return ["node_modules/**"].concat(ignorePatterns); +} + +var ignoreFileFinder; + +/** + * Find an ignore file in the current directory or a parent directory. + * @returns {string} Path of ignore file or an empty string. + */ +function findIgnoreFile() { + if (!ignoreFileFinder) { + ignoreFileFinder = new FileFinder(ESLINT_IGNORE_FILENAME); + } + + return ignoreFileFinder.findInDirectoryOrParents(); +} + + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * IgnoredPaths + * @constructor + * @class IgnoredPaths + * @param {Array} patterns to be matched against file paths + */ +function IgnoredPaths(patterns) { + this.patterns = patterns; +} + +/** + * IgnoredPaths initializer + * @param {Object} options object containing 'ignore' and 'ignorePath' properties + * @returns {IgnoredPaths} object, with patterns loaded from the ignore file + */ +IgnoredPaths.load = function (options) { + var patterns; + + options = options || {}; + + if (options.ignore) { + patterns = loadIgnoreFile(options.ignorePath || findIgnoreFile()); + } else { + patterns = []; + } + + return new IgnoredPaths(patterns); +}; + +/** + * Determine whether a file path is included in the configured ignore patterns + * @param {string} filepath Path to check + * @returns {boolean} true if the file path matches one or more patterns, false otherwise + */ +IgnoredPaths.prototype.contains = function (filepath) { + if (this.patterns === null) { + throw new Error("No ignore patterns loaded, call 'load' first"); + } + + filepath = filepath.replace("\\", "/"); + filepath = filepath.replace(/^\.\//, ""); + return this.patterns.reduce(function(ignored, pattern) { + var negated = pattern[0] === "!", + matches; + + if (negated) { + pattern = pattern.slice(1); + } + + // Remove leading "current folder" prefix + if (pattern.indexOf("./") === 0) { + pattern = pattern.slice(2); + } + + matches = minimatch(filepath, pattern) || minimatch(filepath, pattern + "/**"); + + return matches ? !negated : ignored; + }, false); +}; + +module.exports = IgnoredPaths; diff --git a/tools/eslint/lib/load-rules.js b/tools/eslint/lib/load-rules.js new file mode 100644 index 00000000000000..62183f344d3b68 --- /dev/null +++ b/tools/eslint/lib/load-rules.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Module for loading rules from files and directories. + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + path = require("path"); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Load all rule modules from specified directory. + * @param {String} [rulesDir] Path to rules directory, may be relative. Defaults to `lib/rules`. + * @returns {Object} Loaded rule modules by rule ids (file names). + */ +module.exports = function(rulesDir) { + if (!rulesDir) { + rulesDir = path.join(__dirname, "rules"); + } else { + rulesDir = path.resolve(process.cwd(), rulesDir); + } + + var rules = Object.create(null); + fs.readdirSync(rulesDir).forEach(function(file) { + if (path.extname(file) !== ".js") { + return; + } + rules[file.slice(0, -3)] = require(path.join(rulesDir, file)); + }); + return rules; +}; diff --git a/tools/eslint/lib/options.js b/tools/eslint/lib/options.js new file mode 100644 index 00000000000000..4b5803c1153409 --- /dev/null +++ b/tools/eslint/lib/options.js @@ -0,0 +1,121 @@ +/** + * @fileoverview Options configuration for optionator. + * @author George Zahariev + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var optionator = require("optionator"); + +//------------------------------------------------------------------------------ +// Initialization and Public Interface +//------------------------------------------------------------------------------ + +// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" +module.exports = optionator({ + prepend: "eslint [options] file.js [file.js] [dir]", + concatRepeatedArrays: true, + mergeRepeatedObjects: true, + options: [{ + heading: "Options" + }, { + option: "help", + alias: "h", + type: "Boolean", + description: "Show help" + }, { + option: "config", + alias: "c", + type: "path::String", + description: "Use configuration from this file" + }, { + option: "rulesdir", + type: "[path::String]", + description: "Use additional rules from this directory" + }, { + option: "format", + alias: "f", + type: "String", + default: "stylish", + description: "Use a specific output format" + }, { + option: "version", + alias: "v", + type: "Boolean", + description: "Outputs the version number" + }, { + option: "reset", + type: "Boolean", + default: "false", + description: "Set all default rules to off" + }, { + option: "eslintrc", + type: "Boolean", + default: "true", + description: "Disable use of configuration from .eslintrc" + }, { + option: "env", + type: "[String]", + description: "Specify environments" + }, { + option: "ext", + type: "[String]", + default: ".js", + description: "Specify JavaScript file extensions" + }, { + option: "plugin", + type: "[String]", + description: "Specify plugins" + }, { + option: "global", + type: "[String]", + description: "Define global variables" + }, { + option: "rule", + type: "Object", + description: "Specify rules" + }, + { + option: "ignore-path", + type: "path::String", + description: "Specify path of ignore file" + }, + { + option: "ignore", + type: "Boolean", + default: "true", + description: "Disable use of .eslintignore" + }, + { + option: "color", + type: "Boolean", + default: "true", + description: "Disable color in piped output" + }, + { + option: "output-file", + alias: "o", + type: "path::String", + description: "Specify file to write report to" + }, + { + option: "quiet", + type: "Boolean", + default: "false", + description: "Report errors only" + }, + { + option: "stdin", + type: "Boolean", + default: "false", + description: "Lint code provided on " + }, + { + option: "stdin-filename", + type: "String", + description: "Specify filename to process STDIN as" + }] +}); diff --git a/tools/eslint/lib/rule-context.js b/tools/eslint/lib/rule-context.js new file mode 100644 index 00000000000000..0513685f6d6acb --- /dev/null +++ b/tools/eslint/lib/rule-context.js @@ -0,0 +1,107 @@ +/** + * @fileoverview RuleContext utility for rules + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var PASSTHROUGHS = [ + "getAllComments", + "getAncestors", + "getComments", + "getFilename", + "getFirstToken", + "getFirstTokens", + "getJSDocComment", + "getLastToken", + "getLastTokens", + "getNodeByRangeIndex", + "getScope", + "getSource", + "getSourceLines", + "getTokenAfter", + "getTokenBefore", + "getTokenByRangeStart", + "getTokens", + "getTokensAfter", + "getTokensBefore", + "getTokensBetween", + "markVariableAsUsed", + "isMarkedAsUsed" + ]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Acts as an abstraction layer between rules and the main eslint object. + * @constructor + * @param {string} ruleId The ID of the rule using this object. + * @param {eslint} eslint The eslint object. + * @param {number} severity The configured severity level of the rule. + * @param {array} options The configuration information to be added to the rule. + * @param {object} settings The configuration settings passed from the config file. + * @param {object} ecmaFeatures The ecmaFeatures settings passed from the config file. + */ +function RuleContext(ruleId, eslint, severity, options, settings, ecmaFeatures) { + + /** + * The read-only ID of the rule. + */ + Object.defineProperty(this, "id", { + value: ruleId + }); + + /** + * The read-only options of the rule + */ + Object.defineProperty(this, "options", { + value: options + }); + + /** + * The read-only settings shared between all rules + */ + Object.defineProperty(this, "settings", { + value: settings + }); + + /** + * The read-only ecmaFeatures shared across all rules + */ + Object.defineProperty(this, "ecmaFeatures", { + value: Object.create(ecmaFeatures) + }); + Object.freeze(this.ecmaFeatures); + + // copy over passthrough methods + PASSTHROUGHS.forEach(function(name) { + this[name] = function() { + return eslint[name].apply(eslint, arguments); + }; + }, this); + + /** + * Passthrough to eslint.report() that automatically assigns the rule ID and severity. + * @param {ASTNode} node The AST node related to the message. + * @param {Object=} location The location of the error. + * @param {string} message The message to display to the user. + * @param {Object} opts Optional template data which produces a formatted message + * with symbols being replaced by this object's values. + * @returns {void} + */ + this.report = function(node, location, message, opts) { + eslint.report(ruleId, severity, node, location, message, opts); + }; + +} + +RuleContext.prototype = { + constructor: RuleContext +}; + +module.exports = RuleContext; diff --git a/tools/eslint/lib/rules.js b/tools/eslint/lib/rules.js new file mode 100644 index 00000000000000..eef942fcf15473 --- /dev/null +++ b/tools/eslint/lib/rules.js @@ -0,0 +1,88 @@ +/** + * @fileoverview Defines a storage for rules. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var loadRules = require("./load-rules"); + +//------------------------------------------------------------------------------ +// Privates +//------------------------------------------------------------------------------ + +var rules = Object.create(null); + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Registers a rule module for rule id in storage. + * @param {String} ruleId Rule id (file name). + * @param {Function} ruleModule Rule handler. + * @returns {void} + */ +function define(ruleId, ruleModule) { + rules[ruleId] = ruleModule; +} + +exports.define = define; + +/** + * Loads and registers all rules from passed rules directory. + * @param {String} [rulesDir] Path to rules directory, may be relative. Defaults to `lib/rules`. + * @returns {void} + */ +function load(rulesDir) { + var newRules = loadRules(rulesDir); + Object.keys(newRules).forEach(function(ruleId) { + define(ruleId, newRules[ruleId]); + }); +} + +exports.load = load; + +/** + * Registers all given rules of a plugin. + * @param {Object} pluginRules A key/value map of rule definitions. + * @param {String} pluginName The name of the plugin without prefix (`eslint-plugin-`). + * @returns {void} + */ +exports.import = function (pluginRules, pluginName) { + Object.keys(pluginRules).forEach(function (ruleId) { + var qualifiedRuleId = pluginName + "/" + ruleId, + rule = pluginRules[ruleId]; + + define(qualifiedRuleId, rule); + }); +}; + +/** + * Access rule handler by id (file name). + * @param {String} ruleId Rule id (file name). + * @returns {Function} Rule handler. + */ +exports.get = function(ruleId) { + return rules[ruleId]; +}; + +/** + * Reset rules storage. + * Should be used only in tests. + * @returns {void} + */ +exports.testClear = function() { + rules = Object.create(null); +}; + +//------------------------------------------------------------------------------ +// Initialization +//------------------------------------------------------------------------------ + +// loads built-in rules +load(); diff --git a/tools/eslint/lib/rules/block-scoped-var.js b/tools/eslint/lib/rules/block-scoped-var.js new file mode 100644 index 00000000000000..6b23167fd1f6ab --- /dev/null +++ b/tools/eslint/lib/rules/block-scoped-var.js @@ -0,0 +1,318 @@ +/** + * @fileoverview Rule to check for "block scoped" variables by binding context + * @author Matt DuVall + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var scopeStack = []; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines whether an identifier is in declaration position or is a non-declaration reference. + * @param {ASTNode} id The identifier. + * @param {ASTNode} parent The identifier's parent AST node. + * @returns {Boolean} true when the identifier is in declaration position. + */ + function isDeclaration(id, parent) { + switch (parent.type) { + case "FunctionDeclaration": + case "FunctionExpression": + return parent.params.indexOf(id) > -1 || id === parent.id; + + case "VariableDeclarator": + return id === parent.id; + + case "CatchClause": + return id === parent.param; + + default: + return false; + } + } + + /** + * Determines whether an identifier is in property position. + * @param {ASTNode} id The identifier. + * @param {ASTNode} parent The identifier's parent AST node. + * @returns {Boolean} true when the identifier is in property position. + */ + function isProperty(id, parent) { + switch (parent.type) { + case "MemberExpression": + return id === parent.property && !parent.computed; + + case "Property": + return id === parent.key; + + default: + return false; + } + } + + /** + * Pushes a new scope object on the scope stack. + * @returns {void} + */ + function pushScope() { + scopeStack.push([]); + } + + /** + * Removes the topmost scope object from the scope stack. + * @returns {void} + */ + function popScope() { + scopeStack.pop(); + } + + /** + * Declares the given names in the topmost scope object. + * @param {[String]} names A list of names to declare. + * @returns {void} + */ + function declare(names) { + [].push.apply(scopeStack[scopeStack.length - 1], names); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + /** + * Declares all relevant identifiers for module imports. + * @param {ASTNode} node The AST node representing an import. + * @returns {void} + * @private + */ + function declareImports(node) { + declare([node.local.name]); + + if (node.imported && node.imported.name !== node.local.name) { + declare([node.imported.name]); + } + } + + /** + * Declares all relevant identifiers for classes. + * @param {ASTNode} node The AST node representing a class. + * @returns {void} + * @private + */ + function declareClass(node) { + + if (node.id) { + declare([node.id.name]); + } + + pushScope(); + } + + /** + * Declares all relevant identifiers for classes. + * @param {ASTNode} node The AST node representing a class. + * @returns {void} + * @private + */ + function declareClassMethod(node) { + pushScope(); + + declare([node.key.name]); + } + + /** + * Add declarations based on the type of node being passed. + * @param {ASTNode} node The node containing declarations. + * @returns {void} + * @private + */ + function declareByNodeType(node) { + + var declarations = []; + + switch (node.type) { + case "Identifier": + declarations.push(node.name); + break; + + case "ObjectPattern": + node.properties.forEach(function(property) { + declarations.push(property.key.name); + if (property.value) { + declarations.push(property.value.name); + } + }); + break; + + case "ArrayPattern": + node.elements.forEach(function(element) { + if (element) { + declarations.push(element.name); + } + }); + break; + + case "AssignmentPattern": + declareByNodeType(node.left); + break; + + case "RestElement": + declareByNodeType(node.argument); + break; + + // no default + } + + declare(declarations); + + } + + /** + * Adds declarations of the function parameters and pushes the scope + * @param {ASTNode} node The node containing declarations. + * @returns {void} + * @private + */ + function functionHandler(node) { + pushScope(); + + node.params.forEach(function(param) { + declareByNodeType(param); + }); + + declare(node.rest ? [node.rest.name] : []); + declare(["arguments"]); + } + + /** + * Adds declaration of the function name in its parent scope then process the function + * @param {ASTNode} node The node containing declarations. + * @returns {void} + * @private + */ + function functionDeclarationHandler(node) { + declare(node.id ? [node.id.name] : []); + functionHandler(node); + } + + /** + * Process function declarations and declares its name in its own scope + * @param {ASTNode} node The node containing declarations. + * @returns {void} + * @private + */ + function functionExpressionHandler(node) { + functionHandler(node); + declare(node.id ? [node.id.name] : []); + } + + function variableDeclarationHandler(node) { + node.declarations.forEach(function(declaration) { + declareByNodeType(declaration.id); + }); + + } + + return { + "Program": function() { + var scope = context.getScope(); + scopeStack = [scope.variables.map(function(v) { + return v.name; + })]; + + // global return creates another scope + if (context.ecmaFeatures.globalReturn) { + scope = scope.childScopes[0]; + scopeStack.push(scope.variables.map(function(v) { + return v.name; + })); + } + }, + + "ImportSpecifier": declareImports, + "ImportDefaultSpecifier": declareImports, + "ImportNamespaceSpecifier": declareImports, + + "BlockStatement": function(node) { + var statements = node.body; + pushScope(); + statements.forEach(function(stmt) { + if (stmt.type === "VariableDeclaration") { + variableDeclarationHandler(stmt); + } else if (stmt.type === "FunctionDeclaration") { + declare([stmt.id.name]); + } + }); + }, + + "VariableDeclaration": function (node) { + variableDeclarationHandler(node); + }, + + "BlockStatement:exit": popScope, + + "CatchClause": function(node) { + pushScope(); + declare([node.param.name]); + }, + "CatchClause:exit": popScope, + + "FunctionDeclaration": functionDeclarationHandler, + "FunctionDeclaration:exit": popScope, + + "ClassDeclaration": declareClass, + "ClassDeclaration:exit": popScope, + + "ClassExpression": declareClass, + "ClassExpression:exit": popScope, + + "MethodDefinition": declareClassMethod, + "MethodDefinition:exit": popScope, + + "FunctionExpression": functionExpressionHandler, + "FunctionExpression:exit": popScope, + + // Arrow functions cannot have names + "ArrowFunctionExpression": functionHandler, + "ArrowFunctionExpression:exit": popScope, + + "ForStatement": function() { + pushScope(); + }, + "ForStatement:exit": popScope, + + "ForInStatement": function() { + pushScope(); + }, + "ForInStatement:exit": popScope, + + "ForOfStatement": function() { + pushScope(); + }, + "ForOfStatement:exit": popScope, + + "Identifier": function(node) { + var ancestor = context.getAncestors().pop(); + if (isDeclaration(node, ancestor) || isProperty(node, ancestor) || ancestor.type === "LabeledStatement") { + return; + } + + for (var i = 0, l = scopeStack.length; i < l; i++) { + if (scopeStack[i].indexOf(node.name) > -1) { + return; + } + } + + context.report(node, "\"" + node.name + "\" used outside of binding context."); + } + }; + +}; diff --git a/tools/eslint/lib/rules/brace-style.js b/tools/eslint/lib/rules/brace-style.js new file mode 100644 index 00000000000000..599e86f68b91d5 --- /dev/null +++ b/tools/eslint/lib/rules/brace-style.js @@ -0,0 +1,204 @@ +/** + * @fileoverview Rule to flag block statements that do not use the one true brace style + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var style = context.options[0] || "1tbs"; + var params = context.options[1] || {}; + + var OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.", + BODY_MESSAGE = "Statement inside of curly braces should be on next line.", + CLOSE_MESSAGE = "Closing curly brace does not appear on the same line as the subsequent block.", + CLOSE_MESSAGE_SINGLE = "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", + CLOSE_MESSAGE_STROUSTRUP = "Closing curly brace appears on the same line as the subsequent block."; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a given node is a block statement. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a block statement, false if not. + * @private + */ + function isBlock(node) { + return node && node.type === "BlockStatement"; + } + + + /** + * Binds a list of properties to a function that verifies that the opening + * curly brace is on the same line as its controlling statement of a given + * node. + * @param {...string} The properties to check on the node. + * @returns {Function} A function that will perform the check on a node + * @private + */ + function checkBlock() { + var blockProperties = arguments; + + return function(node) { + [].forEach.call(blockProperties, function(blockProp) { + var block = node[blockProp], previousToken, curlyToken, curlyTokenEnd, curlyTokensOnSameLine; + block = node[blockProp]; + + if (isBlock(block)) { + + previousToken = context.getTokenBefore(block); + curlyToken = context.getFirstToken(block); + curlyTokenEnd = context.getLastToken(block); + curlyTokensOnSameLine = curlyToken.loc.start.line === curlyTokenEnd.loc.start.line; + + if (previousToken.loc.start.line !== curlyToken.loc.start.line) { + context.report(node, OPEN_MESSAGE); + } else if (block.body.length && params.allowSingleLine) { + + if (curlyToken.loc.start.line === block.body[0].loc.start.line && !curlyTokensOnSameLine) { + context.report(block.body[0], BODY_MESSAGE); + } else if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line && !curlyTokensOnSameLine) { + context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE); + } + + } else if (block.body.length && curlyToken.loc.start.line === block.body[0].loc.start.line) { + context.report(block.body[0], BODY_MESSAGE); + } + } + }); + }; + } + + /** + * Enforces the configured brace style on IfStatements + * @param {ASTNode} node An IfStatement node. + * @returns {void} + * @private + */ + function checkIfStatement(node) { + var tokens, + alternateIsBlock = false, + alternateIsIfBlock = false; + + checkBlock("consequent", "alternate")(node); + + if (node.alternate) { + + alternateIsBlock = isBlock(node.alternate); + alternateIsIfBlock = node.alternate.type === "IfStatement" && isBlock(node.alternate.consequent); + + if (alternateIsBlock || alternateIsIfBlock) { + tokens = context.getTokensBefore(node.alternate, 2); + + if (style === "1tbs") { + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node.alternate, CLOSE_MESSAGE); + } + } else if (style === "stroustrup") { + if (tokens[0].loc.start.line === tokens[1].loc.start.line) { + context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP); + } + } + } + + } + } + + /** + * Enforces the configured brace style on TryStatements + * @param {ASTNode} node A TryStatement node. + * @returns {void} + * @private + */ + function checkTryStatement(node) { + var tokens; + + checkBlock("block", "finalizer")(node); + + if (isBlock(node.finalizer)) { + tokens = context.getTokensBefore(node.finalizer, 2); + if (style === "1tbs") { + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node.finalizer, CLOSE_MESSAGE); + } + } else if (style === "stroustrup") { + if (tokens[0].loc.start.line === tokens[1].loc.start.line) { + context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP); + } + } + } + } + + /** + * Enforces the configured brace style on CatchClauses + * @param {ASTNode} node A CatchClause node. + * @returns {void} + * @private + */ + function checkCatchClause(node) { + var previousToken = context.getTokenBefore(node), + firstToken = context.getFirstToken(node); + + checkBlock("body")(node); + + if (isBlock(node.body)) { + if (style === "1tbs") { + if (previousToken.loc.start.line !== firstToken.loc.start.line) { + context.report(node, CLOSE_MESSAGE); + } + } else if (style === "stroustrup") { + if (previousToken.loc.start.line === firstToken.loc.start.line) { + context.report(node, CLOSE_MESSAGE_STROUSTRUP); + } + } + } + } + + /** + * Enforces the configured brace style on SwitchStatements + * @param {ASTNode} node A SwitchStatement node. + * @returns {void} + * @private + */ + function checkSwitchStatement(node) { + var tokens; + if (node.cases && node.cases.length) { + tokens = context.getTokensBefore(node.cases[0], 2); + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node, OPEN_MESSAGE); + } + } else { + tokens = context.getLastTokens(node, 3); + if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { + context.report(node, OPEN_MESSAGE); + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": checkBlock("body"), + "FunctionExpression": checkBlock("body"), + "ArrowFunctionExpression": checkBlock("body"), + "IfStatement": checkIfStatement, + "TryStatement": checkTryStatement, + "CatchClause": checkCatchClause, + "DoWhileStatement": checkBlock("body"), + "WhileStatement": checkBlock("body"), + "WithStatement": checkBlock("body"), + "ForStatement": checkBlock("body"), + "ForInStatement": checkBlock("body"), + "ForOfStatement": checkBlock("body"), + "SwitchStatement": checkSwitchStatement + }; + +}; diff --git a/tools/eslint/lib/rules/camelcase.js b/tools/eslint/lib/rules/camelcase.js new file mode 100644 index 00000000000000..5b1b8020da0f23 --- /dev/null +++ b/tools/eslint/lib/rules/camelcase.js @@ -0,0 +1,99 @@ +/** + * @fileoverview Rule to flag non-camelcased identifiers + * @author Nicholas C. Zakas + * @copyright 2015 Dieter Oberkofler. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if a string contains an underscore and isn't all upper-case + * @param {String} name The string to check. + * @returns {boolean} if the string is underscored + * @private + */ + function isUnderscored(name) { + + // if there's an underscore, it might be A_CONSTANT, which is okay + return name.indexOf("_") > -1 && name !== name.toUpperCase(); + } + + /** + * Reports an AST node as a rule violation. + * @param {ASTNode} node The node to report. + * @returns {void} + * @private + */ + function report(node) { + context.report(node, "Identifier '{{name}}' is not in camel case.", { name: node.name }); + } + + var options = context.options[0] || {}, + properties = options.properties || ""; + + if (properties !== "always" && properties !== "never") { + properties = "always"; + } + + return { + + "Identifier": function(node) { + + // Leading and trailing underscores are commonly used to flag private/protected identifiers, strip them + var name = node.name.replace(/^_+|_+$/g, ""), + effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent; + + // MemberExpressions get special rules + if (node.parent.type === "MemberExpression") { + + // "never" check properties + if (properties === "never") { + return; + } + + // Always report underscored object names + if (node.parent.object.type === "Identifier" && + node.parent.object.name === node.name && + isUnderscored(name)) { + report(node); + + // Report AssignmentExpressions only if they are the left side of the assignment + } else if (effectiveParent.type === "AssignmentExpression" && + isUnderscored(name) && + (effectiveParent.right.type !== "MemberExpression" || + effectiveParent.left.type === "MemberExpression" && + effectiveParent.left.property.name === node.name)) { + report(node); + } + + // Properties have their own rules + } else if (node.parent.type === "Property") { + + // "never" check properties + if (properties === "never") { + return; + } + + if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + report(node); + } + + // Report anything that is underscored that isn't a CallExpression + } else if (isUnderscored(name) && effectiveParent.type !== "CallExpression") { + report(node); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/comma-dangle.js b/tools/eslint/lib/rules/comma-dangle.js new file mode 100644 index 00000000000000..da3776d4243dae --- /dev/null +++ b/tools/eslint/lib/rules/comma-dangle.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Rule to forbid or enforce dangling commas. + * @author Ian Christian Myers + * @copyright 2015 Mathias Schreck + * @copyright 2013 Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var allowDangle = context.options[0]; + var forbidDangle = allowDangle !== "always-multiline" && allowDangle !== "always"; + var UNEXPECTED_MESSAGE = "Unexpected trailing comma."; + var MISSING_MESSAGE = "Missing trailing comma."; + + /** + * Checks the given node for trailing comma and reports violations. + * @param {ASTNode} node The node of an ObjectExpression or ArrayExpression + * @returns {void} + */ + function checkForTrailingComma(node) { + var items = node.properties || node.elements, + length = items.length, + nodeIsMultiLine = node.loc.start.line !== node.loc.end.line, + lastItem, + penultimateToken, + hasDanglingComma; + + if (length) { + lastItem = items[length - 1]; + if (lastItem) { + penultimateToken = context.getLastToken(node, 1); + hasDanglingComma = penultimateToken.value === ","; + + if (forbidDangle && hasDanglingComma) { + context.report(lastItem, penultimateToken.loc.start, UNEXPECTED_MESSAGE); + } else if (allowDangle === "always-multiline") { + if (hasDanglingComma && !nodeIsMultiLine) { + context.report(lastItem, penultimateToken.loc.start, UNEXPECTED_MESSAGE); + } else if (!hasDanglingComma && nodeIsMultiLine) { + context.report(lastItem, penultimateToken.loc.end, MISSING_MESSAGE); + } + } else if (allowDangle === "always" && !hasDanglingComma) { + context.report(lastItem, lastItem.loc.end, MISSING_MESSAGE); + } + } + } + } + + return { + "ObjectExpression": checkForTrailingComma, + "ArrayExpression": checkForTrailingComma + }; +}; diff --git a/tools/eslint/lib/rules/comma-spacing.js b/tools/eslint/lib/rules/comma-spacing.js new file mode 100644 index 00000000000000..32136a352393c4 --- /dev/null +++ b/tools/eslint/lib/rules/comma-spacing.js @@ -0,0 +1,159 @@ +/** + * @fileoverview Comma spacing - validates spacing before and after comma + * @author Vignesh Anand aka vegetableman. + * @copyright 2014 Vignesh Anand. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var options = { + before: context.options[0] ? !!context.options[0].before : false, + after: context.options[0] ? !!context.options[0].after : true + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // the index of the last comment that was checked + var lastCommentIndex = 0; + + /** + * Determines whether two adjacent tokens have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + var punctuationLength = context.getTokensBetween(left, right).length; // the length of any parenthesis + return (left.range[1] + punctuationLength) < right.range[0]; + } + + /** + * Checks whether two tokens are on the same line. + * @param {ASTNode} left The leftmost token. + * @param {ASTNode} right The rightmost token. + * @returns {boolean} True if the tokens are on the same line, false if not. + * @private + */ + function isSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + } + + /** + * Determines if a given token is a comma operator. + * @param {ASTNode} token The token to check. + * @returns {boolean} True if the token is a comma, false if not. + * @private + */ + function isComma(token) { + return !!token && (token.type === "Punctuator") && (token.value === ","); + } + + /** + * Reports a spacing error with an appropriate message. + * @param {ASTNode} node The binary expression node to report. + * @param {string} dir Is the error "before" or "after" the comma? + * @returns {void} + * @private + */ + function report(node, dir) { + context.report(node, options[dir] ? + "A space is required " + dir + " ','." : + "There should be no space " + dir + " ','."); + } + + /** + * Validates the spacing around a comma token. + * @param {Object} tokens - The tokens to be validated. + * @param {Token} tokens.comma The token representing the comma. + * @param {Token} [tokens.left] The last token before the comma. + * @param {Token} [tokens.right] The first token after the comma. + * @param {Token|ASTNode} reportItem The item to use when reporting an error. + * @returns {void} + * @private + */ + function validateCommaItemSpacing(tokens, reportItem) { + if (tokens.left && isSameLine(tokens.left, tokens.comma) && + (options.before !== isSpaced(tokens.left, tokens.comma)) + ) { + report(reportItem, "before"); + } + if (tokens.right && isSameLine(tokens.comma, tokens.right) && + (options.after !== isSpaced(tokens.comma, tokens.right)) + ) { + report(reportItem, "after"); + } + } + + /** + * Determines if a given source index is in a comment or not by checking + * the index against the comment range. Since the check goes straight + * through the file, once an index is passed a certain comment, we can + * go to the next comment to check that. + * @param {int} index The source index to check. + * @param {ASTNode[]} comments An array of comment nodes. + * @returns {boolean} True if the index is within a comment, false if not. + * @private + */ + function isIndexInComment(index, comments) { + + var comment; + + while (lastCommentIndex < comments.length) { + + comment = comments[lastCommentIndex]; + + if (comment.range[0] <= index && index < comment.range[1]) { + return true; + } else if (index > comment.range[1]) { + lastCommentIndex++; + } else { + break; + } + + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program": function() { + + var source = context.getSource(), + allComments = context.getAllComments(), + pattern = /,/g, + commaToken, + previousToken, + nextToken; + + while (pattern.test(source)) { + + // do not flag anything inside of comments + if (!isIndexInComment(pattern.lastIndex, allComments)) { + commaToken = context.getTokenByRangeStart(pattern.lastIndex - 1); + + if (commaToken && commaToken.type !== "JSXText") { + previousToken = context.getTokenBefore(commaToken); + nextToken = context.getTokenAfter(commaToken); + validateCommaItemSpacing({ + comma: commaToken, + left: isComma(previousToken) ? null : previousToken, + right: isComma(nextToken) ? null : nextToken + }, commaToken); + } + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/comma-style.js b/tools/eslint/lib/rules/comma-style.js new file mode 100644 index 00000000000000..4b8d1457753398 --- /dev/null +++ b/tools/eslint/lib/rules/comma-style.js @@ -0,0 +1,177 @@ +/** + * @fileoverview Comma style - enforces comma styles of two types: last and first + * @author Vignesh Anand aka vegetableman + * @copyright 2014 Vignesh Anand. All rights reserved. + * @copyright 2015 Evan Simmons. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var style = context.options[0] || "last", + exceptions = {}; + + if (context.options.length === 2 && context.options[1].hasOwnProperty("exceptions")) { + exceptions = context.options[1].exceptions; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether two tokens are on the same line. + * @param {ASTNode} left The leftmost token. + * @param {ASTNode} right The rightmost token. + * @returns {boolean} True if the tokens are on the same line, false if not. + * @private + */ + function isSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + } + + /** + * Determines if a given token is a comma operator. + * @param {ASTNode} token The token to check. + * @returns {boolean} True if the token is a comma, false if not. + * @private + */ + function isComma(token) { + return !!token && (token.type === "Punctuator") && (token.value === ","); + } + + /** + * Validates the spacing around single items in lists. + * @param {Token} previousItemToken The last token from the previous item. + * @param {Token} commaToken The token representing the comma. + * @param {Token} currentItemToken The first token of the current item. + * @param {Token} reportItem The item to use when reporting an error. + * @returns {void} + * @private + */ + function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) { + + // if single line + if (isSameLine(commaToken, currentItemToken) && + isSameLine(previousItemToken, commaToken)) { + + return; + + } else if (!isSameLine(commaToken, currentItemToken) && + !isSameLine(previousItemToken, commaToken)) { + + // lone comma + context.report(reportItem, { + line: commaToken.loc.end.line, + column: commaToken.loc.start.column + }, "Bad line breaking before and after ','."); + + } else if (style === "first" && !isSameLine(commaToken, currentItemToken)) { + + context.report(reportItem, "',' should be placed first."); + + } else if (style === "last" && isSameLine(commaToken, currentItemToken)) { + + context.report(reportItem, { + line: commaToken.loc.end.line, + column: commaToken.loc.end.column + }, "',' should be placed last."); + } + } + + /** + * Checks the comma placement with regards to a declaration/property/element + * @param {ASTNode} node The binary expression node to check + * @param {string} property The property of the node containing child nodes. + * @private + * @returns {void} + */ + function validateComma(node, property) { + var items = node[property], + arrayLiteral = (node.type === "ArrayExpression"), + previousItemToken; + + if (items.length > 1 || arrayLiteral) { + + // seed as opening [ + previousItemToken = context.getFirstToken(node); + + items.forEach(function(item) { + var commaToken = item ? context.getTokenBefore(item) : previousItemToken, + currentItemToken = item ? context.getFirstToken(item) : context.getTokenAfter(commaToken), + reportItem = item || currentItemToken; + + /* + * This works by comparing three token locations: + * - previousItemToken is the last token of the previous item + * - commaToken is the location of the comma before the current item + * - currentItemToken is the first token of the current item + * + * These values get switched around if item is undefined. + * previousItemToken will refer to the last token not belonging + * to the current item, which could be a comma or an opening + * square bracket. currentItemToken could be a comma. + * + * All comparisons are done based on these tokens directly, so + * they are always valid regardless of an undefined item. + */ + if (isComma(commaToken)) { + validateCommaItemSpacing(previousItemToken, commaToken, + currentItemToken, reportItem); + } + + previousItemToken = item ? context.getLastToken(item) : previousItemToken; + }); + + /* + * Special case for array literals that have empty last items, such + * as [ 1, 2, ]. These arrays only have two items show up in the + * AST, so we need to look at the token to verify that there's no + * dangling comma. + */ + if (arrayLiteral) { + + var lastToken = context.getLastToken(node), + nextToLastToken = context.getTokenBefore(lastToken); + + if (isComma(nextToLastToken)) { + validateCommaItemSpacing( + context.getTokenBefore(nextToLastToken), + nextToLastToken, + lastToken, + lastToken + ); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + var nodes = {}; + + if (!exceptions.VariableDeclaration) { + nodes.VariableDeclaration = function(node) { + validateComma(node, "declarations"); + }; + } + if (!exceptions.ObjectExpression) { + nodes.ObjectExpression = function(node) { + validateComma(node, "properties"); + }; + } + if (!exceptions.ArrayExpression) { + nodes.ArrayExpression = function(node) { + validateComma(node, "elements"); + }; + } + + return nodes; +}; diff --git a/tools/eslint/lib/rules/complexity.js b/tools/eslint/lib/rules/complexity.js new file mode 100644 index 00000000000000..36c9c1f4670387 --- /dev/null +++ b/tools/eslint/lib/rules/complexity.js @@ -0,0 +1,88 @@ +/** + * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. + * Counts the number of if, conditional, for, whilte, try, switch/case, + * @author Patrick Brosset + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var THRESHOLD = context.options[0]; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store complexity (handling nested functions) + var fns = []; + + // When parsing a new function, store it in our function stack + function startFunction() { + fns.push(1); + } + + function endFunction(node) { + var complexity = fns.pop(), + name = "anonymous"; + + if (node.id) { + name = node.id.name; + } else if (node.parent.type === "MethodDefinition") { + name = node.parent.key.name; + } + + if (complexity > THRESHOLD) { + context.report(node, "Function '{{name}}' has a complexity of {{complexity}}.", { name: name, complexity: complexity }); + } + } + + function increaseComplexity() { + if (fns.length) { + fns[fns.length - 1] ++; + } + } + + function increaseSwitchComplexity(node) { + // Avoiding `default` + if (node.test) { + increaseComplexity(node); + } + } + + function increaseLogicalComplexity(node) { + // Avoiding && + if (node.operator === "||") { + increaseComplexity(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "ArrowFunctionExpression": startFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + + "CatchClause": increaseComplexity, + "ConditionalExpression": increaseComplexity, + "LogicalExpression": increaseLogicalComplexity, + "ForStatement": increaseComplexity, + "ForInStatement": increaseComplexity, + "ForOfStatement": increaseComplexity, + "IfStatement": increaseComplexity, + "SwitchCase": increaseSwitchComplexity, + "WhileStatement": increaseComplexity, + "DoWhileStatement": increaseComplexity + }; + +}; diff --git a/tools/eslint/lib/rules/consistent-return.js b/tools/eslint/lib/rules/consistent-return.js new file mode 100644 index 00000000000000..38adba7f318ea0 --- /dev/null +++ b/tools/eslint/lib/rules/consistent-return.js @@ -0,0 +1,73 @@ +/** + * @fileoverview Rule to flag consistent return values + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var functions = []; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Marks entrance into a function by pushing a new object onto the functions + * stack. + * @returns {void} + * @private + */ + function enterFunction() { + functions.push({}); + } + + /** + * Marks exit of a function by popping off the functions stack. + * @returns {void} + * @private + */ + function exitFunction() { + functions.pop(); + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": enterFunction, + "FunctionDeclaration": enterFunction, + "FunctionExpression": enterFunction, + "ArrowFunctionExpression": enterFunction, + + "Program:exit": exitFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction, + "ArrowFunctionExpression:exit": exitFunction, + + "ReturnStatement": function(node) { + + var returnInfo = functions[functions.length - 1], + returnTypeDefined = "type" in returnInfo; + + if (returnTypeDefined) { + + if (returnInfo.type !== !!node.argument) { + context.report(node, "Expected " + (returnInfo.type ? "a" : "no") + " return value."); + } + + } else { + returnInfo.type = !!node.argument; + } + + } + }; + +}; diff --git a/tools/eslint/lib/rules/consistent-this.js b/tools/eslint/lib/rules/consistent-this.js new file mode 100644 index 00000000000000..3efb2cd372c0f5 --- /dev/null +++ b/tools/eslint/lib/rules/consistent-this.js @@ -0,0 +1,108 @@ +/** + * @fileoverview Rule to enforce consistent naming of "this" context variables + * @author Raphael Pigulla + * @copyright 2015 Timothy Jones. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var alias = context.options[0]; + + /** + * Reports that a variable declarator or assignment expression is assigning + * a non-'this' value to the specified alias. + * @param {ASTNode} node - The assigning node. + * @returns {void} + */ + function reportBadAssignment(node) { + context.report(node, + "Designated alias '{{alias}}' is not assigned to 'this'.", + { alias: alias }); + } + + /** + * Checks that an assignment to an identifier only assigns 'this' to the + * appropriate alias, and the alias is only assigned to 'this'. + * @param {ASTNode} node - The assigning node. + * @param {Identifier} name - The name of the variable assigned to. + * @param {Expression} value - The value of the assignment. + * @returns {void} + */ + function checkAssignment(node, name, value) { + var isThis = value.type === "ThisExpression"; + + if (name === alias) { + if (!isThis || node.operator && node.operator !== "=") { + reportBadAssignment(node); + } + } else if (isThis) { + context.report(node, + "Unexpected alias '{{name}}' for 'this'.", { name: name }); + } + } + + /** + * Ensures that a variable declaration of the alias in a program or function + * is assigned to the correct value. + * @returns {void} + */ + function ensureWasAssigned() { + var scope = context.getScope(); + + scope.variables.some(function (variable) { + var lookup; + + if (variable.name === alias) { + if (variable.defs.some(function (def) { + return def.node.type === "VariableDeclarator" && + def.node.init !== null; + })) { + return true; + } + + lookup = scope.type === "global" ? scope : variable; + + // The alias has been declared and not assigned: check it was + // assigned later in the same scope. + if (!lookup.references.some(function (reference) { + var write = reference.writeExpr; + + if (reference.from === scope && + write && write.type === "ThisExpression" && + write.parent.operator === "=") { + return true; + } + })) { + variable.defs.map(function (def) { + return def.node; + }).forEach(reportBadAssignment); + } + + return true; + } + }); + } + + return { + "Program:exit": ensureWasAssigned, + "FunctionExpression:exit": ensureWasAssigned, + "FunctionDeclaration:exit": ensureWasAssigned, + + "VariableDeclarator": function (node) { + if (node.init !== null) { + checkAssignment(node, node.id.name, node.init); + } + }, + + "AssignmentExpression": function (node) { + if (node.left.type === "Identifier") { + checkAssignment(node, node.left.name, node.right); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/curly.js b/tools/eslint/lib/rules/curly.js new file mode 100644 index 00000000000000..2bfcfb27982e53 --- /dev/null +++ b/tools/eslint/lib/rules/curly.js @@ -0,0 +1,103 @@ +/** + * @fileoverview Rule to flag statements without curly braces + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var multiOnly = (context.options[0] === "multi"); + var multiLine = (context.options[0] === "multi-line"); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a given node is a one-liner that's on the same line as it's preceding code. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code. + * @private + */ + function isCollapsedOneLiner(node) { + var before = context.getTokenBefore(node), + last = context.getLastToken(node); + return before.loc.start.line === last.loc.end.line; + } + + /** + * Checks the body of a node to see if it's a block statement. Depending on + * the rule options, reports the appropriate problems. + * @param {ASTNode} node The node to report if there's a problem. + * @param {ASTNode} body The body node to check for blocks. + * @param {string} name The name to report if there's a problem. + * @param {string} suffix Additional string to add to the end of a report. + * @returns {void} + */ + function checkBody(node, body, name, suffix) { + var hasBlock = (body.type === "BlockStatement"); + + if (multiOnly) { + if (hasBlock && body.body.length === 1) { + context.report(node, "Unnecessary { after '{{name}}'{{suffix}}.", + { + name: name, + suffix: (suffix ? " " + suffix : "") + } + ); + } + } else if (multiLine) { + if (!hasBlock && !isCollapsedOneLiner(body)) { + context.report(node, "Expected { after '{{name}}'{{suffix}}.", + { + name: name, + suffix: (suffix ? " " + suffix : "") + } + ); + } + } else { + if (!hasBlock) { + context.report(node, "Expected { after '{{name}}'{{suffix}}.", + { + name: name, + suffix: (suffix ? " " + suffix : "") + } + ); + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "IfStatement": function(node) { + + checkBody(node, node.consequent, "if", "condition"); + + if (node.alternate && node.alternate.type !== "IfStatement") { + checkBody(node, node.alternate, "else"); + } + + }, + + "WhileStatement": function(node) { + checkBody(node, node.body, "while", "condition"); + }, + + "DoWhileStatement": function (node) { + checkBody(node, node.body, "do"); + }, + + "ForStatement": function(node) { + checkBody(node, node.body, "for", "condition"); + } + }; + +}; diff --git a/tools/eslint/lib/rules/default-case.js b/tools/eslint/lib/rules/default-case.js new file mode 100644 index 00000000000000..da0da1ad7d4567 --- /dev/null +++ b/tools/eslint/lib/rules/default-case.js @@ -0,0 +1,64 @@ +/** + * @fileoverview require default case in switch statements + * @author Aliaksei Shytkin + */ +"use strict"; + +var COMMENT_VALUE = "no default"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Shortcut to get last element of array + * @param {*[]} collection Array + * @returns {*} Last element + */ + function last(collection) { + return collection[collection.length - 1]; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "SwitchStatement": function(node) { + + if (!node.cases.length) { + // skip check of empty switch because there is no easy way + // to extract comments inside it now + return; + } + + var hasDefault = node.cases.some(function(v) { + return v.test === null; + }); + + if (!hasDefault) { + + var comment; + var comments; + + var lastCase = last(node.cases); + comments = context.getComments(lastCase).trailing; + + if (comments.length) { + comment = last(comments); + } + + if (!comment || comment.value.trim() !== COMMENT_VALUE) { + context.report(node, "Expected a default case."); + } + } + } + }; +}; diff --git a/tools/eslint/lib/rules/dot-notation.js b/tools/eslint/lib/rules/dot-notation.js new file mode 100644 index 00000000000000..bf89cbfdf8e4d9 --- /dev/null +++ b/tools/eslint/lib/rules/dot-notation.js @@ -0,0 +1,104 @@ +/** + * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. + * @author Josh Perez + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +var validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/; +var keywords = [ + "this", + "function", + "if", + "return", + "var", + "else", + "for", + "new", + "in", + "typeof", + "while", + "case", + "break", + "try", + "catch", + "delete", + "throw", + "switch", + "continue", + "default", + "instanceof", + "do", + "void", + "finally", + "with", + "debugger", + "implements", + "interface", + "package", + "private", + "protected", + "public", + "static", + "class", + "enum", + "export", + "extends", + "import", + "super", + "true", + "false", + "null", + "abstract", + "boolean", + "byte", + "char", + "const", + "double", + "final", + "float", + "goto", + "int", + "long", + "native", + "short", + "synchronized", + "throws", + "transient", + "volatile" +]; + +module.exports = function(context) { + var options = context.options[0] || {}; + var allowKeywords = options.allowKeywords === void 0 || !!options.allowKeywords; + + var allowPattern; + if (options.allowPattern) { + allowPattern = new RegExp(options.allowPattern); + } + + return { + "MemberExpression": function(node) { + if ( + node.computed && + node.property.type === "Literal" && + validIdentifier.test(node.property.value) && + (allowKeywords || keywords.indexOf("" + node.property.value) === -1) + ) { + if (!(allowPattern && allowPattern.test(node.property.value))) { + context.report(node, "[" + JSON.stringify(node.property.value) + "] is better written in dot notation."); + } + } + if ( + !allowKeywords && + !node.computed && + keywords.indexOf("" + node.property.name) !== -1 + ) { + context.report(node, "." + node.property.name + " is a syntax error."); + } + } + }; +}; diff --git a/tools/eslint/lib/rules/eol-last.js b/tools/eslint/lib/rules/eol-last.js new file mode 100644 index 00000000000000..96c78c18b4585a --- /dev/null +++ b/tools/eslint/lib/rules/eol-last.js @@ -0,0 +1,36 @@ +/** + * @fileoverview Require file to end with single newline. + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function checkBadEOF(node) { + // Get the whole source code, not for node only. + var src = context.getSource(), location = {column: 1}; + + if (src.length === 0) { + return; + } + + if (src[src.length - 1] !== "\n") { + // file is not newline-terminated + location.line = src.split(/\n/g).length; + context.report(node, location, "Newline required at end of file but not found."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/eqeqeq.js b/tools/eslint/lib/rules/eqeqeq.js new file mode 100644 index 00000000000000..e847a8327eb16f --- /dev/null +++ b/tools/eslint/lib/rules/eqeqeq.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Rule to flag statements that use != and == instead of !== and === + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Checks if an expression is a typeof expression + * @param {ASTNode} node The node to check + * @returns {boolean} if the node is a typeof expression + */ + function isTypeOf(node) { + return node.type === "UnaryExpression" && node.operator === "typeof"; + } + + /** + * Checks if either operand of a binary expression is a typeof operation + * @param {ASTNode} node The node to check + * @returns {boolean} if one of the operands is typeof + * @private + */ + function isTypeOfBinary(node) { + return isTypeOf(node.left) || isTypeOf(node.right); + } + + /** + * Checks if operands are literals of the same type (via typeof) + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are of same type + * @private + */ + function areLiteralsAndSameType(node) { + return node.left.type === "Literal" && node.right.type === "Literal" && + typeof node.left.value === typeof node.right.value; + } + + /** + * Checks if one of the operands is a literal null + * @param {ASTNode} node The node to check + * @returns {boolean} if operands are null + * @private + */ + function isNullCheck(node) { + return (node.right.type === "Literal" && node.right.value === null) || + (node.left.type === "Literal" && node.left.value === null); + } + + /** + * Gets the location (line and column) of the binary expression's operator + * @param {ASTNode} node The binary expression node to check + * @param {String} operator The operator to find + * @returns {Object} { line, column } location of operator + * @private + */ + function getOperatorLocation(node) { + var opToken = context.getTokenAfter(node.left); + return {line: opToken.loc.start.line, column: opToken.loc.start.column}; + } + + return { + "BinaryExpression": function(node) { + if (node.operator !== "==" && node.operator !== "!=") { + return; + } + + if (context.options[0] === "smart" && (isTypeOfBinary(node) || + areLiteralsAndSameType(node)) || isNullCheck(node)) { + return; + } + + if (context.options[0] === "allow-null" && isNullCheck(node)) { + return; + } + + context.report( + node, getOperatorLocation(node), + "Expected '{{op}}=' and instead saw '{{op}}'.", + {op: node.operator} + ); + } + }; + +}; diff --git a/tools/eslint/lib/rules/func-names.js b/tools/eslint/lib/rules/func-names.js new file mode 100644 index 00000000000000..eb4d9be10a62ef --- /dev/null +++ b/tools/eslint/lib/rules/func-names.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to warn when a function expression does not have a name. + * @author Kyle T. Nunery + * @copyright 2015 Brandon Mills. All rights reserved. + * @copyright 2014 Kyle T. Nunery. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Determines whether the current FunctionExpression node is a get, set, or + * shorthand method in an object literal or a class. + * @returns {boolean} True if the node is a get, set, or shorthand method. + */ + function isObjectOrClassMethod() { + var parent = context.getAncestors().pop(); + + return (parent.type === "MethodDefinition" || ( + parent.type === "Property" && ( + parent.method || + parent.kind === "get" || + parent.kind === "set" + ) + )); + } + + return { + "FunctionExpression": function(node) { + + var name = node.id && node.id.name; + + if (!name && !isObjectOrClassMethod()) { + context.report(node, "Missing function expression name."); + } + } + }; +}; diff --git a/tools/eslint/lib/rules/func-style.js b/tools/eslint/lib/rules/func-style.js new file mode 100644 index 00000000000000..f54350e76515ef --- /dev/null +++ b/tools/eslint/lib/rules/func-style.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to enforce a particular function style + * @author Nicholas C. Zakas + * @copyright 2013 Nicholas C. Zakas. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var style = context.options[0], + enforceDeclarations = (style === "declaration"); + + return { + + "FunctionDeclaration": function(node) { + if (!enforceDeclarations) { + context.report(node, "Expected a function expression."); + } + }, + + "FunctionExpression": function() { + var parent = context.getAncestors().pop(); + + if (enforceDeclarations && parent.type === "VariableDeclarator") { + context.report(parent, "Expected a function declaration."); + } + }, + + "ArrowFunctionExpression": function() { + var parent = context.getAncestors().pop(); + + if (enforceDeclarations && parent.type === "VariableDeclarator") { + context.report(parent, "Expected a function declaration."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/generator-star-spacing.js b/tools/eslint/lib/rules/generator-star-spacing.js new file mode 100644 index 00000000000000..fe0b82bd1980e2 --- /dev/null +++ b/tools/eslint/lib/rules/generator-star-spacing.js @@ -0,0 +1,83 @@ +/** + * @fileoverview Rule to check the spacing around the * in generator functions. + * @author Jamund Ferguson + * @copyright 2015 Brandon Mills. All rights reserved. + * @copyright 2014 Jamund Ferguson. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var mode = { + before: { before: true, after: false }, + after: { before: false, after: true }, + both: { before: true, after: true }, + neither: { before: false, after: false } + }[context.options[0] || "before"]; + + /** + * Checks the spacing between two tokens before or after the star token. + * @param {string} side Either "before" or "after". + * @param {Token} leftToken `function` keyword token if side is "before", or + * star token if side is "after". + * @param {Token} rightToken Star token if side is "before", or identifier + * token if side is "after". + * @returns {void} + */ + function checkSpacing(side, leftToken, rightToken) { + if (!!(rightToken.range[0] - leftToken.range[1]) !== mode[side]) { + context.report( + leftToken.value === "*" ? leftToken : rightToken, + "{{type}} space {{side}} *.", + { + type: mode[side] ? "Missing" : "Unexpected", + side: side + } + ); + } + } + + /** + * Enforces the spacing around the star if node is a generator function. + * @param {ASTNode} node A function expression or declaration node. + * @returns {void} + */ + function checkFunction(node) { + var isMethod, starToken, tokenBefore, tokenAfter; + + if (!node.generator) { + return; + } + + isMethod = !!context.getAncestors().pop().method; + + if (isMethod) { + starToken = context.getTokenBefore(node, 1); + } else { + starToken = context.getFirstToken(node, 1); + } + + // Only check before when preceded by `function` keyword + tokenBefore = context.getTokenBefore(starToken); + if (tokenBefore.value === "function") { + checkSpacing("before", tokenBefore, starToken); + } + + // Only check after when followed by an identifier + tokenAfter = context.getTokenAfter(starToken); + if (tokenAfter.type === "Identifier") { + checkSpacing("after", starToken, tokenAfter); + } + } + + return { + "FunctionDeclaration": checkFunction, + "FunctionExpression": checkFunction + }; + +}; diff --git a/tools/eslint/lib/rules/generator-star.js b/tools/eslint/lib/rules/generator-star.js new file mode 100644 index 00000000000000..4541e6711c117f --- /dev/null +++ b/tools/eslint/lib/rules/generator-star.js @@ -0,0 +1,70 @@ +/** + * @fileoverview Rule to check for the position of the * in your generator functions + * @author Jamund Ferguson + * @copyright 2014 Jamund Ferguson. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var position = context.options[0] || "end"; + + /** + * Check the position of the star compared to the expected position. + * @param {ASTNode} node - the entire function node + * @returns {void} + */ + function checkStarPosition(node) { + var starToken; + + if (!node.generator) { + return; + } + + // Blocked, pending decision to fix or work around in eslint/espree#36 + if (context.getAncestors().pop().method) { + return; + } + + starToken = context.getFirstToken(node, 1); + + // check for function *name() {} + if (position === "end") { + + // * starts where the next identifier begins + if (starToken.range[1] !== context.getTokenAfter(starToken).range[0]) { + context.report(node, "Expected a space before *."); + } + } + + // check for function* name() {} + if (position === "start") { + + // * begins where the previous identifier ends + if (starToken.range[0] !== context.getTokenBefore(starToken).range[1]) { + context.report(node, "Expected no space before *."); + } + } + + // check for function * name() {} + if (position === "middle") { + + // must be a space before and afer the * + if (starToken.range[0] <= context.getTokenBefore(starToken).range[1] || + starToken.range[1] >= context.getTokenAfter(starToken).range[0]) { + context.report(node, "Expected spaces around *."); + } + } + } + + return { + "FunctionDeclaration": checkStarPosition, + "FunctionExpression": checkStarPosition + }; + +}; diff --git a/tools/eslint/lib/rules/global-strict.js b/tools/eslint/lib/rules/global-strict.js new file mode 100644 index 00000000000000..c16c62db92bf1d --- /dev/null +++ b/tools/eslint/lib/rules/global-strict.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to flag or require global strict mode. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var mode = context.options[0]; + + if (mode === "always") { + + return { + "Program": function(node) { + if (node.body.length > 0) { + var statement = node.body[0]; + + if (!(statement.type === "ExpressionStatement" && statement.expression.value === "use strict")) { + context.report(node, "Use the global form of \"use strict\"."); + } + } + } + }; + + } else { // mode = "never" + + return { + "ExpressionStatement": function(node) { + var parent = context.getAncestors().pop(); + + if (node.expression.value === "use strict" && parent.type === "Program") { + context.report(node, "Use the function form of \"use strict\"."); + } + } + }; + + } + +}; diff --git a/tools/eslint/lib/rules/guard-for-in.js b/tools/eslint/lib/rules/guard-for-in.js new file mode 100644 index 00000000000000..d79651d38c45a0 --- /dev/null +++ b/tools/eslint/lib/rules/guard-for-in.js @@ -0,0 +1,30 @@ +/** + * @fileoverview Rule to flag for-in loops without if statements inside + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ForInStatement": function(node) { + + /* + * If the for-in statement has {}, then the real body is the body + * of the BlockStatement. Otherwise, just use body as provided. + */ + var body = node.body.type === "BlockStatement" ? node.body.body[0] : node.body; + + if (body && body.type !== "IfStatement") { + context.report(node, "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/handle-callback-err.js b/tools/eslint/lib/rules/handle-callback-err.js new file mode 100644 index 00000000000000..f57e4d1752dc17 --- /dev/null +++ b/tools/eslint/lib/rules/handle-callback-err.js @@ -0,0 +1,118 @@ +/** + * @fileoverview Ensure handling of errors when we know they exist. + * @author Jamund Ferguson + * @copyright 2014 Jamund Ferguson. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var errorArgument = context.options[0] || "err"; + var callbacks = []; + var scopes = 0; + + /** + * Checks if the given argument should be interpreted as a regexp pattern. + * @param {string} stringToCheck The string which should be checked. + * @returns {boolean} Whether or not the string should be interpreted as a pattern. + */ + function isPattern(stringToCheck) { + var firstChar = stringToCheck[0]; + return firstChar === "^"; + } + + /** + * Checks if the given name matches the configured error argument. + * @param {string} name The name which should be compared. + * @returns {boolean} Whether or not the given name matches the configured error variable name. + */ + function matchesConfiguredErrorName(name) { + if (isPattern(errorArgument)) { + var regexp = new RegExp(errorArgument); + return regexp.test(name); + } + return name === errorArgument; + } + + /** + * Check the arguments to see if we need to start tracking the error object. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function startFunction(node) { + + // keep track of nested scopes + scopes++; + + // check if the first argument matches our argument name + var firstArg = node.params && node.params[0]; + if (firstArg && matchesConfiguredErrorName(firstArg.name)) { + callbacks.push({handled: false, depth: scopes, errorVariableName: firstArg.name}); + } + } + + /** + * At the end of a function check to see if the error was handled. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function endFunction(node) { + + var callback = callbacks[callbacks.length - 1] || {}; + + // check if a callback is ending, if so pop it off the stack + if (callback.depth === scopes) { + callbacks.pop(); + + // check if there were no handled errors since the last callback + if (!callback.handled) { + context.report(node, "Expected error to be handled."); + } + } + + // less nested functions + scopes--; + + } + + /** + * Check to see if we're handling the error object properly. + * @param {ASTNode} node The AST node to check. + * @returns {void} + */ + function checkForError(node) { + if (callbacks.length > 0) { + var callback = callbacks[callbacks.length - 1] || {}; + + // make sure the node's name matches our error argument name + var isAboutError = node.name === callback.errorVariableName; + + // we don't consider these use cases as "handling" the error + var doNotCount = ["FunctionDeclaration", "ArrowFunctionExpression", "FunctionExpression", "CatchClause"]; + + // make sure this identifier isn't used as part of one of them + var isHandled = doNotCount.indexOf(node.parent.type) === -1; + + if (isAboutError && isHandled) { + // record that this callback handled its error + callback.handled = true; + } + } + } + + return { + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "ArrowFunctionExpression": startFunction, + "Identifier": checkForError, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction + }; + +}; diff --git a/tools/eslint/lib/rules/indent.js b/tools/eslint/lib/rules/indent.js new file mode 100644 index 00000000000000..b0e838e74bb3f7 --- /dev/null +++ b/tools/eslint/lib/rules/indent.js @@ -0,0 +1,464 @@ +/** + * @fileoverview This option sets a specific tab width for your code + * This rule has been ported and modified from JSCS. + * @author Dmitriy Shekhovtsov + * @copyright 2015 Dmitriy Shekhovtsov. All rights reserved. + * @copyright 2013 Dulin Marat and other contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +/*eslint no-use-before-define:[2, "nofunc"]*/ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + // indentation defaults: 4 spaces + var indentChar = " "; + var indentSize = 4; + var options = {indentSwitchCase: false}; + + var lines = null; + var indentStack = [0]; + var linesToCheck = null; + var breakIndents = null; + + if (context.options.length) { + if (context.options[0] === "tab") { + indentChar = "\t"; + indentSize = 1; + } else if (typeof context.options[0] === "number") { + indentSize = context.options[0]; + } + + if (context.options[1]) { + var opts = context.options[1]; + options.indentSwitchCase = opts.indentSwitchCase === true; + } + } + + var blockParents = [ + "IfStatement", + "WhileStatement", + "DoWhileStatement", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "FunctionDeclaration", + "FunctionExpression", + "ArrowExpression", + "CatchClause", + "WithStatement" + ]; + + var indentableNodes = { + BlockStatement: "body", + Program: "body", + ObjectExpression: "properties", + ArrayExpression: "elements", + SwitchStatement: "cases" + }; + + if (options.indentSwitchCase) { + indentableNodes.SwitchCase = "consequent"; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Mark line to be checked + * @param {Number} line - line number + * @returns {void} + */ + function markCheckLine(line) { + linesToCheck[line].check = true; + } + + /** + * Mark line with targeted node to be checked + * @param {ASTNode} checkNode - targeted node + * @returns {void} + */ + function markCheck(checkNode) { + markCheckLine(checkNode.loc.start.line - 1); + } + + /** + * Sets pushing indent of current node + * @param {ASTNode} node - targeted node + * @param {Number} indents - indents count to push + * @returns {void} + */ + function markPush(node, indents) { + linesToCheck[node.loc.start.line - 1].push.push(indents); + } + + /** + * Marks line as outdent, end of block statement for example + * @param {ASTNode} node - targeted node + * @param {Number} outdents - count of outedents in targeted line + * @returns {void} + */ + function markPop(node, outdents) { + linesToCheck[node.loc.end.line - 1].pop.push(outdents); + } + + /** + * Set alt push for current node + * @param {ASTNode} node - targeted node + * @returns {void} + */ + function markPushAlt(node) { + linesToCheck[node.loc.start.line - 1].pushAltLine.push(node.loc.end.line - 1); + } + + /** + * Marks end of node block to be checked + * and marks targeted node as indent pushing + * @param {ASTNode} pushNode - targeted node + * @param {Number} indents - indent count to push + * @returns {void} + */ + function markPushAndEndCheck(pushNode, indents) { + markPush(pushNode, indents); + markCheckLine(pushNode.loc.end.line - 1); + } + + /** + * Mark node as switch case statement + * and set push\pop indentation changes + * @param {ASTNode} caseNode - targeted node + * @param {ASTNode[]} children - consequent child nodes of case node + * @returns {void} + */ + function markCase(caseNode, children) { + var outdentNode = getCaseOutdent(children); + + if (outdentNode) { + // If a case statement has a `break` as a direct child and it is the + // first one encountered, use it as the example for all future case indentation + if (breakIndents === null) { + breakIndents = (caseNode.loc.start.column === outdentNode.loc.start.column) ? 1 : 0; + } + markPop(outdentNode, breakIndents); + } else { + markPop(caseNode, 0); + } + } + + /** + * Mark child nodes to be checked later of targeted node, + * only if child node not in same line as targeted one + * (if child and parent nodes wrote in single line) + * @param {ASTNode} node - targeted node + * @returns {void} + */ + function markChildren(node) { + getChildren(node).forEach(function(childNode) { + if (childNode.loc.start.line !== node.loc.start.line || node.type === "Program") { + markCheck(childNode); + } + }); + } + + /** + * Mark child block as scope pushing and mark to check + * @param {ASTNode} node - target node + * @param {String} property - target node property containing child + * @returns {void} + */ + function markAlternateBlockStatement(node, property) { + var child = node[property]; + if (child && child.type === "BlockStatement") { + markCheck(child); + } + } + + /** + * Checks whether node is multiline or single line + * @param {ASTNode} node - target node + * @returns {boolean} - is multiline node + */ + function isMultiline(node) { + return node.loc.start.line !== node.loc.end.line; + } + + /** + * Get switch case statement outdent node if any + * @param {ASTNode[]} caseChildren - case statement childs + * @returns {ASTNode} - outdent node + */ + function getCaseOutdent(caseChildren) { + var outdentNode; + caseChildren.some(function(node) { + if (node.type === "BreakStatement") { + outdentNode = node; + return true; + } + }); + + return outdentNode; + } + + /** + * Returns block containing node + * @param {ASTNode} node - targeted node + * @returns {ASTNode} - block node + */ + function getBlockNodeToMark(node) { + var parent = node.parent; + + // The parent of an else is the entire if/else block. To avoid over indenting + // in the case of a non-block if with a block else, mark push where the else starts, + // not where the if starts! + if (parent.type === "IfStatement" && parent.alternate === node) { + return node; + } + + // The end line to check of a do while statement needs to be the location of the + // closing curly brace, not the while statement, to avoid marking the last line of + // a multiline while as a line to check. + if (parent.type === "DoWhileStatement") { + return node; + } + + // Detect bare blocks: a block whose parent doesn"t expect blocks in its syntax specifically. + if (blockParents.indexOf(parent.type) === -1) { + return node; + } + + return parent; + } + + /** + * Get node's children + * @param {ASTNode} node - current node + * @returns {ASTNode[]} - children + */ + function getChildren(node) { + var childrenProperty = indentableNodes[node.type]; + return node[childrenProperty]; + } + + /** + * Gets indentation in line `i` + * @param {Number} i - number of line to get indentation + * @returns {Number} - count of indentation symbols + */ + function getIndentationFromLine(i) { + var rNotIndentChar = new RegExp("[^" + indentChar + "]"); + var firstContent = lines[i].search(rNotIndentChar); + if (firstContent === -1) { + firstContent = lines[i].length; + } + return firstContent; + } + + /** + * Compares expected and actual indentation + * and reports any violations + * @param {ASTNode} node - node used only for reporting + * @returns {void} + */ + function checkIndentations(node) { + linesToCheck.forEach(function(line, i) { + var actualIndentation = getIndentationFromLine(i); + var expectedIndentation = getExpectedIndentation(line, actualIndentation); + + if (line.check) { + + if (actualIndentation !== expectedIndentation) { + context.report(node, + {line: i + 1, column: expectedIndentation}, + "Expected indentation of " + expectedIndentation + " characters."); + // correct the indentation so that future lines + // can be validated appropriately + actualIndentation = expectedIndentation; + } + } + + if (line.push.length) { + pushExpectedIndentations(line, actualIndentation); + } + }); + } + + /** + * Counts expected indentation for given line number + * @param {Number} line - line number + * @param {Number} actual - actual indentation + * @returns {number} - expected indentation + */ + function getExpectedIndentation(line, actual) { + var outdent = indentSize * Math.max.apply(null, line.pop); + + var idx = indentStack.length - 1; + var expected = indentStack[idx]; + + if (!Array.isArray(expected)) { + expected = [expected]; + } + + expected = expected.map(function(value) { + if (line.pop.length) { + value -= outdent; + } + + return value; + }).reduce(function(previous, current) { + // when the expected is an array, resolve the value + // back into a Number by checking both values are the actual indentation + return actual === current ? current : previous; + }); + + indentStack[idx] = expected; + + line.pop.forEach(function() { + indentStack.pop(); + }); + + return expected; + } + + /** + * Store in stack expected indentations + * @param {Number} line - current line + * @param {Number} actualIndentation - actual indentation at current line + * @returns {void} + */ + function pushExpectedIndentations(line, actualIndentation) { + var indents = Math.max.apply(null, line.push); + var expected = actualIndentation + (indentSize * indents); + + // when a line has alternate indentations, push an array of possible values + // on the stack, to be resolved when checked against an actual indentation + if (line.pushAltLine.length) { + expected = [expected]; + line.pushAltLine.forEach(function(altLine) { + expected.push(getIndentationFromLine(altLine) + (indentSize * indents)); + }); + } + + line.push.forEach(function() { + indentStack.push(expected); + }); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program": function (node) { + lines = context.getSourceLines(); + linesToCheck = lines.map(function () { + return { + push: [], + pushAltLine: [], + pop: [], + check: false + }; + }); + + if (!isMultiline(node)) { + return; + } + + markChildren(node); + }, + "Program:exit": function (node) { + checkIndentations(node); + }, + + "BlockStatement": function (node) { + if (!isMultiline(node)) { + return; + } + + markChildren(node); + markPop(node, 1); + + markPushAndEndCheck(getBlockNodeToMark(node), 1); + }, + + "IfStatement": function (node) { + markAlternateBlockStatement(node, "alternate"); + }, + + "TryStatement": function (node) { + markAlternateBlockStatement(node, "handler"); + markAlternateBlockStatement(node, "finalizer"); + }, + + "SwitchStatement": function (node) { + if (!isMultiline(node)) { + return; + } + + var indents = 1; + var children = getChildren(node); + + if (children.length && node.loc.start.column === children[0].loc.start.column) { + indents = 0; + } + + markChildren(node); + markPop(node, indents); + markPushAndEndCheck(node, indents); + }, + + "SwitchCase": function (node) { + if (!options.indentSwitchCase) { + return; + } + + if (!isMultiline(node)) { + return; + } + + var children = getChildren(node); + + if (children.length === 1 && children[0].type === "BlockStatement") { + return; + } + + markPush(node, 1); + markCheck(node); + markChildren(node); + + markCase(node, children); + }, + + // indentations inside of function expressions can be offset from + // either the start of the function or the end of the function, therefore + // mark all starting lines of functions as potential indentations + "FunctionDeclaration": function (node) { + markPushAlt(node); + }, + "FunctionExpression": function (node) { + markPushAlt(node); + } + }; + +}; diff --git a/tools/eslint/lib/rules/key-spacing.js b/tools/eslint/lib/rules/key-spacing.js new file mode 100644 index 00000000000000..3ffaf9302fc660 --- /dev/null +++ b/tools/eslint/lib/rules/key-spacing.js @@ -0,0 +1,307 @@ +/** + * @fileoverview Rule to specify spacing of object literal keys and values + * @author Brandon Mills + * @copyright 2014 Brandon Mills. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether a string contains a line terminator as defined in + * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 + * @param {string} str String to test. + * @returns {boolean} True if str contains a line terminator. + */ +function containsLineTerminator(str) { + return /[\n\r\u2028\u2029]/.test(str); +} + +/** + * Gets the last element of an array. + * @param {Array} arr An array. + * @returns {any} Last element of arr. + */ +function last(arr) { + return arr[arr.length - 1]; +} + +/** + * Checks whether a property is a member of the property group it follows. + * @param {ASTNode} lastMember The last Property known to be in the group. + * @param {ASTNode} candidate The next Property that might be in the group. + * @returns {boolean} True if the candidate property is part of the group. + */ +function continuesPropertyGroup(lastMember, candidate) { + var groupEndLine = lastMember.loc.end.line, + candidateStartLine = candidate.loc.start.line, + comments, i; + + if (candidateStartLine - groupEndLine <= 1) { + return true; + } + + // Check that the first comment is adjacent to the end of the group, the + // last comment is adjacent to the candidate property, and that successive + // comments are adjacent to each other. + comments = candidate.leadingComments; + if ( + comments && + comments[0].loc.start.line - groupEndLine <= 1 && + candidateStartLine - last(comments).loc.end.line <= 1 + ) { + for (i = 1; i < comments.length; i++) { + if (comments[i].loc.start.line - comments[i - 1].loc.end.line > 1) { + return false; + } + } + return true; + } + + return false; +} + +/** + * Checks whether a node is contained on a single line. + * @param {ASTNode} node AST Node being evaluated. + * @returns {boolean} True if the node is a single line. + */ +function isSingleLine(node) { + return (node.loc.end.line === node.loc.start.line); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +var messages = { + key: "{{error}} space after {{computed}}key \"{{key}}\".", + value: "{{error}} space before value for {{computed}}key \"{{key}}\"." +}; + +module.exports = function(context) { + + /** + * OPTIONS + * "key-spacing": [2, { + * beforeColon: false, + * afterColon: true, + * align: "colon" // Optional, or "value" + * } + */ + + var options = context.options[0] || {}, + align = options.align, + beforeColon = +!!options.beforeColon, // Defaults to false + afterColon = +!(options.afterColon === false); // Defaults to true + + /** + * Gets an object literal property's key as the identifier name or string value. + * @param {ASTNode} property Property node whose key to retrieve. + * @returns {string} The property's key. + */ + function getKey(property) { + var key = property.key; + + if (property.computed) { + return context.getSource().slice(key.range[0], key.range[1]); + } + + return property.key.name || property.key.value; + } + + /** + * Reports an appropriately-formatted error if spacing is incorrect on one + * side of the colon. + * @param {ASTNode} property Key-value pair in an object literal. + * @param {string} side Side being verified - either "key" or "value". + * @param {string} whitespace Actual whitespace string. + * @param {int} expected Expected whitespace length. + * @returns {void} + */ + function report(property, side, whitespace, expected) { + var diff = whitespace.length - expected, + key = property.key, + firstTokenAfterColon = context.getTokenAfter(key, 1), + location = side === "key" ? key.loc.start : firstTokenAfterColon.loc.start; + + if (diff && !(expected && containsLineTerminator(whitespace))) { + context.report(property[side], location, messages[side], { + error: diff > 0 ? "Extra" : "Missing", + computed: property.computed ? "computed " : "", + key: getKey(property) + }); + } + } + + /** + * Gets the number of characters in a key, including quotes around string + * keys and braces around computed property keys. + * @param {ASTNode} property Property of on object literal. + * @returns {int} Width of the key. + */ + function getKeyWidth(property) { + var key = property.key, + startToken, endToken; + + // [computed]: value + if (property.computed) { + startToken = context.getTokenBefore(key); + endToken = context.getTokenAfter(key); + return endToken.range[1] - startToken.range[0]; + } + + // name: value + if (key.type === "Identifier") { + return key.name.length; + } + + // "literal": value + // 42: value + if (key.type === "Literal") { + return key.raw.length; + } + } + + /** + * Gets the whitespace around the colon in an object literal property. + * @param {ASTNode} property Property node from an object literal. + * @returns {Object} Whitespace before and after the property's colon. + */ + function getPropertyWhitespace(property) { + var whitespace = /(\s*):(\s*)/.exec(context.getSource().slice( + property.key.range[1], property.value.range[0] + )); + + if (whitespace) { + return { + beforeColon: whitespace[1], + afterColon: whitespace[2] + }; + } + } + + /** + * Creates groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {Array.} Groups of property AST node lists. + */ + function createGroups(node) { + if (node.properties.length === 1) { + return [node.properties]; + } + + return node.properties.reduce(function(groups, property) { + var currentGroup = last(groups), + prev = last(currentGroup); + + if (!prev || continuesPropertyGroup(prev, property)) { + currentGroup.push(property); + } else { + groups.push([property]); + } + + return groups; + }, [[]]); + } + + /** + * Verifies correct vertical alignment of a group of properties. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {void} + */ + function verifyGroupAlignment(properties) { + var length = properties.length, + widths = properties.map(getKeyWidth), // Width of keys, including quotes + targetWidth = Math.max.apply(null, widths), + i, property, whitespace, width; + + // Conditionally include one space before or after colon + targetWidth += (align === "colon" ? beforeColon : afterColon); + + for (i = 0; i < length; i++) { + property = properties[i]; + whitespace = getPropertyWhitespace(property); + + if (!whitespace) { + continue; // Object literal getters/setters lack a colon + } + + width = widths[i]; + + if (align === "value") { + report(property, "key", whitespace.beforeColon, beforeColon); + report(property, "value", whitespace.afterColon, targetWidth - width); + } else { // align = "colon" + report(property, "key", whitespace.beforeColon, targetWidth - width); + report(property, "value", whitespace.afterColon, afterColon); + } + } + } + + /** + * Verifies vertical alignment, taking into account groups of properties. + * @param {ASTNode} node ObjectExpression node being evaluated. + * @returns {void} + */ + function verifyAlignment(node) { + createGroups(node).forEach(function(group) { + verifyGroupAlignment(group); + }); + } + + /** + * Verifies spacing of property conforms to specified options. + * @param {ASTNode} node Property node being evaluated. + * @returns {void} + */ + function verifySpacing(node) { + var whitespace = getPropertyWhitespace(node); + if (whitespace) { // Object literal getters/setters lack colons + report(node, "key", whitespace.beforeColon, beforeColon); + report(node, "value", whitespace.afterColon, afterColon); + } + } + + /** + * Verifies spacing of each property in a list. + * @param {ASTNode[]} properties List of Property AST nodes. + * @returns {void} + */ + function verifyListSpacing(properties) { + var length = properties.length; + + for (var i = 0; i < length; i++) { + verifySpacing(properties[i]); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + if (align) { // Verify vertical alignment + + return { + "ObjectExpression": function(node) { + if (isSingleLine(node)) { + verifyListSpacing(node.properties); + } else { + verifyAlignment(node); + } + } + }; + + } else { // Strictly obey beforeColon and afterColon in each property + + return { + "Property": function (node) { + verifySpacing(node); + } + }; + + } + +}; diff --git a/tools/eslint/lib/rules/max-depth.js b/tools/eslint/lib/rules/max-depth.js new file mode 100644 index 00000000000000..cc7e3662572ae1 --- /dev/null +++ b/tools/eslint/lib/rules/max-depth.js @@ -0,0 +1,83 @@ +/** + * @fileoverview A rule to set the maximum depth block can be nested in a function. + * @author Ian Christian Myers + * @copyright 2013 Ian Christian Myers. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var functionStack = [], + maxDepth = context.options[0] || 4; + + function startFunction() { + functionStack.push(0); + } + + function endFunction() { + functionStack.pop(); + } + + function pushBlock(node) { + var len = ++functionStack[functionStack.length - 1]; + + if (len > maxDepth) { + context.report(node, "Blocks are nested too deeply ({{depth}}).", + { depth: len }); + } + } + + function popBlock() { + functionStack[functionStack.length - 1]--; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "Program": startFunction, + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "ArrowFunctionExpression": startFunction, + + "IfStatement": function(node) { + if (node.parent.type !== "IfStatement") { + pushBlock(node); + } + }, + "SwitchStatement": pushBlock, + "TryStatement": pushBlock, + "DoWhileStatement": pushBlock, + "WhileStatement": pushBlock, + "WithStatement": pushBlock, + "ForStatement": pushBlock, + "ForInStatement": pushBlock, + "ForOfStatement": pushBlock, + + "IfStatement:exit": popBlock, + "SwitchStatement:exit": popBlock, + "TryStatement:exit": popBlock, + "DoWhileStatement:exit": popBlock, + "WhileStatement:exit": popBlock, + "WithStatement:exit": popBlock, + "ForStatement:exit": popBlock, + "ForInStatement:exit": popBlock, + "ForOfStatement:exit": popBlock, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction, + "Program:exit": endFunction + }; + +}; diff --git a/tools/eslint/lib/rules/max-len.js b/tools/eslint/lib/rules/max-len.js new file mode 100644 index 00000000000000..a36dd73b1bb938 --- /dev/null +++ b/tools/eslint/lib/rules/max-len.js @@ -0,0 +1,65 @@ +/** + * @fileoverview Rule to check for max length on a line. + * @author Matt DuVall + * @copyright 2013 Matt DuVall. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Creates a string that is made up of repeating a given string a certain + * number of times. This uses exponentiation of squares to achieve significant + * performance gains over the more traditional implementation of such + * functionality. + * @param {string} str The string to repeat. + * @param {int} num The number of times to repeat the string. + * @returns {string} The created string. + * @private + */ + function stringRepeat(str, num) { + var result = ""; + for (num |= 0; num > 0; num >>>= 1, str += str) { + if (num & 1) { + result += str; + } + } + return result; + } + + var tabWidth = context.options[1]; + + var maxLength = context.options[0], + tabString = stringRepeat(" ", tabWidth); + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + function checkProgramForMaxLength(node) { + var lines = context.getSourceLines(); + + // Replace the tabs + // Split (honors line-ending) + // Iterate + lines.forEach(function(line, i) { + if (line.replace(/\t/g, tabString).length > maxLength) { + context.report(node, { line: i + 1, col: 1 }, "Line " + (i + 1) + " exceeds the maximum line length of " + maxLength + "."); + } + }); + } + + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "Program": checkProgramForMaxLength + }; + +}; diff --git a/tools/eslint/lib/rules/max-nested-callbacks.js b/tools/eslint/lib/rules/max-nested-callbacks.js new file mode 100644 index 00000000000000..590274ffd1c3b3 --- /dev/null +++ b/tools/eslint/lib/rules/max-nested-callbacks.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to enforce a maximum number of nested callbacks. + * @author Ian Christian Myers + * @copyright 2013 Ian Christian Myers. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Constants + //-------------------------------------------------------------------------- + + var THRESHOLD = context.options[0]; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var callbackStack = []; + + /** + * Checks a given function node for too many callbacks. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + var parent = node.parent; + + if (parent.type === "CallExpression") { + callbackStack.push(node); + } + + if (callbackStack.length > THRESHOLD) { + var opts = {num: callbackStack.length, max: THRESHOLD}; + context.report(node, "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}.", opts); + } + } + + /** + * Pops the call stack. + * @returns {void} + * @private + */ + function popStack() { + callbackStack.pop(); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "ArrowFunctionExpression": checkFunction, + "ArrowFunctionExpression:exit": popStack, + + "FunctionExpression": checkFunction, + "FunctionExpression:exit": popStack + }; + +}; diff --git a/tools/eslint/lib/rules/max-params.js b/tools/eslint/lib/rules/max-params.js new file mode 100644 index 00000000000000..931548932f5031 --- /dev/null +++ b/tools/eslint/lib/rules/max-params.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Rule to flag when a function has too many parameters + * @author Ilya Volodin + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var numParams = context.options[0] || 3; + + /** + * Checks a function to see if it has too many parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + if (node.params.length > numParams) { + context.report(node, "This function has too many parameters ({{count}}). Maximum allowed is {{max}}.", { + count: node.params.length, + max: numParams + }); + } + } + + return { + "FunctionDeclaration": checkFunction, + "ArrowFunctionExpression": checkFunction, + "FunctionExpression": checkFunction + }; + +}; diff --git a/tools/eslint/lib/rules/max-statements.js b/tools/eslint/lib/rules/max-statements.js new file mode 100644 index 00000000000000..9fe11bfd91d8bc --- /dev/null +++ b/tools/eslint/lib/rules/max-statements.js @@ -0,0 +1,55 @@ +/** + * @fileoverview A rule to set the maximum number of statements in a function. + * @author Ian Christian Myers + * @copyright 2013 Ian Christian Myers. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var functionStack = [], + maxStatements = context.options[0] || 10; + + function startFunction() { + functionStack.push(0); + } + + function endFunction(node) { + var count = functionStack.pop(); + + if (count > maxStatements) { + context.report(node, "This function has too many statements ({{count}}). Maximum allowed is {{max}}.", + { count: count, max: maxStatements }); + } + } + + function countStatements(node) { + functionStack[functionStack.length - 1] += node.body.length; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "ArrowFunctionExpression": startFunction, + + "BlockStatement": countStatements, + + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction + }; + +}; diff --git a/tools/eslint/lib/rules/new-cap.js b/tools/eslint/lib/rules/new-cap.js new file mode 100644 index 00000000000000..1474fc80289cbb --- /dev/null +++ b/tools/eslint/lib/rules/new-cap.js @@ -0,0 +1,197 @@ +/** + * @fileoverview Rule to flag use of constructors without capital letters + * @author Nicholas C. Zakas + * @copyright 2014 Jordan Harband. All rights reserved. + * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved. + */ + +"use strict"; + +var CAPS_ALLOWED = [ + "Array", + "Boolean", + "Date", + "Error", + "Function", + "Number", + "Object", + "RegExp", + "String", + "Symbol" +]; + +/** + * Ensure that if the key is provided, it must be an array. + * @param {Object} obj Object to check with `key`. + * @param {string} key Object key to check on `obj`. + * @param {*} fallback If obj[key] is not present, this will be returned. + * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback` + */ +function checkArray(obj, key, fallback) { + if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) { + throw new TypeError(key + ", if provided, must be an Array"); + } + return obj[key] || fallback; +} + +/** + * A reducer function to invert an array to an Object mapping the string form of the key, to `true`. + * @param {Object} map Accumulator object for the reduce. + * @param {string} key Object key to set to `true`. + * @returns {Object} Returns the updated Object for further reduction. + */ +function invert(map, key) { + map[key] = true; + return map; +} + +/** + * Creates an object with the cap is new exceptions as its keys and true as their values. + * @param {Object} config Rule configuration + * @returns {Object} Object with cap is new exceptions. + */ +function calculateCapIsNewExceptions(config) { + var capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED); + + if (capIsNewExceptions !== CAPS_ALLOWED) { + capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED); + } + + return capIsNewExceptions.reduce(invert, {}); +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var config = context.options[0] || {}; + config.newIsCap = config.newIsCap === false ? false : true; + config.capIsNew = config.capIsNew === false ? false : true; + + var newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {}); + + var capIsNewExceptions = calculateCapIsNewExceptions(config); + + var listeners = {}; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Get exact callee name from expression + * @param {ASTNode} node CallExpression or NewExpression node + * @returns {string} name + */ + function extractNameFromExpression(node) { + + var name = "", + property; + + if (node.callee.type === "MemberExpression") { + property = node.callee.property; + + if (property.type === "Literal" && (typeof property.value === "string")) { + name = property.value; + } else if (property.type === "Identifier" && !node.callee.computed) { + name = property.name; + } + } else { + name = node.callee.name; + } + return name; + } + + /** + * Returns the capitalization state of the string - + * Whether the first character is uppercase, lowercase, or non-alphabetic + * @param {string} str String + * @returns {string} capitalization state: "non-alpha", "lower", or "upper" + */ + function getCap(str) { + var firstChar = str.charAt(0); + + var firstCharLower = firstChar.toLowerCase(); + var firstCharUpper = firstChar.toUpperCase(); + + if (firstCharLower === firstCharUpper) { + // char has no uppercase variant, so it's non-alphabetic + return "non-alpha"; + } else if (firstChar === firstCharLower) { + return "lower"; + } else { + return "upper"; + } + } + + /** + * Check if capitalization is allowed for a CallExpression + * @param {Object} allowedMap Object mapping calleeName to a Boolean + * @param {ASTNode} node CallExpression node + * @param {string} calleeName Capitalized callee name from a CallExpression + * @returns {Boolean} Returns true if the callee may be capitalized + */ + function isCapAllowed(allowedMap, node, calleeName) { + if (allowedMap[calleeName]) { + return true; + } + if (calleeName === "UTC" && node.callee.type === "MemberExpression") { + // allow if callee is Date.UTC + return node.callee.object.type === "Identifier" && + node.callee.object.name === "Date"; + } + return false; + } + + /** + * Reports the given message for the given node. The location will be the start of the property or the callee. + * @param {ASTNode} node CallExpression or NewExpression node. + * @param {string} message The message to report. + * @returns {void} + */ + function report(node, message) { + var callee = node.callee; + + if (callee.type === "MemberExpression") { + callee = callee.property; + } + + context.report(node, callee.loc.start, message); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + if (config.newIsCap) { + listeners.NewExpression = function(node) { + + var constructorName = extractNameFromExpression(node); + if (constructorName) { + var capitalization = getCap(constructorName); + var isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName); + if (!isAllowed) { + report(node, "A constructor name should not start with a lowercase letter."); + } + } + }; + } + + if (config.capIsNew) { + listeners.CallExpression = function(node) { + + var calleeName = extractNameFromExpression(node); + if (calleeName) { + var capitalization = getCap(calleeName); + var isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName); + if (!isAllowed) { + report(node, "A function with a name starting with an uppercase letter should only be used as a constructor."); + } + } + }; + } + + return listeners; +}; diff --git a/tools/eslint/lib/rules/new-parens.js b/tools/eslint/lib/rules/new-parens.js new file mode 100644 index 00000000000000..adc2f70c92f6cc --- /dev/null +++ b/tools/eslint/lib/rules/new-parens.js @@ -0,0 +1,27 @@ +/** + * @fileoverview Rule to flag when using constructor without parentheses + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "NewExpression": function(node) { + var tokens = context.getTokens(node); + var prenticesTokens = tokens.filter(function(token) { + return token.value === "(" || token.value === ")"; + }); + if (prenticesTokens.length < 2) { + context.report(node, "Missing '()' invoking a constructor"); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/newline-after-var.js b/tools/eslint/lib/rules/newline-after-var.js new file mode 100644 index 00000000000000..7a6c3cff2fb059 --- /dev/null +++ b/tools/eslint/lib/rules/newline-after-var.js @@ -0,0 +1,121 @@ +/** + * @fileoverview Rule to check empty newline after "var" statement + * @author Gopal Venkatesan + * @copyright 2015 Gopal Venkatesan. All rights reserved. + * @copyright 2015 Casey Visco. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var ALWAYS_MESSAGE = "Expected blank line after variable declarations.", + NEVER_MESSAGE = "Unexpected blank line after variable declarations."; + + // Default `mode` to "always". This means that invalid options will also + // be treated as "always" and the only special case is "never" + var mode = context.options[0] === "never" ? "never" : "always"; + + // Cache line numbers of comments for faster lookup + var comments = context.getAllComments().map(function (token) { + return token.loc.start.line; + }); + + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determine if provided keyword is a variable declaration + * @private + * @param {string} keyword - keyword to test + * @returns {boolean} True if `keyword` is a type of var + */ + function isVar(keyword) { + return keyword === "var" || keyword === "let" || keyword === "const"; + } + + /** + * Determine if provided keyword is a variant of for specifiers + * @private + * @param {string} keyword - keyword to test + * @returns {boolean} True if `keyword` is a variant of for specifier + */ + function isForTypeSpecifier(keyword) { + return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; + } + + /** + * Determine if provided keyword is an export specifiers + * @private + * @param {string} nodeType - nodeType to test + * @returns {boolean} True if `nodeType` is an export specifier + */ + function isExportSpecifier(nodeType) { + return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" || + nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration"; + } + + /** + * Checks that a blank line exists after a variable declaration when mode is + * set to "always", or checks that there is no blank line when mode is set + * to "never" + * @private + * @param {ASTNode} node - `VariableDeclaration` node to test + * @returns {void} + */ + function checkForBlankLine(node) { + var lastToken = context.getLastToken(node), + nextToken = context.getTokenAfter(node), + nextLineNum = lastToken.loc.end.line + 1, + noNextLineToken, + hasNextLineComment; + + // Ignore if there is no following statement + if (!nextToken) { + return; + } + + // Ignore if parent of node is a for variant + if (isForTypeSpecifier(node.parent.type)) { + return; + } + + // Ignore if parent of node is an export specifier + if (isExportSpecifier(node.parent.type)) { + return; + } + + // Some coding styles use multiple `var` statements, so do nothing if + // the next token is a `var` statement. + if (nextToken.type === "Keyword" && isVar(nextToken.value)) { + return; + } + + // Next statement is not a `var`... + noNextLineToken = nextToken.loc.start.line > nextLineNum; + hasNextLineComment = comments.indexOf(nextLineNum) >= 0; + + if (mode === "never" && noNextLineToken && !hasNextLineComment) { + context.report(node, NEVER_MESSAGE, { identifier: node.name }); + } + + if (mode === "always" && (!noNextLineToken || hasNextLineComment)) { + context.report(node, ALWAYS_MESSAGE, { identifier: node.name }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration": checkForBlankLine + }; + +}; diff --git a/tools/eslint/lib/rules/no-alert.js b/tools/eslint/lib/rules/no-alert.js new file mode 100644 index 00000000000000..1f14b533d71a13 --- /dev/null +++ b/tools/eslint/lib/rules/no-alert.js @@ -0,0 +1,54 @@ +/** + * @fileoverview Rule to flag use of alert, confirm, prompt + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +function matchProhibited(name) { + return name.match(/^(alert|confirm|prompt)$/); +} + +function report(context, node, result) { + context.report(node, "Unexpected {{name}}.", { name: result[1] }); +} + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "CallExpression": function(node) { + + var result; + + // without window. + if (node.callee.type === "Identifier") { + + result = matchProhibited(node.callee.name); + + if (result) { + report(context, node, result); + } + + } else if (node.callee.type === "MemberExpression" && node.callee.property.type === "Identifier") { + + result = matchProhibited(node.callee.property.name); + + if (result && node.callee.object.name === "window") { + report(context, node, result); + } + + } + + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-array-constructor.js b/tools/eslint/lib/rules/no-array-constructor.js new file mode 100644 index 00000000000000..a37d674c807ece --- /dev/null +++ b/tools/eslint/lib/rules/no-array-constructor.js @@ -0,0 +1,29 @@ +/** + * @fileoverview Disallow construction of dense arrays using the Array constructor + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function check(node) { + if ( + node.arguments.length !== 1 && + node.callee.type === "Identifier" && + node.callee.name === "Array" + ) { + context.report(node, "The array literal notation [] is preferrable."); + } + } + + return { + "CallExpression": check, + "NewExpression": check + }; + +}; diff --git a/tools/eslint/lib/rules/no-bitwise.js b/tools/eslint/lib/rules/no-bitwise.js new file mode 100644 index 00000000000000..942317f3d0eebd --- /dev/null +++ b/tools/eslint/lib/rules/no-bitwise.js @@ -0,0 +1,55 @@ +/** + * @fileoverview Rule to flag bitwise identifiers + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var BITWISE_OPERATORS = [ + "^", "|", "&", "<<", ">>", ">>>", + "^=", "|=", "&=", "<<=", ">>=", ">>>=", + "~" + ]; + + /** + * Reports an unexpected use of a bitwise operator. + * @param {ASTNode} node Node which contains the bitwise operator. + * @returns {void} + */ + function report(node) { + context.report(node, "Unexpected use of '{{operator}}'.", { operator: node.operator }); + } + + /** + * Checks if the given node has a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {boolean} Whether or not the node has a bitwise operator. + */ + function hasBitwiseOperator(node) { + return BITWISE_OPERATORS.indexOf(node.operator) !== -1; + } + + /** + * Report if the given node contains a bitwise operator. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNodeForBitwiseOperator(node) { + if (hasBitwiseOperator(node)) { + report(node); + } + } + + return { + "AssignmentExpression": checkNodeForBitwiseOperator, + "BinaryExpression": checkNodeForBitwiseOperator, + "UnaryExpression": checkNodeForBitwiseOperator + }; + +}; diff --git a/tools/eslint/lib/rules/no-caller.js b/tools/eslint/lib/rules/no-caller.js new file mode 100644 index 00000000000000..b489d79c548a50 --- /dev/null +++ b/tools/eslint/lib/rules/no-caller.js @@ -0,0 +1,27 @@ +/** + * @fileoverview Rule to flag use of arguments.callee and arguments.caller. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + var objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/)) { + context.report(node, "Avoid arguments.{{property}}.", { property: propertyName }); + } + + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-catch-shadow.js b/tools/eslint/lib/rules/no-catch-shadow.js new file mode 100644 index 00000000000000..af07c462920930 --- /dev/null +++ b/tools/eslint/lib/rules/no-catch-shadow.js @@ -0,0 +1,50 @@ +/** + * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + function paramIsShadowing(scope, name) { + var found = scope.variables.some(function(variable) { + return variable.name === name; + }); + + if (found) { + return true; + } + + if (scope.upper) { + return paramIsShadowing(scope.upper, name); + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "CatchClause": function(node) { + var scope = context.getScope(); + + if (paramIsShadowing(scope, node.param.name)) { + context.report(node, "Value of '{{name}}' may be overwritten in IE 8 and earlier.", + { name: node.param.name }); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-comma-dangle.js b/tools/eslint/lib/rules/no-comma-dangle.js new file mode 100644 index 00000000000000..32b2a73658edaa --- /dev/null +++ b/tools/eslint/lib/rules/no-comma-dangle.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to flag trailing commas in object literals. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + function checkForTrailingComma(node) { + var items = node.properties || node.elements, + length = items.length, + lastItem, penultimateToken; + + if (length) { + lastItem = items[length - 1]; + if (lastItem) { + penultimateToken = context.getLastToken(node, 1); + if (penultimateToken.value === ",") { + context.report(lastItem, penultimateToken.loc.start, "Trailing comma."); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "ObjectExpression": checkForTrailingComma, + "ArrayExpression": checkForTrailingComma + }; + +}; diff --git a/tools/eslint/lib/rules/no-cond-assign.js b/tools/eslint/lib/rules/no-cond-assign.js new file mode 100644 index 00000000000000..9b00fe4e32beba --- /dev/null +++ b/tools/eslint/lib/rules/no-cond-assign.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule to flag assignment in a conditional statement's test expression + * @author Stephen Murray + */ +"use strict"; + +var NODE_DESCRIPTIONS = { + "DoWhileStatement": "a 'do...while' statement", + "ForStatement": "a 'for' statement", + "IfStatement": "an 'if' statement", + "WhileStatement": "a 'while' statement" +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var prohibitAssign = (context.options[0] || "except-parens"); + + /** + * Check whether an AST node is the test expression for a conditional statement. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`. + */ + function isConditionalTestExpression(node) { + return node.parent && + node.parent.test && + node === node.parent.test; + } + + /** + * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. + * @param {!Object} node The node to use at the start of the search. + * @returns {?Object} The closest ancestor node that represents a conditional statement. + */ + function findConditionalAncestor(node) { + var currentAncestor = node; + + while ((currentAncestor = currentAncestor.parent)) { + if (isConditionalTestExpression(currentAncestor)) { + return currentAncestor.parent; + } + } + + return null; + } + + /** + * Check whether the code represented by an AST node is enclosed in parentheses. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the code is enclosed in parentheses; otherwise, `false`. + */ + function isParenthesised(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + + return previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + /** + * Check whether the code represented by an AST node is enclosed in two sets of parentheses. + * @param {!Object} node The node to test. + * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`. + */ + function isParenthesisedTwice(node) { + var previousToken = context.getTokenBefore(node, 1), + nextToken = context.getTokenAfter(node, 1); + + return isParenthesised(node) && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + /** + * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses. + * @param {!Object} node The node for the conditional statement. + * @returns {void} + */ + function testForAssign(node) { + if (node.test && (node.test.type === "AssignmentExpression") && !isParenthesisedTwice(node.test)) { + // must match JSHint's error message + context.report(node, "Expected a conditional expression and instead saw an assignment."); + } + } + + /** + * Check whether an assignment expression is descended from a conditional statement's test expression. + * @param {!Object} node The node for the assignment expression. + * @returns {void} + */ + function testForConditionalAncestor(node) { + var ancestor = findConditionalAncestor(node); + + if (ancestor) { + context.report(ancestor, "Unexpected assignment within {{type}}.", { + type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type + }); + } + } + + if (prohibitAssign === "always") { + return { + "AssignmentExpression": testForConditionalAncestor + }; + } + + return { + "DoWhileStatement": testForAssign, + "ForStatement": testForAssign, + "IfStatement": testForAssign, + "WhileStatement": testForAssign + }; + +}; diff --git a/tools/eslint/lib/rules/no-console.js b/tools/eslint/lib/rules/no-console.js new file mode 100644 index 00000000000000..929f00045ede5a --- /dev/null +++ b/tools/eslint/lib/rules/no-console.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Rule to flag use of console object + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + + if (node.object.name === "console") { + context.report(node, "Unexpected console statement."); + } + + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-constant-condition.js b/tools/eslint/lib/rules/no-constant-condition.js new file mode 100644 index 00000000000000..394a9c9bb8bacd --- /dev/null +++ b/tools/eslint/lib/rules/no-constant-condition.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Rule to flag use constant conditions + * @author Christian Schulz + * @copyright 2014 Christian Schulz. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if a node has a constant truthiness value. + * @param {ASTNode} node The AST node to check. + * @returns {Bool} true when node's truthiness is constant + * @private + */ + function isConstant(node) { + switch (node.type) { + case "Literal": + case "ArrowFunctionExpression": + case "FunctionExpression": + case "ObjectExpression": + case "ArrayExpression": + return true; + case "UnaryExpression": + return isConstant(node.argument); + case "BinaryExpression": + case "LogicalExpression": + return isConstant(node.left) && isConstant(node.right); + case "AssignmentExpression": + return (node.operator === "=") && isConstant(node.right); + case "SequenceExpression": + return isConstant(node.expressions[node.expressions.length - 1]); + // no default + } + return false; + } + + /** + * Reports when the given node contains a constant condition. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkConstantCondition(node) { + if (node.test && isConstant(node.test)) { + context.report(node, "Unexpected constant condition."); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "ConditionalExpression": checkConstantCondition, + "IfStatement": checkConstantCondition, + "WhileStatement": checkConstantCondition, + "DoWhileStatement": checkConstantCondition, + "ForStatement": checkConstantCondition + }; + +}; diff --git a/tools/eslint/lib/rules/no-continue.js b/tools/eslint/lib/rules/no-continue.js new file mode 100644 index 00000000000000..b48101300576e3 --- /dev/null +++ b/tools/eslint/lib/rules/no-continue.js @@ -0,0 +1,21 @@ +/** + * @fileoverview Rule to flag use of continue statement + * @author Borislav Zhivkov + * @copyright 2015 Borislav Zhivkov. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "ContinueStatement": function(node) { + context.report(node, "Unexpected use of continue statement"); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-control-regex.js b/tools/eslint/lib/rules/no-control-regex.js new file mode 100644 index 00000000000000..a800acc87fefd1 --- /dev/null +++ b/tools/eslint/lib/rules/no-control-regex.js @@ -0,0 +1,56 @@ +/** + * @fileoverview Rule to forbid control charactes from regular expressions. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function getRegExp(node) { + + if (node.value instanceof RegExp) { + return node.value; + } else if (typeof node.value === "string") { + + var parent = context.getAncestors().pop(); + if ((parent.type === "NewExpression" || parent.type === "CallExpression") && + parent.callee.type === "Identifier" && parent.callee.name === "RegExp") { + + // there could be an invalid regular expression string + try { + return new RegExp(node.value); + } catch (ex) { + return null; + } + + } + } else { + return null; + } + + } + + + + return { + + "Literal": function(node) { + + var computedValue, + regex = getRegExp(node); + + if (regex) { + computedValue = regex.toString(); + if (/[\x00-\x1f]/.test(computedValue)) { + context.report(node, "Unexpected control character in regular expression."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-debugger.js b/tools/eslint/lib/rules/no-debugger.js new file mode 100644 index 00000000000000..1a9a7e7d70d589 --- /dev/null +++ b/tools/eslint/lib/rules/no-debugger.js @@ -0,0 +1,20 @@ +/** + * @fileoverview Rule to flag use of a debugger statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "DebuggerStatement": function(node) { + context.report(node, "Unexpected 'debugger' statement."); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-delete-var.js b/tools/eslint/lib/rules/no-delete-var.js new file mode 100644 index 00000000000000..a863d6897a55eb --- /dev/null +++ b/tools/eslint/lib/rules/no-delete-var.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Rule to flag when deleting variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "UnaryExpression": function(node) { + if (node.operator === "delete" && node.argument.type === "Identifier") { + context.report(node, "Variables should not be deleted."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-div-regex.js b/tools/eslint/lib/rules/no-div-regex.js new file mode 100644 index 00000000000000..17347480c64050 --- /dev/null +++ b/tools/eslint/lib/rules/no-div-regex.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Rule to check for ambiguous div operator in regexes + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + var token = context.getFirstToken(node); + + if (token.type === "RegularExpression" && token.value[1] === "=") { + context.report(node, "A regular expression literal can be confused with '/='."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-dupe-args.js b/tools/eslint/lib/rules/no-dupe-args.js new file mode 100644 index 00000000000000..458622e5e0db85 --- /dev/null +++ b/tools/eslint/lib/rules/no-dupe-args.js @@ -0,0 +1,83 @@ +/** + * @fileoverview Rule to flag duplicate arguments + * @author Jamund Ferguson + * @copyright 2015 Jamund Ferguson. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines if a given node has duplicate parameters. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkParams(node) { + var params = {}, + dups = {}; + + + /** + * Marks a given param as either seen or duplicated. + * @param {string} name The name of the param to mark. + * @returns {void} + * @private + */ + function markParam(name) { + if (params.hasOwnProperty(name)) { + dups[name] = 1; + } else { + params[name] = 1; + } + } + + // loop through and find each duplicate param + node.params.forEach(function(param) { + + switch (param.type) { + case "Identifier": + markParam(param.name); + break; + + case "ObjectPattern": + param.properties.forEach(function(property) { + markParam(property.key.name); + }); + break; + + case "ArrayPattern": + param.elements.forEach(function(element) { + markParam(element.name); + }); + break; + + // no default + } + }); + + // log an error for each duplicate (not 2 for each) + Object.keys(dups).forEach(function(currentParam) { + context.report(node, "Duplicate param '{{key}}'.", { key: currentParam }); + }); + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": checkParams, + "FunctionExpression": checkParams + }; + +}; diff --git a/tools/eslint/lib/rules/no-dupe-keys.js b/tools/eslint/lib/rules/no-dupe-keys.js new file mode 100644 index 00000000000000..522f6ace6db1cd --- /dev/null +++ b/tools/eslint/lib/rules/no-dupe-keys.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Rule to flag use of duplicate keys in an object. + * @author Ian Christian Myers + * @copyright 2013 Ian Christian Myers. All rights reserved. + * @copyright 2013 Nicholas C. Zakas. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ObjectExpression": function(node) { + + // Object that will be a map of properties--safe because we will + // prefix all of the keys. + var nodeProps = Object.create(null); + + node.properties.forEach(function(property) { + var keyName = property.key.name || property.key.value, + key = property.kind + "-" + keyName, + checkProperty = (!property.computed || property.key.type === "Literal"); + + if (checkProperty) { + if (nodeProps[key]) { + context.report(node, "Duplicate key '{{key}}'.", { key: keyName }); + } else { + nodeProps[key] = true; + } + } + }); + + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-duplicate-case.js b/tools/eslint/lib/rules/no-duplicate-case.js new file mode 100644 index 00000000000000..89de7174fcb8c0 --- /dev/null +++ b/tools/eslint/lib/rules/no-duplicate-case.js @@ -0,0 +1,59 @@ +/** + * @fileoverview Rule to disallow a duplicate case label. + * @author Dieter Oberkofler + * @copyright 2015 Dieter Oberkofler. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Get a hash value for the node + * @param {ASTNode} node The node. + * @returns {string} A hash value for the node. + * @private + */ + function getHash(node) { + if (node.type === "Literal") { + return node.type + typeof node.value + node.value; + } else if (node.type === "Identifier") { + return node.type + typeof node.name + node.name; + } else if (node.type === "MemberExpression") { + return node.type + getHash(node.object) + getHash(node.property); + } + } + + var switchStatement = []; + + return { + + "SwitchStatement": function(/*node*/) { + switchStatement.push({}); + }, + + "SwitchStatement:exit": function(/*node*/) { + switchStatement.pop(); + }, + + "SwitchCase": function(node) { + var currentSwitch = switchStatement[switchStatement.length - 1], + hashValue; + + if (node.test) { + hashValue = getHash(node.test); + if (typeof hashValue !== "undefined" && currentSwitch.hasOwnProperty(hashValue)) { + context.report(node, "Duplicate case label."); + } else { + currentSwitch[hashValue] = true; + } + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-else-return.js b/tools/eslint/lib/rules/no-else-return.js new file mode 100644 index 00000000000000..2496095365781f --- /dev/null +++ b/tools/eslint/lib/rules/no-else-return.js @@ -0,0 +1,123 @@ +/** + * @fileoverview Rule to flag `else` after a `return` in `if` + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Display the context report if rule is violated + * + * @param {Node} node The 'else' node + * @returns {void} + */ + function displayReport(node) { + context.report(node, "Unexpected 'else' after 'return'."); + } + + /** + * Check to see if the node is a ReturnStatement + * + * @param {Node} node The node being evaluated + * @returns {boolean} True if node is a return + */ + function checkForReturn(node) { + return node.type === "ReturnStatement"; + } + + /** + * Naive return checking, does not iterate through the whole + * BlockStatement because we make the assumption that the ReturnStatement + * will be the last node in the body of the BlockStatement. + * + * @param {Node} node The consequent/alternate node + * @returns {boolean} True if it has a return + */ + function naiveHasReturn(node) { + if (node.type === "BlockStatement") { + var body = node.body, + lastChildNode = body[body.length - 1]; + + return lastChildNode && checkForReturn(lastChildNode); + } + return checkForReturn(node); + } + + /** + * Check to see if the node is valid for evaluation, + * meaning it has an else and not an else-if + * + * @param {Node} node The node being evaluated + * @returns {boolean} True if the node is valid + */ + function hasElse(node) { + return node.alternate && node.consequent && node.alternate.type !== "IfStatement"; + } + + /** + * If the consequent is an IfStatement, check to see if it has an else + * and both its consequent and alternate path return, meaning this is + * a nested case of rule violation. If-Else not considered currently. + * + * @param {Node} node The consequent node + * @returns {boolean} True if this is a nested rule violation + */ + function checkForIf(node) { + return node.type === "IfStatement" && hasElse(node) && + naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent); + } + + /** + * Check the consequent/body node to make sure it is not + * a ReturnStatement or an IfStatement that returns on both + * code paths. If it is, display the context report. + * + * @param {Node} node The consequent or body node + * @param {Node} alternate The alternate node + * @returns {void} + */ + function checkForReturnOrIf(node, alternate) { + if (checkForReturn(node) || checkForIf(node)) { + displayReport(alternate); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "IfStatement": function (node) { + // Don't bother finding a ReturnStatement, if there's no `else` + // or if the alternate is also an if (indicating an else if). + if (hasElse(node)) { + var consequent = node.consequent, + alternate = node.alternate; + // If we have a BlockStatement, check each consequent body node. + if (consequent.type === "BlockStatement") { + var body = consequent.body; + body.forEach(function (bodyNode) { + checkForReturnOrIf(bodyNode, alternate); + }); + // If not a block statement, make sure the consequent isn't a ReturnStatement + // or an IfStatement with returns on both paths + } else { + checkForReturnOrIf(consequent, alternate); + } + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-empty-class.js b/tools/eslint/lib/rules/no-empty-class.js new file mode 100644 index 00000000000000..009c1446b42ada --- /dev/null +++ b/tools/eslint/lib/rules/no-empty-class.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to flag the use of empty character classes in regular expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/* +plain-English description of the following regexp: +0. `^` fix the match at the beginning of the string +1. `\/`: the `/` that begins the regexp +2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following + 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) + 2.1. `\\.`: an escape sequence + 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty +3. `\/` the `/` that ends the regexp +4. `[gimy]*`: optional regexp flags +5. `$`: fix the match at the end of the string +*/ +var regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimy]*$/; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + var token = context.getFirstToken(node); + if (token.type === "RegularExpression" && !regex.test(token.value)) { + context.report(node, "Empty class."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-empty-label.js b/tools/eslint/lib/rules/no-empty-label.js new file mode 100644 index 00000000000000..371c629a824867 --- /dev/null +++ b/tools/eslint/lib/rules/no-empty-label.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Rule to flag when label is not used for a loop or switch + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "LabeledStatement": function(node) { + var type = node.body.type; + + if (type !== "ForStatement" && type !== "WhileStatement" && type !== "DoWhileStatement" && type !== "SwitchStatement" && type !== "ForInStatement" && type !== "ForOfStatement") { + context.report(node, "Unexpected label {{l}}", {l: node.label.name}); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-empty.js b/tools/eslint/lib/rules/no-empty.js new file mode 100644 index 00000000000000..1c2307d63f8725 --- /dev/null +++ b/tools/eslint/lib/rules/no-empty.js @@ -0,0 +1,47 @@ +/** + * @fileoverview Rule to flag use of an empty block statement + * @author Nicholas C. Zakas + * @copyright Nicholas C. Zakas. All rights reserved. + * @copyright 2015 Dieter Oberkofler. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "BlockStatement": function(node) { + var parent = node.parent, + parentType = parent.type; + + // if the body is not empty, we can just return immediately + if (node.body.length !== 0) { + return; + } + + // a function is generally allowed to be empty + if (parentType === "FunctionDeclaration" || parentType === "FunctionExpression" || parentType === "ArrowFunctionExpression") { + return; + } + + // any other block is only allowed to be empty, if it contains a comment + if (context.getComments(node).trailing.length > 0) { + return; + } + + context.report(node, "Empty block statement."); + }, + + "SwitchStatement": function(node) { + + if (typeof node.cases === "undefined" || node.cases.length === 0) { + context.report(node, "Empty switch statement."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-eq-null.js b/tools/eslint/lib/rules/no-eq-null.js new file mode 100644 index 00000000000000..deee40c36a6fd6 --- /dev/null +++ b/tools/eslint/lib/rules/no-eq-null.js @@ -0,0 +1,27 @@ +/** + * @fileoverview Rule to flag comparisons to null without a type-checking + * operator. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "BinaryExpression": function(node) { + var badOperator = node.operator === "==" || node.operator === "!="; + + if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || + node.left.type === "Literal" && node.left.raw === "null" && badOperator) { + context.report(node, "Use ‘===’ to compare with ‘null’."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-eval.js b/tools/eslint/lib/rules/no-eval.js new file mode 100644 index 00000000000000..8eced727db31e8 --- /dev/null +++ b/tools/eslint/lib/rules/no-eval.js @@ -0,0 +1,24 @@ +/** + * @fileoverview Rule to flag use of eval() statement + * @author Nicholas C. Zakas + * @copyright 2015 Mathias Schreck. All rights reserved. + * @copyright 2013 Nicholas C. Zakas. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "CallExpression": function(node) { + if (node.callee.name === "eval") { + context.report(node, "eval can be harmful."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-ex-assign.js b/tools/eslint/lib/rules/no-ex-assign.js new file mode 100644 index 00000000000000..6ea5a2236013f3 --- /dev/null +++ b/tools/eslint/lib/rules/no-ex-assign.js @@ -0,0 +1,40 @@ +/** + * @fileoverview Rule to flag assignment of the exception parameter + * @author Stephen Murray + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var catchStack = []; + + return { + + "CatchClause": function(node) { + catchStack.push(node.param.name); + }, + + "CatchClause:exit": function() { + catchStack.pop(); + }, + + "AssignmentExpression": function(node) { + + if (catchStack.length > 0) { + + var exceptionName = catchStack[catchStack.length - 1]; + + if (node.left.name && node.left.name === exceptionName) { + context.report(node, "Do not assign to the exception parameter."); + } + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-extend-native.js b/tools/eslint/lib/rules/no-extend-native.js new file mode 100644 index 00000000000000..a600de09be1cc6 --- /dev/null +++ b/tools/eslint/lib/rules/no-extend-native.js @@ -0,0 +1,77 @@ +/** + * @fileoverview Rule to flag adding properties to native object's prototypes. + * @author David Nelson + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var BUILTINS = [ + "Object", "Function", "Array", "String", "Boolean", "Number", "Date", + "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", + "SyntaxError", "TypeError", "URIError" +]; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + // handle the Array.prototype.extra style case + "AssignmentExpression": function(node) { + var lhs = node.left, affectsProto; + + if (lhs.type !== "MemberExpression" || lhs.object.type !== "MemberExpression") { + return; + } + + affectsProto = lhs.object.computed ? + lhs.object.property.type === "Literal" && lhs.object.property.value === "prototype" : + lhs.object.property.name === "prototype"; + + if (!affectsProto) { + return; + } + + BUILTINS.forEach(function(builtin) { + if (lhs.object.object.name === builtin) { + context.report(node, builtin + " prototype is read only, properties should not be added."); + } + }); + }, + + // handle the Object.defineProperty(Array.prototype) case + "CallExpression": function(node) { + + var callee = node.callee, + subject, + object; + + // only worry about Object.defineProperty + if (callee.type === "MemberExpression" && + callee.object.name === "Object" && + callee.property.name === "defineProperty") { + + // verify the object being added to is a native prototype + subject = node.arguments[0]; + object = subject.object; + + if (object && + object.type === "Identifier" && + (BUILTINS.indexOf(object.name) > -1) && + subject.property.name === "prototype") { + + context.report(node, object.name + " prototype is read only, properties should not be added."); + } + } + + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-extra-bind.js b/tools/eslint/lib/rules/no-extra-bind.js new file mode 100644 index 00000000000000..b585730633e673 --- /dev/null +++ b/tools/eslint/lib/rules/no-extra-bind.js @@ -0,0 +1,79 @@ +/** + * @fileoverview Rule to flag unnecessary bind calls + * @author Bence Dányi + * @copyright 2014 Bence Dányi. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var scope = [{ + depth: -1, + found: 0 + }]; + + /** + * Get the topmost scope + * @returns {Object} The topmost scope + */ + function getTopScope() { + return scope[scope.length - 1]; + } + + /** + * Increment the depth of the top scope + * @returns {void} + */ + function incrementScopeDepth() { + var top = getTopScope(); + top.depth++; + } + + /** + * Decrement the depth of the top scope + * @returns {void} + */ + function decrementScopeDepth() { + var top = getTopScope(); + top.depth--; + } + + return { + "CallExpression": function(node) { + if (node.arguments.length === 1 && + node.callee.type === "MemberExpression" && + node.callee.property.name === "bind" && + /FunctionExpression$/.test(node.callee.object.type)) { + scope.push({ + call: node, + depth: -1, + found: 0 + }); + } + }, + "CallExpression:exit": function(node) { + var top = getTopScope(); + if (top.call === node && top.found === 0) { + context.report(node, "The function binding is unnecessary."); + scope.pop(); + } + }, + "ArrowFunctionExpression": incrementScopeDepth, + "ArrowFunctionExpression:exit": decrementScopeDepth, + "FunctionExpression": incrementScopeDepth, + "FunctionExpression:exit": decrementScopeDepth, + "FunctionDeclaration": incrementScopeDepth, + "FunctionDeclaration:exit": decrementScopeDepth, + "ThisExpression": function() { + var top = getTopScope(); + if (top.depth === 0) { + top.found++; + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-extra-boolean-cast.js b/tools/eslint/lib/rules/no-extra-boolean-cast.js new file mode 100644 index 00000000000000..605d7b1210ef9d --- /dev/null +++ b/tools/eslint/lib/rules/no-extra-boolean-cast.js @@ -0,0 +1,69 @@ +/** + * @fileoverview Rule to flag unnecessary double negation in Boolean contexts + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "UnaryExpression": function (node) { + var ancestors = context.getAncestors(), + parent = ancestors.pop(), + grandparent = ancestors.pop(); + + // Exit early if it's guaranteed not to match + if (node.operator !== "!" || + parent.type !== "UnaryExpression" || + parent.operator !== "!") { + return; + } + + // if () ... + if (grandparent.type === "IfStatement") { + context.report(node, "Redundant double negation in an if statement condition."); + + // do ... while () + } else if (grandparent.type === "DoWhileStatement") { + context.report(node, "Redundant double negation in a do while loop condition."); + + // while () ... + } else if (grandparent.type === "WhileStatement") { + context.report(node, "Redundant double negation in a while loop condition."); + + // ? ... : ... + } else if ((grandparent.type === "ConditionalExpression" && + parent === grandparent.test)) { + context.report(node, "Redundant double negation in a ternary condition."); + + // for (...; ; ...) ... + } else if ((grandparent.type === "ForStatement" && + parent === grandparent.test)) { + context.report(node, "Redundant double negation in a for loop condition."); + + // ! + } else if ((grandparent.type === "UnaryExpression" && + grandparent.operator === "!")) { + context.report(node, "Redundant multiple negation."); + + // Boolean() + } else if ((grandparent.type === "CallExpression" && + grandparent.callee.type === "Identifier" && + grandparent.callee.name === "Boolean")) { + context.report(node, "Redundant double negation in call to Boolean()."); + + // new Boolean() + } else if ((grandparent.type === "NewExpression" && + grandparent.callee.type === "Identifier" && + grandparent.callee.name === "Boolean")) { + context.report(node, "Redundant double negation in Boolean constructor call."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-extra-parens.js b/tools/eslint/lib/rules/no-extra-parens.js new file mode 100644 index 00000000000000..2ec8647a68527f --- /dev/null +++ b/tools/eslint/lib/rules/no-extra-parens.js @@ -0,0 +1,299 @@ +/** + * @fileoverview Disallow parenthesesisng higher precedence subexpressions. + * @author Michael Ficarra + * @copyright 2014 Michael Ficarra. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function isParenthesised(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + + return previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + function isParenthesisedTwice(node) { + var previousToken = context.getTokenBefore(node, 1), + nextToken = context.getTokenAfter(node, 1); + + return isParenthesised(node) && previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + function precedence(node) { + + switch (node.type) { + case "SequenceExpression": + return 0; + + case "AssignmentExpression": + case "ArrowFunctionExpression": + case "YieldExpression": + return 1; + + case "ConditionalExpression": + return 3; + + case "LogicalExpression": + switch (node.operator) { + case "||": + return 4; + case "&&": + return 5; + // no default + } + + /* falls through */ + case "BinaryExpression": + switch (node.operator) { + case "|": + return 6; + case "^": + return 7; + case "&": + return 8; + case "==": + case "!=": + case "===": + case "!==": + return 9; + case "<": + case "<=": + case ">": + case ">=": + case "in": + case "instanceof": + return 10; + case "<<": + case ">>": + case ">>>": + return 11; + case "+": + case "-": + return 12; + case "*": + case "/": + case "%": + return 13; + // no default + } + /* falls through */ + case "UnaryExpression": + return 14; + case "UpdateExpression": + return 15; + case "CallExpression": + // IIFE is allowed to have parens in any position (#655) + if (node.callee.type === "FunctionExpression") { + return -1; + } + return 16; + case "NewExpression": + return 17; + // no default + } + return 18; + } + + function report(node) { + var previousToken = context.getTokenBefore(node); + context.report(node, previousToken.loc.start, "Gratuitous parentheses around expression."); + } + + function dryUnaryUpdate(node) { + if (isParenthesised(node.argument) && precedence(node.argument) >= precedence(node)) { + report(node.argument); + } + } + + function dryCallNew(node) { + if (isParenthesised(node.callee) && precedence(node.callee) >= precedence(node) && + !(node.type === "CallExpression" && node.callee.type === "FunctionExpression")) { + report(node.callee); + } + if (node.arguments.length === 1) { + if (isParenthesisedTwice(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({type: "AssignmentExpression"})) { + report(node.arguments[0]); + } + } else { + [].forEach.call(node.arguments, function(arg) { + if (isParenthesised(arg) && precedence(arg) >= precedence({type: "AssignmentExpression"})) { + report(arg); + } + }); + } + } + + function dryBinaryLogical(node) { + var prec = precedence(node); + if (isParenthesised(node.left) && precedence(node.left) >= prec) { + report(node.left); + } + if (isParenthesised(node.right) && precedence(node.right) > prec) { + report(node.right); + } + } + + return { + "ArrayExpression": function(node) { + [].forEach.call(node.elements, function(e) { + if (e && isParenthesised(e) && precedence(e) >= precedence({type: "AssignmentExpression"})) { + report(e); + } + }); + }, + "ArrowFunctionExpression": function(node) { + if (node.body.type !== "BlockStatement" && isParenthesised(node.body) && precedence(node.body) >= precedence({type: "AssignmentExpression"})) { + report(node.body); + } + }, + "AssignmentExpression": function(node) { + if (isParenthesised(node.right) && precedence(node.right) >= precedence(node)) { + report(node.right); + } + }, + "BinaryExpression": dryBinaryLogical, + "CallExpression": dryCallNew, + "ConditionalExpression": function(node) { + if (isParenthesised(node.test) && precedence(node.test) >= precedence({type: "LogicalExpression", operator: "||"})) { + report(node.test); + } + if (isParenthesised(node.consequent) && precedence(node.consequent) >= precedence({type: "AssignmentExpression"})) { + report(node.consequent); + } + if (isParenthesised(node.alternate) && precedence(node.alternate) >= precedence({type: "AssignmentExpression"})) { + report(node.alternate); + } + }, + "DoWhileStatement": function(node) { + if (isParenthesisedTwice(node.test)) { + report(node.test); + } + }, + "ExpressionStatement": function(node) { + var firstToken; + if (isParenthesised(node.expression)) { + firstToken = context.getFirstToken(node.expression); + if (firstToken.value !== "function" && firstToken.value !== "{") { + report(node.expression); + } + } + }, + "ForInStatement": function(node) { + if (isParenthesised(node.right)) { + report(node.right); + } + }, + "ForOfStatement": function(node) { + if (isParenthesised(node.right)) { + report(node.right); + } + }, + "ForStatement": function(node) { + if (node.init && isParenthesised(node.init)) { + report(node.init); + } + + if (node.test && isParenthesised(node.test)) { + report(node.test); + } + + if (node.update && isParenthesised(node.update)) { + report(node.update); + } + }, + "IfStatement": function(node) { + if (isParenthesisedTwice(node.test)) { + report(node.test); + } + }, + "LogicalExpression": dryBinaryLogical, + "MemberExpression": function(node) { + if ( + isParenthesised(node.object) && + precedence(node.object) >= precedence(node) && + ( + node.computed || + !( + (node.object.type === "Literal" && + typeof node.object.value === "number" && + /^[0-9]+$/.test(context.getFirstToken(node.object).value)) + || + // RegExp literal is allowed to have parens (#1589) + (node.object.type === "Literal" && node.object.regex) + ) + ) + ) { + report(node.object); + } + }, + "NewExpression": dryCallNew, + "ObjectExpression": function(node) { + [].forEach.call(node.properties, function(e) { + var v = e.value; + if (v && isParenthesised(v) && precedence(v) >= precedence({type: "AssignmentExpression"})) { + report(v); + } + }); + }, + "ReturnStatement": function(node) { + if (node.argument && isParenthesised(node.argument) && + // RegExp literal is allowed to have parens (#1589) + !(node.argument.type === "Literal" && node.argument.regex)) { + report(node.argument); + } + }, + "SequenceExpression": function(node) { + [].forEach.call(node.expressions, function(e) { + if (isParenthesised(e) && precedence(e) >= precedence(node)) { + report(e); + } + }); + }, + "SwitchCase": function(node) { + if (node.test && isParenthesised(node.test)) { + report(node.test); + } + }, + "SwitchStatement": function(node) { + if (isParenthesisedTwice(node.discriminant)) { + report(node.discriminant); + } + }, + "ThrowStatement": function(node) { + if (isParenthesised(node.argument)) { + report(node.argument); + } + }, + "UnaryExpression": dryUnaryUpdate, + "UpdateExpression": dryUnaryUpdate, + "VariableDeclarator": function(node) { + if (node.init && isParenthesised(node.init) && + precedence(node.init) >= precedence({type: "AssignmentExpression"}) && + // RegExp literal is allowed to have parens (#1589) + !(node.init.type === "Literal" && node.init.regex)) { + report(node.init); + } + }, + "WhileStatement": function(node) { + if (isParenthesisedTwice(node.test)) { + report(node.test); + } + }, + "WithStatement": function(node) { + if (isParenthesisedTwice(node.object)) { + report(node.object); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-extra-semi.js b/tools/eslint/lib/rules/no-extra-semi.js new file mode 100644 index 00000000000000..e155d982e565a4 --- /dev/null +++ b/tools/eslint/lib/rules/no-extra-semi.js @@ -0,0 +1,21 @@ +/** + * @fileoverview Rule to flag use of unnecessary semicolons + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "EmptyStatement": function(node) { + context.report(node, "Unnecessary semicolon."); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-extra-strict.js b/tools/eslint/lib/rules/no-extra-strict.js new file mode 100644 index 00000000000000..4c6ac16a427670 --- /dev/null +++ b/tools/eslint/lib/rules/no-extra-strict.js @@ -0,0 +1,84 @@ +/** + * @fileoverview Rule to flag unnecessary strict directives. + * @author Ian Christian Myers + * @copyright 2014 Ian Christian Myers. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function directives(block) { + var ds = [], body = block.body, e, i, l; + + if (body) { + for (i = 0, l = body.length; i < l; ++i) { + e = body[i]; + + if ( + e.type === "ExpressionStatement" && + e.expression.type === "Literal" && + typeof e.expression.value === "string" + ) { + ds.push(e.expression); + } else { + break; + } + } + } + + return ds; + } + + function isStrict(directive) { + return directive.value === "use strict"; + } + + function checkForUnnecessaryUseStrict(node) { + var useStrictDirectives = directives(node).filter(isStrict), + scope, + upper; + + switch (useStrictDirectives.length) { + case 0: + break; + + case 1: + scope = context.getScope(); + upper = scope.upper; + + if (upper && upper.functionExpressionScope) { + upper = upper.upper; + } + + if (upper && upper.isStrict) { + context.report(useStrictDirectives[0], "Unnecessary 'use strict'."); + } + break; + + default: + context.report(useStrictDirectives[1], "Multiple 'use strict' directives."); + } + } + + return { + + "Program": checkForUnnecessaryUseStrict, + + "ArrowFunctionExpression": function(node) { + checkForUnnecessaryUseStrict(node.body); + }, + + "FunctionExpression": function(node) { + checkForUnnecessaryUseStrict(node.body); + }, + + "FunctionDeclaration": function(node) { + checkForUnnecessaryUseStrict(node.body); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-fallthrough.js b/tools/eslint/lib/rules/no-fallthrough.js new file mode 100644 index 00000000000000..a137fb3f808e8f --- /dev/null +++ b/tools/eslint/lib/rules/no-fallthrough.js @@ -0,0 +1,95 @@ +/** + * @fileoverview Rule to flag fall-through cases in switch statements. + * @author Matt DuVall + */ +"use strict"; + + +var FALLTHROUGH_COMMENT = /falls\sthrough/; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var switches = []; + + return { + + "SwitchCase": function(node) { + + var consequent = node.consequent, + switchData = switches[switches.length - 1], + i, + comments, + comment; + + /* + * Some developers wrap case bodies in blocks, so if there is just one + * node and it's a block statement, check inside. + */ + if (consequent.length === 1 && consequent[0].type === "BlockStatement") { + consequent = consequent[0]; + } + + // checking on previous case + if (!switchData.lastCaseClosed) { + + // a fall through comment will be the last trailing comment of the last case + comments = context.getComments(switchData.lastCase).trailing; + comment = comments[comments.length - 1]; + + // unless the user doesn't like semicolons, in which case it's first leading comment of this case + if (!comment) { + comments = context.getComments(node).leading; + comment = comments[comments.length - 1]; + } + + // check for comment + if (!comment || !FALLTHROUGH_COMMENT.test(comment.value)) { + + context.report(switchData.lastCase, + "Expected a \"break\" statement before \"{{code}}\".", + { code: node.test ? "case" : "default" }); + } + } + + // now dealing with the current case + switchData.lastCaseClosed = false; + switchData.lastCase = node; + + // try to verify using statements - go backwards as a fast path for the search + if (consequent.length) { + for (i = consequent.length - 1; i >= 0; i--) { + if (/(?:Break|Continue|Return|Throw)Statement/.test(consequent[i].type)) { + switchData.lastCaseClosed = true; + break; + } + } + } else { + // the case statement has no statements, so it must logically fall through + switchData.lastCaseClosed = true; + } + + /* + * Any warnings are triggered when the next SwitchCase occurs. + * There is no need to warn on the last SwitchCase, since it can't + * fall through to anything. + */ + }, + + "SwitchStatement": function(node) { + switches.push({ + node: node, + lastCaseClosed: true, + lastCase: null + }); + }, + + "SwitchStatement:exit": function() { + switches.pop(); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-floating-decimal.js b/tools/eslint/lib/rules/no-floating-decimal.js new file mode 100644 index 00000000000000..c6380d546079dd --- /dev/null +++ b/tools/eslint/lib/rules/no-floating-decimal.js @@ -0,0 +1,28 @@ +/** + * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "Literal": function(node) { + + if (typeof node.value === "number") { + if (node.raw.indexOf(".") === 0) { + context.report(node, "A leading decimal point can be confused with a dot."); + } + if (node.raw.indexOf(".") === node.raw.length - 1) { + context.report(node, "A trailing decimal point can be confused with a dot."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-func-assign.js b/tools/eslint/lib/rules/no-func-assign.js new file mode 100644 index 00000000000000..a9f2858126b4b3 --- /dev/null +++ b/tools/eslint/lib/rules/no-func-assign.js @@ -0,0 +1,81 @@ +/** + * @fileoverview Rule to flag use of function declaration identifiers as variables. + * @author Ian Christian Myers + * @copyright 2013 Ian Christian Myers. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /* + * Walk the scope chain looking for either a FunctionDeclaration or a + * VariableDeclaration with the same name as left-hand side of the + * AssignmentExpression. If we find the FunctionDeclaration first, then we + * warn, because a FunctionDeclaration is trying to become a Variable or a + * FunctionExpression. If we find a VariableDeclaration first, then we have + * a legitimate shadow variable. + */ + function checkIfIdentifierIsFunction(scope, name) { + var variable, + def, + i, + j; + + // Loop over all of the identifiers available in scope. + for (i = 0; i < scope.variables.length; i++) { + variable = scope.variables[i]; + + // For each identifier, see if it was defined in _this_ scope. + for (j = 0; j < variable.defs.length; j++) { + def = variable.defs[j]; + + // Identifier is a function and was declared in this scope + if (def.type === "FunctionName" && def.name.name === name) { + return true; + } + + // Identifier is a variable and was declared in this scope. This + // is a legitimate shadow variable. + if (def.name && def.name.name === name) { + return false; + } + } + } + + // Check the upper scope. + if (scope.upper) { + return checkIfIdentifierIsFunction(scope.upper, name); + } + + // We've reached the global scope and haven't found anything. + return false; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "AssignmentExpression": function(node) { + var scope = context.getScope(), + name = node.left.name; + + if (checkIfIdentifierIsFunction(scope, name)) { + context.report(node, "'{{name}}' is a function.", { name: name }); + } + + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-implied-eval.js b/tools/eslint/lib/rules/no-implied-eval.js new file mode 100644 index 00000000000000..f798dcdade4642 --- /dev/null +++ b/tools/eslint/lib/rules/no-implied-eval.js @@ -0,0 +1,74 @@ +/** + * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval + * @author James Allardice + * @copyright 2015 Mathias Schreck. All rights reserved. + * @copyright 2013 James Allardice. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var IMPLIED_EVAL = /set(?:Timeout|Interval)/; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks if the first argument of a given CallExpression node is a string literal. + * @param {ASTNode} node The CallExpression node the check. + * @returns {boolean} True if the first argument is a string literal, false if not. + */ + function hasStringLiteralArgument(node) { + var firstArgument = node.arguments[0]; + + return firstArgument && firstArgument.type === "Literal" && typeof firstArgument.value === "string"; + } + + /** + * Checks if the given MemberExpression node is window.setTimeout or window.setInterval. + * @param {ASTNode} node The MemberExpression node to check. + * @returns {boolean} Whether or not the given node is window.set*. + */ + function isSetMemberExpression(node) { + var object = node.object, + property = node.property, + hasSetPropertyName = IMPLIED_EVAL.test(property.name) || IMPLIED_EVAL.test(property.value); + + return object.name === "window" && hasSetPropertyName; + + } + + /** + * Determines if a node represents a call to setTimeout/setInterval with + * a string argument. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node matches, false if not. + * @private + */ + function isImpliedEval(node) { + var isMemberExpression = (node.callee.type === "MemberExpression"), + isIdentifier = (node.callee.type === "Identifier"), + isSetMethod = (isIdentifier && IMPLIED_EVAL.test(node.callee.name)) || + (isMemberExpression && isSetMemberExpression(node.callee)); + + return isSetMethod && hasStringLiteralArgument(node); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "CallExpression": function(node) { + if (isImpliedEval(node)) { + context.report(node, "Implied eval. Consider passing a function instead of a string."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-inline-comments.js b/tools/eslint/lib/rules/no-inline-comments.js new file mode 100644 index 00000000000000..091ad9bee45ebb --- /dev/null +++ b/tools/eslint/lib/rules/no-inline-comments.js @@ -0,0 +1,47 @@ +/** + * @fileoverview Enforces or disallows inline comments. + * @author Greg Cochard + * @copyright 2014 Greg Cochard. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Will check that comments are not on lines starting with or ending with code + * @param {ASTNode} node The comment node to check + * @private + * @returns {void} + */ + function testCodeAroundComment(node) { + + // Get the whole line and cut it off at the start of the comment + var startLine = String(context.getSourceLines()[node.loc.start.line - 1]); + var endLine = String(context.getSourceLines()[node.loc.end.line - 1]); + + var preamble = startLine.slice(0, node.loc.start.column).trim(); + + // Also check after the comment + var postamble = endLine.slice(node.loc.end.column).trim(); + + // Should be empty if there was only whitespace around the comment + if (preamble || postamble) { + context.report(node, "Unexpected comment inline with code."); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "LineComment": testCodeAroundComment, + "BlockComment": testCodeAroundComment + + }; +}; diff --git a/tools/eslint/lib/rules/no-inner-declarations.js b/tools/eslint/lib/rules/no-inner-declarations.js new file mode 100644 index 00000000000000..664639d575d5c7 --- /dev/null +++ b/tools/eslint/lib/rules/no-inner-declarations.js @@ -0,0 +1,72 @@ +/** + * @fileoverview Rule to enforce declarations in program or function body root. + * @author Brandon Mills + * @copyright 2014 Brandon Mills. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Find the nearest Program or Function ancestor node. + * @returns {Object} Ancestor's type and distance from node. + */ + function nearestBody() { + var ancestors = context.getAncestors(), + ancestor = ancestors.pop(), + generation = 1; + + while (ancestor && ["Program", "FunctionDeclaration", + "FunctionExpression", "ArrowFunctionExpression" + ].indexOf(ancestor.type) < 0) { + generation += 1; + ancestor = ancestors.pop(); + } + + return { + // Type of containing ancestor + type: ancestor.type, + // Separation between ancestor and node + distance: generation + }; + } + + /** + * Ensure that a given node is at a program or function body's root. + * @param {ASTNode} node Declaration node to check. + * @returns {void} + */ + function check(node) { + var body = nearestBody(node), + valid = ((body.type === "Program" && body.distance === 1) || + body.distance === 2); + + if (!valid) { + context.report(node, "Move {{type}} declaration to {{body}} root.", + { + type: (node.type === "FunctionDeclaration" ? + "function" : "variable"), + body: (body.type === "Program" ? + "program" : "function body") + } + ); + } + } + + return { + + "FunctionDeclaration": check, + "VariableDeclaration": function(node) { + if (context.options[0] === "both" && node.kind === "var") { + check(node); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-invalid-regexp.js b/tools/eslint/lib/rules/no-invalid-regexp.js new file mode 100644 index 00000000000000..cea5372f153c8b --- /dev/null +++ b/tools/eslint/lib/rules/no-invalid-regexp.js @@ -0,0 +1,51 @@ +/** + * @fileoverview Validate strings passed to the RegExp constructor + * @author Michael Ficarra + * @copyright 2014 Michael Ficarra. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var espree = require("espree"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; + } + + function check(node) { + if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(node.arguments[0])) { + var flags = isString(node.arguments[1]) ? node.arguments[1].value : ""; + + try { + void new RegExp(node.arguments[0].value); + } catch(e) { + context.report(node, e.message); + } + + if (flags) { + + try { + espree.parse("/./" + flags, { ecmaFeatures: context.ecmaFeatures }); + } catch (ex) { + context.report(node, "Invalid flags supplied to RegExp constructor '" + flags + "'"); + } + } + + } + } + + return { + "CallExpression": check, + "NewExpression": check + }; + +}; diff --git a/tools/eslint/lib/rules/no-irregular-whitespace.js b/tools/eslint/lib/rules/no-irregular-whitespace.js new file mode 100644 index 00000000000000..3599f0cecdf48a --- /dev/null +++ b/tools/eslint/lib/rules/no-irregular-whitespace.js @@ -0,0 +1,92 @@ +/** + * @fileoverview Rule to disalow whitespace that is not a tab or space, whitespace inside strings and comments are allowed + * @author Jonathan Kingston + * @copyright 2014 Jonathan Kingston. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var irregularWhitespace = /[\u0085\u00A0\ufeff\f\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000]+/mg; + + // Module store of errors that we have found + var errors = []; + + /** + * Removes errors that occur inside a string node + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeStringError(node) { + var locStart = node.loc.start; + var locEnd = node.loc.end; + + errors = errors.filter(function (error) { + var errorLoc = error[1]; + if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) { + if (errorLoc.column >= locStart.column && errorLoc.column <= locEnd.column) { + return false; + } + } + return true; + }); + } + + /** + * Checks nodes for errors that we are choosing to ignore and calls the relevent methods to remove the errors + * @param {ASTNode} node to check for matching errors. + * @returns {void} + * @private + */ + function removeInvalidNodeErrors(node) { + if (typeof node.value === "string") { + // If we have irregular characters remove them from the errors list + if (node.value.match(irregularWhitespace)) { + removeStringError(node); + } + } + } + + return { + "Program": function (node) { + /** + * As we can easily fire warnings for all white space issues with all the source its simpler to fire them here + * This means we can check all the application code without having to worry about issues caused in the parser tokens + * When writing this code also evaluating per node was missing out connecting tokens in some cases + * We can later filter the errors when they are found to be not an issue in nodes we don't care about + */ + var sourceLines = context.getSourceLines(); + + sourceLines.forEach(function (sourceLine, lineIndex) { + var location, + match = irregularWhitespace.exec(sourceLine); + + if (match !== null) { + location = { + line: lineIndex + 1, + column: match.index + }; + + errors.push([node, location, "Irregular whitespace not allowed"]); + } + }); + }, + "Identifier": removeInvalidNodeErrors, + "Literal": removeInvalidNodeErrors, + "Statement": removeInvalidNodeErrors, + "Expression": removeInvalidNodeErrors, + "Program:exit": function () { + + // If we have any errors remaining report on them + errors.forEach(function (error) { + context.report.apply(this, error); + }); + } + }; +}; diff --git a/tools/eslint/lib/rules/no-iterator.js b/tools/eslint/lib/rules/no-iterator.js new file mode 100644 index 00000000000000..564c09abfa6966 --- /dev/null +++ b/tools/eslint/lib/rules/no-iterator.js @@ -0,0 +1,26 @@ +/** + * @fileoverview Rule to flag usage of __iterator__ property + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + + if (node.property && + (node.property.type === "Identifier" && node.property.name === "__iterator__" && !node.computed) || + (node.property.type === "Literal" && node.property.value === "__iterator__")) { + context.report(node, "Reserved name '__iterator__'."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-label-var.js b/tools/eslint/lib/rules/no-label-var.js new file mode 100644 index 00000000000000..b82bd0af6087c2 --- /dev/null +++ b/tools/eslint/lib/rules/no-label-var.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Rule to flag labels that are the same as an identifier + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + function findIdentifier(scope, identifier) { + var found = false; + + scope.variables.forEach(function(variable) { + if (variable.name === identifier) { + found = true; + } + }); + + scope.references.forEach(function(reference) { + if (reference.identifier.name === identifier) { + found = true; + } + }); + + // If we have not found the identifier in this scope, check the parent + // scope. + if (scope.upper && !found) { + return findIdentifier(scope.upper, identifier); + } + + return found; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "LabeledStatement": function(node) { + + // Fetch the innermost scope. + var scope = context.getScope(); + + // Recursively find the identifier walking up the scope, starting + // with the innermost scope. + if (findIdentifier(scope, node.label.name)) { + context.report(node, "Found identifier with same name as label."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-labels.js b/tools/eslint/lib/rules/no-labels.js new file mode 100644 index 00000000000000..8b5086a2958185 --- /dev/null +++ b/tools/eslint/lib/rules/no-labels.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Disallow Labeled Statements + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "LabeledStatement": function(node) { + context.report(node, "Unexpected labeled statement."); + }, + + "BreakStatement": function(node) { + + if (node.label) { + context.report(node, "Unexpected label in break statement."); + } + + }, + + "ContinueStatement": function(node) { + + if (node.label) { + context.report(node, "Unexpected label in continue statement."); + } + + } + + + }; + +}; diff --git a/tools/eslint/lib/rules/no-lone-blocks.js b/tools/eslint/lib/rules/no-lone-blocks.js new file mode 100644 index 00000000000000..25d8c34f00e9b1 --- /dev/null +++ b/tools/eslint/lib/rules/no-lone-blocks.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Rule to flag blocks with no reason to exist + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "BlockStatement": function (node) { + // Check for any occurrence of BlockStatement > BlockStatement or + // Program > BlockStatement + var parent = context.getAncestors().pop(); + if (parent.type === "BlockStatement" || parent.type === "Program") { + context.report(node, "Block is nested inside another block."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-lonely-if.js b/tools/eslint/lib/rules/no-lonely-if.js new file mode 100644 index 00000000000000..59d807da30de39 --- /dev/null +++ b/tools/eslint/lib/rules/no-lonely-if.js @@ -0,0 +1,28 @@ +/** + * @fileoverview Rule to disallow if as the only statmenet in an else block + * @author Brandon Mills + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "IfStatement": function(node) { + var ancestors = context.getAncestors(), + parent = ancestors.pop(), + grandparent = ancestors.pop(); + + if (parent && parent.type === "BlockStatement" && + parent.body.length === 1 && grandparent && + grandparent.type === "IfStatement" && + parent === grandparent.alternate) { + context.report(node, "Unexpected if as the only statement in an else block."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-loop-func.js b/tools/eslint/lib/rules/no-loop-func.js new file mode 100644 index 00000000000000..ec68611b72eb90 --- /dev/null +++ b/tools/eslint/lib/rules/no-loop-func.js @@ -0,0 +1,49 @@ +/** + * @fileoverview Rule to flag creation of function inside a loop + * @author Ilya Volodin + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var loopNodeTypes = [ + "ForStatement", + "WhileStatement", + "ForInStatement", + "ForOfStatement", + "DoWhileStatement" + ]; + + /** + * Checks if the given node is a loop. + * @param {ASTNode} node The AST node to check. + * @returns {boolean} Whether or not the node is a loop. + */ + function isLoop(node) { + return loopNodeTypes.indexOf(node.type) > -1; + } + + /** + * Reports if the given node has an ancestor node which is a loop. + * @param {ASTNode} node The AST node to check. + * @returns {boolean} Whether or not the node is within a loop. + */ + function checkForLoops(node) { + var ancestors = context.getAncestors(); + + if (ancestors.some(isLoop)) { + context.report(node, "Don't make functions within a loop"); + } + } + + return { + "ArrowFunctionExpression": checkForLoops, + "FunctionExpression": checkForLoops, + "FunctionDeclaration": checkForLoops + }; +}; diff --git a/tools/eslint/lib/rules/no-mixed-requires.js b/tools/eslint/lib/rules/no-mixed-requires.js new file mode 100644 index 00000000000000..d75fc56abbd09e --- /dev/null +++ b/tools/eslint/lib/rules/no-mixed-requires.js @@ -0,0 +1,159 @@ +/** + * @fileoverview Rule to enforce grouped require statements for Node.JS + * @author Raphael Pigulla + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Returns the list of built-in modules. + * + * @returns {string[]} An array of built-in Node.js modules. + */ + function getBuiltinModules() { + // This list is generated using `require("repl")._builtinLibs.concat('repl').sort()` + // This particular list is as per nodejs v0.12.2 and iojs v0.7.1 + return [ + "assert", "buffer", "child_process", "cluster", "crypto", + "dgram", "dns", "domain", "events", "fs", "http", "https", + "net", "os", "path", "punycode", "querystring", "readline", + "repl", "smalloc", "stream", "string_decoder", "tls", "tty", + "url", "util", "v8", "vm", "zlib" + ]; + } + + var BUILTIN_MODULES = getBuiltinModules(); + + var DECL_REQUIRE = "require", + DECL_UNINITIALIZED = "uninitialized", + DECL_OTHER = "other"; + + var REQ_CORE = "core", + REQ_FILE = "file", + REQ_MODULE = "module", + REQ_COMPUTED = "computed"; + + /** + * Determines the type of a declaration statement. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The type of declaration represented by the expression. + */ + function getDeclarationType(initExpression) { + if (!initExpression) { + // "var x;" + return DECL_UNINITIALIZED; + } + + if (initExpression.type === "CallExpression" && + initExpression.callee.type === "Identifier" && + initExpression.callee.name === "require" + ) { + // "var x = require('util');" + return DECL_REQUIRE; + } else if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return getDeclarationType(initExpression.object); + } + + // "var x = 42;" + return DECL_OTHER; + } + + /** + * Determines the type of module that is loaded via require. + * @param {ASTNode} initExpression The init node of the VariableDeclarator. + * @returns {string} The module type. + */ + function inferModuleType(initExpression) { + if (initExpression.type === "MemberExpression") { + // "var x = require('glob').Glob;" + return inferModuleType(initExpression.object); + } else if (initExpression.arguments.length === 0) { + // "var x = require();" + return REQ_COMPUTED; + } + + var arg = initExpression.arguments[0]; + + if (arg.type !== "Literal" || typeof arg.value !== "string") { + // "var x = require(42);" + return REQ_COMPUTED; + } + + if (BUILTIN_MODULES.indexOf(arg.value) !== -1) { + // "var fs = require('fs');" + return REQ_CORE; + } else if (/^\.{0,2}\//.test(arg.value)) { + // "var utils = require('./utils');" + return REQ_FILE; + } else { + // "var async = require('async');" + return REQ_MODULE; + } + } + + /** + * Check if the list of variable declarations is mixed, i.e. whether it + * contains both require and other declarations. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are mixed, false if not. + */ + function isMixed(declarations) { + var contains = {}; + + declarations.forEach(function (declaration) { + var type = getDeclarationType(declaration.init); + contains[type] = true; + }); + + return !!( + contains[DECL_REQUIRE] && + (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) + ); + } + + /** + * Check if all require declarations in the given list are of the same + * type. + * @param {ASTNode} declarations The list of VariableDeclarators. + * @returns {boolean} True if the declarations are grouped, false if not. + */ + function isGrouped(declarations) { + var found = {}; + + declarations.forEach(function (declaration) { + if (getDeclarationType(declaration.init) === DECL_REQUIRE) { + found[inferModuleType(declaration.init)] = true; + } + }); + + return Object.keys(found).length <= 1; + } + + + return { + + "VariableDeclaration": function(node) { + var grouping = !!context.options[0]; + + if (isMixed(node.declarations)) { + context.report( + node, + "Do not mix 'require' and other declarations." + ); + } else if (grouping && !isGrouped(node.declarations)) { + context.report( + node, + "Do not mix core, module, file and computed requires." + ); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js new file mode 100644 index 00000000000000..7b76d76db99d7d --- /dev/null +++ b/tools/eslint/lib/rules/no-mixed-spaces-and-tabs.js @@ -0,0 +1,68 @@ +/** + * @fileoverview Disallow mixed spaces and tabs for indentation + * @author Jary Niebur + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2014 Jary Niebur. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var smartTabs; + + switch (context.options[0]) { + case true: // Support old syntax, maybe add deprecation warning here + case "smart-tabs": + smartTabs = true; + break; + default: + smartTabs = false; + } + + var COMMENT_START = /^\s*\/\*/, + MAYBE_COMMENT = /^\s*\*/; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function(node) { + /* + * At least one space followed by a tab + * or the reverse before non-tab/-space + * characters begin. + */ + var regex = /^(?=[\t ]*(\t | \t))/, + match, + lines = context.getSourceLines(); + + if (smartTabs) { + /* + * At least one space followed by a tab + * before non-tab/-space characters begin. + */ + regex = /^(?=[\t ]* \t)/; + } + + lines.forEach(function(line, i) { + match = regex.exec(line); + + if (match) { + + if (!MAYBE_COMMENT.test(line) && !COMMENT_START.test(lines[i - 1])) { + context.report(node, { line: i + 1, column: match.index + 1 }, "Mixed spaces and tabs."); + } + + } + }); + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-multi-spaces.js b/tools/eslint/lib/rules/no-multi-spaces.js new file mode 100644 index 00000000000000..9e247c1533d11a --- /dev/null +++ b/tools/eslint/lib/rules/no-multi-spaces.js @@ -0,0 +1,101 @@ +/** + * @fileoverview Disallow use of multiple spaces. + * @author Nicholas C. Zakas + * @copyright 2015 Brandon Mills. All rights reserved. + * @copyright 2015 Nicholas C. Zakas. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // the index of the last comment that was checked + var exceptions = { "Property": true }, + hasExceptions = true, + options = context.options[0], + lastCommentIndex = 0; + + if (options && options.exceptions) { + Object.keys(options.exceptions).forEach(function (key) { + if (options.exceptions[key]) { + exceptions[key] = true; + } else { + delete exceptions[key]; + } + }); + hasExceptions = Object.keys(exceptions).length > 0; + } + + /** + * Determines if a given source index is in a comment or not by checking + * the index against the comment range. Since the check goes straight + * through the file, once an index is passed a certain comment, we can + * go to the next comment to check that. + * @param {int} index The source index to check. + * @param {ASTNode[]} comments An array of comment nodes. + * @returns {boolean} True if the index is within a comment, false if not. + * @private + */ + function isIndexInComment(index, comments) { + + var comment; + + while (lastCommentIndex < comments.length) { + + comment = comments[lastCommentIndex]; + + if (comment.range[0] <= index && index < comment.range[1]) { + return true; + } else if (index > comment.range[1]) { + lastCommentIndex++; + } else { + break; + } + + } + + return false; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Program": function() { + + var source = context.getSource(), + allComments = context.getAllComments(), + pattern = /[^\n\r\u2028\u2029 ] {2,}/g, // note: repeating space + token, + parent; + + while (pattern.test(source)) { + + // do not flag anything inside of comments + if (!isIndexInComment(pattern.lastIndex, allComments)) { + + token = context.getTokenByRangeStart(pattern.lastIndex); + + if (token) { + if (hasExceptions) { + parent = context.getNodeByRangeIndex(pattern.lastIndex - 1); + } + + if (!parent || !exceptions[parent.type]) { + context.report(token, token.loc.start, + "Multiple spaces found before '{{value}}'.", + { value: token.value }); + } + } + + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-multi-str.js b/tools/eslint/lib/rules/no-multi-str.js new file mode 100644 index 00000000000000..1d4810b97d7530 --- /dev/null +++ b/tools/eslint/lib/rules/no-multi-str.js @@ -0,0 +1,41 @@ +/** + * @fileoverview Rule to flag when using multiline strings + * @author Ilya Volodin + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Determines if a given node is part of JSX syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a JSX node, false if not. + * @private + */ + function isJSXElement(node) { + return node.type.indexOf("JSX") === 0; + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "Literal": function(node) { + var lineBreak = /\n/; + + if (lineBreak.test(node.raw) && !isJSXElement(node.parent)) { + context.report(node, "Multiline support is limited to browsers supporting ES5 only."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-multiple-empty-lines.js b/tools/eslint/lib/rules/no-multiple-empty-lines.js new file mode 100644 index 00000000000000..9cfea63daab2fc --- /dev/null +++ b/tools/eslint/lib/rules/no-multiple-empty-lines.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Disallows multiple blank lines. + * implementation adapted from the no-trailing-spaces rule. + * @author Greg Cochard + * @copyright 2014 Greg Cochard. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // Use options.max or 2 as default + var numLines = 2; + + if (context.options.length) { + numLines = context.options[0].max; + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function checkBlankLines(node) { + var lines = context.getSourceLines(), + currentLocation = -1, + lastLocation, + blankCounter = 0, + location, + trimmedLines = lines.map(function(str) { + return str.trim(); + }); + + // Aggregate and count blank lines + do { + lastLocation = currentLocation; + currentLocation = trimmedLines.indexOf("", currentLocation + 1); + if (lastLocation === currentLocation - 1) { + blankCounter++; + } else { + if (blankCounter >= numLines) { + location = { + line: lastLocation + 1, + column: lines[lastLocation].length + }; + context.report(node, location, "Multiple blank lines not allowed."); + } + + // Finally, reset the blank counter + blankCounter = 0; + } + } while (currentLocation !== -1); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-native-reassign.js b/tools/eslint/lib/rules/no-native-reassign.js new file mode 100644 index 00000000000000..29ff4a3836b2b4 --- /dev/null +++ b/tools/eslint/lib/rules/no-native-reassign.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Rule to flag when re-assigning native objects + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var nativeObjects = ["Array", "Boolean", "Date", "decodeURI", + "decodeURIComponent", "encodeURI", "encodeURIComponent", + "Error", "eval", "EvalError", "Function", "isFinite", + "isNaN", "JSON", "Math", "Number", "Object", "parseInt", + "parseFloat", "RangeError", "ReferenceError", "RegExp", + "String", "SyntaxError", "TypeError", "URIError", + "Map", "NaN", "Set", "WeakMap", "Infinity", "undefined"]; + + return { + + "AssignmentExpression": function(node) { + if (nativeObjects.indexOf(node.left.name) >= 0) { + context.report(node, node.left.name + " is a read-only native object."); + } + }, + + "VariableDeclarator": function(node) { + if (nativeObjects.indexOf(node.id.name) >= 0) { + context.report(node, "Redefinition of '{{nativeObject}}'.", { nativeObject: node.id.name }); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-negated-in-lhs.js b/tools/eslint/lib/rules/no-negated-in-lhs.js new file mode 100644 index 00000000000000..75bdf7319216b1 --- /dev/null +++ b/tools/eslint/lib/rules/no-negated-in-lhs.js @@ -0,0 +1,23 @@ +/** + * @fileoverview A rule to disallow negated left operands of the `in` operator + * @author Michael Ficarra + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "BinaryExpression": function(node) { + if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { + context.report(node, "The `in` expression's left operand is negated"); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-nested-ternary.js b/tools/eslint/lib/rules/no-nested-ternary.js new file mode 100644 index 00000000000000..10b0683f9529f5 --- /dev/null +++ b/tools/eslint/lib/rules/no-nested-ternary.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Rule to flag nested ternary expressions + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "ConditionalExpression": function(node) { + if (node.alternate.type === "ConditionalExpression" || + node.consequent.type === "ConditionalExpression") { + context.report(node, "Do not nest ternary expressions"); + } + } + }; +}; diff --git a/tools/eslint/lib/rules/no-new-func.js b/tools/eslint/lib/rules/no-new-func.js new file mode 100644 index 00000000000000..c0e64350ed4ffa --- /dev/null +++ b/tools/eslint/lib/rules/no-new-func.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Rule to flag when using new Function + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "NewExpression": function(node) { + if (node.callee.name === "Function") { + context.report(node, "The Function constructor is eval."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-new-object.js b/tools/eslint/lib/rules/no-new-object.js new file mode 100644 index 00000000000000..426d7129da63de --- /dev/null +++ b/tools/eslint/lib/rules/no-new-object.js @@ -0,0 +1,23 @@ +/** + * @fileoverview A rule to disallow calls to the Object constructor + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "NewExpression": function(node) { + if (node.callee.name === "Object") { + context.report(node, "The object literal notation {} is preferrable."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-new-require.js b/tools/eslint/lib/rules/no-new-require.js new file mode 100644 index 00000000000000..27d25d22afb9c7 --- /dev/null +++ b/tools/eslint/lib/rules/no-new-require.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Rule to disallow use of new operator with the `require` function + * @author Wil Moore III + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "NewExpression": function(node) { + if (node.callee.type === "Identifier" && node.callee.name === "require") { + context.report(node, "Unexpected use of new with require."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-new-wrappers.js b/tools/eslint/lib/rules/no-new-wrappers.js new file mode 100644 index 00000000000000..4dbc60d5b4fa1f --- /dev/null +++ b/tools/eslint/lib/rules/no-new-wrappers.js @@ -0,0 +1,24 @@ +/** + * @fileoverview Rule to flag when using constructor for wrapper objects + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "NewExpression": function(node) { + var wrapperObjects = ["String", "Number", "Boolean", "Math", "JSON"]; + if (wrapperObjects.indexOf(node.callee.name) > -1) { + context.report(node, "Do not use {{fn}} as a constructor.", { fn: node.callee.name }); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-new.js b/tools/eslint/lib/rules/no-new.js new file mode 100644 index 00000000000000..914a6493039190 --- /dev/null +++ b/tools/eslint/lib/rules/no-new.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Rule to flag statements with function invocation preceded by + * "new" and not part of assignment + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ExpressionStatement": function(node) { + + if (node.expression.type === "NewExpression") { + context.report(node, "Do not use 'new' for side effects."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-obj-calls.js b/tools/eslint/lib/rules/no-obj-calls.js new file mode 100644 index 00000000000000..246720c2c4abd5 --- /dev/null +++ b/tools/eslint/lib/rules/no-obj-calls.js @@ -0,0 +1,26 @@ +/** + * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "CallExpression": function(node) { + + if (node.callee.type === "Identifier") { + var name = node.callee.name; + if (name === "Math" || name === "JSON") { + context.report(node, "'{{name}}' is not a function.", { name: name }); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-octal-escape.js b/tools/eslint/lib/rules/no-octal-escape.js new file mode 100644 index 00000000000000..d6c75a868dbbae --- /dev/null +++ b/tools/eslint/lib/rules/no-octal-escape.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Rule to flag octal escape sequences in string literals. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + if (typeof node.value !== "string") { + return; + } + + var match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-3][0-7]{1,2}|[4-7][0-7]|[0-7])/), + octalDigit; + + if (match) { + octalDigit = match[2]; + + // \0 is actually not considered an octal + if (match[2] !== "0" || typeof match[3] !== "undefined") { + context.report(node, "Don't use octal: '\\{{octalDigit}}'. Use '\\u....' instead.", + { octalDigit: octalDigit }); + } + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-octal.js b/tools/eslint/lib/rules/no-octal.js new file mode 100644 index 00000000000000..dae4f7fe94c5fa --- /dev/null +++ b/tools/eslint/lib/rules/no-octal.js @@ -0,0 +1,23 @@ +/** + * @fileoverview Rule to flag when initializing octal literal + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + if (typeof node.value === "number" && /^0[0-7]/.test(node.raw)) { + context.report(node, "Octal literals should not be used."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-param-reassign.js b/tools/eslint/lib/rules/no-param-reassign.js new file mode 100644 index 00000000000000..c38f0ef6f4ea32 --- /dev/null +++ b/tools/eslint/lib/rules/no-param-reassign.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Disallow reassignment of function parameters. + * @author Nat Burns + * @copyright 2014 Nat Burns. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Finds the declaration for a given variable by name, searching up the scope tree. + * @param {Scope} scope The scope in which to search. + * @param {String} name The name of the variable. + * @returns {Variable} The declaration information for the given variable, or null if no declaration was found. + */ + function findDeclaration(scope, name) { + var variables = scope.variables; + + for (var i = 0; i < variables.length; i++) { + if (variables[i].name === name) { + return variables[i]; + } + } + + if (scope.upper) { + return findDeclaration(scope.upper, name); + } else { + return null; + } + } + + /** + * Determines if a given variable is declared as a function parameter. + * @param {Variable} variable The variable declaration. + * @returns {boolean} True if the variable is a function parameter, false otherwise. + */ + function isParameter(variable) { + var defs = variable.defs; + + for (var i = 0; i < defs.length; i++) { + if (defs[i].type === "Parameter") { + return true; + } + } + + return false; + } + + /** + * Checks whether a given node is an assignment to a function parameter. + * If so, a linting error will be reported. + * @param {ASTNode} node The node to check. + * @param {String} name The name of the variable being assigned to. + * @returns {void} + */ + function checkParameter(node, name) { + var declaration = findDeclaration(context.getScope(), name); + + if (declaration && isParameter(declaration)) { + context.report(node, "Assignment to function parameter '{{name}}'.", { name: name }); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "AssignmentExpression": function(node) { + checkParameter(node, node.left.name); + }, + + "UpdateExpression": function(node) { + checkParameter(node, node.argument.name); + } + }; +}; diff --git a/tools/eslint/lib/rules/no-path-concat.js b/tools/eslint/lib/rules/no-path-concat.js new file mode 100644 index 00000000000000..b5555891576ce5 --- /dev/null +++ b/tools/eslint/lib/rules/no-path-concat.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Disallow string concatenation when using __dirname and __filename + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MATCHER = /^__(?:dir|file)name$/; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "BinaryExpression": function(node) { + + var left = node.left, + right = node.right; + + if (node.operator === "+" && + ((left.type === "Identifier" && MATCHER.test(left.name)) || + (right.type === "Identifier" && MATCHER.test(right.name))) + ) { + + context.report(node, "Use path.join() or path.resolve() instead of + to create paths."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-plusplus.js b/tools/eslint/lib/rules/no-plusplus.js new file mode 100644 index 00000000000000..268af7ee647501 --- /dev/null +++ b/tools/eslint/lib/rules/no-plusplus.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Rule to flag use of unary increment and decrement operators. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "UpdateExpression": function(node) { + context.report(node, "Unary operator '" + node.operator + "' used."); + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-process-env.js b/tools/eslint/lib/rules/no-process-env.js new file mode 100644 index 00000000000000..54a0cb49285375 --- /dev/null +++ b/tools/eslint/lib/rules/no-process-env.js @@ -0,0 +1,28 @@ +/** + * @fileoverview Disallow the use of process.env() + * @author Vignesh Anand + * @copyright 2014 Vignesh Anand. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + var objectName = node.object.name, + propertyName = node.property.name; + + if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { + context.report(node, "Unexpected use of process.env."); + } + + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-process-exit.js b/tools/eslint/lib/rules/no-process-exit.js new file mode 100644 index 00000000000000..84006f2dbd1a5d --- /dev/null +++ b/tools/eslint/lib/rules/no-process-exit.js @@ -0,0 +1,31 @@ +/** + * @fileoverview Disallow the use of process.exit() + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "CallExpression": function(node) { + var callee = node.callee; + + if (callee.type === "MemberExpression" && callee.object.name === "process" && + callee.property.name === "exit" + ) { + context.report(node, "Don't use process.exit(); throw an error instead."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-proto.js b/tools/eslint/lib/rules/no-proto.js new file mode 100644 index 00000000000000..0ab434c1f544ca --- /dev/null +++ b/tools/eslint/lib/rules/no-proto.js @@ -0,0 +1,26 @@ +/** + * @fileoverview Rule to flag usage of __proto__ property + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + + if (node.property && + (node.property.type === "Identifier" && node.property.name === "__proto__" && !node.computed) || + (node.property.type === "Literal" && node.property.value === "__proto__")) { + context.report(node, "The '__proto__' property is deprecated."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-redeclare.js b/tools/eslint/lib/rules/no-redeclare.js new file mode 100644 index 00000000000000..da1b7bff4c282b --- /dev/null +++ b/tools/eslint/lib/rules/no-redeclare.js @@ -0,0 +1,58 @@ +/** + * @fileoverview Rule to flag when the same variable is declared more then once. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Find variables in a given scope and flag redeclared ones. + * @param {Scope} scope An escope scope object. + * @returns {void} + * @private + */ + function findVariablesInScope(scope) { + scope.variables.forEach(function(variable) { + + if (variable.identifiers && variable.identifiers.length > 1) { + variable.identifiers.sort(function(a, b) { + return a.range[1] - b.range[1]; + }); + + for (var i = 1, l = variable.identifiers.length; i < l; i++) { + context.report(variable.identifiers[i], "{{a}} is already defined", {a: variable.name}); + } + } + }); + + } + + /** + * Find variables in a given node's associated scope. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function findVariables(node) { + var scope = context.getScope(); + + findVariablesInScope(scope); + + // globalReturn means one extra scope to check + if (node.type === "Program" && context.ecmaFeatures.globalReturn) { + findVariablesInScope(scope.childScopes[0]); + } + } + + return { + "Program": findVariables, + "FunctionExpression": findVariables, + "FunctionDeclaration": findVariables + }; +}; diff --git a/tools/eslint/lib/rules/no-regex-spaces.js b/tools/eslint/lib/rules/no-regex-spaces.js new file mode 100644 index 00000000000000..edbf76d51313c8 --- /dev/null +++ b/tools/eslint/lib/rules/no-regex-spaces.js @@ -0,0 +1,33 @@ +/** + * @fileoverview Rule to count multiple spaces in regular expressions + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + var token = context.getFirstToken(node), + nodeType = token.type, + nodeValue = token.value, + multipleSpacesRegex = /( {2,})+?/, + regexResults; + + if (nodeType === "RegularExpression") { + regexResults = multipleSpacesRegex.exec(nodeValue); + + if (regexResults !== null) { + context.report(node, "Spaces are hard to count. Use {" + regexResults[0].length + "}."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-reserved-keys.js b/tools/eslint/lib/rules/no-reserved-keys.js new file mode 100644 index 00000000000000..d94dcffb974e66 --- /dev/null +++ b/tools/eslint/lib/rules/no-reserved-keys.js @@ -0,0 +1,54 @@ +/** + * @fileoverview Rule to disallow reserved words being used as keys + * @author Emil Bay + * @copyright 2014 Emil Bay. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MESSAGE = "Reserved word '{{key}}' used as key."; + + var reservedWords = [ + "abstract", + "boolean", "break", "byte", + "case", "catch", "char", "class", "const", "continue", + "debugger", "default", "delete", "do", "double", + "else", "enum", "export", "extends", + "final", "finally", "float", "for", "function", + "goto", + "if", "implements", "import", "in", "instanceof", "int", "interface", + "long", + "native", "new", + "package", "private", "protected", "public", + "return", + "short", "static", "super", "switch", "synchronized", + "this", "throw", "throws", "transient", "try", "typeof", + "var", "void", "volatile", + "while", "with" + ]; + + return { + + "ObjectExpression": function(node) { + node.properties.forEach(function(property) { + + if (property.key.type === "Identifier") { + var keyName = property.key.name; + + if (reservedWords.indexOf("" + keyName) !== -1) { + context.report(node, MESSAGE, { key: keyName }); + } + } + + }); + + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-restricted-modules.js b/tools/eslint/lib/rules/no-restricted-modules.js new file mode 100644 index 00000000000000..a4c13517dfb31b --- /dev/null +++ b/tools/eslint/lib/rules/no-restricted-modules.js @@ -0,0 +1,72 @@ +/** + * @fileoverview Restrict usage of specified node modules. + * @author Christian Schulz + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + // trim restricted module names + var restrictedModules = context.options; + + // if no modules are restricted we don't need to check the CallExpressions + if (restrictedModules.length === 0) { + return {}; + } + + /** + * Function to check if a node is a string literal. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a string literal. + */ + function isString(node) { + return node && node.type === "Literal" && typeof node.value === "string"; + } + + /** + * Function to check if a node is a require call. + * @param {ASTNode} node The node to check. + * @returns {boolean} If the node is a require call. + */ + function isRequireCall(node) { + return node.callee.type === "Identifier" && node.callee.name === "require"; + } + + /** + * Function to check if a node has an argument that is an restricted module and return its name. + * @param {ASTNode} node The node to check + * @returns {undefined|String} restricted module name or undefined if node argument isn't restricted. + */ + function getRestrictedModuleName(node) { + var moduleName; + + // node has arguments and first argument is string + if (node.arguments.length && isString(node.arguments[0])) { + var argumentValue = node.arguments[0].value.trim(); + + // check if argument value is in restricted modules array + if (restrictedModules.indexOf(argumentValue) !== -1) { + moduleName = argumentValue; + } + } + + return moduleName; + } + + return { + "CallExpression": function (node) { + if (isRequireCall(node)) { + var restrictedModuleName = getRestrictedModuleName(node); + + if (restrictedModuleName) { + context.report(node, "'{{moduleName}}' module is restricted from being used.", { + moduleName: restrictedModuleName + }); + } + } + } + }; +}; diff --git a/tools/eslint/lib/rules/no-return-assign.js b/tools/eslint/lib/rules/no-return-assign.js new file mode 100644 index 00000000000000..65a751c0e84000 --- /dev/null +++ b/tools/eslint/lib/rules/no-return-assign.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Rule to flag when return statement contains assignment + * @author Ilya Volodin + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ReturnStatement": function(node) { + if (node.argument && node.argument.type === "AssignmentExpression") { + context.report(node, "Return statement should not contain assignment."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-script-url.js b/tools/eslint/lib/rules/no-script-url.js new file mode 100644 index 00000000000000..9ae9ba1a3ad20f --- /dev/null +++ b/tools/eslint/lib/rules/no-script-url.js @@ -0,0 +1,32 @@ +/** + * @fileoverview Rule to flag when using javascript: urls + * @author Ilya Volodin + */ +/*jshint scripturl: true */ +/*eslint no-script-url: 0*/ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + + var value; + + if (node.value && typeof node.value === "string") { + value = node.value.toLowerCase(); + + if (value.indexOf("javascript:") === 0) { + context.report(node, "Script URL is a form of eval."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-self-compare.js b/tools/eslint/lib/rules/no-self-compare.js new file mode 100644 index 00000000000000..dc68c50046f2ff --- /dev/null +++ b/tools/eslint/lib/rules/no-self-compare.js @@ -0,0 +1,27 @@ +/** + * @fileoverview Rule to flag comparison where left part is the same as the right + * part. + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "BinaryExpression": function(node) { + var operators = ["===", "==", "!==", "!=", ">", "<", ">=", "<="]; + if (operators.indexOf(node.operator) > -1 && + (node.left.type === "Identifier" && node.right.type === "Identifier" && node.left.name === node.right.name || + node.left.type === "Literal" && node.right.type === "Literal" && node.left.value === node.right.value)) { + context.report(node, "Comparing to itself is potentially pointless."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-sequences.js b/tools/eslint/lib/rules/no-sequences.js new file mode 100644 index 00000000000000..7edcd40d700358 --- /dev/null +++ b/tools/eslint/lib/rules/no-sequences.js @@ -0,0 +1,92 @@ +/** + * @fileoverview Rule to flag use of comma operator + * @author Brandon Mills + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Parts of the grammar that are required to have parens. + */ + var parenthesized = { + "DoWhileStatement": "test", + "IfStatement": "test", + "SwitchStatement": "discriminant", + "WhileStatement": "test", + "WithStatement": "object" + + // Omitting CallExpression - commas are parsed as argument separators + // Omitting NewExpression - commas are parsed as argument separators + // Omitting ForInStatement - parts aren't individually parenthesised + // Omitting ForStatement - parts aren't individually parenthesised + }; + + /** + * Determines whether a node is required by the grammar to be wrapped in + * parens, e.g. the test of an if statement. + * @param {ASTNode} node - The AST node + * @returns {boolean} True if parens around node belong to parent node. + */ + function requiresExtraParens(node) { + return node.parent && parenthesized[node.parent.type] != null && + node === node.parent[parenthesized[node.parent.type]]; + } + + /** + * Check if a node is wrapped in parens. + * @param {ASTNode} node - The AST node + * @returns {boolean} True if the node has a paren on each side. + */ + function isParenthesised(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + + return previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + /** + * Check if a node is wrapped in two levels of parens. + * @param {ASTNode} node - The AST node + * @returns {boolean} True if two parens surround the node on each side. + */ + function isParenthesisedTwice(node) { + var previousToken = context.getTokenBefore(node, 1), + nextToken = context.getTokenAfter(node, 1); + + return isParenthesised(node) && previousToken && nextToken && + previousToken.value === "(" && previousToken.range[1] <= node.range[0] && + nextToken.value === ")" && nextToken.range[0] >= node.range[1]; + } + + return { + "SequenceExpression": function(node) { + // Always allow sequences in for statement update + if (node.parent.type === "ForStatement" && + (node === node.parent.init || node === node.parent.update)) { + return; + } + + // Wrapping a sequence in extra parens indicates intent + if (requiresExtraParens(node)) { + if (isParenthesisedTwice(node)) { + return; + } + } else { + if (isParenthesised(node)) { + return; + } + } + + context.report(node, "Unexpected use of comma operator."); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-shadow-restricted-names.js b/tools/eslint/lib/rules/no-shadow-restricted-names.js new file mode 100644 index 00000000000000..e720a0a153438b --- /dev/null +++ b/tools/eslint/lib/rules/no-shadow-restricted-names.js @@ -0,0 +1,49 @@ +/** + * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1) + * @author Michael Ficarra + * @copyright 2013 Michael Ficarra. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var RESTRICTED = ["undefined", "NaN", "Infinity", "arguments", "eval"]; + + function checkForViolation(id) { + if (RESTRICTED.indexOf(id.name) > -1) { + context.report(id, "Shadowing of global property \"" + id.name + "\"."); + } + } + + return { + "VariableDeclarator": function(node) { + checkForViolation(node.id); + }, + "ArrowFunctionExpression": function(node) { + if (node.id) { + checkForViolation(node.id); + } + [].map.call(node.params, checkForViolation); + }, + "FunctionExpression": function(node) { + if (node.id) { + checkForViolation(node.id); + } + [].map.call(node.params, checkForViolation); + }, + "FunctionDeclaration": function(node) { + if (node.id) { + checkForViolation(node.id); + [].map.call(node.params, checkForViolation); + } + }, + "CatchClause": function(node) { + checkForViolation(node.param); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-shadow.js b/tools/eslint/lib/rules/no-shadow.js new file mode 100644 index 00000000000000..4906fa58f261f8 --- /dev/null +++ b/tools/eslint/lib/rules/no-shadow.js @@ -0,0 +1,72 @@ +/** + * @fileoverview Rule to flag on declaring variables already declared in the outer scope + * @author Ilya Volodin + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Checks if a variable is contained in the list of given scope variables. + * @param {Object} variable The variable to check. + * @param {Array} scopeVars The scope variables to look for. + * @returns {boolean} Whether or not the variable is contains in the list of scope variables. + */ + function isContainedInScopeVars(variable, scopeVars) { + return scopeVars.some(function (scopeVar) { + if (scopeVar.identifiers.length > 0) { + return variable.name === scopeVar.name; + } + return false; + }); + } + + /** + * Checks if the given variables are shadowed in the given scope. + * @param {Array} variables The variables to look for + * @param {Object} scope The scope to be checked. + * @returns {void} + */ + function checkShadowsInScope(variables, scope) { + variables.forEach(function (variable) { + if (isContainedInScopeVars(variable, scope.variables) && + // "arguments" is a special case that has no identifiers (#1759) + variable.identifiers.length > 0 && + + // function names are exempt + variable.defs.length && variable.defs[0].type !== "FunctionName" + ) { + context.report(variable.identifiers[0], "{{a}} is already declared in the upper scope.", {a: variable.name}); + } + }); + } + + /** + * Checks the current context for shadowed variables. + * @returns {void} + */ + function checkForShadows() { + var scope = context.getScope(), + variables = scope.variables; + + // iterate through the array of variables and find duplicates with the upper scope + var upper = scope.upper; + while (upper) { + checkShadowsInScope(variables, upper); + upper = upper.upper; + } + } + + return { + "FunctionDeclaration": checkForShadows, + "FunctionExpression": checkForShadows, + "ArrowFunctionExpression": checkForShadows + }; + +}; diff --git a/tools/eslint/lib/rules/no-space-before-semi.js b/tools/eslint/lib/rules/no-space-before-semi.js new file mode 100644 index 00000000000000..33926741e0b677 --- /dev/null +++ b/tools/eslint/lib/rules/no-space-before-semi.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Rule to disallow whitespace before the semicolon + * @author Jonathan Kingston + * @copyright 2015 Mathias Schreck + * @copyright 2014 Jonathan Kingston + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Checks whether two tokens are on the same line. + * @param {Object} left The leftmost token. + * @param {Object} right The rightmost token. + * @returns {boolean} True if the tokens are on the same line, false if not. + * @private + */ + function isSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + } + + /** + * Checks if a given token has leading whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has leading space, false if not. + */ + function hasLeadingSpace(token) { + var tokenBefore = context.getTokenBefore(token); + return isSameLine(tokenBefore, token) && isSpaced(tokenBefore, token); + } + + /** + * Checks if the given token is a semicolon. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the given token is a semicolon. + */ + function isSemicolon(token) { + return token.type === "Punctuator" && token.value === ";"; + } + + /** + * Reports if the given token has leading space. + * @param {Token} token The semicolon token to check. + * @param {ASTNode} node The corresponding node of the token. + * @returns {void} + */ + function checkSemiTokenForLeadingSpace(token, node) { + if (isSemicolon(token) && hasLeadingSpace(token)) { + context.report(node, token.loc.start, "Unexpected whitespace before semicolon."); + } + } + + /** + * Checks leading space before the semicolon with the assumption that the last token is the semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + var token = context.getLastToken(node); + checkSemiTokenForLeadingSpace(token, node); + } + + return { + "VariableDeclaration": checkNode, + "ExpressionStatement": checkNode, + "BreakStatement": checkNode, + "ContinueStatement": checkNode, + "DebuggerStatement": checkNode, + "ReturnStatement": checkNode, + "ThrowStatement": checkNode, + "ForStatement": function (node) { + if (node.init) { + checkSemiTokenForLeadingSpace(context.getTokenAfter(node.init), node); + } + + if (node.test) { + checkSemiTokenForLeadingSpace(context.getTokenAfter(node.test), node); + } + } + }; +}; diff --git a/tools/eslint/lib/rules/no-spaced-func.js b/tools/eslint/lib/rules/no-spaced-func.js new file mode 100644 index 00000000000000..7fb9fc286472a4 --- /dev/null +++ b/tools/eslint/lib/rules/no-spaced-func.js @@ -0,0 +1,35 @@ +/** + * @fileoverview Rule to check that spaced function application + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function detectOpenSpaces(node) { + var lastCalleeToken = context.getLastToken(node.callee); + var tokens = context.getTokens(node); + var i = tokens.indexOf(lastCalleeToken), l = tokens.length; + while (i < l && tokens[i].value !== "(") { + ++i; + } + if (i >= l) { + return; + } + // look for a space between the callee and the open paren + if (tokens[i - 1].range[1] !== tokens[i].range[0]) { + context.report(node, "Unexpected space between function name and paren."); + } + } + + return { + "CallExpression": detectOpenSpaces, + "NewExpression": detectOpenSpaces + }; + +}; diff --git a/tools/eslint/lib/rules/no-sparse-arrays.js b/tools/eslint/lib/rules/no-sparse-arrays.js new file mode 100644 index 00000000000000..143097713f08d6 --- /dev/null +++ b/tools/eslint/lib/rules/no-sparse-arrays.js @@ -0,0 +1,31 @@ +/** + * @fileoverview Disallow sparse arrays + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "ArrayExpression": function(node) { + + var emptySpot = node.elements.indexOf(null) > -1; + + if (emptySpot) { + context.report(node, "Unexpected comma in middle of array."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-sync.js b/tools/eslint/lib/rules/no-sync.js new file mode 100644 index 00000000000000..1a9d27d637c507 --- /dev/null +++ b/tools/eslint/lib/rules/no-sync.js @@ -0,0 +1,28 @@ +/** + * @fileoverview Rule to check for properties whose identifier ends with the string Sync + * @author Matt DuVall + */ + +/*jshint node:true*/ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "MemberExpression": function(node) { + var propertyName = node.property.name, + syncRegex = /.*Sync$/; + + if (syncRegex.exec(propertyName) !== null) { + context.report(node, "Unexpected sync method: '" + propertyName + "'."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-ternary.js b/tools/eslint/lib/rules/no-ternary.js new file mode 100644 index 00000000000000..6ae8e9a272b29a --- /dev/null +++ b/tools/eslint/lib/rules/no-ternary.js @@ -0,0 +1,22 @@ +/** + * @fileoverview Rule to flag use of ternary operators. + * @author Ian Christian Myers + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ConditionalExpression": function(node) { + context.report(node, "Ternary operator used."); + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-throw-literal.js b/tools/eslint/lib/rules/no-throw-literal.js new file mode 100644 index 00000000000000..d02e7786b694c1 --- /dev/null +++ b/tools/eslint/lib/rules/no-throw-literal.js @@ -0,0 +1,31 @@ +/** + * @fileoverview Rule to restrict what can be thrown as an exception. + * @author Dieter Oberkofler + * @copyright 2015 Dieter Oberkofler. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "ThrowStatement": function(node) { + + if (node.argument.type === "Literal") { + context.report(node, "Do not throw a literal."); + } else if (node.argument.type === "Identifier") { + if (node.argument.name === "undefined") { + context.report(node, "Do not throw undefined."); + } + } + + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-trailing-spaces.js b/tools/eslint/lib/rules/no-trailing-spaces.js new file mode 100644 index 00000000000000..d299eb5151221c --- /dev/null +++ b/tools/eslint/lib/rules/no-trailing-spaces.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Disallow trailing spaces at the end of lines. + * @author Nodeca Team + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var TRAILER = "[ \t\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]+$"; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program": function checkTrailingSpaces(node) { + + // Let's hack. Since Esprima does not return whitespace nodes, + // fetch the source code and do black magic via regexps. + + var src = context.getSource(), + re = new RegExp(TRAILER, "mg"), + match, lines, location; + + while ((match = re.exec(src)) !== null) { + lines = src.slice(0, re.lastIndex).split(/\r?\n/g); + + location = { + line: lines.length, + column: lines[lines.length - 1].length - match[0].length + 1 + }; + + // Passing node is a bit dirty, because message data will contain + // big text in `source`. But... who cares :) ? + // One more kludge will not make worse the bloody wizardry of this plugin. + context.report(node, location, "Trailing spaces not allowed."); + } + } + + }; +}; diff --git a/tools/eslint/lib/rules/no-undef-init.js b/tools/eslint/lib/rules/no-undef-init.js new file mode 100644 index 00000000000000..60ad5700f87f5c --- /dev/null +++ b/tools/eslint/lib/rules/no-undef-init.js @@ -0,0 +1,26 @@ +/** + * @fileoverview Rule to flag when initializing to undefined + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "VariableDeclarator": function(node) { + var name = node.id.name; + var init = node.init && node.init.name; + + if (init === "undefined") { + context.report(node, "It's not necessary to initialize '{{name}}' to undefined.", { name: name }); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-undef.js b/tools/eslint/lib/rules/no-undef.js new file mode 100644 index 00000000000000..5ee07f312473fa --- /dev/null +++ b/tools/eslint/lib/rules/no-undef.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Rule to flag references to undeclared variables. + * @author Mark Macdonald + * @copyright 2015 Nicholas C. Zakas. All rights reserved. + * @copyright 2013 Mark Macdonald. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// none! + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +function isImplicitGlobal(variable) { + return variable.defs.every(function(def) { + return def.type === "ImplicitGlobalVariable"; + }); +} + +/** + * Gets the declared variable, defined in `scope`, that `ref` refers to. + * @param {Scope} scope The scope in which to search. + * @param {Reference} ref The reference to find in the scope. + * @returns {Variable} The variable, or null if ref refers to an undeclared variable. + */ +function getDeclaredGlobalVariable(scope, ref) { + var declaredGlobal = null; + scope.variables.some(function(variable) { + if (variable.name === ref.identifier.name) { + // If it's an implicit global, it must have a `writeable` field (indicating it was declared) + if (!isImplicitGlobal(variable) || {}.hasOwnProperty.call(variable, "writeable")) { + declaredGlobal = variable; + return true; + } + } + return false; + }); + return declaredGlobal; +} + +/** + * Checks if the given node is the argument of a typeof operator. + * @param {ASTNode} node The AST node being checked. + * @returns {boolean} Whether or not the node is the argument of a typeof operator. + */ +function hasTypeOfOperator(node) { + var parent = node.parent; + return parent.type === "UnaryExpression" && parent.operator === "typeof"; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var NOT_DEFINED_MESSAGE = "\"{{name}}\" is not defined.", + READ_ONLY_MESSAGE = "\"{{name}}\" is read only."; + + return { + + "Program:exit": function(/*node*/) { + + var globalScope = context.getScope(); + + globalScope.through.forEach(function(ref) { + var variable = getDeclaredGlobalVariable(globalScope, ref), + name = ref.identifier.name; + + if (hasTypeOfOperator(ref.identifier)) { + return; + } + + if (!variable) { + context.report(ref.identifier, NOT_DEFINED_MESSAGE, { name: name }); + } else if (ref.isWrite() && variable.writeable === false) { + context.report(ref.identifier, READ_ONLY_MESSAGE, { name: name }); + } + }); + + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-undefined.js b/tools/eslint/lib/rules/no-undefined.js new file mode 100644 index 00000000000000..4d96eb3e92537e --- /dev/null +++ b/tools/eslint/lib/rules/no-undefined.js @@ -0,0 +1,25 @@ +/** + * @fileoverview Rule to flag references to the undefined variable. + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Identifier": function(node) { + if (node.name === "undefined") { + var parent = context.getAncestors().pop(); + if (!parent || parent.type !== "MemberExpression" || node !== parent.property || parent.computed) { + context.report(node, "Unexpected use of undefined."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-underscore-dangle.js b/tools/eslint/lib/rules/no-underscore-dangle.js new file mode 100644 index 00000000000000..354c1e4cda28dd --- /dev/null +++ b/tools/eslint/lib/rules/no-underscore-dangle.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Rule to flag trailing underscores in variable declarations. + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //------------------------------------------------------------------------- + // Helpers + //------------------------------------------------------------------------- + + function hasTrailingUnderscore(identifier) { + var len = identifier.length; + + return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_"); + } + + function isSpecialCaseIdentifierForMemberExpression(identifier) { + return identifier === "__proto__"; + } + + function isSpecialCaseIdentifierInVariableExpression(identifier) { + // Checks for the underscore library usage here + return identifier === "_"; + } + + function checkForTrailingUnderscoreInFunctionDeclaration(node) { + if (node.id) { + var identifier = node.id.name; + + if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier)) { + context.report(node, "Unexpected dangling \"_\" in \"" + identifier + "\"."); + } + } + } + + function checkForTrailingUnderscoreInVariableExpression(node) { + var identifier = node.id.name; + + if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && + !isSpecialCaseIdentifierInVariableExpression(identifier)) { + context.report(node, "Unexpected dangling \"_\" in \"" + identifier + "\"."); + } + } + + function checkForTrailingUnderscoreInMemberExpression(node) { + var identifier = node.property.name; + + if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && + !isSpecialCaseIdentifierForMemberExpression(identifier)) { + context.report(node, "Unexpected dangling \"_\" in \"" + identifier + "\"."); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "FunctionDeclaration": checkForTrailingUnderscoreInFunctionDeclaration, + "VariableDeclarator": checkForTrailingUnderscoreInVariableExpression, + "MemberExpression": checkForTrailingUnderscoreInMemberExpression + }; + +}; diff --git a/tools/eslint/lib/rules/no-unreachable.js b/tools/eslint/lib/rules/no-unreachable.js new file mode 100644 index 00000000000000..6606b6adae82b6 --- /dev/null +++ b/tools/eslint/lib/rules/no-unreachable.js @@ -0,0 +1,96 @@ +/** + * @fileoverview Checks for unreachable code due to return, throws, break, and continue. + * @author Joel Feenstra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + + +function report(context, node, unreachableType) { + var keyword; + switch (unreachableType) { + case "BreakStatement": + keyword = "break"; + break; + case "ContinueStatement": + keyword = "continue"; + break; + case "ReturnStatement": + keyword = "return"; + break; + case "ThrowStatement": + keyword = "throw"; + break; + default: + return; + } + context.report(node, "Found unexpected statement after a {{type}}.", { type: keyword }); +} + + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Checks if a node is an exception for no-unreachable because of variable/function hoisting + * @param {ASTNode} node The AST node to check. + * @returns {boolean} if the node doesn't trigger unreachable + * @private + */ + function isUnreachableAllowed(node) { + return node.type === "FunctionDeclaration" || + node.type === "VariableDeclaration" && + node.declarations.every(function(declaration) { + return declaration.type === "VariableDeclarator" && declaration.init === null; + }); + } + + /* + * Verifies that the given node is the last node or followed exclusively by + * hoisted declarations + * @param {ASTNode} node Node that should be the last node + * @returns {void} + * @private + */ + function checkNode(node) { + var parent = context.getAncestors().pop(); + var field, i, sibling; + + switch (parent.type) { + case "SwitchCase": + field = "consequent"; + break; + case "Program": + case "BlockStatement": + field = "body"; + break; + default: + return; + } + + for (i = parent[field].length - 1; i >= 0; i--) { + sibling = parent[field][i]; + if (sibling === node) { + return; // Found the last reachable statement, all done + } + + if (!isUnreachableAllowed(sibling)) { + report(context, sibling, node.type); + } + } + } + + return { + "ReturnStatement": checkNode, + "ThrowStatement": checkNode, + "ContinueStatement": checkNode, + "BreakStatement": checkNode + }; + +}; diff --git a/tools/eslint/lib/rules/no-unused-expressions.js b/tools/eslint/lib/rules/no-unused-expressions.js new file mode 100644 index 00000000000000..7036f90e7c71be --- /dev/null +++ b/tools/eslint/lib/rules/no-unused-expressions.js @@ -0,0 +1,74 @@ +/** + * @fileoverview Flag expressions in statement position that do not side effect + * @author Michael Ficarra + * @copyright 2013 Michael Ficarra. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * @param {ASTNode} node - any node + * @returns {Boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return node.type === "ExpressionStatement" && + node.expression.type === "Literal" && typeof node.expression.value === "string"; + } + + /** + * @param {Function} predicate - ([a] -> Boolean) the function used to make the determination + * @param {a[]} list - the input list + * @returns {a[]} the leading sequence of members in the given list that pass the given predicate + */ + function takeWhile(predicate, list) { + for (var i = 0, l = list.length; i < l; ++i) { + if (!predicate(list[i])) { + break; + } + } + return [].slice.call(list, 0, i); + } + + /** + * @param {ASTNode} node - a Program or BlockStatement node + * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body + */ + function directives(node) { + return takeWhile(looksLikeDirective, node.body); + } + + /** + * @param {ASTNode} node - any node + * @param {ASTNode[]} ancestors - the given node's ancestors + * @returns {Boolean} whether the given node is considered a directive in its current position + */ + function isDirective(node, ancestors) { + var parent = ancestors[ancestors.length - 1], + grandparent = ancestors[ancestors.length - 2]; + return (parent.type === "Program" || parent.type === "BlockStatement" && + (/Function/.test(grandparent.type))) && + directives(parent).indexOf(node) >= 0; + } + + return { + "ExpressionStatement": function(node) { + + var type = node.expression.type, + ancestors = context.getAncestors(); + + if ( + !/^(?:Assignment|Call|New|Update|Yield)Expression$/.test(type) && + (type !== "UnaryExpression" || ["delete", "void"].indexOf(node.expression.operator) < 0) && + !isDirective(node, ancestors) + ) { + context.report(node, "Expected an assignment or function call and instead saw an expression."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-unused-vars.js b/tools/eslint/lib/rules/no-unused-vars.js new file mode 100644 index 00000000000000..d6ec43bf1d6aac --- /dev/null +++ b/tools/eslint/lib/rules/no-unused-vars.js @@ -0,0 +1,180 @@ +/** + * @fileoverview Rule to flag declared but unused variables + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MESSAGE = "{{name}} is defined but never used"; + + var config = { + vars: "all", + args: "after-used" + }; + + if (context.options[0]) { + if (typeof context.options[0] === "string") { + config.vars = context.options[0]; + } else { + config.vars = context.options[0].vars || config.vars; + config.args = context.options[0].args || config.args; + } + } + + /** + * Determines if a given variable is being exported from a module. + * @param {Variable} variable EScope variable object. + * @returns {boolean} True if the variable is exported, false if not. + * @private + */ + function isExported(variable) { + + var definition = variable.defs[0]; + + if (definition) { + + definition = definition.node; + if (definition.type === "VariableDeclarator") { + definition = definition.parent; + } + + return definition.parent.type.indexOf("Export") === 0; + } else { + return false; + } + } + + /** + * Determines if a reference is a read operation. + * @param {Reference} ref - an escope Reference + * @returns {Boolean} whether the given reference represents a read operation + * @private + */ + function isReadRef(ref) { + return ref.isRead(); + } + + /** + * Determine if an identifier is referencing the enclosing function name. + * @param {Reference} ref The reference to check. + * @returns {boolean} True if it's a self-reference, false if not. + * @private + */ + function isSelfReference(ref) { + + if (ref.from.type === "function" && ref.from.block.id) { + return ref.identifier.name === ref.from.block.id.name; + } + + return false; + } + + /** + * Determines if a reference should be counted as a read. A reference should + * be counted only if it's a read and it's not a reference to the containing + * function declaration name. + * @param {Reference} ref The reference to check. + * @returns {boolean} True if it's a value read reference, false if not. + * @private + */ + function isValidReadRef(ref) { + return isReadRef(ref) && !isSelfReference(ref); + } + + /** + * Gets an array of local variables without read references. + * @param {Scope} scope - an escope Scope object + * @returns {Variable[]} most of the local variables with no read references + * @private + */ + function getUnusedLocals(scope) { + var unused = []; + var variables = scope.variables; + + if (scope.type !== "global" && scope.type !== "TDZ") { + for (var i = 0, l = variables.length; i < l; ++i) { + + // skip function expression names + if (scope.functionExpressionScope || variables[i].eslintUsed) { + continue; + } + // skip implicit "arguments" variable + if (scope.type === "function" && variables[i].name === "arguments" && variables[i].identifiers.length === 0) { + continue; + } + + var def = variables[i].defs[0], + type = def.type; + + // skip catch variables + if (type === "CatchClause") { + continue; + } + + // skip any setter argument + if (type === "Parameter" && def.node.parent.type === "Property" && def.node.parent.kind === "set") { + continue; + } + + // if "args" option is "none", skip any parameter + if (config.args === "none" && type === "Parameter") { + continue; + } + + // if "args" option is "after-used", skip all but the last parameter + if (config.args === "after-used" && type === "Parameter" && variables[i].defs[0].index < variables[i].defs[0].node.params.length - 1) { + continue; + } + + if (variables[i].references.filter(isValidReadRef).length === 0 && !isExported(variables[i])) { + unused.push(variables[i]); + } + } + } + + return [].concat.apply(unused, scope.childScopes.map(getUnusedLocals)); + } + + return { + "Program:exit": function(programNode) { + var globalScope = context.getScope(); + var unused = getUnusedLocals(globalScope); + var i, l; + + // determine unused globals + if (config.vars === "all") { + var unresolvedRefs = globalScope.through.filter(isValidReadRef).map(function(ref) { + return ref.identifier.name; + }); + + for (i = 0, l = globalScope.variables.length; i < l; ++i) { + if (unresolvedRefs.indexOf(globalScope.variables[i].name) < 0 && + !globalScope.variables[i].eslintUsed && !isExported(globalScope.variables[i])) { + unused.push(globalScope.variables[i]); + } + } + } + + for (i = 0, l = unused.length; i < l; ++i) { + if (unused[i].eslintExplicitGlobal) { + context.report(programNode, MESSAGE, unused[i]); + } else if (unused[i].defs.length > 0) { + + // TODO: Remove when https://github.com/estools/escope/issues/49 is resolved + if (unused[i].defs[0].type === "ClassName") { + continue; + } + + context.report(unused[i].identifiers[0], MESSAGE, unused[i]); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-use-before-define.js b/tools/eslint/lib/rules/no-use-before-define.js new file mode 100644 index 00000000000000..3f175dc78b6306 --- /dev/null +++ b/tools/eslint/lib/rules/no-use-before-define.js @@ -0,0 +1,67 @@ +/** + * @fileoverview Rule to flag use of variables before they are defined + * @author Ilya Volodin + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var NO_FUNC = "nofunc"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function findDeclaration(name, scope) { + // try searching in the current scope first + for (var i = 0, l = scope.variables.length; i < l; i++) { + if (scope.variables[i].name === name) { + return scope.variables[i]; + } + } + // check if there's upper scope and call recursivly till we find the variable + if (scope.upper) { + return findDeclaration(name, scope.upper); + } + } + + function findVariables() { + var scope = context.getScope(); + var typeOption = context.options[0]; + + function checkLocationAndReport(reference, declaration) { + if (typeOption !== NO_FUNC || declaration.defs[0].type !== "FunctionName") { + if (declaration.identifiers[0].range[1] > reference.identifier.range[1]) { + context.report(reference.identifier, "{{a}} was used before it was defined", {a: reference.identifier.name}); + } + } + } + + scope.references.forEach(function(reference) { + // if the reference is resolved check for declaration location + // if not, it could be function invocation, try to find manually + if (reference.resolved && reference.resolved.identifiers.length > 0) { + checkLocationAndReport(reference, reference.resolved); + } else { + var declaration = findDeclaration(reference.identifier.name, scope); + // if there're no identifiers, this is a global environment variable + if (declaration && declaration.identifiers.length !== 0) { + checkLocationAndReport(reference, declaration); + } + } + }); + } + + return { + "Program": findVariables, + "FunctionExpression": findVariables, + "FunctionDeclaration": findVariables, + "ArrowFunctionExpression": findVariables + }; +}; diff --git a/tools/eslint/lib/rules/no-var.js b/tools/eslint/lib/rules/no-var.js new file mode 100644 index 00000000000000..6b47b3dab06d7f --- /dev/null +++ b/tools/eslint/lib/rules/no-var.js @@ -0,0 +1,24 @@ +/** + * @fileoverview Rule to check for the usage of var. + * @author Jamund Ferguson + * @copyright 2014 Jamund Ferguson. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "VariableDeclaration": function (node) { + if (node.kind === "var") { + context.report(node, "Unexpected var, use let or const instead."); + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/no-void.js b/tools/eslint/lib/rules/no-void.js new file mode 100644 index 00000000000000..11c54af7fc043d --- /dev/null +++ b/tools/eslint/lib/rules/no-void.js @@ -0,0 +1,26 @@ +/** + * @fileoverview Rule to disallow use of void operator. + * @author Mike Sidorov + * @copyright 2014 Mike Sidorov. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "UnaryExpression": function(node) { + if (node.operator === "void") { + context.report(node, "Expected 'undefined' and instead saw 'void'."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-warning-comments.js b/tools/eslint/lib/rules/no-warning-comments.js new file mode 100644 index 00000000000000..58b6764ff1f676 --- /dev/null +++ b/tools/eslint/lib/rules/no-warning-comments.js @@ -0,0 +1,84 @@ +/** + * @fileoverview Rule that warns about used warning comments + * @author Alexander Schmidt + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + + var configuration = context.options[0] || {}, + warningTerms = configuration.terms || ["todo", "fixme", "xxx"], + location = configuration.location || "start", + warningRegExps; + + /** + * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified + * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not + * require word boundaries on that side. + * + * @param {String} term A term to convert to a RegExp + * @returns {RegExp} The term converted to a RegExp + */ + function convertToRegExp(term) { + var escaped = term.replace(/[-\/\\$\^*+?.()|\[\]{}]/g, "\\$&"), + // If the term ends in a word character (a-z0-9_), ensure a word boundary at the end, so that substrings do + // not get falsely matched. eg "todo" in a string such as "mastodon". + // If the term ends in a non-word character, then \b won't match on the boundary to the next non-word + // character, which would likely be a space. For example `/\bFIX!\b/.test('FIX! blah') === false`. + // In these cases, use no bounding match. Same applies for the prefix, handled below. + suffix = /\w$/.test(term) ? "\\b" : "", + prefix; + + if (location === "start") { + // When matching at the start, ignore leading whitespace, and there's no need to worry about word boundaries + prefix = "^\\s*"; + } else if (/^\w/.test(term)) { + prefix = "\\b"; + } else { + prefix = ""; + } + + return new RegExp(prefix + escaped + suffix, "i"); + } + + /** + * Checks the specified comment for matches of the configured warning terms and returns the matches. + * @param {String} comment The comment which is checked. + * @returns {Array} All matched warning terms for this comment. + */ + function commentContainsWarningTerm(comment) { + var matches = []; + + warningRegExps.forEach(function (regex, index) { + if (regex.test(comment)) { + matches.push(warningTerms[index]); + } + }); + + return matches; + } + + /** + * Checks the specified node for matching warning comments and reports them. + * @param {ASTNode} node The AST node being checked. + * @returns {void} undefined. + */ + function checkComment(node) { + var matches = commentContainsWarningTerm(node.value); + + matches.forEach(function (matchedTerm) { + context.report(node, "Unexpected " + matchedTerm + " comment."); + }); + } + + warningRegExps = warningTerms.map(convertToRegExp); + return { + "BlockComment": checkComment, + "LineComment": checkComment + }; +}; diff --git a/tools/eslint/lib/rules/no-with.js b/tools/eslint/lib/rules/no-with.js new file mode 100644 index 00000000000000..1b889dc5f457a9 --- /dev/null +++ b/tools/eslint/lib/rules/no-with.js @@ -0,0 +1,20 @@ +/** + * @fileoverview Rule to flag use of with statement + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "WithStatement": function(node) { + context.report(node, "Unexpected use of 'with' statement."); + } + }; + +}; diff --git a/tools/eslint/lib/rules/no-wrap-func.js b/tools/eslint/lib/rules/no-wrap-func.js new file mode 100644 index 00000000000000..a99c09ee384ab6 --- /dev/null +++ b/tools/eslint/lib/rules/no-wrap-func.js @@ -0,0 +1,44 @@ +/** + * @fileoverview Rule to flag wrapping non-iife in parens + * @author Ilya Volodin + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Checks a function expression to see if its surrounded by parens. + * @param {ASTNode} node The node to check. + * @returns {void} + * @private + */ + function checkFunction(node) { + var previousToken, nextToken; + + if (node.type === "ArrowFunctionExpression" && + /(?:Call|New|Logical|Binary|Conditional|Update)Expression/.test(node.parent.type) + ) { + return; + } + + if (!/CallExpression|NewExpression/.test(node.parent.type)) { + previousToken = context.getTokenBefore(node); + nextToken = context.getTokenAfter(node); + if (previousToken.value === "(" && nextToken.value === ")") { + context.report(node, "Wrapping non-IIFE function literals in parens is unnecessary."); + } + } + } + + return { + "ArrowFunctionExpression": checkFunction, + "FunctionExpression": checkFunction + }; + +}; diff --git a/tools/eslint/lib/rules/object-shorthand.js b/tools/eslint/lib/rules/object-shorthand.js new file mode 100644 index 00000000000000..548c9245d685cc --- /dev/null +++ b/tools/eslint/lib/rules/object-shorthand.js @@ -0,0 +1,63 @@ +/** + * @fileoverview Rule to enforce concise object methods and properties. + * @author Jamund Ferguson + * @copyright 2015 Jamund Ferguson. All rights reserved. + */ + +"use strict"; + +var OPTIONS = { + always: "always", + never: "never", + methods: "methods", + properties: "properties" +}; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var APPLY = context.options[0] || OPTIONS.always; + var APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always; + var APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always; + var APPLY_NEVER = APPLY === OPTIONS.never; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "Property": function(node) { + var isConciseProperty = node.method || node.shorthand, + type; + + // if we're "never" and concise we should warn now + if (APPLY_NEVER && isConciseProperty) { + type = node.method ? "method" : "property"; + context.report(node, "Expected longform " + type + " syntax."); + } + + // at this point if we're concise or if we're "never" we can leave + if (APPLY_NEVER || isConciseProperty) { + return; + } + + if (node.value.type === "ArrowFunctionExpression" && APPLY_TO_METHODS) { + + // {x: ()=>{}} should be written as {x() {}} + context.report(node, "Expected method shorthand."); + } else if (node.value.type === "FunctionExpression" && APPLY_TO_METHODS) { + + // {x: function(){}} should be written as {x() {}} + context.report(node, "Expected method shorthand."); + } else if (node.key.name === node.value.name && APPLY_TO_PROPS) { + + // {x: x} should be written as {x} + context.report(node, "Expected property shorthand."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/one-var.js b/tools/eslint/lib/rules/one-var.js new file mode 100644 index 00000000000000..fd28522f0fadff --- /dev/null +++ b/tools/eslint/lib/rules/one-var.js @@ -0,0 +1,175 @@ +/** + * @fileoverview A rule to ensure the use of a single variable declaration. + * @author Ian Christian Myers + * @copyright 2015 Joey Baker. All rights reserved. + * @copyright 2015 Danny Fritz. All rights reserved. + * @copyright 2013 Ian Christian Myers. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MODE = context.options[0] || "always"; + var options = {}; + + // simple options configuration with just a string or no option + if (typeof context.options[0] === "string" || context.options[0] == null) { + options.var = MODE; + options.let = MODE; + options.const = MODE; + } else { + options = context.options[0]; + } + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var functionStack = []; + var blockStack = []; + + /** + * Increments the blockStack counter. + * @returns {void} + * @private + */ + function startBlock() { + blockStack.push({let: false, const: false}); + } + + /** + * Increments the functionStack counter. + * @returns {void} + * @private + */ + function startFunction() { + functionStack.push(false); + startBlock(); + } + + /** + * Decrements the blockStack counter. + * @returns {void} + * @private + */ + function endBlock() { + blockStack.pop(); + } + + /** + * Decrements the functionStack counter. + * @returns {void} + * @private + */ + function endFunction() { + functionStack.pop(); + endBlock(); + } + + /** + * Determines if there is more than one var statement in the current scope. + * @returns {boolean} Returns true if it is the first var declaration, false if not. + * @private + */ + function hasOnlyOneVar() { + if (functionStack[functionStack.length - 1]) { + return true; + } else { + functionStack[functionStack.length - 1] = true; + return false; + } + } + + /** + * Determines if there is more than one let statement in the current scope. + * @returns {boolean} Returns true if it is the first let declaration, false if not. + * @private + */ + function hasOnlyOneLet() { + if (blockStack[blockStack.length - 1].let) { + return true; + } else { + blockStack[blockStack.length - 1].let = true; + return false; + } + } + + /** + * Determines if there is more than one const statement in the current scope. + * @returns {boolean} Returns true if it is the first const declaration, false if not. + * @private + */ + function hasOnlyOneConst() { + if (blockStack[blockStack.length - 1].const) { + return true; + } else { + blockStack[blockStack.length - 1].const = true; + return false; + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "Program": startFunction, + "FunctionDeclaration": startFunction, + "FunctionExpression": startFunction, + "ArrowFunctionExpression": startFunction, + "BlockStatement": startBlock, + "ForStatement": startBlock, + "SwitchStatement": startBlock, + + "VariableDeclaration": function(node) { + var declarationCount = node.declarations.length; + + if (node.kind === "var") { + if (options.var === "never") { + if (declarationCount > 1) { + context.report(node, "Split 'var' declaration into multiple statements."); + } + } else { + if (hasOnlyOneVar()) { + context.report(node, "Combine this with the previous 'var' statement."); + } + } + } else if (node.kind === "let") { + if (options.let === "never") { + if (declarationCount > 1) { + context.report(node, "Split 'let' declaration into multiple statements."); + } + } else { + if (hasOnlyOneLet()) { + context.report(node, "Combine this with the previous 'let' statement."); + } + } + } else if (node.kind === "const") { + if (options.const === "never") { + if (declarationCount > 1) { + context.report(node, "Split 'const' declaration into multiple statements."); + } + } else { + if (hasOnlyOneConst()) { + context.report(node, "Combine this with the previous 'const' statement."); + } + } + + } + }, + + "ForStatement:exit": endBlock, + "SwitchStatement:exit": endBlock, + "BlockStatement:exit": endBlock, + "Program:exit": endFunction, + "FunctionDeclaration:exit": endFunction, + "FunctionExpression:exit": endFunction, + "ArrowFunctionExpression:exit": endFunction + }; + +}; diff --git a/tools/eslint/lib/rules/operator-assignment.js b/tools/eslint/lib/rules/operator-assignment.js new file mode 100644 index 00000000000000..7ebb74d2bae246 --- /dev/null +++ b/tools/eslint/lib/rules/operator-assignment.js @@ -0,0 +1,112 @@ +/** + * @fileoverview Rule to replace assignment expressions with operator assignment + * @author Brandon Mills + * @copyright 2014 Brandon Mills. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Checks whether an operator is commutative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is commutative and has a + * shorthand form. + */ +function isCommutativeOperatorWithShorthand(operator) { + return ["*", "&", "^", "|"].indexOf(operator) >= 0; +} + +/** + * Checks whether an operator is not commuatative and has an operator assignment + * shorthand form. + * @param {string} operator Operator to check. + * @returns {boolean} True if the operator is not commuatative and has + * a shorthand form. + */ +function isNonCommutativeOperatorWithShorthand(operator) { + return ["+", "-", "/", "%", "<<", ">>", ">>>"].indexOf(operator) >= 0; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +/** + * Checks whether two expressions reference the same value. For example: + * a = a + * a.b = a.b + * a[0] = a[0] + * a['b'] = a['b'] + * @param {ASTNode} a Left side of the comparison. + * @param {ASTNode} b Right side of the comparison. + * @returns {boolean} True if both sides match and reference the same value. + */ +function same(a, b) { + if (a.type !== b.type) { + return false; + } + + switch (a.type) { + case "Identifier": + return a.name === b.name; + case "Literal": + return a.value === b.value; + case "MemberExpression": + // x[0] = x[0] + // x[y] = x[y] + // x.y = x.y + return same(a.object, b.object) && same(a.property, b.property); + default: + return false; + } +} + +module.exports = function(context) { + + /** + * Ensures that an assignment uses the shorthand form where possible. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function verify(node) { + var expr, left, operator; + + if (node.operator !== "=" || node.right.type !== "BinaryExpression") { + return; + } + + left = node.left; + expr = node.right; + operator = expr.operator; + + if (isCommutativeOperatorWithShorthand(operator)) { + if (same(left, expr.left) || same(left, expr.right)) { + context.report(node, "Assignment can be replaced with operator assignment."); + } + } else if (isNonCommutativeOperatorWithShorthand(operator)) { + if (same(left, expr.left)) { + context.report(node, "Assignment can be replaced with operator assignment."); + } + } + } + + /** + * Warns if an assignment expression uses operator assignment shorthand. + * @param {ASTNode} node An AssignmentExpression node. + * @returns {void} + */ + function prohibit(node) { + if (node.operator !== "=") { + context.report(node, "Unexpected operator assignment shorthand."); + } + } + + return { + "AssignmentExpression": context.options[0] !== "never" ? verify : prohibit + }; + +}; diff --git a/tools/eslint/lib/rules/operator-linebreak.js b/tools/eslint/lib/rules/operator-linebreak.js new file mode 100644 index 00000000000000..020c61544c6a89 --- /dev/null +++ b/tools/eslint/lib/rules/operator-linebreak.js @@ -0,0 +1,100 @@ +/** + * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before + * @author Benoît Zugmeyer + * @copyright 2015 Benoît Zugmeyer. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var style = context.options[0] || "after"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Checks whether two tokens are on the same line. + * @param {ASTNode} left The leftmost token. + * @param {ASTNode} right The rightmost token. + * @returns {boolean} True if the tokens are on the same line, false if not. + * @private + */ + function isSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + } + + /** + * Checks the operator placement + * @param {ASTNode} node The binary operator node to check + * @private + * @returns {void} + */ + function validateBinaryExpression(node) { + var leftToken = context.getLastToken(node.left || node.id); + var operatorToken = context.getTokenAfter(leftToken); + + // When the left part of a binary expression is a single expression wrapped in + // parentheses (ex: `(a) + b`), leftToken will be the last token of the expression + // and operatorToken will be the closing parenthesis. + // The leftToken should be the last closing parenthesis, and the operatorToken + // should be the token right after that. + while (operatorToken.value === ")") { + leftToken = operatorToken; + operatorToken = context.getTokenAfter(operatorToken); + } + + var rightToken = context.getTokenAfter(operatorToken); + var operator = operatorToken.value; + + // if single line + if (isSameLine(leftToken, operatorToken) && + isSameLine(operatorToken, rightToken)) { + + return; + + } else if (!isSameLine(leftToken, operatorToken) && + !isSameLine(operatorToken, rightToken)) { + + // lone operator + context.report(node, { + line: operatorToken.loc.end.line, + column: operatorToken.loc.end.column + }, "Bad line breaking before and after '" + operator + "'."); + + } else if (style === "before" && isSameLine(leftToken, operatorToken)) { + + context.report(node, { + line: operatorToken.loc.end.line, + column: operatorToken.loc.end.column + }, "'" + operator + "' should be placed at the beginning of the line."); + + } else if (style === "after" && isSameLine(operatorToken, rightToken)) { + + context.report(node, { + line: operatorToken.loc.end.line, + column: operatorToken.loc.end.column + }, "'" + operator + "' should be placed at the end of the line."); + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "BinaryExpression": validateBinaryExpression, + "LogicalExpression": validateBinaryExpression, + "AssignmentExpression": validateBinaryExpression, + "VariableDeclarator": function (node) { + if (node.init) { + validateBinaryExpression(node); + } + } + }; +}; diff --git a/tools/eslint/lib/rules/padded-blocks.js b/tools/eslint/lib/rules/padded-blocks.js new file mode 100644 index 00000000000000..9a5be4df0e33a1 --- /dev/null +++ b/tools/eslint/lib/rules/padded-blocks.js @@ -0,0 +1,92 @@ +/** + * @fileoverview A rule to ensure blank lines within blocks. + * @author Mathias Schreck + * @copyright 2014 Mathias Schreck. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var requirePadding = context.options[0] !== "never"; + + var ALWAYS_MESSAGE = "Block must be padded by blank lines.", + NEVER_MESSAGE = "Block must not be padded by blank lines."; + + /** + * Checks if the given non empty block node has a blank line before its first child node. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {boolean} Whether or not the block starts with a blank line. + */ + function isBlockTopPadded(node) { + var blockStart = node.loc.start.line, + first = node.body[0], + firstLine = first.loc.start.line, + expectedFirstLine = blockStart + 2, + leadingComments = context.getComments(first).leading; + + if (leadingComments.length > 0) { + firstLine = leadingComments[0].loc.start.line; + } + + return expectedFirstLine <= firstLine; + } + + /** + * Checks if the given non empty block node has a blank line after its last child node. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {boolean} Whether or not the block ends with a blank line. + */ + function isBlockBottomPadded(node) { + var blockEnd = node.loc.end.line, + last = node.body[node.body.length - 1], + lastLine = context.getLastToken(last).loc.end.line, + expectedLastLine = blockEnd - 2, + trailingComments = context.getComments(last).trailing; + + if (trailingComments.length > 0) { + lastLine = trailingComments[trailingComments.length - 1].loc.end.line; + } + + return lastLine <= expectedLastLine; + } + + /** + * Checks the given BlockStatement node to be padded if the block is not empty. + * @param {ASTNode} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPadding(node) { + if (node.body.length > 0) { + + var blockHasTopPadding = isBlockTopPadded(node), + blockHasBottomPadding = isBlockBottomPadded(node); + + if (requirePadding) { + if (!blockHasTopPadding) { + context.report(node, ALWAYS_MESSAGE); + } + + if (!blockHasBottomPadding) { + context.report(node, node.loc.end, ALWAYS_MESSAGE); + } + } else { + if (blockHasTopPadding) { + context.report(node, NEVER_MESSAGE); + } + + if (blockHasBottomPadding) { + context.report(node, node.loc.end, NEVER_MESSAGE); + } + } + } + } + + return { + "BlockStatement": checkPadding + }; + +}; diff --git a/tools/eslint/lib/rules/quote-props.js b/tools/eslint/lib/rules/quote-props.js new file mode 100644 index 00000000000000..ccac9478535194 --- /dev/null +++ b/tools/eslint/lib/rules/quote-props.js @@ -0,0 +1,66 @@ +/** + * @fileoverview Rule to flag non-quoted property names in object literals. + * @author Mathias Bynens + * @copyright 2014 Brandon Mills. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var espree = require("espree"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MODE = context.options[0]; + + /** + * Ensures that a property's key is quoted only when necessary + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function asNeeded(node) { + var key = node.key, + tokens; + + if (key.type === "Literal" && typeof key.value === "string") { + try { + tokens = espree.tokenize(key.value); + } catch (e) { + return; + } + + if (tokens.length === 1 && + (["Identifier", "Null", "Boolean"].indexOf(tokens[0].type) >= 0 || + (tokens[0].type === "Numeric" && "" + +tokens[0].value === tokens[0].value)) + ) { + context.report(node, "Unnecessarily quoted property `{{value}}` found.", key); + } + } + } + + /** + * Ensures that a property's key is quoted + * @param {ASTNode} node Property AST node + * @returns {void} + */ + function always(node) { + var key = node.key; + + if (!node.method && !(key.type === "Literal" && typeof key.value === "string")) { + context.report(node, "Unquoted property `{{key}}` found.", { + key: key.name || key.value + }); + } + } + + return { + "Property": MODE === "as-needed" ? asNeeded : always + }; + +}; diff --git a/tools/eslint/lib/rules/quotes.js b/tools/eslint/lib/rules/quotes.js new file mode 100644 index 00000000000000..2bb10ea5e4affc --- /dev/null +++ b/tools/eslint/lib/rules/quotes.js @@ -0,0 +1,83 @@ +/** + * @fileoverview A rule to choose between single and double quote marks + * @author Matt DuVall , Brandon Payton + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var QUOTE_SETTINGS = { + "double": { + quote: "\"", + alternateQuote: "'", + description: "doublequote" + }, + "single": { + quote: "'", + alternateQuote: "\"", + description: "singlequote" + }, + "backtick": { + quote: "`", + alternateQuote: "\"", + description: "backtick" + } +}; + +var AVOID_ESCAPE = "avoid-escape"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + /** + * Validate that a string passed in is surrounded by the specified character + * @param {string} val The text to check. + * @param {string} character The character to see if it's surrounded by. + * @returns {boolean} True if the text is surrounded by the character, false if not. + * @private + */ + function isSurroundedBy(val, character) { + return val[0] === character && val[val.length - 1] === character; + } + + /** + * Determines if a given node is part of JSX syntax. + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a JSX node, false if not. + * @private + */ + function isJSXElement(node) { + return node.type.indexOf("JSX") === 0; + } + + return { + + "Literal": function(node) { + var val = node.value, + rawVal = node.raw, + quoteOption = context.options[0], + settings = QUOTE_SETTINGS[quoteOption], + avoidEscape = context.options[1] === AVOID_ESCAPE, + isValid; + + if (settings && typeof val === "string") { + isValid = isJSXElement(node.parent) || isSurroundedBy(rawVal, settings.quote); + + if (!isValid && avoidEscape) { + isValid = isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0; + } + + if (!isValid) { + context.report(node, "Strings must use " + settings.description + "."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/radix.js b/tools/eslint/lib/rules/radix.js new file mode 100644 index 00000000000000..a0c7acfb2e3ebf --- /dev/null +++ b/tools/eslint/lib/rules/radix.js @@ -0,0 +1,39 @@ +/** + * @fileoverview Rule to flag use of parseInt without a radix argument + * @author James Allardice + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + "CallExpression": function(node) { + + var radix; + + if (node.callee.name === "parseInt") { + + if (node.arguments.length < 2) { + context.report(node, "Missing radix parameter."); + } else { + + radix = node.arguments[1]; + + // don't allow non-numeric literals or undefined + if ((radix.type === "Literal" && typeof radix.value !== "number") || + (radix.type === "Identifier" && radix.name === "undefined") + ) { + context.report(node, "Invalid radix parameter."); + } + } + + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/semi-spacing.js b/tools/eslint/lib/rules/semi-spacing.js new file mode 100644 index 00000000000000..05ced44593438f --- /dev/null +++ b/tools/eslint/lib/rules/semi-spacing.js @@ -0,0 +1,152 @@ +/** + * @fileoverview Validates spacing before and after semicolon + * @author Mathias Schreck + * @copyright 2015 Mathias Schreck + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + + var config = context.options[0], + requireSpaceBefore = false, + requireSpaceAfter = true; + + if (typeof config === "object") { + if (config.hasOwnProperty("before")) { + requireSpaceBefore = config.before; + } + if (config.hasOwnProperty("after")) { + requireSpaceAfter = config.after; + } + } + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Checks whether two tokens are on the same line. + * @param {Object} left The leftmost token. + * @param {Object} right The rightmost token. + * @returns {boolean} True if the tokens are on the same line, false if not. + * @private + */ + function isSameLine(left, right) { + return left.loc.end.line === right.loc.start.line; + } + + /** + * Checks if a given token has leading whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has leading space, false if not. + */ + function hasLeadingSpace(token) { + var tokenBefore = context.getTokenBefore(token); + return tokenBefore && isSameLine(tokenBefore, token) && isSpaced(tokenBefore, token); + } + + /** + * Checks if a given token has trailing whitespace. + * @param {Object} token The token to check. + * @returns {boolean} True if the given token has trailing space, false if not. + */ + function hasTrailingSpace(token) { + var tokenAfter = context.getTokenAfter(token); + return tokenAfter && isSameLine(token, tokenAfter) && isSpaced(token, tokenAfter); + } + + /** + * Checks if the given token is the last token in its line. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the token is the last in its line. + */ + function isLastTokenInCurrentLine(token) { + var tokenAfter = context.getTokenAfter(token); + return !(tokenAfter && isSameLine(token, tokenAfter)); + } + + /** + * Checks if the given token is a semicolon. + * @param {Token} token The token to check. + * @returns {boolean} Whether or not the given token is a semicolon. + */ + function isSemicolon(token) { + return token.type === "Punctuator" && token.value === ";"; + } + + /** + * Reports if the given token has invalid spacing. + * @param {Token} token The semicolon token to check. + * @param {ASTNode} node The corresponding node of the token. + * @returns {void} + */ + function checkSemicolonSpacing(token, node) { + var location; + + if (isSemicolon(token)) { + location = token.loc.start; + + if (hasLeadingSpace(token)) { + if (!requireSpaceBefore) { + context.report(node, location, "Unexpected whitespace before semicolon."); + } + } else { + if (requireSpaceBefore) { + context.report(node, location, "Missing whitespace before semicolon."); + } + } + + if (!isLastTokenInCurrentLine(token)) { + if (hasTrailingSpace(token)) { + if (!requireSpaceAfter) { + context.report(node, location, "Unexpected whitespace after semicolon."); + } + } else { + if (requireSpaceAfter) { + context.report(node, location, "Missing whitespace after semicolon."); + } + } + } + } + } + + /** + * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkNode(node) { + var token = context.getLastToken(node); + checkSemicolonSpacing(token, node); + } + + return { + "VariableDeclaration": checkNode, + "ExpressionStatement": checkNode, + "BreakStatement": checkNode, + "ContinueStatement": checkNode, + "DebuggerStatement": checkNode, + "ReturnStatement": checkNode, + "ThrowStatement": checkNode, + "ForStatement": function (node) { + if (node.init) { + checkSemicolonSpacing(context.getTokenAfter(node.init), node); + } + + if (node.test) { + checkSemicolonSpacing(context.getTokenAfter(node.test), node); + } + } + }; +}; diff --git a/tools/eslint/lib/rules/semi.js b/tools/eslint/lib/rules/semi.js new file mode 100644 index 00000000000000..a9f841cd73ceb5 --- /dev/null +++ b/tools/eslint/lib/rules/semi.js @@ -0,0 +1,130 @@ +/** + * @fileoverview Rule to flag missing semicolons. + * @author Nicholas C. Zakas + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +module.exports = function(context) { + + var OPT_OUT_PATTERN = /[\[\(\/\+\-]/; // One of [(/+- + + var always = context.options[0] !== "never"; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Reports a semicolon error with appropriate location and message. + * @param {ASTNode} node The node with an extra or missing semicolon. + * @returns {void} + */ + function report(node) { + var message = always ? "Missing semicolon." : "Extra semicolon."; + context.report(node, context.getLastToken(node).loc.end, message); + } + + /** + * Checks whether a token is a semicolon punctuator. + * @param {Token} token The token. + * @returns {boolean} True if token is a semicolon punctuator. + */ + function isSemicolon(token) { + return (token.type === "Punctuator" && token.value === ";"); + } + + /** + * Check if a semicolon is unnecessary, only true if: + * - next token is on a new line and is not one of the opt-out tokens + * - next token is a valid statement divider + * @param {Token} lastToken last token of current node. + * @returns {boolean} whether the semicolon is unnecessary. + */ + function isUnnecessarySemicolon(lastToken) { + var isDivider, isOptOutToken, lastTokenLine, nextToken, nextTokenLine; + + if (!isSemicolon(lastToken)) { + return false; + } + + nextToken = context.getTokenAfter(lastToken); + + if (!nextToken) { + return true; + } + + lastTokenLine = lastToken.loc.end.line; + nextTokenLine = nextToken.loc.start.line; + isOptOutToken = OPT_OUT_PATTERN.test(nextToken.value); + isDivider = (nextToken.value === "}" || nextToken.value === ";"); + + return (lastTokenLine !== nextTokenLine && !isOptOutToken) || isDivider; + } + + /** + * Checks a node to see if it's followed by a semicolon. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolon(node) { + var lastToken = context.getLastToken(node); + + if (always) { + if (!isSemicolon(lastToken)) { + report(node); + } + } else { + if (isUnnecessarySemicolon(lastToken)) { + report(node); + } + } + } + + /** + * Checks to see if there's a semicolon after a variable declaration. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function checkForSemicolonForVariableDeclaration(node) { + var ancestors = context.getAncestors(), + parentIndex = ancestors.length - 1, + parent = ancestors[parentIndex]; + + if ((parent.type !== "ForStatement" || parent.init !== node) && + (!/^For(?:In|Of)Statement/.test(parent.type) || parent.left !== node) + ) { + checkForSemicolon(node); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + + "VariableDeclaration": checkForSemicolonForVariableDeclaration, + "ExpressionStatement": checkForSemicolon, + "ReturnStatement": checkForSemicolon, + "ThrowStatement": checkForSemicolon, + "DebuggerStatement": checkForSemicolon, + "BreakStatement": checkForSemicolon, + "ContinueStatement": checkForSemicolon, + "ImportDeclaration": checkForSemicolon, + "ExportAllDeclaration": checkForSemicolon, + "ExportNamedDeclaration": function (node) { + if (!node.declaration) { + checkForSemicolon(node); + } + }, + "ExportDefaultDeclaration": function (node) { + if (!/(?:Class|Function)Declaration/.test(node.declaration.type)) { + checkForSemicolon(node); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/sort-vars.js b/tools/eslint/lib/rules/sort-vars.js new file mode 100644 index 00000000000000..8d4b6a8980dd44 --- /dev/null +++ b/tools/eslint/lib/rules/sort-vars.js @@ -0,0 +1,37 @@ +/** + * @fileoverview Rule to require sorting of variables within a single Variable Declaration block + * @author Ilya Volodin + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var configuration = context.options[0] || {}, + ignoreCase = configuration.ignoreCase || false; + + return { + "VariableDeclaration": function(node) { + node.declarations.reduce(function(memo, decl) { + var lastVariableName = memo.id.name, + currenVariableName = decl.id.name; + + if (ignoreCase) { + lastVariableName = lastVariableName.toLowerCase(); + currenVariableName = currenVariableName.toLowerCase(); + } + + if (currenVariableName < lastVariableName) { + context.report(decl, "Variables within the same declaration block should be sorted alphabetically"); + return memo; + } else { + return decl; + } + }, node.declarations[0]); + } + }; +}; diff --git a/tools/eslint/lib/rules/space-after-function-name.js b/tools/eslint/lib/rules/space-after-function-name.js new file mode 100644 index 00000000000000..c477768c467f09 --- /dev/null +++ b/tools/eslint/lib/rules/space-after-function-name.js @@ -0,0 +1,43 @@ +/** + * @fileoverview Rule to enforce consistent spacing after function names + * @author Roberto Vidal + * @copyright 2014 Roberto Vidal. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var requiresSpace = context.options[0] === "always"; + + /** + * Reports if the give named function node has the correct spacing after its name + * + * @param {ASTNode} node The node to which the potential problem belongs. + * @returns {void} + */ + function check(node) { + var tokens = context.getFirstTokens(node, 3), + hasSpace = tokens[1].range[1] < tokens[2].range[0]; + + if (hasSpace !== requiresSpace) { + context.report(node, "Function name \"{{name}}\" must {{not}}be followed by whitespace.", { + name: node.id.name, + not: requiresSpace ? "" : "not " + }); + } + } + + return { + "FunctionDeclaration": check, + "FunctionExpression": function (node) { + if (node.id) { + check(node); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/space-after-keywords.js b/tools/eslint/lib/rules/space-after-keywords.js new file mode 100644 index 00000000000000..3ece8bb065adb9 --- /dev/null +++ b/tools/eslint/lib/rules/space-after-keywords.js @@ -0,0 +1,76 @@ +/** + * @fileoverview Rule to enforce the number of spaces after certain keywords + * @author Nick Fisher + * @copyright 2014 Nick Fisher. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // unless the first option is `"never"`, then a space is required + var requiresSpace = context.options[0] !== "never"; + + /** + * Check if the separation of two adjacent tokens meets the spacing rules, and report a problem if not. + * + * @param {ASTNode} node The node to which the potential problem belongs. + * @param {Token} left The first token. + * @param {Token} right The second token + * @returns {void} + */ + function checkTokens(node, left, right) { + var hasSpace = left.range[1] < right.range[0], + value = left.value; + + if (hasSpace !== requiresSpace) { + context.report(node, "Keyword \"{{value}}\" must {{not}}be followed by whitespace.", { + value: value, + not: requiresSpace ? "" : "not " + }); + } + } + + /** + * Check if the given node (`if`, `for`, `while`, etc), has the correct spacing after it. + * @param {ASTNode} node The node to check. + * @returns {void} + */ + function check(node) { + var tokens = context.getFirstTokens(node, 2); + checkTokens(node, tokens[0], tokens[1]); + } + + return { + "IfStatement": function (node) { + check(node); + // check the `else` + if (node.alternate && node.alternate.type !== "IfStatement") { + checkTokens(node.alternate, context.getTokenBefore(node.alternate), context.getFirstToken(node.alternate)); + } + }, + "ForStatement": check, + "ForOfStatement": check, + "ForInStatement": check, + "WhileStatement": check, + "DoWhileStatement": function (node) { + check(node); + // check the `while` + var whileTokens = context.getTokensBefore(node.test, 2); + checkTokens(node, whileTokens[0], whileTokens[1]); + }, + "SwitchStatement": check, + "TryStatement": function (node) { + check(node); + // check the `finally` + if (node.finalizer) { + checkTokens(node.finalizer, context.getTokenBefore(node.finalizer), context.getFirstToken(node.finalizer)); + } + }, + "CatchStatement": check, + "WithStatement": check + }; +}; diff --git a/tools/eslint/lib/rules/space-before-blocks.js b/tools/eslint/lib/rules/space-before-blocks.js new file mode 100644 index 00000000000000..963ff42598d3a1 --- /dev/null +++ b/tools/eslint/lib/rules/space-before-blocks.js @@ -0,0 +1,85 @@ +/** + * @fileoverview A rule to ensure whitespace before blocks. + * @author Mathias Schreck + * @copyright 2014 Mathias Schreck. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var requireSpace = context.options[0] !== "never"; + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + */ + function isSameLine(left, right) { + return left.loc.start.line === right.loc.start.line; + } + + /** + * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. + * @param {ASTNode|Token} node The AST node of a BlockStatement. + * @returns {void} undefined. + */ + function checkPrecedingSpace(node) { + var precedingToken = context.getTokenBefore(node), + hasSpace; + + if (precedingToken && isSameLine(precedingToken, node)) { + hasSpace = isSpaced(precedingToken, node); + + if (requireSpace) { + if (!hasSpace) { + context.report(node, "Missing space before opening brace."); + } + } else { + if (hasSpace) { + context.report(node, "Unexpected space before opening brace."); + } + } + } + } + + /** + * Checks if the CaseBlock of an given SwitchStatement node has a preceding space. + * @param {ASTNode} node The node of a SwitchStatement. + * @returns {void} undefined. + */ + function checkSpaceBeforeCaseBlock(node) { + var cases = node.cases, + firstCase, + openingBrace; + + if (cases.length > 0) { + firstCase = cases[0]; + openingBrace = context.getTokenBefore(firstCase); + } else { + openingBrace = context.getLastToken(node, 1); + } + + checkPrecedingSpace(openingBrace); + } + + return { + "BlockStatement": checkPrecedingSpace, + "SwitchStatement": checkSpaceBeforeCaseBlock + }; + +}; diff --git a/tools/eslint/lib/rules/space-before-function-paren.js b/tools/eslint/lib/rules/space-before-function-paren.js new file mode 100644 index 00000000000000..b56409ada091f5 --- /dev/null +++ b/tools/eslint/lib/rules/space-before-function-paren.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule to validate spacing before function paren. + * @author Mathias Schreck + * @copyright 2015 Mathias Schreck + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var configuration = context.options[0], + requireAnonymousFunctionSpacing = true, + requireNamedFunctionSpacing = true; + + if (typeof configuration === "object") { + requireAnonymousFunctionSpacing = configuration.anonymous !== "never"; + requireNamedFunctionSpacing = configuration.named !== "never"; + } else if (configuration === "never") { + requireAnonymousFunctionSpacing = false; + requireNamedFunctionSpacing = false; + } + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Determines whether a function has a name. + * @param {ASTNode} node The function node. + * @returns {boolean} Whether the function has a name. + */ + function isNamedFunction(node) { + var parent; + + if (node.id) { + return true; + } + + parent = context.getAncestors().pop(); + return parent.type === "MethodDefinition" || + (parent.type === "Property" && + ( + parent.kind === "get" || + parent.kind === "set" || + parent.method + ) + ); + } + + /** + * Validates the spacing before function parentheses. + * @param {ASTNode} node The node to be validated. + * @returns {void} + */ + function validateSpacingBeforeParentheses(node) { + var isNamed = isNamedFunction(node), + tokens, + leftToken, + rightToken, + location; + + if (node.generator && !isNamed) { + return; + } + + tokens = context.getTokens(node); + + if (node.generator) { + if (node.id) { + leftToken = tokens[2]; + rightToken = tokens[3]; + } else { + // Object methods are named but don't have an id + leftToken = context.getTokenBefore(node); + rightToken = tokens[0]; + } + } else if (isNamed) { + if (node.id) { + leftToken = tokens[1]; + rightToken = tokens[2]; + } else { + // Object methods are named but don't have an id + leftToken = context.getTokenBefore(node); + rightToken = tokens[0]; + } + } else { + leftToken = tokens[0]; + rightToken = tokens[1]; + } + + location = leftToken.loc.end; + + if (isSpaced(leftToken, rightToken)) { + if ((isNamed && !requireNamedFunctionSpacing) || (!isNamed && !requireAnonymousFunctionSpacing)) { + context.report(node, location, "Unexpected space before function parentheses."); + } + } else { + if ((isNamed && requireNamedFunctionSpacing) || (!isNamed && requireAnonymousFunctionSpacing)) { + context.report(node, location, "Missing space before function parentheses."); + } + } + } + + return { + "FunctionDeclaration": validateSpacingBeforeParentheses, + "FunctionExpression": validateSpacingBeforeParentheses + }; +}; diff --git a/tools/eslint/lib/rules/space-before-function-parentheses.js b/tools/eslint/lib/rules/space-before-function-parentheses.js new file mode 100644 index 00000000000000..b40351d0b9f8e7 --- /dev/null +++ b/tools/eslint/lib/rules/space-before-function-parentheses.js @@ -0,0 +1,117 @@ +/** + * @fileoverview Rule to validate spacing before function parentheses. + * @author Mathias Schreck + * @copyright 2015 Mathias Schreck + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var configuration = context.options[0], + requireAnonymousFunctionSpacing = true, + requireNamedFunctionSpacing = true; + + if (typeof configuration === "object") { + requireAnonymousFunctionSpacing = configuration.anonymous !== "never"; + requireNamedFunctionSpacing = configuration.named !== "never"; + } else if (configuration === "never") { + requireAnonymousFunctionSpacing = false; + requireNamedFunctionSpacing = false; + } + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Determines whether a function has a name. + * @param {ASTNode} node The function node. + * @returns {boolean} Whether the function has a name. + */ + function isNamedFunction(node) { + var parent; + + if (node.id) { + return true; + } + + parent = context.getAncestors().pop(); + return parent.type === "MethodDefinition" || + (parent.type === "Property" && + ( + parent.kind === "get" || + parent.kind === "set" || + parent.method + ) + ); + } + + /** + * Validates the spacing before function parentheses. + * @param {ASTNode} node The node to be validated. + * @returns {void} + */ + function validateSpacingBeforeParentheses(node) { + var isNamed = isNamedFunction(node), + tokens, + leftToken, + rightToken, + location; + + if (node.generator && !isNamed) { + return; + } + + tokens = context.getTokens(node); + + if (node.generator) { + if (node.id) { + leftToken = tokens[2]; + rightToken = tokens[3]; + } else { + // Object methods are named but don't have an id + leftToken = context.getTokenBefore(node); + rightToken = tokens[0]; + } + } else if (isNamed) { + if (node.id) { + leftToken = tokens[1]; + rightToken = tokens[2]; + } else { + // Object methods are named but don't have an id + leftToken = context.getTokenBefore(node); + rightToken = tokens[0]; + } + } else { + leftToken = tokens[0]; + rightToken = tokens[1]; + } + + location = leftToken.loc.end; + + if (isSpaced(leftToken, rightToken)) { + if ((isNamed && !requireNamedFunctionSpacing) || (!isNamed && !requireAnonymousFunctionSpacing)) { + context.report(node, location, "Unexpected space before function parentheses."); + } + } else { + if ((isNamed && requireNamedFunctionSpacing) || (!isNamed && requireAnonymousFunctionSpacing)) { + context.report(node, location, "Missing space before function parentheses."); + } + } + } + + return { + "FunctionDeclaration": validateSpacingBeforeParentheses, + "FunctionExpression": validateSpacingBeforeParentheses + }; +}; diff --git a/tools/eslint/lib/rules/space-in-brackets.js b/tools/eslint/lib/rules/space-in-brackets.js new file mode 100644 index 00000000000000..1b5fcec466de5a --- /dev/null +++ b/tools/eslint/lib/rules/space-in-brackets.js @@ -0,0 +1,272 @@ +/** + * @fileoverview Disallows or enforces spaces inside of brackets. + * @author Ian Christian Myers + * @copyright 2014 Brandyn Bennett. All rights reserved. + * @copyright 2014 Michael Ficarra. No rights reserved. + * @copyright 2014 Vignesh Anand. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var spaced = context.options[0] === "always"; + + /** + * Determines whether an option is set, relative to the spacing option. + * If spaced is "always", then check whether option is set to false. + * If spaced is "never", then check whether option is set to true. + * @param {Object} option - The option to exclude. + * @returns {boolean} Whether or not the property is excluded. + */ + function isOptionSet(option) { + return context.options[1] != null ? context.options[1][option] === !spaced : false; + } + + var options = { + spaced: spaced, + singleElementException: isOptionSet("singleValue"), + objectsInArraysException: isOptionSet("objectsInArrays"), + arraysInArraysException: isOptionSet("arraysInArrays"), + arraysInObjectsException: isOptionSet("arraysInObjects"), + objectsInObjectsException: isOptionSet("objectsInObjects"), + propertyNameException: isOptionSet("propertyName") + }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Determines whether two adjacent tokens are have whitespace between them. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not there is space between the tokens. + */ + function isSpaced(left, right) { + return left.range[1] < right.range[0]; + } + + /** + * Determines whether two adjacent tokens are on the same line. + * @param {Object} left - The left token object. + * @param {Object} right - The right token object. + * @returns {boolean} Whether or not the tokens are on the same line. + */ + function isSameLine(left, right) { + return left.loc.start.line === right.loc.start.line; + } + + /** + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ + function reportNoBeginningSpace(node, token) { + context.report(node, token.loc.start, + "There should be no space after '" + token.value + "'"); + } + + /** + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ + function reportNoEndingSpace(node, token) { + context.report(node, token.loc.start, + "There should be no space before '" + token.value + "'"); + } + + /** + * Reports that there should be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ + function reportRequiredBeginningSpace(node, token) { + context.report(node, token.loc.start, + "A space is required after '" + token.value + "'"); + } + + /** + * Reports that there should be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ + function reportRequiredEndingSpace(node, token) { + context.report(node, token.loc.start, + "A space is required before '" + token.value + "'"); + } + + + /** + * Determines if spacing in curly braces is valid. + * @param {ASTNode} node The AST node to check. + * @param {Token} first The first token to check (should be the opening brace) + * @param {Token} second The second token to check (should be first after the opening brace) + * @param {Token} penultimate The penultimate token to check (should be last before closing brace) + * @param {Token} last The last token to check (should be closing brace) + * @returns {void} + */ + function validateBraceSpacing(node, first, second, penultimate, last) { + var closingCurlyBraceMustBeSpaced = + options.arraysInObjectsException && penultimate.value === "]" || + options.objectsInObjectsException && penultimate.value === "}" + ? !options.spaced : options.spaced; + + if (isSameLine(first, second)) { + if (options.spaced && !isSpaced(first, second)) { + reportRequiredBeginningSpace(node, first); + } + if (!options.spaced && isSpaced(first, second)) { + reportNoBeginningSpace(node, first); + } + } + + if (isSameLine(penultimate, last)) { + if (closingCurlyBraceMustBeSpaced && !isSpaced(penultimate, last)) { + reportRequiredEndingSpace(node, last); + } + if (!closingCurlyBraceMustBeSpaced && isSpaced(penultimate, last)) { + reportNoEndingSpace(node, last); + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + MemberExpression: function(node) { + if (!node.computed) { + return; + } + + var property = node.property, + before = context.getTokenBefore(property), + first = context.getFirstToken(property), + last = context.getLastToken(property), + after = context.getTokenAfter(property); + + var propertyNameMustBeSpaced = options.propertyNameException ? + !options.spaced : options.spaced; + + if (isSameLine(before, first)) { + if (propertyNameMustBeSpaced) { + if (!isSpaced(before, first) && isSameLine(before, first)) { + reportRequiredBeginningSpace(node, before); + } + } else { + if (isSpaced(before, first)) { + reportNoBeginningSpace(node, before); + } + } + } + + if (isSameLine(last, after)) { + if (propertyNameMustBeSpaced) { + if (!isSpaced(last, after) && isSameLine(last, after)) { + reportRequiredEndingSpace(node, after); + } + } else { + if (isSpaced(last, after)) { + reportNoEndingSpace(node, after); + } + } + } + }, + + ArrayExpression: function(node) { + if (node.elements.length === 0) { + return; + } + + var first = context.getFirstToken(node), + second = context.getFirstToken(node, 1), + penultimate = context.getLastToken(node, 1), + last = context.getLastToken(node); + + var openingBracketMustBeSpaced = + options.objectsInArraysException && second.value === "{" || + options.arraysInArraysException && second.value === "[" || + options.singleElementException && node.elements.length === 1 + ? !options.spaced : options.spaced; + + var closingBracketMustBeSpaced = + options.objectsInArraysException && penultimate.value === "}" || + options.arraysInArraysException && penultimate.value === "]" || + options.singleElementException && node.elements.length === 1 + ? !options.spaced : options.spaced; + + if (isSameLine(first, second)) { + if (openingBracketMustBeSpaced && !isSpaced(first, second)) { + reportRequiredBeginningSpace(node, first); + } + if (!openingBracketMustBeSpaced && isSpaced(first, second)) { + reportNoBeginningSpace(node, first); + } + } + + if (isSameLine(penultimate, last)) { + if (closingBracketMustBeSpaced && !isSpaced(penultimate, last)) { + reportRequiredEndingSpace(node, last); + } + if (!closingBracketMustBeSpaced && isSpaced(penultimate, last)) { + reportNoEndingSpace(node, last); + } + } + }, + + ImportDeclaration: function(node) { + + var firstSpecifier = node.specifiers[0], + lastSpecifier = node.specifiers[node.specifiers.length - 1]; + + // don't do anything for namespace or default imports + if (firstSpecifier.type === "ImportSpecifier" && lastSpecifier.type === "ImportSpecifier") { + var first = context.getTokenBefore(firstSpecifier), + second = context.getFirstToken(firstSpecifier), + penultimate = context.getLastToken(lastSpecifier), + last = context.getTokenAfter(lastSpecifier); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + }, + + ExportNamedDeclaration: function(node) { + + var firstSpecifier = node.specifiers[0], + lastSpecifier = node.specifiers[node.specifiers.length - 1], + first = context.getTokenBefore(firstSpecifier), + second = context.getFirstToken(firstSpecifier), + penultimate = context.getLastToken(lastSpecifier), + last = context.getTokenAfter(lastSpecifier); + + validateBraceSpacing(node, first, second, penultimate, last); + + }, + + ObjectExpression: function(node) { + if (node.properties.length === 0) { + return; + } + + var first = context.getFirstToken(node), + second = context.getFirstToken(node, 1), + penultimate = context.getLastToken(node, 1), + last = context.getLastToken(node); + + validateBraceSpacing(node, first, second, penultimate, last); + } + + }; + +}; diff --git a/tools/eslint/lib/rules/space-in-parens.js b/tools/eslint/lib/rules/space-in-parens.js new file mode 100644 index 00000000000000..ff124c12985c18 --- /dev/null +++ b/tools/eslint/lib/rules/space-in-parens.js @@ -0,0 +1,262 @@ +/** + * @fileoverview Disallows or enforces spaces inside of parentheses. + * @author Jonathan Rajavuori + * @copyright 2014 David Clark. All rights reserved. + * @copyright 2014 Jonathan Rajavuori. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var MISSING_SPACE_MESSAGE = "There must be a space inside this paren.", + REJECTED_SPACE_MESSAGE = "There should be no spaces inside this paren.", + exceptionsArray = (context.options.length === 2) ? context.options[1].exceptions : [], + options = {}, + rejectedSpaceRegExp, + missingSpaceRegExp, + spaceChecks; + + if (exceptionsArray && exceptionsArray.length) { + options.braceException = exceptionsArray.indexOf("{}") !== -1 || false; + options.bracketException = exceptionsArray.indexOf("[]") !== -1 || false; + options.parenException = exceptionsArray.indexOf("()") !== -1 || false; + options.empty = exceptionsArray.indexOf("empty") !== -1 || false; + } + + /** + * Used with the `never` option to produce, given the exception options, + * two regular expressions to check for missing and rejected spaces. + * @param {Object} opts The exception options + * @returns {Object} `missingSpace` and `rejectedSpace` regular expressions + * @private + */ + function getNeverChecks(opts) { + var missingSpaceOpeners = [], + missingSpaceClosers = [], + rejectedSpaceOpeners = ["\\s"], + rejectedSpaceClosers = ["\\s"], + missingSpaceCheck, + rejectedSpaceCheck; + + // Populate openers and closers + if (opts.braceException) { + missingSpaceOpeners.push("\\{"); + missingSpaceClosers.push("\\}"); + rejectedSpaceOpeners.push("\\{"); + rejectedSpaceClosers.push("\\}"); + } + if (opts.bracketException) { + missingSpaceOpeners.push("\\["); + missingSpaceClosers.push("\\]"); + rejectedSpaceOpeners.push("\\["); + rejectedSpaceClosers.push("\\]"); + } + if (opts.parenException) { + missingSpaceOpeners.push("\\("); + missingSpaceClosers.push("\\)"); + rejectedSpaceOpeners.push("\\("); + rejectedSpaceClosers.push("\\)"); + } + if (opts.empty) { + missingSpaceOpeners.push("\\)"); + missingSpaceClosers.push("\\("); + rejectedSpaceOpeners.push("\\)"); + rejectedSpaceClosers.push("\\("); + } + + if (missingSpaceOpeners.length) { + missingSpaceCheck = "\\((" + missingSpaceOpeners.join("|") + ")"; + if (missingSpaceClosers.length) { + missingSpaceCheck += "|"; + } + } + if (missingSpaceClosers.length) { + missingSpaceCheck += "(" + missingSpaceClosers.join("|") + ")\\)"; + } + + // compose the rejected regexp + rejectedSpaceCheck = "\\( +[^" + rejectedSpaceOpeners.join("") + "]"; + rejectedSpaceCheck += "|[^" + rejectedSpaceClosers.join("") + "] +\\)"; + + return { + // e.g. \((\{)|(\})\) --- where {} is an exception + missingSpace: missingSpaceCheck || ".^", + // e.g. \( +[^ \n\r\{]|[^ \n\r\}] +\) --- where {} is an exception + rejectedSpace: rejectedSpaceCheck + }; + } + + /** + * Used with the `always` option to produce, given the exception options, + * two regular expressions to check for missing and rejected spaces. + * @param {Object} opts The exception options + * @returns {Object} `missingSpace` and `rejectedSpace` regular expressions + * @private + */ + function getAlwaysChecks(opts) { + var missingSpaceOpeners = ["\\s", "\\)"], + missingSpaceClosers = ["\\s", "\\("], + rejectedSpaceOpeners = [], + rejectedSpaceClosers = [], + missingSpaceCheck, + rejectedSpaceCheck; + + // Populate openers and closers + if (opts.braceException) { + missingSpaceOpeners.push("\\{"); + missingSpaceClosers.push("\\}"); + rejectedSpaceOpeners.push(" \\{"); + rejectedSpaceClosers.push("\\} "); + } + if (opts.bracketException) { + missingSpaceOpeners.push("\\["); + missingSpaceClosers.push("\\]"); + rejectedSpaceOpeners.push(" \\["); + rejectedSpaceClosers.push("\\] "); + } + if (opts.parenException) { + missingSpaceOpeners.push("\\("); + missingSpaceClosers.push("\\)"); + rejectedSpaceOpeners.push(" \\("); + rejectedSpaceClosers.push("\\) "); + } + if (opts.empty) { + rejectedSpaceOpeners.push(" \\)"); + rejectedSpaceClosers.push("\\( "); + } + + // compose the allowed regexp + missingSpaceCheck = "\\([^" + missingSpaceOpeners.join("") + "]"; + missingSpaceCheck += "|[^" + missingSpaceClosers.join("") + "]\\)"; + + // compose the rejected regexp + if (rejectedSpaceOpeners.length) { + rejectedSpaceCheck = "\\((" + rejectedSpaceOpeners.join("|") + ")"; + if (rejectedSpaceClosers.length) { + rejectedSpaceCheck += "|"; + } + } + if (rejectedSpaceClosers.length) { + rejectedSpaceCheck += "(" + rejectedSpaceClosers.join("|") + ")\\)"; + } + + return { + // e.g. \([^ \)\r\n\{]|[^ \(\r\n\}]\) --- where {} is an exception + missingSpace: missingSpaceCheck, + // e.g. \(( \{})|(\} )\) --- where {} is an excpetion + rejectedSpace: rejectedSpaceCheck || ".^" + }; + } + + spaceChecks = (context.options[0] === "always") ? getAlwaysChecks(options) : getNeverChecks(options); + missingSpaceRegExp = new RegExp(spaceChecks.missingSpace, "mg"); + rejectedSpaceRegExp = new RegExp(spaceChecks.rejectedSpace, "mg"); + + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + var skipRanges = []; + + /** + * Adds the range of a node to the set to be skipped when checking parens + * @param {ASTNode} node The node to skip + * @returns {void} + * @private + */ + function addSkipRange(node) { + skipRanges.push(node.range); + } + + /** + * Sorts the skipRanges array. Must be called before shouldSkip + * @returns {void} + * @private + */ + function sortSkipRanges() { + skipRanges.sort(function (a, b) { + return a[0] - b[0]; + }); + } + + /** + * Checks if a certain position in the source should be skipped + * @param {Number} pos The 0-based index in the source + * @returns {boolean} whether the position should be skipped + * @private + */ + function shouldSkip(pos) { + var i, len, range; + for (i = 0, len = skipRanges.length; i < len; i += 1) { + range = skipRanges[i]; + if (pos < range[0]) { + break; + } else if (pos < range[1]) { + return true; + } + } + return false; + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "Program:exit": function checkParenSpaces(node) { + + var nextMatch, + nextLine, + column, + line = 1, + source = context.getSource(), + pos = 0; + + function checkMatch(match, message) { + if (source.charAt(match.index) !== "(") { + // Matched a closing paren pattern + match.index += 1; + } + + if (!shouldSkip(match.index)) { + while ((nextLine = source.indexOf("\n", pos)) !== -1 && nextLine < match.index) { + pos = nextLine + 1; + line += 1; + } + column = match.index - pos; + + context.report(node, { line: line, column: column }, message); + } + } + + sortSkipRanges(); + + while ((nextMatch = rejectedSpaceRegExp.exec(source)) !== null) { + checkMatch(nextMatch, REJECTED_SPACE_MESSAGE); + } + + while ((nextMatch = missingSpaceRegExp.exec(source)) !== null) { + checkMatch(nextMatch, MISSING_SPACE_MESSAGE); + } + + }, + + + // These nodes can contain parentheses that this rule doesn't care about + + LineComment: addSkipRange, + + BlockComment: addSkipRange, + + Literal: addSkipRange + + }; + +}; diff --git a/tools/eslint/lib/rules/space-infix-ops.js b/tools/eslint/lib/rules/space-infix-ops.js new file mode 100644 index 00000000000000..a3f3c940ac0b64 --- /dev/null +++ b/tools/eslint/lib/rules/space-infix-ops.js @@ -0,0 +1,94 @@ +/** + * @fileoverview Require spaces around infix operators + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var int32Hint = context.options[0] ? context.options[0].int32Hint === true : false; + + var OPERATORS = [ + "*", "/", "%", "+", "-", "<<", ">>", ">>>", "<", "<=", ">", ">=", "in", + "instanceof", "==", "!=", "===", "!==", "&", "^", "|", "&&", "||", "=", + "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", + "?", ":", "," + ]; + + /** + * Returns the first token which violates the rule + * @param {ASTNode} left - The left node of the main node + * @param {ASTNode} right - The right node of the main node + * @returns {object} The violator token or null + * @private + */ + function getFirstNonSpacedToken(left, right) { + var op, tokens = context.getTokensBetween(left, right, 1); + for (var i = 1, l = tokens.length - 1; i < l; ++i) { + op = tokens[i]; + if ( + op.type === "Punctuator" && + OPERATORS.indexOf(op.value) >= 0 && + (tokens[i - 1].range[1] >= op.range[0] || op.range[1] >= tokens[i + 1].range[0]) + ) { + return op; + } + } + return null; + } + + /** + * Reports an AST node as a rule violation + * @param {ASTNode} mainNode - The node to report + * @param {object} culpritToken - The token which has a problem + * @returns {void} + * @private + */ + function report(mainNode, culpritToken) { + context.report(mainNode, culpritToken.loc.start, "Infix operators must be spaced."); + } + + function checkBinary(node) { + var nonSpacedNode = getFirstNonSpacedToken(node.left, node.right); + + if (nonSpacedNode) { + if (!(int32Hint && context.getSource(node).substr(-2) === "|0")) { + report(node, nonSpacedNode); + } + } + } + + function checkConditional(node) { + var nonSpacedConsequesntNode = getFirstNonSpacedToken(node.test, node.consequent); + var nonSpacedAlternateNode = getFirstNonSpacedToken(node.consequent, node.alternate); + + if (nonSpacedConsequesntNode) { + report(node, nonSpacedConsequesntNode); + } else if (nonSpacedAlternateNode) { + report(node, nonSpacedAlternateNode); + } + } + + function checkVar(node) { + var nonSpacedNode; + + if (node.init) { + nonSpacedNode = getFirstNonSpacedToken(node.id, node.init); + if (nonSpacedNode) { + report(node, nonSpacedNode); + } + } + } + + return { + "AssignmentExpression": checkBinary, + "BinaryExpression": checkBinary, + "LogicalExpression": checkBinary, + "ConditionalExpression": checkConditional, + "VariableDeclarator": checkVar + }; + +}; diff --git a/tools/eslint/lib/rules/space-return-throw-case.js b/tools/eslint/lib/rules/space-return-throw-case.js new file mode 100644 index 00000000000000..27928adec7959a --- /dev/null +++ b/tools/eslint/lib/rules/space-return-throw-case.js @@ -0,0 +1,36 @@ +/** + * @fileoverview Require spaces following return, throw, and case + * @author Michael Ficarra + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + function check(node) { + var tokens = context.getFirstTokens(node, 2), + value = tokens[0].value; + + if (tokens[0].range[1] >= tokens[1].range[0]) { + context.report(node, "Keyword \"" + value + "\" must be followed by whitespace."); + } + } + + return { + "ReturnStatement": function(node) { + if (node.argument) { + check(node); + } + }, + "SwitchCase": function(node) { + if (node.test) { + check(node); + } + }, + "ThrowStatement": check + }; + +}; diff --git a/tools/eslint/lib/rules/space-unary-ops.js b/tools/eslint/lib/rules/space-unary-ops.js new file mode 100644 index 00000000000000..2fe8a3f40637ff --- /dev/null +++ b/tools/eslint/lib/rules/space-unary-ops.js @@ -0,0 +1,118 @@ +/** + * @fileoverview This rule shoud require or disallow spaces before or after unary operations. + * @author Marcin Kumorek + * @copyright 2014 Marcin Kumorek. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + var options = context.options && Array.isArray(context.options) && context.options[0] || { words: true, nonwords: false }; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * Check if the parent unary operator is "!" in order to know if it's "!!" convert to Boolean or just "!" negation + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the parent is unary "!" operator + */ + function isParentUnaryBangExpression(node) { + return node && node.parent && node.parent.type === "UnaryExpression" && node.parent.operator === "!"; + } + + /** + * Checks if the type is a unary word expression + * @param {string} type value of AST token + * @returns {boolean} Whether the word is in the list of known words + */ + function isWordExpression(type) { + return ["delete", "new", "typeof", "void"].indexOf(type) !== -1; + } + + /** + * Check if the node's child argument is an "ObjectExpression" + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the argument's type is "ObjectExpression" + */ + function isArgumentObjectExpression(node) { + return node.argument && node.argument.type && node.argument.type === "ObjectExpression"; + } + + /** + * Check Unary Word Operators for spaces after the word operator + * @param {ASTnode} node AST node + * @param {object} firstToken first token from the AST node + * @param {object} secondToken second token from the AST node + * @returns {void} + */ + function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken) { + if (options.words) { + if (secondToken.range[0] === firstToken.range[1]) { + context.report(node, "Unary word operator \"" + firstToken.value + "\" must be followed by whitespace."); + } + } + + if (!options.words && isArgumentObjectExpression(node)) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report(node, "Unexpected space after unary word operator \"" + firstToken.value + "\"."); + } + } + } + + /** + * Checks UnaryExpression, UpdateExpression and NewExpression for spaces before and after the operator + * @param {ASTnode} node AST node + * @returns {void} + */ + function checkForSpaces(node) { + var tokens = context.getFirstTokens(node, 2), + firstToken = tokens[0], + secondToken = tokens[1]; + + if (isWordExpression(firstToken.value)) { + checkUnaryWordOperatorForSpaces(node, firstToken, secondToken); + return void 0; + } + + if (options.nonwords) { + if (node.prefix) { + if (isParentUnaryBangExpression(node)) { + return void 0; + } + if (firstToken.range[1] === secondToken.range[0]) { + context.report(node, "Unary operator \"" + firstToken.value + "\" must be followed by whitespace."); + } + } else { + if (firstToken.range[1] === secondToken.range[0]) { + context.report(node, "Space is required before unary expressions \"" + secondToken.value + "\"."); + } + } + } else { + if (node.prefix) { + if (secondToken.range[0] > firstToken.range[1]) { + context.report(node, "Unexpected space after unary operator \"" + firstToken.value + "\"."); + } + } else { + if (secondToken.range[0] > firstToken.range[1]) { + context.report(node, "Unexpected space before unary operator \"" + secondToken.value + "\"."); + } + } + } + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "UnaryExpression": checkForSpaces, + "UpdateExpression": checkForSpaces, + "NewExpression": checkForSpaces + }; + +}; diff --git a/tools/eslint/lib/rules/spaced-line-comment.js b/tools/eslint/lib/rules/spaced-line-comment.js new file mode 100644 index 00000000000000..af5ba8cdb6a8ca --- /dev/null +++ b/tools/eslint/lib/rules/spaced-line-comment.js @@ -0,0 +1,71 @@ +/** + * @fileoverview Enforces or disallows a space beginning a single-line comment. + * @author Greg Cochard + * @copyright 2014 Greg Cochard. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + // Unless the first option is never, require a space + var requireSpace = context.options[0] !== "never"; + + // Default to match anything, so all will fail if there are no exceptions + var exceptionMatcher = new RegExp(" "); + + // Grab the exceptions array and build a RegExp matcher for it + var hasExceptions = context.options.length === 2; + var unescapedExceptions = hasExceptions ? context.options[1].exceptions : []; + var exceptions; + + if (unescapedExceptions.length) { + exceptions = unescapedExceptions.map(function(s) { + return s.replace(/([.*+?${}()|\^\[\]\/\\])/g, "\\$1"); + }); + exceptionMatcher = new RegExp("(^(" + exceptions.join(")+$)|(^(") + ")+$)"); + } + + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "LineComment": function checkCommentForSpace(node) { + + if (requireSpace) { + + // If length is zero, ignore it + if (node.value.length === 0) { + return; + } + + // Space expected and not found + if (node.value.indexOf(" ") !== 0 && node.value.indexOf("\t") !== 0) { + + /* + * Do two tests; one for space starting the line, + * and one for a comment comprised only of exceptions + */ + if (hasExceptions && !exceptionMatcher.test(node.value)) { + context.report(node, "Expected exception block, space or tab after // in comment."); + } else if (!hasExceptions) { + context.report(node, "Expected space or tab after // in comment."); + } + } + + } else { + + if (node.value.indexOf(" ") === 0 || node.value.indexOf("\t") === 0) { + context.report(node, "Unexpected space or tab after // in comment."); + } + } + } + + }; +}; diff --git a/tools/eslint/lib/rules/strict.js b/tools/eslint/lib/rules/strict.js new file mode 100644 index 00000000000000..16d8612891ea09 --- /dev/null +++ b/tools/eslint/lib/rules/strict.js @@ -0,0 +1,236 @@ +/** + * @fileoverview Rule to control usage of strict mode directives. + * @author Brandon Mills + * @copyright 2015 Brandon Mills. All rights reserved. + * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2013 Ian Christian Myers. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +var messages = { + function: "Use the function form of \"use strict\".", + global: "Use the global form of \"use strict\".", + multiple: "Multiple \"use strict\" directives.", + never: "Strict mode is not permitted.", + unnecessary: "Unnecessary \"use strict\" directive." +}; + +/** + * Gets all of the Use Strict Directives in the Directive Prologue of a group of + * statements. + * @param {ASTNode[]} statements Statements in the program or function body. + * @returns {ASTNode[]} All of the Use Strict Directives. + */ +function getUseStrictDirectives(statements) { + var directives = [], + i, statement; + + for (i = 0; i < statements.length; i++) { + statement = statements[i]; + + if ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + statement.expression.value === "use strict" + ) { + directives[i] = statement; + } else { + break; + } + } + + return directives; +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var mode = context.options[0], + isModule = context.ecmaFeatures.modules, + modes = {}, + scopes = []; + + /** + * Report a node or array of nodes with a given message. + * @param {(ASTNode|ASTNode[])} nodes Node or nodes to report. + * @param {string} message Message to display. + * @returns {void} + */ + function report(nodes, message) { + var i; + + if (Array.isArray(nodes)) { + for (i = 0; i < nodes.length; i++) { + context.report(nodes[i], message); + } + } else { + context.report(nodes, message); + } + } + + //-------------------------------------------------------------------------- + // "deprecated" mode (default) + //-------------------------------------------------------------------------- + + /** + * Determines if a given node is "use strict". + * @param {ASTNode} node The node to check. + * @returns {boolean} True if the node is a strict pragma, false if not. + * @void + */ + function isStrictPragma(node) { + return (node && node.type === "ExpressionStatement" && + node.expression.value === "use strict"); + } + + /** + * When you enter a scope, push the strict value from the previous scope + * onto the stack. + * @param {ASTNode} node The AST node being checked. + * @returns {void} + * @private + */ + function enterScope(node) { + + var isStrict = false, + isProgram = (node.type === "Program"), + isParentGlobal = scopes.length === 1, + isParentStrict = scopes.length ? scopes[scopes.length - 1] : false; + + // look for the "use strict" pragma + if (isModule) { + isStrict = true; + } else if (isProgram) { + isStrict = isStrictPragma(node.body[0]) || isParentStrict; + } else { + isStrict = node.body.body && isStrictPragma(node.body.body[0]) || isParentStrict; + } + + scopes.push(isStrict); + + // never warn if the parent is strict or the function is strict + if (!isParentStrict && !isStrict && isParentGlobal) { + context.report(node, "Missing \"use strict\" statement."); + } + } + + /** + * When you exit a scope, pop off the top scope and see if it's true or + * false. + * @returns {void} + * @private + */ + function exitScope() { + scopes.pop(); + } + + modes.deprecated = { + "Program": enterScope, + "FunctionDeclaration": enterScope, + "FunctionExpression": enterScope, + "ArrowFunctionExpression": enterScope, + + "Program:exit": exitScope, + "FunctionDeclaration:exit": exitScope, + "FunctionExpression:exit": exitScope, + "ArrowFunctionExpression:exit": exitScope + }; + + //-------------------------------------------------------------------------- + // "never" mode + //-------------------------------------------------------------------------- + + modes.never = { + "Program": function(node) { + report(getUseStrictDirectives(node.body), messages.never); + }, + "FunctionDeclaration": function(node) { + report(getUseStrictDirectives(node.body.body), messages.never); + }, + "FunctionExpression": function(node) { + report(getUseStrictDirectives(node.body.body), messages.never); + } + }; + + //-------------------------------------------------------------------------- + // "global" mode + //-------------------------------------------------------------------------- + + modes.global = { + "Program": function(node) { + var useStrictDirectives = getUseStrictDirectives(node.body); + + if (!isModule && node.body.length && useStrictDirectives.length < 1) { + report(node, messages.global); + } else if (isModule) { + report(useStrictDirectives, messages.unnecessary); + } else { + report(useStrictDirectives.slice(1), messages.multiple); + } + }, + "FunctionDeclaration": function(node) { + report(getUseStrictDirectives(node.body.body), messages.global); + }, + "FunctionExpression": function(node) { + report(getUseStrictDirectives(node.body.body), messages.global); + } + }; + + //-------------------------------------------------------------------------- + // "function" mode + //-------------------------------------------------------------------------- + + /** + * Entering a function pushes a new nested scope onto the stack. The new + * scope is true if the nested function is strict mode code. + * @param {ASTNode} node The function declaration or expression. + * @returns {void} + */ + function enterFunction(node) { + var useStrictDirectives = getUseStrictDirectives(node.body.body), + isParentGlobal = scopes.length === 0, + isParentStrict = isModule || (scopes.length && scopes[scopes.length - 1]), + isStrict = useStrictDirectives.length > 0 || isModule; + + if (isStrict) { + if (isParentStrict && useStrictDirectives.length) { + report(useStrictDirectives[0], messages.unnecessary); + } + + report(useStrictDirectives.slice(1), messages.multiple); + } else if (isParentGlobal && !isModule) { + report(node, messages.function); + } + + scopes.push(isParentStrict || isStrict); + } + + /** + * Exiting a function pops its scope off the stack. + * @returns {void} + */ + function exitFunction() { + scopes.pop(); + } + + modes.function = { + "Program": function(node) { + report(getUseStrictDirectives(node.body), messages.function); + }, + "FunctionDeclaration": enterFunction, + "FunctionExpression": enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression:exit": exitFunction + }; + + return modes[mode || "deprecated"]; + +}; diff --git a/tools/eslint/lib/rules/use-isnan.js b/tools/eslint/lib/rules/use-isnan.js new file mode 100644 index 00000000000000..d7a3f537683952 --- /dev/null +++ b/tools/eslint/lib/rules/use-isnan.js @@ -0,0 +1,24 @@ +/** + * @fileoverview Rule to flag comparisons to the value NaN + * @author James Allardice + * @copyright 2014 Jordan Harband. All rights reserved. + * @copyright 2013 James Allardice. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + + return { + "BinaryExpression": function (node) { + if (/^(?:[<>]|[!=]=)=?$/.test(node.operator) && (node.left.name === "NaN" || node.right.name === "NaN")) { + context.report(node, "Use the isNaN function to compare with NaN."); + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/valid-jsdoc.js b/tools/eslint/lib/rules/valid-jsdoc.js new file mode 100644 index 00000000000000..a79bf7fea49544 --- /dev/null +++ b/tools/eslint/lib/rules/valid-jsdoc.js @@ -0,0 +1,191 @@ +/** + * @fileoverview Validates JSDoc comments are syntactically correct + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var doctrine = require("doctrine"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var options = context.options[0] || {}, + prefer = options.prefer || {}, + + // these both default to true, so you have to explicitly make them false + requireReturn = options.requireReturn === false ? false : true, + requireParamDescription = options.requireParamDescription !== false, + requireReturnDescription = options.requireReturnDescription !== false; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + // Using a stack to store if a function returns or not (handling nested functions) + var fns = []; + + /** + * When parsing a new function, store it in our function stack. + * @returns {void} + * @private + */ + function startFunction() { + fns.push({returnPresent: false}); + } + + /** + * Indicate that return has been found in the current function. + * @param {ASTNode} node The return node. + * @returns {void} + * @private + */ + function addReturn(node) { + var functionState = fns[fns.length - 1]; + + if (functionState && node.argument !== null) { + functionState.returnPresent = true; + } + } + + /** + * Validate the JSDoc node and output warnings if anything is wrong. + * @param {ASTNode} node The AST node to check. + * @returns {void} + * @private + */ + function checkJSDoc(node) { + var jsdocNode = context.getJSDocComment(node), + functionData = fns.pop(), + hasReturns = false, + hasConstructor = false, + params = Object.create(null), + jsdoc; + + // make sure only to validate JSDoc comments + if (jsdocNode) { + + try { + jsdoc = doctrine.parse(jsdocNode.value, { + strict: true, + unwrap: true, + sloppy: true + }); + } catch (ex) { + + if (/braces/i.test(ex.message)) { + context.report(jsdocNode, "JSDoc type missing brace."); + } else { + context.report(jsdocNode, "JSDoc syntax error."); + } + + return; + } + + jsdoc.tags.forEach(function(tag) { + + switch (tag.title) { + + case "param": + if (!tag.type) { + context.report(jsdocNode, "Missing JSDoc parameter type for '{{name}}'.", { name: tag.name }); + } + + if (!tag.description && requireParamDescription) { + context.report(jsdocNode, "Missing JSDoc parameter description for '{{name}}'.", { name: tag.name }); + } + + if (params[tag.name]) { + context.report(jsdocNode, "Duplicate JSDoc parameter '{{name}}'.", { name: tag.name }); + } else if (tag.name.indexOf(".") === -1) { + params[tag.name] = 1; + } + break; + + case "return": + case "returns": + hasReturns = true; + + if (!requireReturn && !functionData.returnPresent && tag.type.name !== "void" && tag.type.name !== "undefined") { + context.report(jsdocNode, "Unexpected @" + tag.title + " tag; function has no return statement."); + } else { + if (!tag.type) { + context.report(jsdocNode, "Missing JSDoc return type."); + } + + if (tag.type.name !== "void" && !tag.description && requireReturnDescription) { + context.report(jsdocNode, "Missing JSDoc return description."); + } + } + + break; + + case "constructor": + case "class": + hasConstructor = true; + break; + + // no default + } + + // check tag preferences + if (prefer.hasOwnProperty(tag.title)) { + context.report(jsdocNode, "Use @{{name}} instead.", { name: prefer[tag.title] }); + } + + }); + + // check for functions missing @returns + if (!hasReturns && !hasConstructor) { + if (requireReturn || functionData.returnPresent) { + context.report(jsdocNode, "Missing JSDoc @returns for function."); + } + } + + // check the parameters + var jsdocParams = Object.keys(params); + + node.params.forEach(function(param, i) { + var name = param.name; + + // TODO(nzakas): Figure out logical things to do with destructured, default, rest params + if (param.type === "Identifier") { + if (jsdocParams[i] && (name !== jsdocParams[i])) { + context.report(jsdocNode, "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", { + name: name, + jsdocName: jsdocParams[i] + }); + } else if (!params[name]) { + context.report(jsdocNode, "Missing JSDoc for parameter '{{name}}'.", { + name: name + }); + } + } + }); + + } + + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "ArrowFunctionExpression": startFunction, + "FunctionExpression": startFunction, + "FunctionDeclaration": startFunction, + "ArrowFunctionExpression:exit": checkJSDoc, + "FunctionExpression:exit": checkJSDoc, + "FunctionDeclaration:exit": checkJSDoc, + "ReturnStatement": addReturn + }; + +}; diff --git a/tools/eslint/lib/rules/valid-typeof.js b/tools/eslint/lib/rules/valid-typeof.js new file mode 100644 index 00000000000000..a108ab360fb0d7 --- /dev/null +++ b/tools/eslint/lib/rules/valid-typeof.js @@ -0,0 +1,40 @@ +/** + * @fileoverview Ensures that the results of typeof are compared against a valid string + * @author Ian Christian Myers + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function"], + OPERATORS = ["==", "===", "!=", "!=="]; + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + + "UnaryExpression": function (node) { + var parent, sibling; + + if (node.operator === "typeof") { + parent = context.getAncestors().pop(); + + if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) { + sibling = parent.left === node ? parent.right : parent.left; + + if (sibling.type === "Literal" && VALID_TYPES.indexOf(sibling.value) === -1) { + context.report(sibling, "Invalid typeof comparison value"); + } + } + } + } + + }; + +}; diff --git a/tools/eslint/lib/rules/vars-on-top.js b/tools/eslint/lib/rules/vars-on-top.js new file mode 100644 index 00000000000000..4af70a880339fa --- /dev/null +++ b/tools/eslint/lib/rules/vars-on-top.js @@ -0,0 +1,113 @@ +/** + * @fileoverview Rule to enforce var declarations are only at the top of a function. + * @author Danny Fritz + * @author Gyandeep Singh + * @copyright 2014 Danny Fritz. All rights reserved. + * @copyright 2014 Gyandeep Singh. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + var errorMessage = "All \"var\" declarations must be at the top of the function scope."; + + //-------------------------------------------------------------------------- + // Helpers + //-------------------------------------------------------------------------- + + /** + * @param {ASTNode} node - any node + * @returns {Boolean} whether the given node structurally represents a directive + */ + function looksLikeDirective(node) { + return node.type === "ExpressionStatement" && + node.expression.type === "Literal" && typeof node.expression.value === "string"; + } + + /** + * Check to see if its a ES6 import declaration + * @param {ASTNode} node - any node + * @returns {Boolean} whether the given node represents a import declaration + */ + function looksLikeImport(node) { + return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" || + node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier"; + } + + /** + * Checks whether this variable is on top of the block body + * @param {ASTNode} node - The node to check + * @param {ASTNode[]} statements - collection of ASTNodes for the parent node block + * @returns {Boolean} True if var is on top otherwise false + */ + function isVarOnTop(node, statements) { + var i = 0, l = statements.length; + + // skip over directives + for (; i < l; ++i) { + if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) { + break; + } + } + + for (; i < l; ++i) { + if (statements[i].type !== "VariableDeclaration") { + return false; + } + if (statements[i] === node) { + return true; + } + } + } + + /** + * Checks whether variable is on top at the global level + * @param {ASTNode} node - The node to check + * @param {ASTNode} parent - Parent of the node + * @returns {void} + */ + function globalVarCheck(node, parent) { + if (!isVarOnTop(node, parent.body)) { + context.report(node, errorMessage); + } + } + + /** + * Checks whether variable is on top at functional block scope level + * @param {ASTNode} node - The node to check + * @param {ASTNode} parent - Parent of the node + * @param {ASTNode} grandParent - Parent of the node's parent + * @returns {void} + */ + function blockScopeVarCheck(node, parent, grandParent) { + if (!(/Function/.test(grandParent.type) && + parent.type === "BlockStatement" && + isVarOnTop(node, parent.body))) { + context.report(node, errorMessage); + } + } + + //-------------------------------------------------------------------------- + // Public API + //-------------------------------------------------------------------------- + + return { + "VariableDeclaration": function (node) { + var ancestors = context.getAncestors(); + var parent = ancestors.pop(); + var grandParent = ancestors.pop(); + + if (node.kind === "var") {// check variable is `var` type and not `let` or `const` + if (parent.type === "Program") {// That means its a global variable + globalVarCheck(node, parent); + } else { + blockScopeVarCheck(node, parent, grandParent); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/wrap-iife.js b/tools/eslint/lib/rules/wrap-iife.js new file mode 100644 index 00000000000000..eb3c5d1dc3f059 --- /dev/null +++ b/tools/eslint/lib/rules/wrap-iife.js @@ -0,0 +1,42 @@ +/** + * @fileoverview Rule to flag when IIFE is not wrapped in parens + * @author Ilya Volodin + * @copyright 2013 Ilya Volodin. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + var style = context.options[0] || "outside"; + + function wrapped(node) { + var previousToken = context.getTokenBefore(node), + nextToken = context.getTokenAfter(node); + return previousToken && previousToken.value === "(" && + nextToken && nextToken.value === ")"; + } + + return { + + "CallExpression": function(node) { + if (node.callee.type === "FunctionExpression") { + var callExpressionWrapped = wrapped(node), + functionExpressionWrapped = wrapped(node.callee); + + if (!callExpressionWrapped && !functionExpressionWrapped) { + context.report(node, "Wrap an immediate function invocation in parentheses."); + } else if (style === "inside" && !functionExpressionWrapped) { + context.report(node, "Wrap only the function expression in parens."); + } else if (style === "outside" && !callExpressionWrapped) { + context.report(node, "Move the invocation into the parens that contain the function."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/wrap-regex.js b/tools/eslint/lib/rules/wrap-regex.js new file mode 100644 index 00000000000000..e2cc7d225322ea --- /dev/null +++ b/tools/eslint/lib/rules/wrap-regex.js @@ -0,0 +1,36 @@ +/** + * @fileoverview Rule to flag when regex literals are not wrapped in parens + * @author Matt DuVall + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function(context) { + + return { + + "Literal": function(node) { + var token = context.getFirstToken(node), + nodeType = token.type, + source, + grandparent, + ancestors; + + if (nodeType === "RegularExpression") { + source = context.getTokenBefore(node); + ancestors = context.getAncestors(); + grandparent = ancestors[ancestors.length - 1]; + + if (grandparent.type === "MemberExpression" && grandparent.object === node && + (!source || source.value !== "(")) { + context.report(node, "Wrap the regexp literal in parens to disambiguate the slash."); + } + } + } + }; + +}; diff --git a/tools/eslint/lib/rules/yoda.js b/tools/eslint/lib/rules/yoda.js new file mode 100644 index 00000000000000..cdb5bdad0834ce --- /dev/null +++ b/tools/eslint/lib/rules/yoda.js @@ -0,0 +1,210 @@ +/** + * @fileoverview Rule to require or disallow yoda comparisons + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2014 Brandon Mills. All rights reserved. + */ +"use strict"; + +//-------------------------------------------------------------------------- +// Helpers +//-------------------------------------------------------------------------- + +/** + * Determines whether an operator is a comparison operator. + * @param {String} operator The operator to check. + * @returns {boolean} Whether or not it is a comparison operator. + */ +function isComparisonOperator(operator) { + return (/^(==|===|!=|!==|<|>|<=|>=)$/).test(operator); +} + +/** + * Determines whether an operator is one used in a range test. + * Allowed operators are `<` and `<=`. + * @param {String} operator The operator to check. + * @returns {boolean} Whether the operator is used in range tests. + */ +function isRangeTestOperator(operator) { + return ["<", "<="].indexOf(operator) >= 0; +} + +/** + * Determines whether a non-Literal node is a negative number that should be + * treated as if it were a single Literal node. + * @param {ASTNode} node Node to test. + * @returns {boolean} True if the node is a negative number that looks like a + * real literal and should be treated as such. + */ +function looksLikeLiteral(node) { + return (node.type === "UnaryExpression" && + node.operator === "-" && + node.prefix && + node.argument.type === "Literal" && + typeof node.argument.value === "number"); +} + +/** + * Attempts to derive a Literal node from nodes that are treated like literals. + * @param {ASTNode} node Node to normalize. + * @returns {ASTNode} The original node if the node is already a Literal, or a + * normalized Literal node with the negative number as the + * value if the node represents a negative number literal, + * otherwise null if the node cannot be converted to a + * normalized literal. + */ +function getNormalizedLiteral(node) { + if (node.type === "Literal") { + return node; + } + + if (looksLikeLiteral(node)) { + return { + type: "Literal", + value: -node.argument.value, + raw: "-" + node.argument.value + }; + } + + return null; +} + +/** + * Checks whether two expressions reference the same value. For example: + * a = a + * a.b = a.b + * a[0] = a[0] + * a['b'] = a['b'] + * @param {ASTNode} a Left side of the comparison. + * @param {ASTNode} b Right side of the comparison. + * @returns {boolean} True if both sides match and reference the same value. + */ +function same(a, b) { + if (a.type !== b.type) { + return false; + } + + switch (a.type) { + case "Identifier": + return a.name === b.name; + case "Literal": + return a.value === b.value; + case "MemberExpression": + // x[0] = x[0] + // x[y] = x[y] + // x.y = x.y + return same(a.object, b.object) && same(a.property, b.property); + case "ThisExpression": + return true; + default: + return false; + } +} + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = function (context) { + + // Default to "never" (!always) if no option + var always = (context.options[0] === "always"); + var exceptRange = (context.options[1] && context.options[1].exceptRange); + + /** + * Determines whether node represents a range test. + * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside" + * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and + * both operators must be `<` or `<=`. Finally, the literal on the left side + * must be less than or equal to the literal on the right side so that the + * test makes any sense. + * @param {ASTNode} node LogicalExpression node to test. + * @returns {Boolean} Whether node is a range test. + */ + function isRangeTest(node) { + var left = node.left, + right = node.right; + + /** + * Determines whether node is of the form `0 <= x && x < 1`. + * @returns {Boolean} Whether node is a "between" range test. + */ + function isBetweenTest() { + var leftLiteral, rightLiteral; + + return (node.operator === "&&" && + (leftLiteral = getNormalizedLiteral(left.left)) && + (rightLiteral = getNormalizedLiteral(right.right)) && + leftLiteral.value <= rightLiteral.value && + same(left.right, right.left)); + } + + /** + * Determines whether node is of the form `x < 0 || 1 <= x`. + * @returns {Boolean} Whether node is an "outside" range test. + */ + function isOutsideTest() { + var leftLiteral, rightLiteral; + + return (node.operator === "||" && + (leftLiteral = getNormalizedLiteral(left.right)) && + (rightLiteral = getNormalizedLiteral(right.left)) && + leftLiteral.value <= rightLiteral.value && + same(left.left, right.right)); + } + + /** + * Determines whether node is wrapped in parentheses. + * @returns {Boolean} Whether node is preceded immediately by an open + * paren token and followed immediately by a close + * paren token. + */ + function isParenWrapped() { + var tokenBefore, tokenAfter; + + return ((tokenBefore = context.getTokenBefore(node)) && + tokenBefore.value === "(" && + (tokenAfter = context.getTokenAfter(node)) && + tokenAfter.value === ")"); + } + + return (node.type === "LogicalExpression" && + left.type === "BinaryExpression" && + right.type === "BinaryExpression" && + isRangeTestOperator(left.operator) && + isRangeTestOperator(right.operator) && + (isBetweenTest() || isOutsideTest()) && + isParenWrapped()); + } + + //-------------------------------------------------------------------------- + // Public + //-------------------------------------------------------------------------- + + return { + "BinaryExpression": always ? function(node) { + + // Comparisons must always be yoda-style: if ("blue" === color) + if ( + (node.right.type === "Literal" || looksLikeLiteral(node.right)) && + isComparisonOperator(node.operator) && + !(exceptRange && isRangeTest(context.getAncestors().pop())) + ) { + context.report(node, "Expected literal to be on the left side of " + node.operator + "."); + } + + } : function(node) { + + // Comparisons must never be yoda-style (default) + if ( + (node.left.type === "Literal" || looksLikeLiteral(node.left)) && + isComparisonOperator(node.operator) && + !(exceptRange && isRangeTest(context.getAncestors().pop())) + ) { + context.report(node, "Expected literal to be on the right side of " + node.operator + "."); + } + + } + }; + +}; diff --git a/tools/eslint/lib/timing.js b/tools/eslint/lib/timing.js new file mode 100644 index 00000000000000..06e8da70b97e58 --- /dev/null +++ b/tools/eslint/lib/timing.js @@ -0,0 +1,109 @@ +/** + * @fileoverview Tracks performance of individual rules. + * @author Brandon Mills + * @copyright 2014 Brandon Mills. All rights reserved. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/* istanbul ignore next */ +function alignLeft(str, len, ch) { + return str + new Array(len - str.length + 1).join(ch || " "); +} + +/* istanbul ignore next */ +function alignRight(str, len, ch) { + return new Array(len - str.length + 1).join(ch || " ") + str; +} + +//------------------------------------------------------------------------------ +// Module definition +//------------------------------------------------------------------------------ + +var enabled = !!process.env.TIMING; + +var HEADERS = ["Rule", "Time (ms)", "Relative"]; +var ALIGN = [alignLeft, alignRight, alignRight]; + +/* istanbul ignore next */ +function display(data) { + var total = 0; + var rows = Object.keys(data) + .map(function(key) { + var time = data[key]; + total += time; + return [key, time]; + }) + .sort(function(a, b) { + return b[1] - a[1]; + }) + .slice(0, 10); + + rows.forEach(function(row) { + row.push((row[1] * 100 / total).toFixed(1) + "%"); + row[1] = row[1].toFixed(3); + }); + + rows.unshift(HEADERS); + + var widths = []; + rows.forEach(function(row) { + var len = row.length, i, n; + for (i = 0; i < len; i++) { + n = row[i].length; + if (!widths[i] || n > widths[i]) { + widths[i] = n; + } + } + }); + + var table = rows.map(function(row) { + return row.map(function(cell, index) { + return ALIGN[index](cell, widths[index]); + }).join(" | "); + }); + table.splice(1, 0, widths.map(function(w, index) { + if (index !== 0 && index !== widths.length - 1) { + w++; + } + + return ALIGN[index](":", w + 1, "-"); + }).join("|")); + + console.log(table.join("\n")); +} + +/* istanbul ignore next */ +module.exports = (function() { + + var data = Object.create(null); + + function time(key, fn) { + if (typeof data[key] === "undefined") { + data[key] = 0; + } + + return function() { + var t = process.hrtime(); + fn.apply(null, Array.prototype.slice.call(arguments)); + t = process.hrtime(t); + data[key] += t[0] * 1e3 + t[1] / 1e6; + }; + } + + if (enabled) { + process.on("exit", function() { + display(data); + }); + } + + return { + time: time, + enabled: enabled + }; + +}()); diff --git a/tools/eslint/lib/token-store.js b/tools/eslint/lib/token-store.js new file mode 100644 index 00000000000000..6a0149414236b7 --- /dev/null +++ b/tools/eslint/lib/token-store.js @@ -0,0 +1,201 @@ +/** + * @fileoverview Object to handle access and retrieval of tokens. + * @author Brandon Mills + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2014 Brandon Mills. All rights reserved. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Implementation +//------------------------------------------------------------------------------ + +module.exports = function(tokens) { + var api = {}, + starts = Object.create(null), + ends = Object.create(null), + index, length, range; + + /** + * Gets tokens in a given interval. + * @param {int} start Inclusive index of the first token. 0 if negative. + * @param {int} end Exclusive index of the last token. + * @returns {Token[]} Tokens in the interval. + */ + function get(start, end) { + var result = [], + i; + + for (i = Math.max(0, start); i < end && i < length; i++) { + result.push(tokens[i]); + } + + return result; + } + + /** + * Gets the index in the tokens array of the last token belonging to a node. + * Usually a node ends exactly at a token, but due to ASI, sometimes a + * node's range extends beyond its last token. + * @param {ASTNode} node The node for which to find the last token's index. + * @returns {int} Index in the tokens array of the node's last token. + */ + function lastTokenIndex(node) { + var end = node.range[1], + cursor = ends[end]; + + // If the node extends beyond its last token, get the token before the + // next token + if (typeof cursor === "undefined") { + cursor = starts[end] - 1; + } + + // If there isn't a next token, the desired token is the last one in the + // array + if (isNaN(cursor)) { + cursor = length - 1; + } + + return cursor; + } + + // Map tokens' start and end range to the index in the tokens array + for (index = 0, length = tokens.length; index < length; index++) { + range = tokens[index].range; + starts[range[0]] = index; + ends[range[1]] = index; + } + + /** + * Gets a number of tokens that precede a given node or token in the token + * stream. + * @param {(ASTNode|Token)} node The AST node or token. + * @param {int} [beforeCount=0] The number of tokens before the node or + * token to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + api.getTokensBefore = function(node, beforeCount) { + var first = starts[node.range[0]]; + return get(first - (beforeCount || 0), first); + }; + + /** + * Gets the token that precedes a given node or token in the token stream. + * @param {(ASTNode|Token)} node The AST node or token. + * @param {int} [skip=0] A number of tokens to skip before the given node or + * token. + * @returns {Token} An object representing the token. + */ + api.getTokenBefore = function(node, skip) { + return tokens[starts[node.range[0]] - (skip || 0) - 1]; + }; + + /** + * Gets a number of tokens that follow a given node or token in the token + * stream. + * @param {(ASTNode|Token)} node The AST node or token. + * @param {int} [afterCount=0] The number of tokens after the node or token + * to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + api.getTokensAfter = function(node, afterCount) { + var start = lastTokenIndex(node) + 1; + return get(start, start + (afterCount || 0)); + }; + + /** + * Gets the token that follows a given node or token in the token stream. + * @param {(ASTNode|Token)} node The AST node or token. + * @param {int} [skip=0] A number of tokens to skip after the given node or + * token. + * @returns {Token} An object representing the token. + */ + api.getTokenAfter = function(node, skip) { + return tokens[lastTokenIndex(node) + (skip || 0) + 1]; + }; + + /** + * Gets all tokens that are related to the given node. + * @param {ASTNode} node The AST node. + * @param {int} [beforeCount=0] The number of tokens before the node to retrieve. + * @param {int} [afterCount=0] The number of tokens after the node to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + api.getTokens = function(node, beforeCount, afterCount) { + return get( + starts[node.range[0]] - (beforeCount || 0), + lastTokenIndex(node) + (afterCount || 0) + 1 + ); + }; + + /** + * Gets the first `count` tokens of the given node's token stream. + * @param {ASTNode} node The AST node. + * @param {int} [count=0] The number of tokens of the node to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + api.getFirstTokens = function(node, count) { + var first = starts[node.range[0]]; + return get( + first, + Math.min(lastTokenIndex(node) + 1, first + (count || 0)) + ); + }; + + /** + * Gets the first token of the given node's token stream. + * @param {ASTNode} node The AST node. + * @param {int} [skip=0] A number of tokens to skip. + * @returns {Token} An object representing the token. + */ + api.getFirstToken = function(node, skip) { + return tokens[starts[node.range[0]] + (skip || 0)]; + }; + + /** + * Gets the last `count` tokens of the given node. + * @param {ASTNode} node The AST node. + * @param {int} [count=0] The number of tokens of the node to retrieve. + * @returns {Token[]} Array of objects representing tokens. + */ + api.getLastTokens = function(node, count) { + var last = lastTokenIndex(node) + 1; + return get(Math.max(starts[node.range[0]], last - (count || 0)), last); + }; + + /** + * Gets the last token of the given node's token stream. + * @param {ASTNode} node The AST node. + * @param {int} [skip=0] A number of tokens to skip. + * @returns {Token} An object representing the token. + */ + api.getLastToken = function(node, skip) { + return tokens[lastTokenIndex(node) - (skip || 0)]; + }; + + /** + * Gets all of the tokens between two non-overlapping nodes. + * @param {ASTNode} left Node before the desired token range. + * @param {ASTNode} right Node after the desired token range. + * @param {int} [padding=0] Number of extra tokens on either side of center. + * @returns {Token[]} Tokens between left and right plus padding. + */ + api.getTokensBetween = function(left, right, padding) { + padding = padding || 0; + return get( + lastTokenIndex(left) + 1 - padding, + starts[right.range[0]] + padding + ); + }; + + /** + * Gets the token starting at the specified index. + * @param {int} startIndex Index of the start of the token's range. + * @returns {Token} The token starting at index, or null if no such token. + */ + api.getTokenByRangeStart = function(startIndex) { + return (tokens[starts[startIndex]] || null); + }; + + return api; +}; diff --git a/tools/eslint/lib/util.js b/tools/eslint/lib/util.js new file mode 100644 index 00000000000000..9fe594a4aed093 --- /dev/null +++ b/tools/eslint/lib/util.js @@ -0,0 +1,85 @@ +/** + * @fileoverview Common utilities. + */ +"use strict"; + +//------------------------------------------------------------------------------ +// Constants +//------------------------------------------------------------------------------ + +var PLUGIN_NAME_PREFIX = "eslint-plugin-", + NAMESPACE_REGEX = /^@.*\//i; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Merges two config objects. This will not only add missing keys, but will also modify values to match. + * @param {Object} base config object + * @param {Object} custom config object. Overrides in this config object will take priority over base. + * @returns {Object} merged config object. + */ +exports.mergeConfigs = function mergeConfigs(base, custom) { + + Object.keys(custom).forEach(function (key) { + var property = custom[key]; + + if (key === "plugins") { + if (!base[key]) { + base[key] = []; + } + + property.forEach(function (plugin) { + // skip duplicates + if (base[key].indexOf(plugin) === -1) { + base[key].push(plugin); + } + }); + return; + } + + if (Array.isArray(base[key]) && !Array.isArray(property) && typeof property === "number") { + // assume that we are just overriding first attribute + base[key][0] = custom[key]; + return; + } + + if (typeof property === "object" && !Array.isArray(property) && property !== null) { + // base[key] might not exist, so be careful with recursion here + base[key] = mergeConfigs(base[key] || {}, custom[key]); + } else { + base[key] = custom[key]; + } + }); + + return base; +}; + +/** + * Removes the prefix `eslint-plugin-` from a plugin name. + * @param {string} pluginName The name of the plugin which may have the prefix. + * @returns {string} The name of the plugin without prefix. + */ +exports.removePluginPrefix = function removePluginPrefix(pluginName) { + return pluginName.indexOf(PLUGIN_NAME_PREFIX) === 0 ? pluginName.substring(PLUGIN_NAME_PREFIX.length) : pluginName; +}; + +/** + * @param {string} pluginName The name of the plugin which may have the prefix. + * @returns {string} The name of the plugins namepace if it has one. + */ +exports.getNamespace = function getNamespace(pluginName) { + return pluginName.match(NAMESPACE_REGEX) ? pluginName.match(NAMESPACE_REGEX)[0] : ""; +}; + +/** + * Removes the namespace from a plugin name. + * @param {string} pluginName The name of the plugin which may have the prefix. + * @returns {string} The name of the plugin without the namespace. + */ +exports.removeNameSpace = function removeNameSpace(pluginName) { + return pluginName.replace(NAMESPACE_REGEX, ""); +}; + +exports.PLUGIN_NAME_PREFIX = PLUGIN_NAME_PREFIX; diff --git a/tools/eslint/lib/util/traverse.js b/tools/eslint/lib/util/traverse.js new file mode 100644 index 00000000000000..ba5520e341bb46 --- /dev/null +++ b/tools/eslint/lib/util/traverse.js @@ -0,0 +1,105 @@ +/** + * @fileoverview Simple directory traversal logic. + * @author Nicholas C. Zakas + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var fs = require("fs"), + path = require("path"), + debug = require("debug"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +debug = debug("eslint:traverse"); + +/** + * Walks a path recursively calling the callback on each file. + * @param {string} name The file or directory path. + * @param {string[]} extensions The file extensions that should cause the callback + * to be called. + * @param {Function} exclude The function to check if file/path should be excluded. + * @param {Function} callback The function to call on each file. + * @returns {void} + * @private + */ +function walk(name, extensions, exclude, callback) { + + var stat, basename; + + stat = fs.statSync(name); + + function traverse(dir, stack) { + stack.push(dir); + + fs.readdirSync(path.join.apply(path, stack)).forEach(function(file) { + var filePath, fileStat; + + // skip all hidded things (dirs, files, links) + if (file[0] === ".") { + return; + } + + filePath = path.join.apply(path, stack.concat([file])); + fileStat = fs.statSync(filePath); + + // if this file or directory is excluded from linting, skip over it. + if (exclude && exclude(filePath)) { + // console.log("Ignoring " + filePath); + debug("Ignoring " + filePath); + return; + } + + // only call callback for files with correct extensions + if (fileStat.isFile() && extensions.indexOf(path.extname(filePath)) > -1) { + callback(filePath); + } else if (fileStat.isDirectory()) { + traverse(file, stack); + } + }); + stack.pop(); + } + + basename = path.basename(name); + + // don't ignore cases like 'eslint ./' + if ((basename !== "." && basename !== ".." && basename[0] === ".") || + (exclude && exclude(name))) { + + debug("Ignoring " + name); + return; + } + + // always call callback for any files that are passed on the command line + if (stat.isFile()) { + callback(name); + } else { + traverse(name, []); + } +} + +/** + * Traverses multiple directories and calls a callback on each file. + * @param {Object} options The option for the traversal. + * param {string[]} options.files An array of file and directory paths to traverse. + * param {Function} options.exclude The function to check if file/path should be excluded. + * @param {Function} callback A function to call for each file. + * @returns {void} + */ +module.exports = function traverse(options, callback) { + + var files = options.files, + exclude = options.exclude, + extensions = options.extensions; + + files.forEach(function(file) { + walk(file, extensions, exclude, callback); + }); + +}; diff --git a/tools/eslint/node_modules/.bin/esparse b/tools/eslint/node_modules/.bin/esparse new file mode 100755 index 00000000000000..4a9984aab05c9d --- /dev/null +++ b/tools/eslint/node_modules/.bin/esparse @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true rhino:true */ + +var fs, espree, fname, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + espree = require('espree'); +} else if (typeof load === 'function') { + try { + load('espree.js'); + } catch (e) { + load('../espree.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using espree version', espree.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } +}); + +if (typeof fname !== 'string') { + console.log('Error: no input file.'); + process.exit(1); +} + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +try { + content = fs.readFileSync(fname, 'utf-8'); + syntax = espree.parse(content, options); + console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/tools/eslint/node_modules/.bin/esvalidate b/tools/eslint/node_modules/.bin/esvalidate new file mode 100755 index 00000000000000..7631d0a29d6a0e --- /dev/null +++ b/tools/eslint/node_modules/.bin/esvalidate @@ -0,0 +1,199 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true plusplus:true node:true rhino:true */ +/*global phantom:true */ + +var fs, system, espree, options, fnames, count; + +if (typeof espree === 'undefined') { + // PhantomJS can only require() relative files + if (typeof phantom === 'object') { + fs = require('fs'); + system = require('system'); + espree = require('./espree'); + } else if (typeof require === 'function') { + fs = require('fs'); + espree = require('espree'); + } else if (typeof load === 'function') { + try { + load('espree.js'); + } catch (e) { + load('../espree.js'); + } + } +} + +// Shims to Node.js objects when running under PhantomJS 1.7+. +if (typeof phantom === 'object') { + fs.readFileSync = fs.read; + process = { + argv: [].slice.call(system.args), + exit: phantom.exit + }; + process.argv.unshift('phantomjs'); +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using espree version', espree.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else { + fnames.push(entry); + } +}); + +if (fnames.length === 0) { + console.log('Error: no input file.'); + process.exit(1); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; +fnames.forEach(function (fname) { + var content, timestamp, syntax, name; + try { + content = fs.readFileSync(fname, 'utf-8'); + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = espree.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log('Error: ' + e.message); + } + } +}); + +if (options.format === 'junit') { + console.log(''); +} + +if (count > 0) { + process.exit(1); +} + +if (count === 0 && typeof phantom === 'object') { + process.exit(0); +} diff --git a/tools/eslint/node_modules/.bin/js-yaml b/tools/eslint/node_modules/.bin/js-yaml new file mode 100755 index 00000000000000..e6029d64ce23eb --- /dev/null +++ b/tools/eslint/node_modules/.bin/js-yaml @@ -0,0 +1,142 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +// stdlib +var fs = require('fs'); + + +// 3rd-party +var argparse = require('argparse'); + + +// internal +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + version: require('../package.json').version, + addHelp: true +}); + + +cli.addArgument([ '-c', '--compact' ], { + help: 'Display errors in compact mode', + action: 'storeTrue' +}); + + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.addArgument([ '-j', '--to-json' ], { + help: argparse.Const.SUPPRESS, + dest: 'json', + action: 'storeTrue' +}); + + +cli.addArgument([ '-t', '--trace' ], { + help: 'Show stack trace on error', + action: 'storeTrue' +}); + +cli.addArgument([ 'file' ], { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + defaultValue: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parseArgs(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (error) { + if (error instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (0 === output.length) { + output = null; + } else if (1 === output.length) { + output = output[0]; + } + } catch (error) { + if (options.trace && error.stack) { + console.error(error.stack); + } else { + console.error(error.toString(options.compact)); + } + + process.exit(1); + } + } else { + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + } + + if (isYaml) { + console.log(JSON.stringify(output, null, ' ')); + } else { + console.log(yaml.dump(output)); + } + + process.exit(0); +}); diff --git a/tools/eslint/node_modules/.bin/mkdirp b/tools/eslint/node_modules/.bin/mkdirp new file mode 100755 index 00000000000000..d95de15ae9743f --- /dev/null +++ b/tools/eslint/node_modules/.bin/mkdirp @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/tools/eslint/node_modules/.bin/strip-json-comments b/tools/eslint/node_modules/.bin/strip-json-comments new file mode 100755 index 00000000000000..ac4da48457a2f5 --- /dev/null +++ b/tools/eslint/node_modules/.bin/strip-json-comments @@ -0,0 +1,41 @@ +#!/usr/bin/env node +'use strict'; +var fs = require('fs'); +var strip = require('./strip-json-comments'); +var input = process.argv[2]; + + +function getStdin(cb) { + var ret = ''; + + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', function (data) { + ret += data; + }); + + process.stdin.on('end', function () { + cb(ret); + }); +} + +if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) { + console.log('strip-json-comments > '); + console.log('or'); + console.log('cat | strip-json-comments > '); + return; +} + +if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) { + console.log(require('./package').version); + return; +} + +if (input) { + process.stdout.write(strip(fs.readFileSync(input, 'utf8'))); + return; +} + +getStdin(function (data) { + process.stdout.write(strip(data)); +}); diff --git a/tools/eslint/node_modules/.bin/user-home b/tools/eslint/node_modules/.bin/user-home new file mode 100755 index 00000000000000..bacbd22755e08f --- /dev/null +++ b/tools/eslint/node_modules/.bin/user-home @@ -0,0 +1,26 @@ +#!/usr/bin/env node +'use strict'; +var pkg = require('./package.json'); +var userHome = require('./'); + +function help() { + console.log([ + pkg.description, + '', + 'Example', + ' $ user-home', + ' /Users/sindresorhus' + ].join('\n')); +} + +if (process.argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (process.argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +process.stdout.write(userHome); diff --git a/tools/eslint/node_modules/chalk/index.js b/tools/eslint/node_modules/chalk/index.js new file mode 100644 index 00000000000000..4138a64dd918a4 --- /dev/null +++ b/tools/eslint/node_modules/chalk/index.js @@ -0,0 +1,100 @@ +'use strict'; +var escapeStringRegexp = require('escape-string-regexp'); +var ansiStyles = require('ansi-styles'); +var stripAnsi = require('strip-ansi'); +var hasAnsi = require('has-ansi'); +var supportsColor = require('supports-color'); +var defineProps = Object.defineProperties; + +function Chalk(options) { + // detect mode if not set manually + this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; +} + +// use bright blue on Windows as the normal blue color is illegible +if (process.platform === 'win32') { + ansiStyles.blue.open = '\u001b[94m'; +} + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + builder.enabled = this.enabled; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function () { + var ret = {}; + + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + ret[key] = { + get: function () { + return build.call(this, this._styles.concat(key)); + } + }; + }); + + return ret; +})(); + +var proto = defineProps(function chalk() {}, styles); + +function applyStyle() { + // support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); + if (argsLen > 1) { + // don't slice `arguments`, it prevents v8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || !str) { + return str; + } + + /*jshint validthis: true */ + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } + + return str; +} + +function init() { + var ret = {}; + + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build.call(this, [name]); + } + }; + }); + + return ret; +} + +defineProps(Chalk.prototype, init()); + +module.exports = new Chalk(); +module.exports.styles = ansiStyles; +module.exports.hasColor = hasAnsi; +module.exports.stripColor = stripAnsi; +module.exports.supportsColor = supportsColor; diff --git a/tools/eslint/node_modules/chalk/license b/tools/eslint/node_modules/chalk/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/chalk/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/chalk/node_modules/.bin/has-ansi b/tools/eslint/node_modules/chalk/node_modules/.bin/has-ansi new file mode 100755 index 00000000000000..0386a82423625f --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/.bin/has-ansi @@ -0,0 +1,45 @@ +#!/usr/bin/env node +'use strict'; +var stdin = require('get-stdin'); +var pkg = require('./package.json'); +var hasAnsi = require('./'); +var argv = process.argv.slice(2); +var input = argv[0]; + +function help() { + console.log([ + '', + ' ' + pkg.description, + '', + ' Usage', + ' has-ansi ', + ' echo | has-ansi', + '', + ' Exits with code 0 if input has ANSI escape codes and 1 if not' + ].join('\n')); +} + +function init(data) { + process.exit(hasAnsi(data) ? 0 : 1); +} + +if (argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +if (process.stdin.isTTY) { + if (!input) { + help(); + return; + } + + init(input); +} else { + stdin(init); +} diff --git a/tools/eslint/node_modules/chalk/node_modules/.bin/strip-ansi b/tools/eslint/node_modules/chalk/node_modules/.bin/strip-ansi new file mode 100755 index 00000000000000..b83f63b907e2e0 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/.bin/strip-ansi @@ -0,0 +1,47 @@ +#!/usr/bin/env node +'use strict'; +var fs = require('fs'); +var pkg = require('./package.json'); +var stripAnsi = require('./'); +var argv = process.argv.slice(2); +var input = argv[0]; + +function help() { + console.log([ + '', + ' ' + pkg.description, + '', + ' Usage', + ' strip-ansi > ', + ' cat | strip-ansi > ', + '', + ' Example', + ' strip-ansi unicorn.txt > unicorn-stripped.txt' + ].join('\n')); +} + +function init(data) { + process.stdout.write(stripAnsi(data)); +} + +if (argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +if (!input && process.stdin.isTTY) { + help(); + return; +} + +if (input) { + init(fs.readFileSync(input, 'utf8')); +} else { + process.stdin.setEncoding('utf8'); + process.stdin.on('data', init); +} diff --git a/tools/eslint/node_modules/chalk/node_modules/.bin/supports-color b/tools/eslint/node_modules/chalk/node_modules/.bin/supports-color new file mode 100755 index 00000000000000..e746987666d422 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/.bin/supports-color @@ -0,0 +1,29 @@ +#!/usr/bin/env node +'use strict'; +var pkg = require('./package.json'); +var supportsColor = require('./'); +var argv = process.argv.slice(2); + +function help() { + console.log([ + '', + ' ' + pkg.description, + '', + ' Usage', + ' supports-color', + '', + ' Exits with code 0 if color is supported and 1 if not' + ].join('\n')); +} + +if (argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +process.exit(supportsColor ? 0 : 1); diff --git a/tools/eslint/node_modules/chalk/node_modules/ansi-styles/index.js b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/index.js new file mode 100644 index 00000000000000..caf9e119ebff82 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var styles = module.exports = { + modifiers: { + reset: [0, 0], + bold: [1, 22], // 21 isn't widely supported and 22 does the same thing + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + colors: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39] + }, + bgColors: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49] + } +}; + +// fix humans +styles.colors.grey = styles.colors.gray; + +Object.keys(styles).forEach(function (groupName) { + var group = styles[groupName]; + + Object.keys(group).forEach(function (styleName) { + var style = group[styleName]; + + styles[styleName] = group[styleName] = { + open: '\u001b[' + style[0] + 'm', + close: '\u001b[' + style[1] + 'm' + }; + }); + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); +}); diff --git a/tools/eslint/node_modules/chalk/node_modules/ansi-styles/license b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/chalk/node_modules/ansi-styles/package.json b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/package.json new file mode 100644 index 00000000000000..d9f9041e8022eb --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/package.json @@ -0,0 +1,80 @@ +{ + "name": "ansi-styles", + "version": "2.0.1", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/ansi-styles.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "devDependencies": { + "mocha": "*" + }, + "gitHead": "da6541334e1681cb803f891fab8abf4313cc4bc1", + "bugs": { + "url": "https://github.com/sindresorhus/ansi-styles/issues" + }, + "homepage": "https://github.com/sindresorhus/ansi-styles", + "_id": "ansi-styles@2.0.1", + "_shasum": "b033f57f93e2d28adeb8bc11138fa13da0fd20a3", + "_from": "ansi-styles@>=2.0.1 <3.0.0", + "_npmVersion": "2.1.16", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + }, + "dist": { + "shasum": "b033f57f93e2d28adeb8bc11138fa13da0fd20a3", + "tarball": "http://registry.npmjs.org/ansi-styles/-/ansi-styles-2.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/ansi-styles/readme.md b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/readme.md new file mode 100644 index 00000000000000..89ec6a7c1ed96d --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/ansi-styles/readme.md @@ -0,0 +1,86 @@ +# ansi-styles [![Build Status](https://travis-ci.org/sindresorhus/ansi-styles.svg?branch=master)](https://travis-ci.org/sindresorhus/ansi-styles) + +> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/sindresorhus/chalk) module for styling your strings. + +![](screenshot.png) + + +## Install + +```sh +$ npm install --save ansi-styles +``` + + +## Usage + +```js +var ansi = require('ansi-styles'); + +console.log(ansi.green.open + 'Hello world!' + ansi.green.close); +``` + + +## API + +Each style has an `open` and `close` property. + + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `gray` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` + + +## Advanced usage + +By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `ansi.modifiers` +- `ansi.colors` +- `ansi.bgColors` + + +###### Example + +```js +console.log(ansi.colors.green.open); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/cli.js b/tools/eslint/node_modules/chalk/node_modules/has-ansi/cli.js new file mode 100755 index 00000000000000..0386a82423625f --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/cli.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node +'use strict'; +var stdin = require('get-stdin'); +var pkg = require('./package.json'); +var hasAnsi = require('./'); +var argv = process.argv.slice(2); +var input = argv[0]; + +function help() { + console.log([ + '', + ' ' + pkg.description, + '', + ' Usage', + ' has-ansi ', + ' echo | has-ansi', + '', + ' Exits with code 0 if input has ANSI escape codes and 1 if not' + ].join('\n')); +} + +function init(data) { + process.exit(hasAnsi(data) ? 0 : 1); +} + +if (argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +if (process.stdin.isTTY) { + if (!input) { + help(); + return; + } + + init(input); +} else { + stdin(init); +} diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/index.js b/tools/eslint/node_modules/chalk/node_modules/has-ansi/index.js new file mode 100644 index 00000000000000..98fae067673731 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +var ansiRegex = require('ansi-regex'); +var re = new RegExp(ansiRegex().source); // remove the `g` flag +module.exports = re.test.bind(re); diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/license b/tools/eslint/node_modules/chalk/node_modules/has-ansi/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/index.js b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/index.js new file mode 100644 index 00000000000000..2fcdd1e472f961 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/index.js @@ -0,0 +1,4 @@ +'use strict'; +module.exports = function () { + return /(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/g; +}; diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/license b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/package.json b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/package.json new file mode 100644 index 00000000000000..4b7be0c62ca2b4 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/package.json @@ -0,0 +1,86 @@ +{ + "name": "ansi-regex", + "version": "1.1.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/ansi-regex.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha test/test.js", + "view-supported": "node test/viewCodes.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "mocha": "*" + }, + "gitHead": "47fb974630af70998157b30fad6eb5e5bd7c7cd6", + "bugs": { + "url": "https://github.com/sindresorhus/ansi-regex/issues" + }, + "homepage": "https://github.com/sindresorhus/ansi-regex", + "_id": "ansi-regex@1.1.1", + "_shasum": "41c847194646375e6a1a5d10c3ca054ef9fc980d", + "_from": "ansi-regex@>=1.0.0 <2.0.0", + "_npmVersion": "2.1.16", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + }, + "dist": { + "shasum": "41c847194646375e6a1a5d10c3ca054ef9fc980d", + "tarball": "http://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/readme.md b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/readme.md new file mode 100644 index 00000000000000..ae876e7292feb7 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/readme.md @@ -0,0 +1,33 @@ +# ansi-regex [![Build Status](https://travis-ci.org/sindresorhus/ansi-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/ansi-regex) + +> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +```sh +$ npm install --save ansi-regex +``` + + +## Usage + +```js +var ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001b[4mcake\u001b[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001b[4mcake\u001b[0m'.match(ansiRegex()); +//=> ['\u001b[4m', '\u001b[0m'] +``` + +*It's a function so you can create multiple instances. Regexes with the global flag will have the `.lastIndex` property changed for each call to methods on the instance. Therefore reusing the instance with multiple calls will not work as expected for `.test()`.* + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/index.js b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/index.js new file mode 100644 index 00000000000000..0f1aeb3df4e0da --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/index.js @@ -0,0 +1,49 @@ +'use strict'; + +module.exports = function (cb) { + var stdin = process.stdin; + var ret = ''; + + if (stdin.isTTY) { + setImmediate(cb, ''); + return; + } + + stdin.setEncoding('utf8'); + + stdin.on('readable', function () { + var chunk; + + while (chunk = stdin.read()) { + ret += chunk; + } + }); + + stdin.on('end', function () { + cb(ret); + }); +}; + +module.exports.buffer = function (cb) { + var stdin = process.stdin; + var ret = []; + var len = 0; + + if (stdin.isTTY) { + setImmediate(cb, new Buffer('')); + return; + } + + stdin.on('readable', function () { + var chunk; + + while (chunk = stdin.read()) { + ret.push(chunk); + len += chunk.length; + } + }); + + stdin.on('end', function () { + cb(Buffer.concat(ret, len)); + }); +}; diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/package.json b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/package.json new file mode 100644 index 00000000000000..65e75915f5f364 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/package.json @@ -0,0 +1,64 @@ +{ + "name": "get-stdin", + "version": "4.0.1", + "description": "Easier stdin", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/get-stdin.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "node test.js && node test-buffer.js && echo unicorns | node test-real.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "std", + "stdin", + "stdio", + "concat", + "buffer", + "stream", + "process", + "stream" + ], + "devDependencies": { + "ava": "0.0.4", + "buffer-equal": "0.0.1" + }, + "gitHead": "65c744975229b25d6cc5c7546f49b6ad9099553f", + "bugs": { + "url": "https://github.com/sindresorhus/get-stdin/issues" + }, + "homepage": "https://github.com/sindresorhus/get-stdin", + "_id": "get-stdin@4.0.1", + "_shasum": "b968c6b0a04384324902e8bf1a5df32579a450fe", + "_from": "get-stdin@>=4.0.1 <5.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "dist": { + "shasum": "b968c6b0a04384324902e8bf1a5df32579a450fe", + "tarball": "http://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/readme.md b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/readme.md new file mode 100644 index 00000000000000..bc1d32a8ad595e --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/readme.md @@ -0,0 +1,44 @@ +# get-stdin [![Build Status](https://travis-ci.org/sindresorhus/get-stdin.svg?branch=master)](https://travis-ci.org/sindresorhus/get-stdin) + +> Easier stdin + + +## Install + +```sh +$ npm install --save get-stdin +``` + + +## Usage + +```js +// example.js +var stdin = require('get-stdin'); + +stdin(function (data) { + console.log(data); + //=> unicorns +}); +``` + +```sh +$ echo unicorns | node example.js +unicorns +``` + + +## API + +### stdin(callback) + +Get `stdin` as a string. + +### stdin.buffer(callback) + +Get `stdin` as a buffer. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/package.json b/tools/eslint/node_modules/chalk/node_modules/has-ansi/package.json new file mode 100644 index 00000000000000..0e330841c459af --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/package.json @@ -0,0 +1,92 @@ +{ + "name": "has-ansi", + "version": "1.0.3", + "description": "Check if a string has ANSI escape codes", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/has-ansi.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "bin": { + "has-ansi": "cli.js" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js", + "cli.js" + ], + "keywords": [ + "cli", + "bin", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern", + "has" + ], + "dependencies": { + "ansi-regex": "^1.1.0", + "get-stdin": "^4.0.1" + }, + "devDependencies": { + "mocha": "*" + }, + "gitHead": "416428ed16f8e9718aec54cea083173af6019917", + "bugs": { + "url": "https://github.com/sindresorhus/has-ansi/issues" + }, + "homepage": "https://github.com/sindresorhus/has-ansi", + "_id": "has-ansi@1.0.3", + "_shasum": "c0b5b1615d9e382b0ff67169d967b425e48ca538", + "_from": "has-ansi@>=1.0.3 <2.0.0", + "_npmVersion": "2.1.16", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + }, + "dist": { + "shasum": "c0b5b1615d9e382b0ff67169d967b425e48ca538", + "tarball": "http://registry.npmjs.org/has-ansi/-/has-ansi-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/has-ansi/readme.md b/tools/eslint/node_modules/chalk/node_modules/has-ansi/readme.md new file mode 100644 index 00000000000000..0fa149a82a1fd0 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/has-ansi/readme.md @@ -0,0 +1,45 @@ +# has-ansi [![Build Status](https://travis-ci.org/sindresorhus/has-ansi.svg?branch=master)](https://travis-ci.org/sindresorhus/has-ansi) + +> Check if a string has [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +```sh +$ npm install --save has-ansi +``` + + +## Usage + +```js +var hasAnsi = require('has-ansi'); + +hasAnsi('\u001b[4mcake\u001b[0m'); +//=> true + +hasAnsi('cake'); +//=> false +``` + + +## CLI + +```sh +$ npm install --global has-ansi +``` + +``` +$ has-ansi --help + + Usage + has-ansi + echo | has-ansi + + Exits with code 0 if input has ANSI escape codes and 1 if not +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/cli.js b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/cli.js new file mode 100755 index 00000000000000..b83f63b907e2e0 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/cli.js @@ -0,0 +1,47 @@ +#!/usr/bin/env node +'use strict'; +var fs = require('fs'); +var pkg = require('./package.json'); +var stripAnsi = require('./'); +var argv = process.argv.slice(2); +var input = argv[0]; + +function help() { + console.log([ + '', + ' ' + pkg.description, + '', + ' Usage', + ' strip-ansi > ', + ' cat | strip-ansi > ', + '', + ' Example', + ' strip-ansi unicorn.txt > unicorn-stripped.txt' + ].join('\n')); +} + +function init(data) { + process.stdout.write(stripAnsi(data)); +} + +if (argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +if (!input && process.stdin.isTTY) { + help(); + return; +} + +if (input) { + init(fs.readFileSync(input, 'utf8')); +} else { + process.stdin.setEncoding('utf8'); + process.stdin.on('data', init); +} diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/index.js b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/index.js new file mode 100644 index 00000000000000..099480fbfc54cb --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/index.js @@ -0,0 +1,6 @@ +'use strict'; +var ansiRegex = require('ansi-regex')(); + +module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; +}; diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/index.js b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/index.js new file mode 100644 index 00000000000000..2fcdd1e472f961 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/index.js @@ -0,0 +1,4 @@ +'use strict'; +module.exports = function () { + return /(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/g; +}; diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/license b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/package.json b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/package.json new file mode 100644 index 00000000000000..4b7be0c62ca2b4 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/package.json @@ -0,0 +1,86 @@ +{ + "name": "ansi-regex", + "version": "1.1.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/ansi-regex.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha test/test.js", + "view-supported": "node test/viewCodes.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "mocha": "*" + }, + "gitHead": "47fb974630af70998157b30fad6eb5e5bd7c7cd6", + "bugs": { + "url": "https://github.com/sindresorhus/ansi-regex/issues" + }, + "homepage": "https://github.com/sindresorhus/ansi-regex", + "_id": "ansi-regex@1.1.1", + "_shasum": "41c847194646375e6a1a5d10c3ca054ef9fc980d", + "_from": "ansi-regex@>=1.0.0 <2.0.0", + "_npmVersion": "2.1.16", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + }, + "dist": { + "shasum": "41c847194646375e6a1a5d10c3ca054ef9fc980d", + "tarball": "http://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/readme.md b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/readme.md new file mode 100644 index 00000000000000..ae876e7292feb7 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/readme.md @@ -0,0 +1,33 @@ +# ansi-regex [![Build Status](https://travis-ci.org/sindresorhus/ansi-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/ansi-regex) + +> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +```sh +$ npm install --save ansi-regex +``` + + +## Usage + +```js +var ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001b[4mcake\u001b[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001b[4mcake\u001b[0m'.match(ansiRegex()); +//=> ['\u001b[4m', '\u001b[0m'] +``` + +*It's a function so you can create multiple instances. Regexes with the global flag will have the `.lastIndex` property changed for each call to methods on the instance. Therefore reusing the instance with multiple calls will not work as expected for `.test()`.* + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/package.json b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/package.json new file mode 100644 index 00000000000000..1645e0d62d8d4a --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/package.json @@ -0,0 +1,89 @@ +{ + "name": "strip-ansi", + "version": "2.0.1", + "description": "Strip ANSI escape codes", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/strip-ansi.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "bin": { + "strip-ansi": "cli.js" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js", + "cli.js" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^1.0.0" + }, + "devDependencies": { + "mocha": "*" + }, + "gitHead": "1eff0936c01f89efa312d9d51deed137259871a1", + "bugs": { + "url": "https://github.com/sindresorhus/strip-ansi/issues" + }, + "homepage": "https://github.com/sindresorhus/strip-ansi", + "_id": "strip-ansi@2.0.1", + "_shasum": "df62c1aa94ed2f114e1d0f21fd1d50482b79a60e", + "_from": "strip-ansi@>=2.0.1 <3.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "dist": { + "shasum": "df62c1aa94ed2f114e1d0f21fd1d50482b79a60e", + "tarball": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/strip-ansi/readme.md b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/readme.md new file mode 100644 index 00000000000000..53ec26436ca545 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/strip-ansi/readme.md @@ -0,0 +1,43 @@ +# strip-ansi [![Build Status](https://travis-ci.org/sindresorhus/strip-ansi.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-ansi) + +> Strip [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +```sh +$ npm install --save strip-ansi +``` + + +## Usage + +```js +var stripAnsi = require('strip-ansi'); + +stripAnsi('\u001b[4mcake\u001b[0m'); +//=> 'cake' +``` + + +## CLI + +```sh +$ npm install --global strip-ansi +``` + +```sh +$ strip-ansi --help + + Usage + strip-ansi > + cat | strip-ansi > + + Example + strip-ansi unicorn.txt > unicorn-stripped.txt +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/node_modules/supports-color/cli.js b/tools/eslint/node_modules/chalk/node_modules/supports-color/cli.js new file mode 100755 index 00000000000000..e746987666d422 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/supports-color/cli.js @@ -0,0 +1,29 @@ +#!/usr/bin/env node +'use strict'; +var pkg = require('./package.json'); +var supportsColor = require('./'); +var argv = process.argv.slice(2); + +function help() { + console.log([ + '', + ' ' + pkg.description, + '', + ' Usage', + ' supports-color', + '', + ' Exits with code 0 if color is supported and 1 if not' + ].join('\n')); +} + +if (argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +process.exit(supportsColor ? 0 : 1); diff --git a/tools/eslint/node_modules/chalk/node_modules/supports-color/index.js b/tools/eslint/node_modules/chalk/node_modules/supports-color/index.js new file mode 100644 index 00000000000000..a17196485d7aed --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/supports-color/index.js @@ -0,0 +1,43 @@ +'use strict'; +var argv = process.argv; + +module.exports = (function () { + if ('FORCE_COLOR' in process.env) { + return true; + } + + if (argv.indexOf('--no-color') !== -1 || + argv.indexOf('--no-colors') !== -1 || + argv.indexOf('--color=false') !== -1) { + return false; + } + + if (argv.indexOf('--color') !== -1 || + argv.indexOf('--colors') !== -1 || + argv.indexOf('--color=true') !== -1 || + argv.indexOf('--color=always') !== -1) { + return true; + } + + if (process.stdout && !process.stdout.isTTY) { + return false; + } + + if (process.platform === 'win32') { + return true; + } + + if ('COLORTERM' in process.env) { + return true; + } + + if (process.env.TERM === 'dumb') { + return false; + } + + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } + + return false; +})(); diff --git a/tools/eslint/node_modules/chalk/node_modules/supports-color/license b/tools/eslint/node_modules/chalk/node_modules/supports-color/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/supports-color/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/chalk/node_modules/supports-color/package.json b/tools/eslint/node_modules/chalk/node_modules/supports-color/package.json new file mode 100644 index 00000000000000..313c3b23eae245 --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/supports-color/package.json @@ -0,0 +1,85 @@ +{ + "name": "supports-color", + "version": "1.3.1", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/supports-color.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "bin": { + "supports-color": "cli.js" + }, + "engines": { + "node": ">=0.8.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js", + "cli.js" + ], + "keywords": [ + "cli", + "bin", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect" + ], + "devDependencies": { + "mocha": "*", + "require-uncached": "^1.0.2" + }, + "gitHead": "09f1b4c336cee7269b4c8b3a8880054a23fcb35e", + "bugs": { + "url": "https://github.com/sindresorhus/supports-color/issues" + }, + "homepage": "https://github.com/sindresorhus/supports-color", + "_id": "supports-color@1.3.1", + "_shasum": "15758df09d8ff3b4acc307539fabe27095e1042d", + "_from": "supports-color@>=1.3.0 <2.0.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "dist": { + "shasum": "15758df09d8ff3b4acc307539fabe27095e1042d", + "tarball": "http://registry.npmjs.org/supports-color/-/supports-color-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/node_modules/supports-color/readme.md b/tools/eslint/node_modules/chalk/node_modules/supports-color/readme.md new file mode 100644 index 00000000000000..fe6016f9d09efb --- /dev/null +++ b/tools/eslint/node_modules/chalk/node_modules/supports-color/readme.md @@ -0,0 +1,46 @@ +# supports-color [![Build Status](https://travis-ci.org/sindresorhus/supports-color.svg?branch=master)](https://travis-ci.org/sindresorhus/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install --save supports-color +``` + + +## Usage + +```js +var supportsColor = require('supports-color'); + +if (supportsColor) { + console.log('Terminal supports color'); +} +``` + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`. + + +## CLI + +``` +$ npm install --global supports-color +``` + +``` +$ supports-color --help + + Usage + supports-color + + Exits with code 0 if color is supported and 1 if not +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/chalk/package.json b/tools/eslint/node_modules/chalk/package.json new file mode 100644 index 00000000000000..6de2bd4f5d91bb --- /dev/null +++ b/tools/eslint/node_modules/chalk/package.json @@ -0,0 +1,83 @@ +{ + "name": "chalk", + "version": "1.0.0", + "description": "Terminal string styling done right. Much color.", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/chalk.git" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "jbnicolai", + "email": "jappelman@xebia.com" + } + ], + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha", + "bench": "matcha benchmark.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "ansi", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^2.0.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^1.0.3", + "strip-ansi": "^2.0.1", + "supports-color": "^1.3.0" + }, + "devDependencies": { + "matcha": "^0.6.0", + "mocha": "*" + }, + "gitHead": "8864d3563313ed15574a38dd5c9d5966080c46ce", + "bugs": { + "url": "https://github.com/sindresorhus/chalk/issues" + }, + "homepage": "https://github.com/sindresorhus/chalk", + "_id": "chalk@1.0.0", + "_shasum": "b3cf4ed0ff5397c99c75b8f679db2f52831f96dc", + "_from": "chalk@>=1.0.0 <2.0.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "dist": { + "shasum": "b3cf4ed0ff5397c99c75b8f679db2f52831f96dc", + "tarball": "http://registry.npmjs.org/chalk/-/chalk-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/chalk/-/chalk-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/chalk/readme.md b/tools/eslint/node_modules/chalk/readme.md new file mode 100644 index 00000000000000..43c7064335d55a --- /dev/null +++ b/tools/eslint/node_modules/chalk/readme.md @@ -0,0 +1,197 @@ +

+
+ chalk +
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/sindresorhus/chalk.svg?branch=master)](https://travis-ci.org/sindresorhus/chalk) [![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg?style=flat)](https://www.youtube.com/watch?v=Sm368W0OsHo) + +[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough. + +**Chalk is a clean and focused alternative.** + +![screenshot](https://github.com/sindresorhus/ansi-styles/raw/master/screenshot.png) + + +## Why + +- Highly performant +- Doesn't extend `String.prototype` +- Expressive API +- Ability to nest styles +- Clean and focused +- Auto-detects color support +- Actively maintained +- [Used by ~3000 modules](https://www.npmjs.com/browse/depended/chalk) + + +## Install + +``` +$ npm install --save chalk +``` + + +## Usage + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +var chalk = require('chalk'); + +// style a string +chalk.blue('Hello world!'); + +// combine styled and normal strings +chalk.blue('Hello') + 'World' + chalk.red('!'); + +// compose multiple styles using the chainable API +chalk.blue.bgRed.bold('Hello world!'); + +// pass in multiple arguments +chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'); + +// nest styles +chalk.red('Hello', chalk.underline.bgBlue('world') + '!'); + +// nest styles of the same type even (color, underline, background) +chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +); +``` + +Easily define your own themes. + +```js +var chalk = require('chalk'); +var error = chalk.bold.red; +console.log(error('Error!')); +``` + +Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data). + +```js +var name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> Hello Sindre +``` + + +## API + +### chalk.` + + +
+

Code coverage report for All files

+

+ + Statements: 100% (0 / 0)      + + + Branches: 100% (0 / 0)      + + + Functions: 100% (0 / 0)      + + + Lines: 100% (0 / 0)      + + Ignored: none      +

+
+
+
+
+ + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
+
+
+ + + + + + + + diff --git a/tools/eslint/node_modules/doctrine/coverage/lcov-report/prettify.css b/tools/eslint/node_modules/doctrine/coverage/lcov-report/prettify.css new file mode 100644 index 00000000000000..b317a7cda31a44 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/tools/eslint/node_modules/doctrine/coverage/lcov-report/prettify.js b/tools/eslint/node_modules/doctrine/coverage/lcov-report/prettify.js new file mode 100644 index 00000000000000..ef51e03866898f --- /dev/null +++ b/tools/eslint/node_modules/doctrine/coverage/lcov-report/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/tools/eslint/node_modules/doctrine/coverage/lcov-report/sort-arrow-sprite.png b/tools/eslint/node_modules/doctrine/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 00000000000000..03f704a609c6fd Binary files /dev/null and b/tools/eslint/node_modules/doctrine/coverage/lcov-report/sort-arrow-sprite.png differ diff --git a/tools/eslint/node_modules/doctrine/coverage/lcov-report/sorter.js b/tools/eslint/node_modules/doctrine/coverage/lcov-report/sorter.js new file mode 100644 index 00000000000000..6afb736c39fb15 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/coverage/lcov-report/sorter.js @@ -0,0 +1,156 @@ +var addSorting = (function () { + "use strict"; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { return document.querySelector('.coverage-summary table'); } + // returns the thead element of the summary table + function getTableHeader() { return getTable().querySelector('thead tr'); } + // returns the tbody element of the summary table + function getTableBody() { return getTable().querySelector('tbody'); } + // returns the th element for nth column + function getNthColumn(n) { return getTableHeader().querySelectorAll('th')[n]; } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + el = getNthColumn(i).querySelector('.sorter'); + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/tools/closure_linter/closure_linter/testdata/empty_file.js b/tools/eslint/node_modules/doctrine/coverage/lcov.info similarity index 100% rename from tools/closure_linter/closure_linter/testdata/empty_file.js rename to tools/eslint/node_modules/doctrine/coverage/lcov.info diff --git a/tools/eslint/node_modules/doctrine/eslint.json b/tools/eslint/node_modules/doctrine/eslint.json new file mode 100644 index 00000000000000..330835b9bf7eb2 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/eslint.json @@ -0,0 +1,22 @@ +{ + "env": { + "node": true + }, + "rules": { + "quotes": [2, "single"], + "valid-jsdoc": [2, true], + "brace-style": [2, true], + "semi": [2, true], + "no-bitwise": [2, true], + "camelcase": [2, true], + "curly": [2, true], + "eqeqeq": [2, "allow-null"], + "wrap-iife": [2, true], + "eqeqeq": [2, true], + "strict": [2, true], + "no-unused-vars": [2, true], + "no-underscore-dangle": [0, false], + "no-use-before-define": [0, false], + "no-constant-condition": [0, false] + } +} diff --git a/tools/eslint/node_modules/doctrine/gulpfile.js b/tools/eslint/node_modules/doctrine/gulpfile.js new file mode 100644 index 00000000000000..a68d0ff930d1b7 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/gulpfile.js @@ -0,0 +1,120 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +'use strict'; + +var gulp = require('gulp'); +var mocha = require('gulp-mocha'); +var jshint = require('gulp-jshint'); +var eslint = require('gulp-eslint'); +var istanbul = require('gulp-istanbul'); +var bump = require('gulp-bump'); +var filter = require('gulp-filter'); +var git = require('gulp-git'); +var tagVersion = require('gulp-tag-version'); + +var SRC = [ 'lib/*.js' ]; + +var TEST = [ 'test/*.js' ]; + +var LINT = [ + 'gulpfile.js' +].concat(SRC); + +var ESLINT_OPTION = { + 'rules': { + 'quotes': 0, + 'eqeqeq': 0, + 'no-use-before-define': 0, + 'no-underscore-dangle': 0, + 'no-shadow': 0, + 'no-constant-condition': 0, + 'no-multi-spaces': 0, + 'dot-notation': [2, {'allowKeywords': false}] + }, + 'env': { + 'node': true + } +}; + +gulp.task('test', function (cb) { + gulp.src(SRC) + .pipe(istanbul()) // Covering files + .on('finish', function () { + gulp.src(TEST) + .pipe(mocha({ + reporter: 'spec', + timeout: 100000 // 100s + })) + .pipe(istanbul.writeReports()) // Creating the reports after tests runned + .on('end', cb); + }); +}); + +gulp.task('lint', function () { + return gulp.src(LINT) + .pipe(jshint('.jshintrc')) + .pipe(jshint.reporter(require('jshint-stylish'))) + .pipe(jshint.reporter('fail')) + .pipe(eslint(ESLINT_OPTION)) + .pipe(eslint.formatEach('compact', process.stderr)) + .pipe(eslint.failOnError()); +}); + + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ prefix: '' })); +} + +gulp.task('patch', [ 'travis' ], function () { return inc('patch'); }); +gulp.task('minor', [ 'travis' ], function () { return inc('minor'); }); +gulp.task('major', [ 'travis' ], function () { return inc('major'); }); + +gulp.task('travis', [ 'lint', 'test' ]); +gulp.task('default', [ 'travis' ]); diff --git a/tools/eslint/node_modules/doctrine/lib/doctrine.js b/tools/eslint/node_modules/doctrine/lib/doctrine.js new file mode 100644 index 00000000000000..dd3cccb263ce71 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/lib/doctrine.js @@ -0,0 +1,809 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2014 Dan Tao + Copyright (C) 2013 Andrew Eisenberg + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var typed, + utility, + isArray, + jsdoc, + esutils, + hasOwnProperty; + + esutils = require('esutils'); + isArray = require('isarray'); + typed = require('./typed'); + utility = require('./utility'); + + function sliceSource(source, index, last) { + return source.slice(index, last); + } + + hasOwnProperty = (function () { + var func = Object.prototype.hasOwnProperty; + return function hasOwnProperty(obj, name) { + return func.call(obj, name); + }; + }()); + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + + function isASCIIAlphanumeric(ch) { + return (ch >= 0x61 /* 'a' */ && ch <= 0x7A /* 'z' */) || + (ch >= 0x41 /* 'A' */ && ch <= 0x5A /* 'Z' */) || + (ch >= 0x30 /* '0' */ && ch <= 0x39 /* '9' */); + } + + function isParamTitle(title) { + return title === 'param' || title === 'argument' || title === 'arg'; + } + + function isProperty(title) { + return title === 'property' || title === 'prop'; + } + + function isNameParameterRequired(title) { + return isParamTitle(title) || isProperty(title) || + title === 'alias' || title === 'this' || title === 'mixes' || title === 'requires'; + } + + function isAllowedName(title) { + return isNameParameterRequired(title) || title === 'const' || title === 'constant'; + } + + function isAllowedNested(title) { + return isProperty(title) || isParamTitle(title); + } + + function isTypeParameterRequired(title) { + return isParamTitle(title) || title === 'define' || title === 'enum' || + title === 'implements' || title === 'return' || + title === 'this' || title === 'type' || title === 'typedef' || + title === 'returns' || isProperty(title); + } + + // Consider deprecation instead using 'isTypeParameterRequired' and 'Rules' declaration to pick when a type is optional/required + // This would require changes to 'parseType' + function isAllowedType(title) { + return isTypeParameterRequired(title) || title === 'throws' || title === 'const' || title === 'constant' || + title === 'namespace' || title === 'member' || title === 'var' || title === 'module' || + title === 'constructor' || title === 'class' || title === 'extends' || title === 'augments' || + title === 'public' || title === 'private' || title === 'protected'; + } + + function trim(str) { + return str.replace(/^\s+/, '').replace(/\s+$/, ''); + } + + function unwrapComment(doc) { + // JSDoc comment is following form + // /** + // * ....... + // */ + // remove /**, */ and * + var BEFORE_STAR = 0, + STAR = 1, + AFTER_STAR = 2, + index, + len, + mode, + result, + ch; + + doc = doc.replace(/^\/\*\*?/, '').replace(/\*\/$/, ''); + index = 0; + len = doc.length; + mode = BEFORE_STAR; + result = ''; + + while (index < len) { + ch = doc.charCodeAt(index); + switch (mode) { + case BEFORE_STAR: + if (esutils.code.isLineTerminator(ch)) { + result += String.fromCharCode(ch); + } else if (ch === 0x2A /* '*' */) { + mode = STAR; + } else if (!esutils.code.isWhiteSpace(ch)) { + result += String.fromCharCode(ch); + mode = AFTER_STAR; + } + break; + + case STAR: + if (!esutils.code.isWhiteSpace(ch)) { + result += String.fromCharCode(ch); + } + mode = esutils.code.isLineTerminator(ch) ? BEFORE_STAR : AFTER_STAR; + break; + + case AFTER_STAR: + result += String.fromCharCode(ch); + if (esutils.code.isLineTerminator(ch)) { + mode = BEFORE_STAR; + } + break; + } + index += 1; + } + + return result; + } + + // JSDoc Tag Parser + + (function (exports) { + var Rules, + index, + lineNumber, + length, + source, + recoverable, + sloppy, + strict; + + function advance() { + var ch = source.charCodeAt(index); + index += 1; + if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(index) === 0x0A /* '\n' */)) { + lineNumber += 1; + } + return String.fromCharCode(ch); + } + + function scanTitle() { + var title = ''; + // waste '@' + advance(); + + while (index < length && isASCIIAlphanumeric(source.charCodeAt(index))) { + title += advance(); + } + + return title; + } + + function seekContent() { + var ch, waiting, last = index; + + waiting = false; + while (last < length) { + ch = source.charCodeAt(last); + if (esutils.code.isLineTerminator(ch) && !(ch === 0x0D /* '\r' */ && source.charCodeAt(last + 1) === 0x0A /* '\n' */)) { + lineNumber += 1; + waiting = true; + } else if (waiting) { + if (ch === 0x40 /* '@' */) { + break; + } + if (!esutils.code.isWhiteSpace(ch)) { + waiting = false; + } + } + last += 1; + } + return last; + } + + // type expression may have nest brace, such as, + // { { ok: string } } + // + // therefore, scanning type expression with balancing braces. + function parseType(title, last) { + var ch, brace, type, direct = false; + + + // search '{' + while (index < last) { + ch = source.charCodeAt(index); + if (esutils.code.isWhiteSpace(ch)) { + advance(); + } else if (ch === 0x7B /* '{' */) { + advance(); + break; + } else { + // this is direct pattern + direct = true; + break; + } + } + + + if (direct) { + return null; + } + + // type expression { is found + brace = 1; + type = ''; + while (index < last) { + ch = source.charCodeAt(index); + if (esutils.code.isLineTerminator(ch)) { + advance(); + } else { + if (ch === 0x7D /* '}' */) { + brace -= 1; + if (brace === 0) { + advance(); + break; + } + } else if (ch === 0x7B /* '{' */) { + brace += 1; + } + type += advance(); + } + } + + if (brace !== 0) { + // braces is not balanced + return utility.throwError('Braces are not balanced'); + } + + if (isParamTitle(title)) { + return typed.parseParamType(type); + } + return typed.parseType(type); + } + + function scanIdentifier(last) { + var identifier; + if (!esutils.code.isIdentifierStart(source.charCodeAt(index))) { + return null; + } + identifier = advance(); + while (index < last && esutils.code.isIdentifierPart(source.charCodeAt(index))) { + identifier += advance(); + } + return identifier; + } + + function skipWhiteSpace(last) { + while (index < last && (esutils.code.isWhiteSpace(source.charCodeAt(index)) || esutils.code.isLineTerminator(source.charCodeAt(index)))) { + advance(); + } + } + + function parseName(last, allowBrackets, allowNestedParams) { + var name = '', useBrackets; + + skipWhiteSpace(last); + + if (index >= last) { + return null; + } + + if (allowBrackets && source.charCodeAt(index) === 0x5B /* '[' */) { + useBrackets = true; + name = advance(); + } + + if (!esutils.code.isIdentifierStart(source.charCodeAt(index))) { + return null; + } + + name += scanIdentifier(last); + + if (allowNestedParams) { + if (source.charCodeAt(index) === 0x3A /* ':' */ && ( + name === 'module' || + name === 'external' || + name === 'event')) { + name += advance(); + name += scanIdentifier(last); + + } + while (source.charCodeAt(index) === 0x2E /* '.' */ || + source.charCodeAt(index) === 0x23 /* '#' */ || + source.charCodeAt(index) === 0x7E /* '~' */) { + name += advance(); + name += scanIdentifier(last); + } + } + + if (useBrackets) { + // do we have a default value for this? + if (source.charCodeAt(index) === 0x3D /* '=' */) { + + // consume the '='' symbol + name += advance(); + // scan in the default value + while (index < last && source.charCodeAt(index) !== 0x5D /* ']' */) { + name += advance(); + } + } + + if (index >= last || source.charCodeAt(index) !== 0x5D /* ']' */) { + // we never found a closing ']' + return null; + } + + // collect the last ']' + name += advance(); + } + + return name; + } + + function skipToTag() { + while (index < length && source.charCodeAt(index) !== 0x40 /* '@' */) { + advance(); + } + if (index >= length) { + return false; + } + utility.assert(source.charCodeAt(index) === 0x40 /* '@' */); + return true; + } + + function TagParser(options, title) { + this._options = options; + this._title = title; + this._tag = { + title: title, + description: null + }; + if (this._options.lineNumbers) { + this._tag.lineNumber = lineNumber; + } + this._last = 0; + // space to save special information for title parsers. + this._extra = { }; + } + + // addError(err, ...) + TagParser.prototype.addError = function addError(errorText) { + var args = Array.prototype.slice.call(arguments, 1), + msg = errorText.replace( + /%(\d)/g, + function (whole, index) { + utility.assert(index < args.length, 'Message reference must be in range'); + return args[index]; + } + ); + + if (!this._tag.errors) { + this._tag.errors = []; + } + if (strict) { + utility.throwError(msg); + } + this._tag.errors.push(msg); + return recoverable; + }; + + TagParser.prototype.parseType = function () { + // type required titles + if (isTypeParameterRequired(this._title)) { + try { + this._tag.type = parseType(this._title, this._last); + if (!this._tag.type) { + if (!isParamTitle(this._title)) { + if (!this.addError('Missing or invalid tag type')) { + return false; + } + } + } + } catch (error) { + this._tag.type = null; + if (!this.addError(error.message)) { + return false; + } + } + } else if (isAllowedType(this._title)) { + // optional types + try { + this._tag.type = parseType(this._title, this._last); + } catch (e) { + //For optional types, lets drop the thrown error when we hit the end of the file + } + } + return true; + }; + + TagParser.prototype._parseNamePath = function (optional) { + var name; + name = parseName(this._last, sloppy && isParamTitle(this._title), true); + if (!name) { + if (!optional) { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } + this._tag.name = name; + return true; + }; + + TagParser.prototype.parseNamePath = function () { + return this._parseNamePath(false); + }; + + TagParser.prototype.parseNamePathOptional = function () { + return this._parseNamePath(true); + }; + + + TagParser.prototype.parseName = function () { + var assign, name; + + // param, property requires name + if (isAllowedName(this._title)) { + this._tag.name = parseName(this._last, sloppy && isParamTitle(this._title), isAllowedNested(this._title)); + if (!this._tag.name) { + if (!isNameParameterRequired(this._title)) { + return true; + } + + // it's possible the name has already been parsed but interpreted as a type + // it's also possible this is a sloppy declaration, in which case it will be + // fixed at the end + if (isParamTitle(this._title) && this._tag.type && this._tag.type.name) { + this._extra.name = this._tag.type; + this._tag.name = this._tag.type.name; + this._tag.type = null; + } else { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } else { + name = this._tag.name; + if (name.charAt(0) === '[' && name.charAt(name.length - 1) === ']') { + // extract the default value if there is one + // example: @param {string} [somebody=John Doe] description + assign = name.substring(1, name.length - 1).split('='); + if (assign[1]) { + this._tag['default'] = assign[1]; + } + this._tag.name = assign[0]; + + // convert to an optional type + if (this._tag.type && this._tag.type.type !== 'OptionalType') { + this._tag.type = { + type: 'OptionalType', + expression: this._tag.type + }; + } + } + } + } + + return true; + }; + + TagParser.prototype.parseDescription = function parseDescription() { + var description = trim(sliceSource(source, index, this._last)); + if (description) { + if ((/^-\s+/).test(description)) { + description = description.substring(2); + } + this._tag.description = description; + } + return true; + }; + + TagParser.prototype.parseKind = function parseKind() { + var kind, kinds; + kinds = { + 'class': true, + 'constant': true, + 'event': true, + 'external': true, + 'file': true, + 'function': true, + 'member': true, + 'mixin': true, + 'module': true, + 'namespace': true, + 'typedef': true + }; + kind = trim(sliceSource(source, index, this._last)); + this._tag.kind = kind; + if (!hasOwnProperty(kinds, kind)) { + if (!this.addError('Invalid kind name \'%0\'', kind)) { + return false; + } + } + return true; + }; + + TagParser.prototype.parseAccess = function parseAccess() { + var access; + access = trim(sliceSource(source, index, this._last)); + this._tag.access = access; + if (access !== 'private' && access !== 'protected' && access !== 'public') { + if (!this.addError('Invalid access name \'%0\'', access)) { + return false; + } + } + return true; + }; + + TagParser.prototype.parseVariation = function parseVariation() { + var variation, text; + text = trim(sliceSource(source, index, this._last)); + variation = parseFloat(text, 10); + this._tag.variation = variation; + if (isNaN(variation)) { + if (!this.addError('Invalid variation \'%0\'', text)) { + return false; + } + } + return true; + }; + + TagParser.prototype.ensureEnd = function () { + var shouldBeEmpty = trim(sliceSource(source, index, this._last)); + if (shouldBeEmpty) { + if (!this.addError('Unknown content \'%0\'', shouldBeEmpty)) { + return false; + } + } + return true; + }; + + TagParser.prototype.epilogue = function epilogue() { + var description; + + description = this._tag.description; + // un-fix potentially sloppy declaration + if (isParamTitle(this._title) && !this._tag.type && description && description.charAt(0) === '[') { + this._tag.type = this._extra.name; + this._tag.name = undefined; + + if (!sloppy) { + if (!this.addError('Missing or invalid tag name')) { + return false; + } + } + } + + return true; + }; + + Rules = { + // http://usejsdoc.org/tags-access.html + 'access': ['parseAccess'], + // http://usejsdoc.org/tags-alias.html + 'alias': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-augments.html + 'augments': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-constructor.html + 'constructor': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-constructor.html + 'class': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-extends.html + 'extends': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-deprecated.html + 'deprecated': ['parseDescription'], + // http://usejsdoc.org/tags-global.html + 'global': ['ensureEnd'], + // http://usejsdoc.org/tags-inner.html + 'inner': ['ensureEnd'], + // http://usejsdoc.org/tags-instance.html + 'instance': ['ensureEnd'], + // http://usejsdoc.org/tags-kind.html + 'kind': ['parseKind'], + // http://usejsdoc.org/tags-mixes.html + 'mixes': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-mixin.html + 'mixin': ['parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-member.html + 'member': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-method.html + 'method': ['parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-module.html + 'module': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-method.html + 'func': ['parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-method.html + 'function': ['parseNamePathOptional', 'ensureEnd'], + // Synonym: http://usejsdoc.org/tags-member.html + 'var': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-name.html + 'name': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-namespace.html + 'namespace': ['parseType', 'parseNamePathOptional', 'ensureEnd'], + // http://usejsdoc.org/tags-private.html + 'private': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-protected.html + 'protected': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-public.html + 'public': ['parseType', 'parseDescription'], + // http://usejsdoc.org/tags-readonly.html + 'readonly': ['ensureEnd'], + // http://usejsdoc.org/tags-requires.html + 'requires': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-since.html + 'since': ['parseDescription'], + // http://usejsdoc.org/tags-static.html + 'static': ['ensureEnd'], + // http://usejsdoc.org/tags-summary.html + 'summary': ['parseDescription'], + // http://usejsdoc.org/tags-this.html + 'this': ['parseNamePath', 'ensureEnd'], + // http://usejsdoc.org/tags-todo.html + 'todo': ['parseDescription'], + // http://usejsdoc.org/tags-variation.html + 'variation': ['parseVariation'], + // http://usejsdoc.org/tags-version.html + 'version': ['parseDescription'] + }; + + TagParser.prototype.parse = function parse() { + var i, iz, sequences, method; + + // empty title + if (!this._title) { + if (!this.addError('Missing or invalid title')) { + return null; + } + } + + // Seek to content last index. + this._last = seekContent(this._title); + + if (hasOwnProperty(Rules, this._title)) { + sequences = Rules[this._title]; + } else { + // default sequences + sequences = ['parseType', 'parseName', 'parseDescription', 'epilogue']; + } + + for (i = 0, iz = sequences.length; i < iz; ++i) { + method = sequences[i]; + if (!this[method]()) { + return null; + } + } + + // Seek global index to end of this tag. + index = this._last; + return this._tag; + }; + + function parseTag(options) { + var title, parser; + + // skip to tag + if (!skipToTag()) { + return null; + } + + // scan title + title = scanTitle(); + + // construct tag parser + parser = new TagParser(options, title); + return parser.parse(); + } + + // + // Parse JSDoc + // + + function scanJSDocDescription() { + var description = '', ch, atAllowed; + + atAllowed = true; + while (index < length) { + ch = source.charCodeAt(index); + + if (atAllowed && ch === 0x40 /* '@' */) { + break; + } + + if (esutils.code.isLineTerminator(ch)) { + atAllowed = true; + } else if (atAllowed && !esutils.code.isWhiteSpace(ch)) { + atAllowed = false; + } + + description += advance(); + } + return trim(description); + } + + function parse(comment, options) { + var tags = [], tag, description, interestingTags, i, iz; + + if (options === undefined) { + options = {}; + } + + if (typeof options.unwrap === 'boolean' && options.unwrap) { + source = unwrapComment(comment); + } else { + source = comment; + } + + // array of relevant tags + if (options.tags) { + if (isArray(options.tags)) { + interestingTags = { }; + for (i = 0, iz = options.tags.length; i < iz; i++) { + if (typeof options.tags[i] === 'string') { + interestingTags[options.tags[i]] = true; + } else { + utility.throwError('Invalid "tags" parameter: ' + options.tags); + } + } + } else { + utility.throwError('Invalid "tags" parameter: ' + options.tags); + } + } + + length = source.length; + index = 0; + lineNumber = 0; + recoverable = options.recoverable; + sloppy = options.sloppy; + strict = options.strict; + + description = scanJSDocDescription(); + + while (true) { + tag = parseTag(options); + if (!tag) { + break; + } + if (!interestingTags || interestingTags.hasOwnProperty(tag.title)) { + tags.push(tag); + } + } + + return { + description: description, + tags: tags + }; + } + exports.parse = parse; + }(jsdoc = {})); + + exports.version = utility.VERSION; + exports.parse = jsdoc.parse; + exports.parseType = typed.parseType; + exports.parseParamType = typed.parseParamType; + exports.unwrapComment = unwrapComment; + exports.Syntax = shallowCopy(typed.Syntax); + exports.Error = utility.DoctrineError; + exports.type = { + Syntax: exports.Syntax, + parseType: typed.parseType, + parseParamType: typed.parseParamType, + stringify: typed.stringify + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/lib/typed.js b/tools/eslint/node_modules/doctrine/lib/typed.js new file mode 100644 index 00000000000000..2b02000e634412 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/lib/typed.js @@ -0,0 +1,1261 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2014 Dan Tao + Copyright (C) 2013 Andrew Eisenberg + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// "typed", the Type Expression Parser for doctrine. + +(function () { + 'use strict'; + + var Syntax, + Token, + source, + length, + index, + previous, + token, + value, + esutils, + utility; + + esutils = require('esutils'); + utility = require('./utility'); + + Syntax = { + NullableLiteral: 'NullableLiteral', + AllLiteral: 'AllLiteral', + NullLiteral: 'NullLiteral', + UndefinedLiteral: 'UndefinedLiteral', + VoidLiteral: 'VoidLiteral', + UnionType: 'UnionType', + ArrayType: 'ArrayType', + RecordType: 'RecordType', + FieldType: 'FieldType', + FunctionType: 'FunctionType', + ParameterType: 'ParameterType', + RestType: 'RestType', + NonNullableType: 'NonNullableType', + OptionalType: 'OptionalType', + NullableType: 'NullableType', + NameExpression: 'NameExpression', + TypeApplication: 'TypeApplication' + }; + + Token = { + ILLEGAL: 0, // ILLEGAL + DOT_LT: 1, // .< + REST: 2, // ... + LT: 3, // < + GT: 4, // > + LPAREN: 5, // ( + RPAREN: 6, // ) + LBRACE: 7, // { + RBRACE: 8, // } + LBRACK: 9, // [ + RBRACK: 10, // ] + COMMA: 11, // , + COLON: 12, // : + STAR: 13, // * + PIPE: 14, // | + QUESTION: 15, // ? + BANG: 16, // ! + EQUAL: 17, // = + NAME: 18, // name token + STRING: 19, // string + NUMBER: 20, // number + EOF: 21 + }; + + function isTypeName(ch) { + return '><(){}[],:*|?!='.indexOf(String.fromCharCode(ch)) === -1 && !esutils.code.isWhiteSpace(ch) && !esutils.code.isLineTerminator(ch); + } + + function Context(previous, index, token, value) { + this._previous = previous; + this._index = index; + this._token = token; + this._value = value; + } + + Context.prototype.restore = function () { + previous = this._previous; + index = this._index; + token = this._token; + value = this._value; + }; + + Context.save = function () { + return new Context(previous, index, token, value); + }; + + function advance() { + var ch = source.charAt(index); + index += 1; + return ch; + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && esutils.code.isHexDigit(source.charCodeAt(index))) { + ch = advance(); + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanString() { + var str = '', quote, ch, code, unescaped, restore; //TODO review removal octal = false + quote = source.charAt(index); + ++index; + + while (index < length) { + ch = advance(); + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = advance(); + if (!esutils.code.isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'u': + case 'x': + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + str += unescaped; + } else { + index = restore; + str += ch; + } + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\v'; + break; + + default: + if (esutils.code.isOctalDigit(ch.charCodeAt(0))) { + code = '01234567'.indexOf(ch); + + // \0 is not octal escape sequence + // Deprecating unused code. TODO review removal + //if (code !== 0) { + // octal = true; + //} + + if (index < length && esutils.code.isOctalDigit(source.charCodeAt(index))) { + //TODO Review Removal octal = true; + code = code * 8 + '01234567'.indexOf(advance()); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + esutils.code.isOctalDigit(source.charCodeAt(index))) { + code = code * 8 + '01234567'.indexOf(advance()); + } + } + str += String.fromCharCode(code); + } else { + str += ch; + } + break; + } + } else { + if (ch === '\r' && source.charCodeAt(index) === 0x0A /* '\n' */) { + ++index; + } + } + } else if (esutils.code.isLineTerminator(ch.charCodeAt(0))) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + utility.throwError('unexpected quote'); + } + + value = str; + return Token.STRING; + } + + function scanNumber() { + var number, ch; + + number = ''; + ch = source.charCodeAt(index); + + if (ch !== 0x2E /* '.' */) { + number = advance(); + ch = source.charCodeAt(index); + + if (number === '0') { + if (ch === 0x78 /* 'x' */ || ch === 0x58 /* 'X' */) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isHexDigit(ch)) { + break; + } + number += advance(); + } + + if (number.length <= 2) { + // only 0x + utility.throwError('unexpected token'); + } + + if (index < length) { + ch = source.charCodeAt(index); + if (esutils.code.isIdentifierStart(ch)) { + utility.throwError('unexpected token'); + } + } + value = parseInt(number, 16); + return Token.NUMBER; + } + + if (esutils.code.isOctalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isOctalDigit(ch)) { + break; + } + number += advance(); + } + + if (index < length) { + ch = source.charCodeAt(index); + if (esutils.code.isIdentifierStart(ch) || esutils.code.isDecimalDigit(ch)) { + utility.throwError('unexpected token'); + } + } + value = parseInt(number, 8); + return Token.NUMBER; + } + + if (esutils.code.isDecimalDigit(ch)) { + utility.throwError('unexpected token'); + } + } + + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } + + if (ch === 0x2E /* '.' */) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } + + if (ch === 0x65 /* 'e' */ || ch === 0x45 /* 'E' */) { + number += advance(); + + ch = source.charCodeAt(index); + if (ch === 0x2B /* '+' */ || ch === 0x2D /* '-' */) { + number += advance(); + } + + ch = source.charCodeAt(index); + if (esutils.code.isDecimalDigit(ch)) { + number += advance(); + while (index < length) { + ch = source.charCodeAt(index); + if (!esutils.code.isDecimalDigit(ch)) { + break; + } + number += advance(); + } + } else { + utility.throwError('unexpected token'); + } + } + + if (index < length) { + ch = source.charCodeAt(index); + if (esutils.code.isIdentifierStart(ch)) { + utility.throwError('unexpected token'); + } + } + + value = parseFloat(number); + return Token.NUMBER; + } + + + function scanTypeName() { + var ch, ch2; + + value = advance(); + while (index < length && isTypeName(source.charCodeAt(index))) { + ch = source.charCodeAt(index); + if (ch === 0x2E /* '.' */) { + if ((index + 1) >= length) { + return Token.ILLEGAL; + } + ch2 = source.charCodeAt(index + 1); + if (ch2 === 0x3C /* '<' */) { + break; + } + } + value += advance(); + } + return Token.NAME; + } + + function next() { + var ch; + + previous = index; + + while (index < length && esutils.code.isWhiteSpace(source.charCodeAt(index))) { + advance(); + } + if (index >= length) { + token = Token.EOF; + return token; + } + + ch = source.charCodeAt(index); + switch (ch) { + case 0x27: /* ''' */ + case 0x22: /* '"' */ + token = scanString(); + return token; + + case 0x3A: /* ':' */ + advance(); + token = Token.COLON; + return token; + + case 0x2C: /* ',' */ + advance(); + token = Token.COMMA; + return token; + + case 0x28: /* '(' */ + advance(); + token = Token.LPAREN; + return token; + + case 0x29: /* ')' */ + advance(); + token = Token.RPAREN; + return token; + + case 0x5B: /* '[' */ + advance(); + token = Token.LBRACK; + return token; + + case 0x5D: /* ']' */ + advance(); + token = Token.RBRACK; + return token; + + case 0x7B: /* '{' */ + advance(); + token = Token.LBRACE; + return token; + + case 0x7D: /* '}' */ + advance(); + token = Token.RBRACE; + return token; + + case 0x2E: /* '.' */ + if (index + 1 < length) { + ch = source.charCodeAt(index + 1); + if (ch === 0x3C /* '<' */) { + advance(); // '.' + advance(); // '<' + token = Token.DOT_LT; + return token; + } + + if (ch === 0x2E /* '.' */ && index + 2 < length && source.charCodeAt(index + 2) === 0x2E /* '.' */) { + advance(); // '.' + advance(); // '.' + advance(); // '.' + token = Token.REST; + return token; + } + + if (esutils.code.isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + } + token = Token.ILLEGAL; + return token; + + case 0x3C: /* '<' */ + advance(); + token = Token.LT; + return token; + + case 0x3E: /* '>' */ + advance(); + token = Token.GT; + return token; + + case 0x2A: /* '*' */ + advance(); + token = Token.STAR; + return token; + + case 0x7C: /* '|' */ + advance(); + token = Token.PIPE; + return token; + + case 0x3F: /* '?' */ + advance(); + token = Token.QUESTION; + return token; + + case 0x21: /* '!' */ + advance(); + token = Token.BANG; + return token; + + case 0x3D: /* '=' */ + advance(); + token = Token.EQUAL; + return token; + + default: + if (esutils.code.isDecimalDigit(ch)) { + token = scanNumber(); + return token; + } + + // type string permits following case, + // + // namespace.module.MyClass + // + // this reduced 1 token TK_NAME + utility.assert(isTypeName(ch)); + token = scanTypeName(); + return token; + } + } + + function consume(target, text) { + utility.assert(token === target, text || 'consumed token not matched'); + next(); + } + + function expect(target, message) { + if (token !== target) { + utility.throwError(message || 'unexpected token'); + } + next(); + } + + // UnionType := '(' TypeUnionList ')' + // + // TypeUnionList := + // <> + // | NonemptyTypeUnionList + // + // NonemptyTypeUnionList := + // TypeExpression + // | TypeExpression '|' NonemptyTypeUnionList + function parseUnionType() { + var elements; + consume(Token.LPAREN, 'UnionType should start with ('); + elements = []; + if (token !== Token.RPAREN) { + while (true) { + elements.push(parseTypeExpression()); + if (token === Token.RPAREN) { + break; + } + expect(Token.PIPE); + } + } + consume(Token.RPAREN, 'UnionType should end with )'); + return { + type: Syntax.UnionType, + elements: elements + }; + } + + // ArrayType := '[' ElementTypeList ']' + // + // ElementTypeList := + // <> + // | TypeExpression + // | '...' TypeExpression + // | TypeExpression ',' ElementTypeList + function parseArrayType() { + var elements; + consume(Token.LBRACK, 'ArrayType should start with ['); + elements = []; + while (token !== Token.RBRACK) { + if (token === Token.REST) { + consume(Token.REST); + elements.push({ + type: Syntax.RestType, + expression: parseTypeExpression() + }); + break; + } else { + elements.push(parseTypeExpression()); + } + if (token !== Token.RBRACK) { + expect(Token.COMMA); + } + } + expect(Token.RBRACK); + return { + type: Syntax.ArrayType, + elements: elements + }; + } + + function parseFieldName() { + var v = value; + if (token === Token.NAME || token === Token.STRING) { + next(); + return v; + } + + if (token === Token.NUMBER) { + consume(Token.NUMBER); + return String(v); + } + + utility.throwError('unexpected token'); + } + + // FieldType := + // FieldName + // | FieldName ':' TypeExpression + // + // FieldName := + // NameExpression + // | StringLiteral + // | NumberLiteral + // | ReservedIdentifier + function parseFieldType() { + var key; + + key = parseFieldName(); + if (token === Token.COLON) { + consume(Token.COLON); + return { + type: Syntax.FieldType, + key: key, + value: parseTypeExpression() + }; + } + return { + type: Syntax.FieldType, + key: key, + value: null + }; + } + + // RecordType := '{' FieldTypeList '}' + // + // FieldTypeList := + // <> + // | FieldType + // | FieldType ',' FieldTypeList + function parseRecordType() { + var fields; + + consume(Token.LBRACE, 'RecordType should start with {'); + fields = []; + if (token === Token.COMMA) { + consume(Token.COMMA); + } else { + while (token !== Token.RBRACE) { + fields.push(parseFieldType()); + if (token !== Token.RBRACE) { + expect(Token.COMMA); + } + } + } + expect(Token.RBRACE); + return { + type: Syntax.RecordType, + fields: fields + }; + } + + // NameExpression := + // Identifier + // | TagIdentifier ':' Identifier + // + // Tag identifier is one of "module", "external" or "event" + // Identifier is the same as Token.NAME, including any dots, something like + // namespace.module.MyClass + function parseNameExpression() { + var name = value; + expect(Token.NAME); + + if (token === Token.COLON && ( + name === 'module' || + name === 'external' || + name === 'event')) { + consume(Token.COLON); + name += ':' + value; + expect(Token.NAME); + } + + return { + type: Syntax.NameExpression, + name: name + }; + } + + // TypeExpressionList := + // TopLevelTypeExpression + // | TopLevelTypeExpression ',' TypeExpressionList + function parseTypeExpressionList() { + var elements = []; + + elements.push(parseTop()); + while (token === Token.COMMA) { + consume(Token.COMMA); + elements.push(parseTop()); + } + return elements; + } + + // TypeName := + // NameExpression + // | NameExpression TypeApplication + // + // TypeApplication := + // '.<' TypeExpressionList '>' + // | '<' TypeExpressionList '>' // this is extension of doctrine + function parseTypeName() { + var expr, applications; + + expr = parseNameExpression(); + if (token === Token.DOT_LT || token === Token.LT) { + next(); + applications = parseTypeExpressionList(); + expect(Token.GT); + return { + type: Syntax.TypeApplication, + expression: expr, + applications: applications + }; + } + return expr; + } + + // ResultType := + // <> + // | ':' void + // | ':' TypeExpression + // + // BNF is above + // but, we remove <> pattern, so token is always TypeToken::COLON + function parseResultType() { + consume(Token.COLON, 'ResultType should start with :'); + if (token === Token.NAME && value === 'void') { + consume(Token.NAME); + return { + type: Syntax.VoidLiteral + }; + } + return parseTypeExpression(); + } + + // ParametersType := + // RestParameterType + // | NonRestParametersType + // | NonRestParametersType ',' RestParameterType + // + // RestParameterType := + // '...' + // '...' Identifier + // + // NonRestParametersType := + // ParameterType ',' NonRestParametersType + // | ParameterType + // | OptionalParametersType + // + // OptionalParametersType := + // OptionalParameterType + // | OptionalParameterType, OptionalParametersType + // + // OptionalParameterType := ParameterType= + // + // ParameterType := TypeExpression | Identifier ':' TypeExpression + // + // Identifier is "new" or "this" + function parseParametersType() { + var params = [], optionalSequence = false, expr, rest = false; + + while (token !== Token.RPAREN) { + if (token === Token.REST) { + // RestParameterType + consume(Token.REST); + rest = true; + } + + expr = parseTypeExpression(); + if (expr.type === Syntax.NameExpression && token === Token.COLON) { + // Identifier ':' TypeExpression + consume(Token.COLON); + expr = { + type: Syntax.ParameterType, + name: expr.name, + expression: parseTypeExpression() + }; + } + if (token === Token.EQUAL) { + consume(Token.EQUAL); + expr = { + type: Syntax.OptionalType, + expression: expr + }; + optionalSequence = true; + } else { + if (optionalSequence) { + utility.throwError('unexpected token'); + } + } + if (rest) { + expr = { + type: Syntax.RestType, + expression: expr + }; + } + params.push(expr); + if (token !== Token.RPAREN) { + expect(Token.COMMA); + } + } + return params; + } + + // FunctionType := 'function' FunctionSignatureType + // + // FunctionSignatureType := + // | TypeParameters '(' ')' ResultType + // | TypeParameters '(' ParametersType ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ')' ResultType + // | TypeParameters '(' 'this' ':' TypeName ',' ParametersType ')' ResultType + function parseFunctionType() { + var isNew, thisBinding, params, result, fnType; + utility.assert(token === Token.NAME && value === 'function', 'FunctionType should start with \'function\''); + consume(Token.NAME); + + // Google Closure Compiler is not implementing TypeParameters. + // So we do not. if we don't get '(', we see it as error. + expect(Token.LPAREN); + + isNew = false; + params = []; + thisBinding = null; + if (token !== Token.RPAREN) { + // ParametersType or 'this' + if (token === Token.NAME && + (value === 'this' || value === 'new')) { + // 'this' or 'new' + // 'new' is Closure Compiler extension + isNew = value === 'new'; + consume(Token.NAME); + expect(Token.COLON); + thisBinding = parseTypeName(); + if (token === Token.COMMA) { + consume(Token.COMMA); + params = parseParametersType(); + } + } else { + params = parseParametersType(); + } + } + + expect(Token.RPAREN); + + result = null; + if (token === Token.COLON) { + result = parseResultType(); + } + + fnType = { + type: Syntax.FunctionType, + params: params, + result: result + }; + if (thisBinding) { + // avoid adding null 'new' and 'this' properties + fnType['this'] = thisBinding; + if (isNew) { + fnType['new'] = true; + } + } + return fnType; + } + + // BasicTypeExpression := + // '*' + // | 'null' + // | 'undefined' + // | TypeName + // | FunctionType + // | UnionType + // | RecordType + // | ArrayType + function parseBasicTypeExpression() { + var context; + switch (token) { + case Token.STAR: + consume(Token.STAR); + return { + type: Syntax.AllLiteral + }; + + case Token.LPAREN: + return parseUnionType(); + + case Token.LBRACK: + return parseArrayType(); + + case Token.LBRACE: + return parseRecordType(); + + case Token.NAME: + if (value === 'null') { + consume(Token.NAME); + return { + type: Syntax.NullLiteral + }; + } + + if (value === 'undefined') { + consume(Token.NAME); + return { + type: Syntax.UndefinedLiteral + }; + } + + context = Context.save(); + if (value === 'function') { + try { + return parseFunctionType(); + } catch (e) { + context.restore(); + } + } + + return parseTypeName(); + + default: + utility.throwError('unexpected token'); + } + } + + // TypeExpression := + // BasicTypeExpression + // | '?' BasicTypeExpression + // | '!' BasicTypeExpression + // | BasicTypeExpression '?' + // | BasicTypeExpression '!' + // | '?' + // | BasicTypeExpression '[]' + function parseTypeExpression() { + var expr; + + if (token === Token.QUESTION) { + consume(Token.QUESTION); + if (token === Token.COMMA || token === Token.EQUAL || token === Token.RBRACE || + token === Token.RPAREN || token === Token.PIPE || token === Token.EOF || + token === Token.RBRACK || token === Token.GT) { + return { + type: Syntax.NullableLiteral + }; + } + return { + type: Syntax.NullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: parseBasicTypeExpression(), + prefix: true + }; + } + + expr = parseBasicTypeExpression(); + if (token === Token.BANG) { + consume(Token.BANG); + return { + type: Syntax.NonNullableType, + expression: expr, + prefix: false + }; + } + + if (token === Token.QUESTION) { + consume(Token.QUESTION); + return { + type: Syntax.NullableType, + expression: expr, + prefix: false + }; + } + + if (token === Token.LBRACK) { + consume(Token.LBRACK); + expect(Token.RBRACK, 'expected an array-style type declaration (' + value + '[])'); + return { + type: Syntax.TypeApplication, + expression: { + type: Syntax.NameExpression, + name: 'Array' + }, + applications: [expr] + }; + } + + return expr; + } + + // TopLevelTypeExpression := + // TypeExpression + // | TypeUnionList + // + // This rule is Google Closure Compiler extension, not ES4 + // like, + // { number | string } + // If strict to ES4, we should write it as + // { (number|string) } + function parseTop() { + var expr, elements; + + expr = parseTypeExpression(); + if (token !== Token.PIPE) { + return expr; + } + + elements = [ expr ]; + consume(Token.PIPE); + while (true) { + elements.push(parseTypeExpression()); + if (token !== Token.PIPE) { + break; + } + consume(Token.PIPE); + } + + return { + type: Syntax.UnionType, + elements: elements + }; + } + + function parseTopParamType() { + var expr; + + if (token === Token.REST) { + consume(Token.REST); + return { + type: Syntax.RestType, + expression: parseTop() + }; + } + + expr = parseTop(); + if (token === Token.EQUAL) { + consume(Token.EQUAL); + return { + type: Syntax.OptionalType, + expression: expr + }; + } + + return expr; + } + + function parseType(src, opt) { + var expr; + + source = src; + length = source.length; + index = 0; + previous = 0; + + next(); + expr = parseTop(); + + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } + + if (token !== Token.EOF) { + utility.throwError('not reach to EOF'); + } + + return expr; + } + + function parseParamType(src, opt) { + var expr; + + source = src; + length = source.length; + index = 0; + previous = 0; + + next(); + expr = parseTopParamType(); + + if (opt && opt.midstream) { + return { + expression: expr, + index: previous + }; + } + + if (token !== Token.EOF) { + utility.throwError('not reach to EOF'); + } + + return expr; + } + + function stringifyImpl(node, compact, topLevel) { + var result, i, iz; + + switch (node.type) { + case Syntax.NullableLiteral: + result = '?'; + break; + + case Syntax.AllLiteral: + result = '*'; + break; + + case Syntax.NullLiteral: + result = 'null'; + break; + + case Syntax.UndefinedLiteral: + result = 'undefined'; + break; + + case Syntax.VoidLiteral: + result = 'void'; + break; + + case Syntax.UnionType: + if (!topLevel) { + result = '('; + } else { + result = ''; + } + + for (i = 0, iz = node.elements.length; i < iz; ++i) { + result += stringifyImpl(node.elements[i], compact); + if ((i + 1) !== iz) { + result += '|'; + } + } + + if (!topLevel) { + result += ')'; + } + break; + + case Syntax.ArrayType: + result = '['; + for (i = 0, iz = node.elements.length; i < iz; ++i) { + result += stringifyImpl(node.elements[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + result += ']'; + break; + + case Syntax.RecordType: + result = '{'; + for (i = 0, iz = node.fields.length; i < iz; ++i) { + result += stringifyImpl(node.fields[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + result += '}'; + break; + + case Syntax.FieldType: + if (node.value) { + result = node.key + (compact ? ':' : ': ') + stringifyImpl(node.value, compact); + } else { + result = node.key; + } + break; + + case Syntax.FunctionType: + result = compact ? 'function(' : 'function ('; + + if (node['this']) { + if (node['new']) { + result += (compact ? 'new:' : 'new: '); + } else { + result += (compact ? 'this:' : 'this: '); + } + + result += stringifyImpl(node['this'], compact); + + if (node.params.length !== 0) { + result += compact ? ',' : ', '; + } + } + + for (i = 0, iz = node.params.length; i < iz; ++i) { + result += stringifyImpl(node.params[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + + result += ')'; + + if (node.result) { + result += (compact ? ':' : ': ') + stringifyImpl(node.result, compact); + } + break; + + case Syntax.ParameterType: + result = node.name + (compact ? ':' : ': ') + stringifyImpl(node.expression, compact); + break; + + case Syntax.RestType: + result = '...'; + if (node.expression) { + result += stringifyImpl(node.expression, compact); + } + break; + + case Syntax.NonNullableType: + if (node.prefix) { + result = '!' + stringifyImpl(node.expression, compact); + } else { + result = stringifyImpl(node.expression, compact) + '!'; + } + break; + + case Syntax.OptionalType: + result = stringifyImpl(node.expression, compact) + '='; + break; + + case Syntax.NullableType: + if (node.prefix) { + result = '?' + stringifyImpl(node.expression, compact); + } else { + result = stringifyImpl(node.expression, compact) + '?'; + } + break; + + case Syntax.NameExpression: + result = node.name; + break; + + case Syntax.TypeApplication: + result = stringifyImpl(node.expression, compact) + '.<'; + for (i = 0, iz = node.applications.length; i < iz; ++i) { + result += stringifyImpl(node.applications[i], compact); + if ((i + 1) !== iz) { + result += compact ? ',' : ', '; + } + } + result += '>'; + break; + + default: + utility.throwError('Unknown type ' + node.type); + } + + return result; + } + + function stringify(node, options) { + if (options == null) { + options = {}; + } + return stringifyImpl(node, options.compact, options.topLevel); + } + + exports.parseType = parseType; + exports.parseParamType = parseParamType; + exports.stringify = stringify; + exports.Syntax = Syntax; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/lib/utility.js b/tools/eslint/node_modules/doctrine/lib/utility.js new file mode 100644 index 00000000000000..bb441258469dc1 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/lib/utility.js @@ -0,0 +1,54 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +(function () { + 'use strict'; + + var VERSION; + + VERSION = require('../package.json').version; + exports.VERSION = VERSION; + + function DoctrineError(message) { + this.name = 'DoctrineError'; + this.message = message; + } + DoctrineError.prototype = (function () { + var Middle = function () { }; + Middle.prototype = Error.prototype; + return new Middle(); + }()); + DoctrineError.prototype.constructor = DoctrineError; + exports.DoctrineError = DoctrineError; + + function throwError(message) { + throw new DoctrineError(message); + } + exports.throwError = throwError; + + exports.assert = require('assert'); +}()); + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/LICENSE.BSD b/tools/eslint/node_modules/doctrine/node_modules/esutils/LICENSE.BSD new file mode 100644 index 00000000000000..3e580c355a96e5 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/README.md b/tools/eslint/node_modules/doctrine/node_modules/esutils/README.md new file mode 100644 index 00000000000000..494fac5edaad47 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/README.md @@ -0,0 +1,169 @@ +### esutils [![Build Status](https://secure.travis-ci.org/Constellation/esutils.svg)](http://travis-ci.org/Constellation/esutils) +esutils ([esutils](http://github.com/Constellation/esutils)) is +utility box for ECMAScript language tools. + +### API + +### ast + +#### ast.isExpression(node) + +Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section +[11](https://es5.github.io/#x11). + +#### ast.isStatement(node) + +Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section +[12](https://es5.github.io/#x12). + +#### ast.isIterationStatement(node) + +Returns true if `node` is an IterationStatement as defined in ECMA262 edition +5.1 section [12.6](https://es5.github.io/#x12.6). + +#### ast.isSourceElement(node) + +Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 +section [14](https://es5.github.io/#x14). + +#### ast.trailingStatement(node) + +Returns `Statement?` if `node` has trailing `Statement`. +```js +if (cond) + consequent; +``` +When taking this `IfStatement`, returns `consequent;` statement. + +#### ast.isProblematicIfStatement(node) + +Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. +```js +{ + type: 'IfStatement', + consequent: { + type: 'WithStatement', + body: { + type: 'IfStatement', + consequent: {type: 'EmptyStatement'} + } + }, + alternate: {type: 'EmptyStatement'} +} +``` +The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. + + +### code + +#### code.isDecimalDigit(code) + +Return true if provided code is decimal digit. + +#### code.isHexDigit(code) + +Return true if provided code is hexadecimal digit. + +#### code.isOctalDigit(code) + +Return true if provided code is octal digit. + +#### code.isWhiteSpace(code) + +Return true if provided code is white space. White space characters are formally defined in ECMA262. + +#### code.isLineTerminator(code) + +Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. + +#### code.isIdentifierStart(code) + +Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. + +#### code.isIdentifierPart(code) + +Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. + +### keyword + +#### keyword.isKeywordES5(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 5.1. They are formally defined in ECMA262 sections +[7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isKeywordES6(id, strict) + +Returns `true` if provided identifier string is a Keyword or Future Reserved Word +in ECMA262 edition 6. They are formally defined in ECMA262 sections +[11.6.2.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-keywords) and +[11.6.2.2](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-future-reserved-words), +respectively. If the `strict` flag is truthy, this function additionally checks whether +`id` is a Keyword or Future Reserved Word under strict mode. + +#### keyword.isReservedWordES5(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. +They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isReservedWordES6(id, strict) + +Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. +They are formally defined in ECMA262 section [11.6.2](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words). +If the `strict` flag is truthy, this function additionally checks whether `id` +is a Reserved Word under strict mode. + +#### keyword.isRestrictedWord(id) + +Returns `true` if provided identifier string is one of `eval` or `arguments`. +They are restricted in strict mode code throughout ECMA262 edition 5.1 and +in ECMA262 edition 6 section [12.1.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-identifiers-static-semantics-early-errors). + +#### keyword.isIdentifierName(id) + +Return true if provided identifier string is an IdentifierName as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). + +#### keyword.isIdentifierES5(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` +flag is truthy, this function additionally checks whether `id` is an Identifier +under strict mode. + +#### keyword.isIdentifierES6(id, strict) + +Return true if provided identifier string is an Identifier as specified in +ECMA262 edition 6 section [12.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-identifiers). +If the `strict` flag is truthy, this function additionally checks whether `id` +is an Identifier under strict mode. + +### License + +Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/ast.js b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/ast.js new file mode 100644 index 00000000000000..8faadae1ce736d --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/ast.js @@ -0,0 +1,144 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + function isExpression(node) { + if (node == null) { return false; } + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + return false; + } + + function isIterationStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + return false; + } + + function isStatement(node) { + if (node == null) { return false; } + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + if (node.alternate == null) { + return false; + } + current = node.consequent; + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + + trailingStatement: trailingStatement + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/code.js b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/code.js new file mode 100644 index 00000000000000..730292a3472918 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/code.js @@ -0,0 +1,101 @@ +/* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var Regex, NON_ASCII_WHITESPACES; + + // See `tools/generate-identifier-regex.js`. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), + NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') + }; + + function isDecimalDigit(ch) { + return (ch >= 48 && ch <= 57); // 0..9 + } + + function isHexDigit(ch) { + return isDecimalDigit(ch) || // 0..9 + (97 <= ch && ch <= 102) || // a..f + (65 <= ch && ch <= 70); // A..F + } + + function isOctalDigit(ch) { + return (ch >= 48 && ch <= 55); // 0..7 + } + + // 7.2 White Space + + NON_ASCII_WHITESPACES = [ + 0x1680, 0x180E, + 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, + 0x202F, 0x205F, + 0x3000, + 0xFEFF + ]; + + function isWhiteSpace(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch >= 97 && ch <= 122) || // a..z + (ch >= 65 && ch <= 90) || // A..Z + (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch === 92) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); + } + + function isIdentifierPart(ch) { + return (ch >= 97 && ch <= 122) || // a..z + (ch >= 65 && ch <= 90) || // A..Z + (ch >= 48 && ch <= 57) || // 0..9 + (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch === 92) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStart: isIdentifierStart, + isIdentifierPart: isIdentifierPart + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/keyword.js b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/keyword.js new file mode 100644 index 00000000000000..884be72fbed5f0 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/keyword.js @@ -0,0 +1,137 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function () { + 'use strict'; + + var code = require('./code'); + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierName(id) { + var i, iz, ch; + + if (id.length === 0) { + return false; + } + + ch = id.charCodeAt(0); + if (!code.isIdentifierStart(ch) || ch === 92) { // \ (backslash) + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + if (!code.isIdentifierPart(ch) || ch === 92) { // \ (backslash) + return false; + } + } + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierName(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierName(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierName: isIdentifierName, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/utils.js b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/utils.js new file mode 100644 index 00000000000000..ce18faa6bc80fa --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/lib/utils.js @@ -0,0 +1,33 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + + +(function () { + 'use strict'; + + exports.ast = require('./ast'); + exports.code = require('./code'); + exports.keyword = require('./keyword'); +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/node_modules/esutils/package.json b/tools/eslint/node_modules/doctrine/node_modules/esutils/package.json new file mode 100644 index 00000000000000..b01fe6004b1ea8 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/esutils/package.json @@ -0,0 +1,66 @@ +{ + "name": "esutils", + "description": "utility box for ECMAScript language tools", + "homepage": "https://github.com/Constellation/esutils", + "main": "lib/utils.js", + "version": "1.1.6", + "engines": { + "node": ">=0.10.0" + }, + "directories": { + "lib": "./lib" + }, + "files": [ + "LICENSE.BSD", + "README.md", + "lib" + ], + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Constellation/esutils.git" + }, + "devDependencies": { + "mocha": "~1.12.0", + "chai": "~1.7.2", + "jshint": "2.1.5", + "coffee-script": "~1.6.3", + "unicode-6.3.0": "~0.1.1", + "regenerate": "~0.5.4" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/Constellation/esutils/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint lib/*.js", + "unit-test": "mocha --compilers coffee:coffee-script -R spec", + "generate-regex": "node tools/generate-identifier-regex.js" + }, + "gitHead": "a91c5ed6199d1019ef071f610848fcd5103ef153", + "bugs": { + "url": "https://github.com/Constellation/esutils/issues" + }, + "_id": "esutils@1.1.6", + "_shasum": "c01ccaa9ae4b897c6d0c3e210ae52f3c7a844375", + "_from": "esutils@>=1.1.6 <2.0.0", + "_npmVersion": "2.0.0-alpha-5", + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "dist": { + "shasum": "c01ccaa9ae4b897c6d0c3e210ae52f3c7a844375", + "tarball": "http://registry.npmjs.org/esutils/-/esutils-1.1.6.tgz" + }, + "_resolved": "https://registry.npmjs.org/esutils/-/esutils-1.1.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/doctrine/node_modules/isarray/README.md b/tools/eslint/node_modules/doctrine/node_modules/isarray/README.md new file mode 100644 index 00000000000000..052a62b8d7b7ae --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/eslint/node_modules/doctrine/node_modules/isarray/build/build.js b/tools/eslint/node_modules/doctrine/node_modules/isarray/build/build.js new file mode 100644 index 00000000000000..ec58596aeebe4e --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/tools/eslint/node_modules/doctrine/node_modules/isarray/component.json b/tools/eslint/node_modules/doctrine/node_modules/isarray/component.json new file mode 100644 index 00000000000000..9e31b683889015 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/tools/eslint/node_modules/doctrine/node_modules/isarray/index.js b/tools/eslint/node_modules/doctrine/node_modules/isarray/index.js new file mode 100644 index 00000000000000..5f5ad45d46dda9 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/tools/eslint/node_modules/doctrine/node_modules/isarray/package.json b/tools/eslint/node_modules/doctrine/node_modules/isarray/package.json new file mode 100644 index 00000000000000..25c8581bee19f6 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/node_modules/isarray/package.json @@ -0,0 +1,54 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "_id": "isarray@0.0.1", + "dist": { + "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" + }, + "_from": "isarray@0.0.1", + "_npmVersion": "1.2.18", + "_npmUser": { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + "maintainers": [ + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + } + ], + "directories": {}, + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + } +} diff --git a/tools/eslint/node_modules/doctrine/package.json b/tools/eslint/node_modules/doctrine/package.json new file mode 100644 index 00000000000000..7de168c4eabd37 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/package.json @@ -0,0 +1,71 @@ +{ + "name": "doctrine", + "description": "JSDoc parser", + "homepage": "http://github.com/Constellation/doctrine.html", + "main": "lib/doctrine.js", + "version": "0.6.4", + "engines": { + "node": ">=0.10.0" + }, + "directories": { + "lib": "./lib" + }, + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Constellation/doctrine.git" + }, + "devDependencies": { + "coveralls": "^2.11.2", + "gulp": "^3.8.10", + "gulp-bump": "^0.1.13", + "gulp-eslint": "^0.5.0", + "gulp-filter": "^2.0.2", + "gulp-git": "^1.0.0", + "gulp-istanbul": "^0.6.0", + "gulp-jshint": "^1.9.0", + "gulp-mocha": "^2.0.0", + "gulp-tag-version": "^1.2.1", + "jshint-stylish": "^1.0.0", + "should": "^5.0.1" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/Constellation/doctrine/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "gulp", + "unit-test": "gulp test", + "lint": "gulp lint", + "coveralls": "cat ./coverage/lcov.info | coveralls && rm -rf ./coverage" + }, + "dependencies": { + "esutils": "^1.1.6", + "isarray": "0.0.1" + }, + "gitHead": "0835299b485ecdfa908d20628d6c8900144590ff", + "bugs": { + "url": "https://github.com/Constellation/doctrine/issues" + }, + "_id": "doctrine@0.6.4", + "_shasum": "81428491a942ef18b0492056eda3800eee57d61d", + "_from": "doctrine@>=0.6.2 <0.7.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "dist": { + "shasum": "81428491a942ef18b0492056eda3800eee57d61d", + "tarball": "http://registry.npmjs.org/doctrine/-/doctrine-0.6.4.tgz" + }, + "_resolved": "https://registry.npmjs.org/doctrine/-/doctrine-0.6.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/doctrine/test/midstream.js b/tools/eslint/node_modules/doctrine/test/midstream.js new file mode 100644 index 00000000000000..2e71bd14e1098e --- /dev/null +++ b/tools/eslint/node_modules/doctrine/test/midstream.js @@ -0,0 +1,61 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*global require describe it*/ +/*jslint node:true */ +'use strict'; + +var fs = require('fs'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + doctrine = require(root); +require('should'); + +describe('midstream', function () { + it('parseType', function () { + var res = doctrine.parseType('string name', { midstream: true }); + res.should.eql({ + "expression": { + "name": "string", + "type": "NameExpression" + }, + "index": 6 + }); + }); + + it('parseParamType', function () { + var res = doctrine.parseParamType('...test ok', { midstream: true }); + res.should.eql({ + "expression": { + "expression": { + "name": "test", + "type": "NameExpression" + }, + "type": "RestType" + }, + "index": 7 + }); + }); +}); + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/test/parse.js b/tools/eslint/node_modules/doctrine/test/parse.js new file mode 100644 index 00000000000000..851e67c0d9a87e --- /dev/null +++ b/tools/eslint/node_modules/doctrine/test/parse.js @@ -0,0 +1,2219 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*global require describe it*/ +/*jslint node:true */ +'use strict'; + +var fs = require('fs'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + doctrine = require(root); +require('should'); + +describe('parse', function () { + it('alias', function () { + var res = doctrine.parse('/** @alias */', { unwrap: true }); + res.tags.should.have.length(0); + }); + + it('alias with name', function () { + var res = doctrine.parse('/** @alias aliasName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'alias'); + res.tags[0].should.have.property('name', 'aliasName'); + }); + + it('alias with namepath', function () { + var res = doctrine.parse('/** @alias aliasName.OK */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'alias'); + res.tags[0].should.have.property('name', 'aliasName.OK'); + }); + + it('const', function () { + var res = doctrine.parse('/** @const */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'const'); + }); + + it('const with name', function () { + var res = doctrine.parse('/** @const constname */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'const'); + res.tags[0].should.have.property('name', 'constname'); + }); + + it('constant with name', function () { + var res = doctrine.parse('/** @constant constname */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'constant'); + res.tags[0].should.have.property('name', 'constname'); + }); + + it('const with type and name', function () { + var res = doctrine.parse('/** @const {String} constname */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'const'); + res.tags[0].should.have.property('name', 'constname'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('constant with type and name', function () { + var res = doctrine.parse('/** @constant {String} constname */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'constant'); + res.tags[0].should.have.property('name', 'constname'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('const multiple', function () { + var res = doctrine.parse("/**@const\n @const*/", { unwrap: true }); + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', 'const'); + res.tags[1].should.have.property('title', 'const'); + }); + + it('const double', function () { + var res = doctrine.parse("/**@const\n @const*/", { unwrap: true }); + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', 'const'); + res.tags[1].should.have.property('title', 'const'); + }); + + it('const triple', function () { + var res = doctrine.parse( + [ + "/**", + " * @const @const", + " * @const @const", + " * @const @const", + " */" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(3); + res.tags[0].should.have.property('title', 'const'); + res.tags[1].should.have.property('title', 'const'); + res.tags[2].should.have.property('title', 'const'); + }); + + it('constructor', function () { + var res = doctrine.parse('/** @constructor */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'constructor'); + }); + + it('constructor with type', function () { + var res = doctrine.parse('/** @constructor {Object} */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'constructor'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('constructor with type and name', function () { + var res = doctrine.parse('/** @constructor {Object} objName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'constructor'); + res.tags[0].should.have.property('name', 'objName'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('class', function () { + var res = doctrine.parse('/** @class */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'class'); + }); + + it('class with type', function () { + var res = doctrine.parse('/** @class {Object} */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'class'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('class with type and name', function () { + var res = doctrine.parse('/** @class {Object} objName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'class'); + res.tags[0].should.have.property('name', 'objName'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('deprecated', function () { + var res = doctrine.parse('/** @deprecated */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'deprecated'); + }); + + it('deprecated', function () { + var res = doctrine.parse('/** @deprecated some text here describing why it is deprecated */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'deprecated'); + res.tags[0].should.have.property('description', 'some text here describing why it is deprecated'); + }); + + it('func', function () { + var res = doctrine.parse('/** @func */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'func'); + }); + + it('func with name', function () { + var res = doctrine.parse('/** @func thingName.func */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'func'); + res.tags[0].should.have.property('name', 'thingName.func'); + }); + + it('func with type', function () { + var res = doctrine.parse('/** @func {Object} thingName.func */', { unwrap: true }); + res.tags.should.have.length(0); + // func does not accept type + }); + + it('function', function () { + var res = doctrine.parse('/** @function */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'function'); + }); + + it('function with name', function () { + var res = doctrine.parse('/** @function thingName.function */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'function'); + res.tags[0].should.have.property('name', 'thingName.function'); + }); + + it('function with type', function () { + var res = doctrine.parse('/** @function {Object} thingName.function */', { unwrap: true }); + res.tags.should.have.length(0); + // function does not accept type + }); + + it('member', function () { + var res = doctrine.parse('/** @member */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'member'); + }); + + it('member with name', function () { + var res = doctrine.parse('/** @member thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'member'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('member with type', function () { + var res = doctrine.parse('/** @member {Object} thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'member'); + res.tags[0].should.have.property('name', 'thingName.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('method', function () { + var res = doctrine.parse('/** @method */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'method'); + }); + + it('method with name', function () { + var res = doctrine.parse('/** @method thingName.function */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'method'); + res.tags[0].should.have.property('name', 'thingName.function'); + }); + + it('method with type', function () { + var res = doctrine.parse('/** @method {Object} thingName.function */', { unwrap: true }); + res.tags.should.have.length(0); + // method does not accept type + }); + + it('mixes', function () { + var res = doctrine.parse('/** @mixes */', { unwrap: true }); + res.tags.should.have.length(0); + }); + + it('mixes with name', function () { + var res = doctrine.parse('/** @mixes thingName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'mixes'); + res.tags[0].should.have.property('name', 'thingName'); + }); + + it('mixes with namepath', function () { + var res = doctrine.parse('/** @mixes thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'mixes'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('mixin', function () { + var res = doctrine.parse('/** @mixin */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'mixin'); + }); + + it('mixin with name', function () { + var res = doctrine.parse('/** @mixin thingName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'mixin'); + res.tags[0].should.have.property('name', 'thingName'); + }); + + it('mixin with namepath', function () { + var res = doctrine.parse('/** @mixin thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'mixin'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('module', function () { + var res = doctrine.parse('/** @module */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'module'); + }); + + it('module with name', function () { + var res = doctrine.parse('/** @module thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'module'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('module with type', function () { + var res = doctrine.parse('/** @module {Object} thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'module'); + res.tags[0].should.have.property('name', 'thingName.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('name', function () { + var res = doctrine.parse('/** @name thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'name'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('name', function () { + var res = doctrine.parse('/** @name thingName#name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'name'); + res.tags[0].should.have.property('name', 'thingName#name'); + }); + + it('name', function () { + var res = doctrine.parse('/** @name thingName~name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'name'); + res.tags[0].should.have.property('name', 'thingName~name'); + }); + + it('name', function () { + var res = doctrine.parse('/** @name {thing} thingName.name */', { unwrap: true }); + // name does not accept type + res.tags.should.have.length(0); + }); + + it('namespace', function () { + var res = doctrine.parse('/** @namespace */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'namespace'); + }); + + it('namespace with name', function () { + var res = doctrine.parse('/** @namespace thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'namespace'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('namespace with type', function () { + var res = doctrine.parse('/** @namespace {Object} thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'namespace'); + res.tags[0].should.have.property('name', 'thingName.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('param', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {String} userName", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'userName'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('param with properties', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {String} user.name", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'user.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('arg with properties', function () { + var res = doctrine.parse( + [ + "/**", + " * @arg {String} user.name", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'arg'); + res.tags[0].should.have.property('name', 'user.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('argument with properties', function () { + var res = doctrine.parse( + [ + "/**", + " * @argument {String} user.name", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'argument'); + res.tags[0].should.have.property('name', 'user.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('param typeless', function () { + var res = doctrine.parse( + [ + "/**", + " * @param userName", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + title: 'param', + type: null, + name: 'userName', + description: null + }); + + var res = doctrine.parse( + [ + "/**", + " * @param userName Something descriptive", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + title: 'param', + type: null, + name: 'userName', + description: 'Something descriptive' + }); + + var res = doctrine.parse( + [ + "/**", + " * @param user.name Something descriptive", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + title: 'param', + type: null, + name: 'user.name', + description: 'Something descriptive' + }); + }); + + it('param broken', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {String} userName", + " * @param {String userName", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'userName'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'String' + }); + }); + + it('param record', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {{ok:String}} userName", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'userName'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'RecordType', + fields: [{ + type: 'FieldType', + key: 'ok', + value: { + type: 'NameExpression', + name: 'String' + } + }] + }); + }); + + it('param record broken', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {{ok:String} userName", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.be.empty; + }); + + it('param multiple lines', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {string|", + " * number} userName", + " * }}", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'userName'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'UnionType', + elements: [{ + type: 'NameExpression', + name: 'string' + }, { + type: 'NameExpression', + name: 'number' + }] + }); + }); + + it('param without braces', function () { + var res = doctrine.parse( + [ + "/**", + " * @param string name description", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'string'); + res.tags[0].should.have.property('type', null); + res.tags[0].should.have.property('description', 'name description'); + }); + + it('param w/ hyphen before description', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {string} name - description", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + title: 'param', + type: { + type: 'NameExpression', + name: 'string' + }, + name: 'name', + description: 'description' + }); + }); + + it('param w/ hyphen + leading space before description', function () { + var res = doctrine.parse( + [ + "/**", + " * @param {string} name - description", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + title: 'param', + type: { + type: 'NameExpression', + name: 'string' + }, + name: 'name', + description: ' description' + }); + }); + + it('description and param separated by blank line', function () { + var res = doctrine.parse( + [ + "/**", + " * Description", + " * blah blah blah", + " *", + " * @param {string} name description", + "*/" + ].join('\n'), { unwrap: true }); + res.description.should.eql('Description\nblah blah blah'); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'string' + }); + res.tags[0].should.have.property('description', 'description'); + }); + + it('regular block comment instead of jsdoc-style block comment', function () { + var res = doctrine.parse( + [ + "/*", + " * Description", + " * blah blah blah", + "*/" + ].join('\n'), { unwrap: true }); + res.description.should.eql("Description\nblah blah blah"); + }); + + it('augments', function () { + var res = doctrine.parse('/** @augments */', { unwrap: true }); + res.tags.should.have.length(1); + }); + + it('augments with name', function () { + var res = doctrine.parse('/** @augments ClassName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'augments'); + res.tags[0].should.have.property('name', 'ClassName'); + }); + + it('augments with type', function () { + var res = doctrine.parse('/** @augments {ClassName} */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'augments'); + res.tags[0].should.have.property('type', { + type: 'NameExpression', + name: 'ClassName' + }); + }); + + it('augments with name', function () { + var res = doctrine.parse('/** @augments ClassName.OK */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'augments'); + res.tags[0].should.have.property('name', 'ClassName.OK'); + }); + + it('extends', function () { + var res = doctrine.parse('/** @extends */', { unwrap: true }); + res.tags.should.have.length(1); + }); + + it('extends with name', function () { + var res = doctrine.parse('/** @extends ClassName */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'extends'); + res.tags[0].should.have.property('name', 'ClassName'); + }); + + it('extends with type', function () { + var res = doctrine.parse('/** @extends {ClassName} */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'extends'); + res.tags[0].should.have.property('type', { + type: 'NameExpression', + name: 'ClassName' + }); + }); + + it('extends with namepath', function () { + var res = doctrine.parse('/** @extends ClassName.OK */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'extends'); + res.tags[0].should.have.property('name', 'ClassName.OK'); + }); + + it('prop', function () { + var res = doctrine.parse( + [ + "/**", + " * @prop {string} thingName - does some stuff", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'prop'); + res.tags[0].should.have.property('description', 'does some stuff'); + res.tags[0].type.should.have.property('name', 'string'); + res.tags[0].should.have.property('name', 'thingName'); + }); + + it('prop without type', function () { + var res = doctrine.parse( + [ + "/**", + " * @prop thingName - does some stuff", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(0); + }); + + + it('property', function () { + var res = doctrine.parse( + [ + "/**", + " * @property {string} thingName - does some stuff", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'property'); + res.tags[0].should.have.property('description', 'does some stuff'); + res.tags[0].type.should.have.property('name', 'string'); + res.tags[0].should.have.property('name', 'thingName'); + }); + + it('property without type', function () { + var res = doctrine.parse( + [ + "/**", + " * @property thingName - does some stuff", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(0); + }); + + it('property with nested name', function () { + var res = doctrine.parse( + [ + "/**", + " * @property {string} thingName.name - does some stuff", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'property'); + res.tags[0].should.have.property('description', 'does some stuff'); + res.tags[0].type.should.have.property('name', 'string'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('throws', function () { + var res = doctrine.parse( + [ + "/**", + " * @throws {Error} if something goes wrong", + " */" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'throws'); + res.tags[0].should.have.property('description', 'if something goes wrong'); + res.tags[0].type.should.have.property('name', 'Error'); + }); + + it('throws without type', function () { + var res = doctrine.parse( + [ + "/**", + " * @throws if something goes wrong", + " */" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'throws'); + res.tags[0].should.have.property('description', 'if something goes wrong'); + }); + + it('kind', function () { + var res = doctrine.parse('/** @kind class */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'kind'); + res.tags[0].should.have.property('kind', 'class'); + }); + + it('kind error', function () { + var res = doctrine.parse('/** @kind ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Invalid kind name \'ng\''); + }); + + it('todo', function () { + var res = doctrine.parse('/** @todo Write the documentation */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'todo'); + res.tags[0].should.have.property('description', 'Write the documentation'); + }); + + it('summary', function () { + // japanese lang + var res = doctrine.parse('/** @summary ゆるゆり3期おめでとー */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'summary'); + res.tags[0].should.have.property('description', 'ゆるゆり3期おめでとー'); + }); + + it('variation', function () { + // japanese lang + var res = doctrine.parse('/** @variation 42 */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'variation'); + res.tags[0].should.have.property('variation', 42); + }); + + it('variation error', function () { + // japanese lang + var res = doctrine.parse('/** @variation Animation */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Invalid variation \'Animation\''); + }); + + it('access', function () { + var res = doctrine.parse('/** @access public */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'access'); + res.tags[0].should.have.property('access', 'public'); + }); + + it('access error', function () { + var res = doctrine.parse('/** @access ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Invalid access name \'ng\''); + }); + + it('public', function () { + var res = doctrine.parse('/** @public */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'public'); + }); + + it('public type and description', function () { + var res = doctrine.parse('/** @public {number} ok */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'public'); + res.tags[0].should.have.property('description', 'ok'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'number' + }); + }); + + it('protected', function () { + var res = doctrine.parse('/** @protected */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'protected'); + }); + + it('protected type and description', function () { + var res = doctrine.parse('/** @protected {number} ok */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'protected'); + res.tags[0].should.have.property('description', 'ok'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'number' + }); + }); + + it('private', function () { + var res = doctrine.parse('/** @private */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'private'); + }); + + it('private type and description', function () { + var res = doctrine.parse('/** @private {number} ok */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'private'); + res.tags[0].should.have.property('description', 'ok'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'number' + }); + }); + + it('readonly', function () { + var res = doctrine.parse('/** @readonly */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'readonly'); + }); + + it('readonly error', function () { + var res = doctrine.parse('/** @readonly ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Unknown content \'ng\''); + }); + + it('requires', function () { + var res = doctrine.parse('/** @requires */', { unwrap: true }); + res.tags.should.have.length(0); + }); + + it('requires with module name', function () { + var res = doctrine.parse('/** @requires name.path */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'requires'); + res.tags[0].should.have.property('name', 'name.path'); + }); + + it('global', function () { + var res = doctrine.parse('/** @global */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'global'); + }); + + it('global error', function () { + var res = doctrine.parse('/** @global ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Unknown content \'ng\''); + }); + + it('inner', function () { + var res = doctrine.parse('/** @inner */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'inner'); + }); + + it('inner error', function () { + var res = doctrine.parse('/** @inner ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Unknown content \'ng\''); + }); + + it('instance', function () { + var res = doctrine.parse('/** @instance */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'instance'); + }); + + it('instance error', function () { + var res = doctrine.parse('/** @instance ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Unknown content \'ng\''); + }); + + it('since', function () { + var res = doctrine.parse('/** @since 1.2.1 */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'since'); + res.tags[0].should.have.property('description', '1.2.1'); + }); + + it('static', function () { + var res = doctrine.parse('/** @static */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'static'); + }); + + it('static error', function () { + var res = doctrine.parse('/** @static ng */', { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Unknown content \'ng\''); + }); + + it('this', function () { + var res = doctrine.parse( + [ + "/**", + " * @this thingName", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'this'); + res.tags[0].should.have.property('name', 'thingName'); + }); + + it('this with namepath', function () { + var res = doctrine.parse( + [ + "/**", + " * @this thingName.name", + "*/" + ].join('\n'), { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'this'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('this error', function () { + var res = doctrine.parse( + [ + "/**", + " * @this", + "*/" + ].join('\n'), { unwrap: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'this'); + res.tags[0].should.have.property('errors'); + res.tags[0].errors.should.have.length(1); + res.tags[0].errors[0].should.equal('Missing or invalid tag name'); + }); + + it('var', function () { + var res = doctrine.parse('/** @var */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'var'); + }); + + it('var with name', function () { + var res = doctrine.parse('/** @var thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'var'); + res.tags[0].should.have.property('name', 'thingName.name'); + }); + + it('var with type', function () { + var res = doctrine.parse('/** @var {Object} thingName.name */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'var'); + res.tags[0].should.have.property('name', 'thingName.name'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + type: 'NameExpression', + name: 'Object' + }); + }); + + it('version', function () { + var res = doctrine.parse('/** @version 1.2.1 */', { unwrap: true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'version'); + res.tags[0].should.have.property('description', '1.2.1'); + }); + + it('incorrect name', function () { + var res = doctrine.parse('/** @name thingName#%name */', { unwrap: true }); + // name does not accept type + res.tags.should.have.length(0); + res.should.eql({ + "description": "", + "tags": [ + ] + }); + }); +}); + +describe('parseType', function () { + it('union type closure-compiler extended', function () { + var type = doctrine.parseType("string|number"); + type.should.eql({ + type: 'UnionType', + elements: [{ + type: 'NameExpression', + name: 'string' + }, { + type: 'NameExpression', + name: 'number' + }] + }); + }); + + it('empty union type', function () { + var type = doctrine.parseType("()"); + type.should.eql({ + type: 'UnionType', + elements: [] + }); + }); + + it('comma last array type', function () { + var type = doctrine.parseType("[string,]"); + type.should.eql({ + type: 'ArrayType', + elements: [{ + type: 'NameExpression', + name: 'string' + }] + }); + }); + + it('array type of all literal', function () { + var type = doctrine.parseType("[*]"); + type.should.eql({ + type: 'ArrayType', + elements: [{ + type: 'AllLiteral' + }] + }); + }); + + it('array type of nullable literal', function () { + var type = doctrine.parseType("[?]"); + type.should.eql({ + type: 'ArrayType', + elements: [{ + type: 'NullableLiteral' + }] + }); + }); + + it('comma last record type', function () { + var type = doctrine.parseType("{,}"); + type.should.eql({ + type: 'RecordType', + fields: [] + }); + }); + + it('type application', function () { + var type = doctrine.parseType("Array."); + type.should.eql({ + type: 'TypeApplication', + expression: { + type: 'NameExpression', + name: 'Array' + }, + applications: [{ + type: 'NameExpression', + name: 'String' + }] + }); + }); + + it('type application with NullableLiteral', function () { + var type = doctrine.parseType("Array"); + type.should.eql({ + type: 'TypeApplication', + expression: { + type: 'NameExpression', + name: 'Array' + }, + applications: [{ + type: 'NullableLiteral' + }] + }); + }); + + it('type application with multiple patterns', function () { + var type = doctrine.parseType("Array."); + type.should.eql({ + type: 'TypeApplication', + expression: { + type: 'NameExpression', + name: 'Array' + }, + applications: [{ + type: 'NameExpression', + name: 'String' + }, { + type: 'NameExpression', + name: 'Number' + }] + }); + }); + + it('type application without dot', function () { + var type = doctrine.parseType("Array"); + type.should.eql({ + type: 'TypeApplication', + expression: { + type: 'NameExpression', + name: 'Array' + }, + applications: [{ + type: 'NameExpression', + name: 'String' + }] + }); + }); + + it('array-style type application', function () { + var type = doctrine.parseType("String[]"); + type.should.eql({ + type: 'TypeApplication', + expression: { + type: 'NameExpression', + name: 'Array' + }, + applications: [{ + type: 'NameExpression', + name: 'String' + }] + }); + }); + + it('function type simple', function () { + var type = doctrine.parseType("function()"); + type.should.eql({ + "type": "FunctionType", + "params": [], + "result": null + }); + }); + + it('function type with name', function () { + var type = doctrine.parseType("function(a)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "NameExpression", + "name": "a" + } + ], + "result": null + }); + }); + it('function type with name and type', function () { + var type = doctrine.parseType("function(a:b)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "ParameterType", + "name": "a", + "expression": { + "type": "NameExpression", + "name": "b" + } + } + ], + "result": null + }); + }); + it('function type with optional param', function () { + var type = doctrine.parseType("function(a=)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "OptionalType", + "expression": { + "type": "NameExpression", + "name": "a" + } + } + ], + "result": null + }); + }); + it('function type with optional param name and type', function () { + var type = doctrine.parseType("function(a:b=)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "OptionalType", + "expression": { + "type": "ParameterType", + "name": "a", + "expression": { + "type": "NameExpression", + "name": "b" + } + } + } + ], + "result": null + }); + }); + it('function type with rest param', function () { + var type = doctrine.parseType("function(...a)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "RestType", + "expression": { + "type": "NameExpression", + "name": "a" + } + } + ], + "result": null + }); + }); + it('function type with rest param name and type', function () { + var type = doctrine.parseType("function(...a:b)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "RestType", + "expression": { + "type": "ParameterType", + "name": "a", + "expression": { + "type": "NameExpression", + "name": "b" + } + } + } + ], + "result": null + }); + }); + + it('function type with optional rest param', function () { + var type = doctrine.parseType("function(...a=)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "RestType", + "expression": { + "type": "OptionalType", + "expression": { + "type": "NameExpression", + "name": "a" + } + } + } + ], + "result": null + }); + }); + it('function type with optional rest param name and type', function () { + var type = doctrine.parseType("function(...a:b=)"); + type.should.eql({ + "type": "FunctionType", + "params": [ + { + "type": "RestType", + "expression": { + "type": "OptionalType", + "expression": { + "type": "ParameterType", + "name": "a", + "expression": { + "type": "NameExpression", + "name": "b" + } + } + } + }], + "result": null + }); + }); + + it('string value in type', function () { + var type; + + type = doctrine.parseType("{'ok':String}"); + type.should.eql({ + "fields": [ + { + "key": "ok", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + } + ], + "type": "RecordType" + }); + + type = doctrine.parseType('{"\\r\\n\\t\\u2028\\x20\\u20\\b\\f\\v\\\r\n\\\n\\0\\07\\012\\o":String}'); + type.should.eql({ + "fields": [ + { + "key": "\r\n\t\u2028\x20u20\b\f\v\0\u0007\u000ao", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + } + ], + "type": "RecordType" + }); + + doctrine.parseType.bind(doctrine, "{'ok\":String}").should.throw('unexpected quote'); + doctrine.parseType.bind(doctrine, "{'o\n':String}").should.throw('unexpected quote'); + }); + + it('number value in type', function () { + var type; + + type = doctrine.parseType("{20:String}"); + type.should.eql({ + "fields": [ + { + "key": "20", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + } + ], + "type": "RecordType" + }); + + type = doctrine.parseType("{.2:String, 30:Number, 0x20:String}"); + type.should.eql({ + "fields": [ + { + "key": "0.2", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + }, + { + "key": "30", + "type": "FieldType", + "value": { + "name": "Number", + "type": "NameExpression" + } + }, + { + "key": "32", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + } + ], + "type": "RecordType" + }); + + + type = doctrine.parseType("{0X2:String, 0:Number, 100e200:String, 10e-20:Number}"); + type.should.eql({ + "fields": [ + { + "key": "2", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + }, + { + "key": "0", + "type": "FieldType", + "value": { + "name": "Number", + "type": "NameExpression" + } + }, + { + "key": "1e+202", + "type": "FieldType", + "value": { + "name": "String", + "type": "NameExpression" + } + }, + { + "key": "1e-19", + "type": "FieldType", + "value": { + "name": "Number", + "type": "NameExpression" + } + } + ], + "type": "RecordType" + }); + + + doctrine.parseType.bind(doctrine, "{0x:String}").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{0x").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{0xd").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{0x2_:").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{021:").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{021_:").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{021").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{08").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{0y").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{0").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{100e2").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{100e-2").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{100e-200:").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "{100e:").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "function(number=, string)").should.throw('not reach to EOF'); + }); + + it('dotted type', function () { + var type; + type = doctrine.parseType("Cocoa.Cappuccino"); + type.should.eql({ + "name": "Cocoa.Cappuccino", + "type": "NameExpression" + }); + }); + + it('rest array type', function () { + var type; + type = doctrine.parseType("[string,...string]"); + type.should.eql({ + "elements": [ + { + "name": "string", + "type": "NameExpression" + }, + { + "expression": { + "name": "string", + "type": "NameExpression" + }, + "type": "RestType" + } + ], + "type": "ArrayType" + }); + }); + + it ('nullable type', function () { + var type; + type = doctrine.parseType("string?"); + type.should.eql({ + "expression": { + "name": "string", + "type": "NameExpression" + }, + "prefix": false, + "type": "NullableType" + }); + }); + + it ('non-nullable type', function () { + var type; + type = doctrine.parseType("string!"); + type.should.eql({ + "expression": { + "name": "string", + "type": "NameExpression" + }, + "prefix": false, + "type": "NonNullableType" + }); + }); + + it ('toplevel multiple pipe type', function () { + var type; + type = doctrine.parseType("string|number|Test"); + type.should.eql({ + "elements": [ + { + "name": "string", + "type": "NameExpression" + }, + { + "name": "number", + "type": "NameExpression" + }, + { + "name": "Test", + "type": "NameExpression" + } + ], + "type": "UnionType" + }); + }); + + it('illegal tokens', function () { + doctrine.parseType.bind(doctrine, ".").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, ".d").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "(").should.throw('unexpected token'); + doctrine.parseType.bind(doctrine, "Test.").should.throw('unexpected token'); + }); +}); + +describe('parseParamType', function () { + it('question', function () { + var type = doctrine.parseParamType("?"); + type.should.eql({ + type: 'NullableLiteral' + }); + }); + + it('question option', function () { + var type = doctrine.parseParamType("?="); + type.should.eql({ + type: 'OptionalType', + expression: { + type: 'NullableLiteral' + } + }); + }); + + it('function option parameters former', function () { + var type = doctrine.parseParamType("function(?, number)"); + type.should.eql({ + type: 'FunctionType', + params: [{ + type: 'NullableLiteral' + }, { + type: 'NameExpression', + name: 'number' + }], + result: null + }); + }); + + it('function option parameters latter', function () { + var type = doctrine.parseParamType("function(number, ?)"); + type.should.eql({ + type: 'FunctionType', + params: [{ + type: 'NameExpression', + name: 'number' + }, { + type: 'NullableLiteral' + }], + result: null + }); + }); + + it('function type union', function () { + var type = doctrine.parseParamType("function(): ?|number"); + type.should.eql({ + type: 'UnionType', + elements: [{ + type: 'FunctionType', + params: [], + result: { + type: 'NullableLiteral' + } + }, { + type: 'NameExpression', + name: 'number' + }] + }); + }); +}); + +describe('invalid', function () { + it('empty union pipe', function () { + doctrine.parseType.bind(doctrine, "(|)").should.throw(); + doctrine.parseType.bind(doctrine, "(string|)").should.throw(); + doctrine.parseType.bind(doctrine, "(string||)").should.throw(); + }); + + it('comma only array type', function () { + doctrine.parseType.bind(doctrine, "[,]").should.throw(); + }); + + it('comma only record type', function () { + doctrine.parseType.bind(doctrine, "{,,}").should.throw(); + }); + + it('incorrect bracket', function () { + doctrine.parseParamType.bind(doctrine, "int[").should.throw(); + }); +}); + +describe('tags option', function() { + it ('only param', function() { + var res = doctrine.parse( + [ + "/**", + " * @const @const", + " * @param {String} y", + " */" + ].join('\n'), { tags: ['param'], unwrap:true }); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'y'); + }); + + it ('param and type', function() { + var res = doctrine.parse( + [ + "/**", + " * @const x", + " * @param {String} y", + " * @type {String} ", + " */" + ].join('\n'), { tags: ['param', 'type'], unwrap:true }); + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('name', 'y'); + res.tags[1].should.have.property('title', 'type'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'String'); + }); + +}); + +describe('invalid tags', function() { + it ('bad tag 1', function() { + doctrine.parse.bind(doctrine, + [ + "/**", + " * @param {String} hucairz", + " */" + ].join('\n'), { tags: 1, unwrap:true }).should.throw(); + }); + + it ('bad tag 2', function() { + doctrine.parse.bind(doctrine, + [ + "/**", + " * @param {String} hucairz", + " */" + ].join('\n'), { tags: ['a', 1], unwrap:true }).should.throw(); + }); +}); + +describe('optional params', function() { + + // should fail since sloppy option not set + it('failure 0', function() { + doctrine.parse( + ["/**", " * @param {String} [val]", " */"].join('\n'), { + unwrap: true + }).should.eql({ + "description": "", + "tags": [] + }); + }); + + it('failure 1', function() { + doctrine.parse( + ["/**", " * @param [val", " */"].join('\n'), { + unwrap: true, sloppy: true + }).should.eql({ + "description": "", + "tags": [] + }); + }); + + it('success 1', function() { + doctrine.parse( + ["/**", " * @param {String} [val]", " */"].join('\n'), { + unwrap: true, sloppy: true + }).should.eql({ + "description": "", + "tags": [{ + "title": "param", + "description": null, + "type": { + "type": "OptionalType", + "expression": { + "type": "NameExpression", + "name": "String" + } + }, + "name": "val" + }] + }); + }); + it('success 2', function() { + doctrine.parse( + ["/**", " * @param {String=} val", " */"].join('\n'), { + unwrap: true, sloppy: true + }).should.eql({ + "description": "", + "tags": [{ + "title": "param", + "description": null, + "type": { + "type": "OptionalType", + "expression": { + "type": "NameExpression", + "name": "String" + } + }, + "name": "val" + }] + }); + }); + + it('success 3', function() { + doctrine.parse( + ["/**", " * @param {String=} [val=abc] some description", " */"].join('\n'), + { unwrap: true, sloppy: true} + ).should.eql({ + "description": "", + "tags": [{ + "title": "param", + "description": "some description", + "type": { + "type": "OptionalType", + "expression": { + "type": "NameExpression", + "name": "String" + } + }, + "name": "val", + "default": "abc" + }] + }); + }); + + it('line numbers', function() { + var res = doctrine.parse( + [ + "/**", + " * @param {string} foo", + " * @returns {string}", + " *", + " * @example", + " * f('blah'); // => undefined", + " */" + ].join('\n'), + { unwrap: true, lineNumbers: true } + ); + + res.tags[0].should.have.property('lineNumber', 1); + res.tags[1].should.have.property('lineNumber', 2); + res.tags[2].should.have.property('lineNumber', 4); + }); + + it('should handle \\r\\n line endings correctly', function() { + var res = doctrine.parse( + [ + "/**", + " * @param {string} foo", + " * @returns {string}", + " *", + " * @example", + " * f('blah'); // => undefined", + " */" + ].join('\r\n'), + { unwrap: true, lineNumbers: true } + ); + + res.tags[0].should.have.property('lineNumber', 1); + res.tags[1].should.have.property('lineNumber', 2); + res.tags[2].should.have.property('lineNumber', 4); + }); +}); + +describe('recovery tests', function() { + it ('params 2', function () { + var res = doctrine.parse( + [ + "@param f", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // ensure both parameters are OK + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('type', null); + res.tags[0].should.have.property('name', 'f'); + + res.tags[1].should.have.property('title', 'param'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'string'); + res.tags[1].type.should.have.property('type', 'NameExpression'); + res.tags[1].should.have.property('name', 'f2'); + }); + + it ('params 2', function () { + var res = doctrine.parse( + [ + "@param string f", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // ensure first parameter is OK even with invalid type name + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('type', null); + res.tags[0].should.have.property('name', 'string'); + res.tags[0].should.have.property('description', 'f'); + + res.tags[1].should.have.property('title', 'param'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'string'); + res.tags[1].type.should.have.property('type', 'NameExpression'); + res.tags[1].should.have.property('name', 'f2'); + }); + + it ('return 1', function() { + var res = doctrine.parse( + [ + "@returns" + ].join('\n'), { recoverable: true }); + + // return tag should exist + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'returns'); + res.tags[0].should.have.property('type', null); + }); + it ('return 2', function() { + var res = doctrine.parse( + [ + "@returns", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // return tag should exist as well as next tag + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', 'returns'); + res.tags[0].should.have.property('type', null); + + res.tags[1].should.have.property('title', 'param'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'string'); + res.tags[1].type.should.have.property('type', 'NameExpression'); + res.tags[1].should.have.property('name', 'f2'); + }); + + it ('extra @ 1', function() { + var res = doctrine.parse( + [ + "@", + "@returns", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // empty tag name shouldn't affect subsequent tags + res.tags.should.have.length(3); + res.tags[0].should.have.property('title', ''); + res.tags[0].should.not.have.property('type'); + + res.tags[1].should.have.property('title', 'returns'); + res.tags[1].should.have.property('type', null); + + res.tags[2].should.have.property('title', 'param'); + res.tags[2].should.have.property('type'); + res.tags[2].type.should.have.property('name', 'string'); + res.tags[2].type.should.have.property('type', 'NameExpression'); + res.tags[2].should.have.property('name', 'f2'); + }); + + it ('extra @ 2', function() { + var res = doctrine.parse( + [ + "@ invalid name", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // empty tag name shouldn't affect subsequent tags + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', ''); + res.tags[0].should.not.have.property('type'); + res.tags[0].should.not.have.property('name'); + res.tags[0].should.have.property('description', 'invalid name'); + + res.tags[1].should.have.property('title', 'param'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'string'); + res.tags[1].type.should.have.property('type', 'NameExpression'); + res.tags[1].should.have.property('name', 'f2'); + }); + + it ('invalid tag 1', function() { + var res = doctrine.parse( + [ + "@111 invalid name", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // invalid tag name shouldn't affect subsequent tags + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', '111'); + res.tags[0].should.not.have.property('type'); + res.tags[0].should.not.have.property('name'); + res.tags[0].should.have.property('description', 'invalid name'); + + res.tags[1].should.have.property('title', 'param'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'string'); + res.tags[1].type.should.have.property('type', 'NameExpression'); + res.tags[1].should.have.property('name', 'f2'); + }); + + it ('invalid tag 1', function() { + var res = doctrine.parse( + [ + "@111", + "@param {string} f2" + ].join('\n'), { recoverable: true }); + + // invalid tag name shouldn't affect subsequent tags + res.tags.should.have.length(2); + res.tags[0].should.have.property('title', '111'); + res.tags[0].should.not.have.property('type'); + res.tags[0].should.not.have.property('name'); + res.tags[0].should.have.property('description', null); + + res.tags[1].should.have.property('title', 'param'); + res.tags[1].should.have.property('type'); + res.tags[1].type.should.have.property('name', 'string'); + res.tags[1].type.should.have.property('type', 'NameExpression'); + res.tags[1].should.have.property('name', 'f2'); + }); + + it ('should not crash on bad type in @param without name', function() { + var res = doctrine.parse("@param {Function(DOMNode)}", { recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + "description": null, + "errors": [ + "not reach to EOF", + "Missing or invalid tag name" + ], + "name": null, + "title": "param", + "type": null + }); + }); + + it ('should not crash on bad type in @param in sloppy mode', function() { + var res = doctrine.parse("@param {int[} [x]", { sloppy: true, recoverable: true }); + res.tags.should.have.length(1); + res.tags[0].should.eql({ + "description": null, + "errors": [ + "expected an array-style type declaration (int[])" + ], + "name": "x", + "title": "param", + "type": null + }); + }); +}); + +describe('exported Syntax', function() { + it ('members', function () { + doctrine.Syntax.should.eql({ + NullableLiteral: 'NullableLiteral', + AllLiteral: 'AllLiteral', + NullLiteral: 'NullLiteral', + UndefinedLiteral: 'UndefinedLiteral', + VoidLiteral: 'VoidLiteral', + UnionType: 'UnionType', + ArrayType: 'ArrayType', + RecordType: 'RecordType', + FieldType: 'FieldType', + FunctionType: 'FunctionType', + ParameterType: 'ParameterType', + RestType: 'RestType', + NonNullableType: 'NonNullableType', + OptionalType: 'OptionalType', + NullableType: 'NullableType', + NameExpression: 'NameExpression', + TypeApplication: 'TypeApplication' + }); + }); +}); + +describe('@ mark contained descriptions', function () { + it ('comment description #10', function () { + doctrine.parse( + [ + '/**', + ' * Prevents the default action. It is equivalent to', + ' * {@code e.preventDefault()}, but can be used as the callback argument of', + ' * {@link goog.events.listen} without declaring another function.', + ' * @param {!goog.events.Event} e An event.', + ' */' + ].join('\n'), + { unwrap: true, sloppy: true }).should.eql({ + 'description': 'Prevents the default action. It is equivalent to\n{@code e.preventDefault()}, but can be used as the callback argument of\n{@link goog.events.listen} without declaring another function.', + 'tags': [{ + 'title': 'param', + 'description': 'An event.', + 'type': { + 'type': 'NonNullableType', + 'expression': { + 'type': 'NameExpression', + 'name': 'goog.events.Event' + }, + 'prefix': true + }, + 'name': 'e' + }] + }); + }); + + it ('tag description', function () { + doctrine.parse( + [ + '/**', + ' * Prevents the default action. It is equivalent to', + ' * @param {!goog.events.Event} e An event.', + ' * {@code e.preventDefault()}, but can be used as the callback argument of', + ' * {@link goog.events.listen} without declaring another function.', + ' */' + ].join('\n'), + { unwrap: true, sloppy: true }).should.eql({ + 'description': 'Prevents the default action. It is equivalent to', + 'tags': [{ + 'title': 'param', + 'description': 'An event.\n{@code e.preventDefault()}, but can be used as the callback argument of\n{@link goog.events.listen} without declaring another function.', + 'type': { + 'type': 'NonNullableType', + 'expression': { + 'type': 'NameExpression', + 'name': 'goog.events.Event' + }, + 'prefix': true + }, + 'name': 'e' + }] + }); + }); +}); + +describe('function', function () { + it ('recognize "function" type', function () { + var res = doctrine.parse( + [ + "@param {function} foo description", + ].join('\n'), {}); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].should.have.property('type'); + res.tags[0].type.should.eql({ + "name": "function", + "type": "NameExpression" + }); + res.tags[0].should.have.property('name', 'foo'); + res.tags[0].should.have.property('description', 'description'); + }); +}); + +describe('tagged namepaths', function () { + it ('recognize module:', function () { + var res = doctrine.parse( + [ + "@alias module:Foo.bar" + ].join('\n'), {}); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'alias'); + res.tags[0].should.have.property('name', 'module:Foo.bar'); + res.tags[0].should.have.property('description', null); + }); + + it ('recognize external:', function () { + var res = doctrine.parse( + [ + "@param {external:Foo.bar} baz description" + ].join('\n'), {}); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'param'); + res.tags[0].type.should.eql({ + "name": "external:Foo.bar", + "type": "NameExpression" + }); + res.tags[0].should.have.property('name', 'baz'); + res.tags[0].should.have.property('description', 'description'); + }); + + it ('recognize event:', function () { + var res = doctrine.parse( + [ + "@function event:Foo.bar" + ].join('\n'), {}); + res.tags.should.have.length(1); + res.tags[0].should.have.property('title', 'function'); + res.tags[0].should.have.property('name', 'event:Foo.bar'); + res.tags[0].should.have.property('description', null); + }); + + it ('invalid bogus:', function () { + var res = doctrine.parse( + [ + "@method bogus:Foo.bar" + ].join('\n'), {}); + res.tags.should.have.length(0); + }); +}); + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/test/strict.js b/tools/eslint/node_modules/doctrine/test/strict.js new file mode 100644 index 00000000000000..f6008d52f91f56 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/test/strict.js @@ -0,0 +1,168 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*global require describe it*/ +/*jslint node:true */ +'use strict'; + +var fs = require('fs'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + doctrine = require(root); +require('should'); + +describe('strict parse', function () { + // https://github.com/Constellation/doctrine/issues/21 + it('unbalanced braces', function () { + (function () { + doctrine.parse( + [ + "/**", + " * @param {const", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Braces are not balanced'); + + (function () { + doctrine.parse( + [ + "/**", + " * @param {const", + " */" + ].join('\n'), { unwrap: true }); + }).should.not.throw(); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @param {string name Param description", + " * @param {int} foo Bar", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Braces are not balanced'); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @param {string name Param description", + " * @param {int} foo Bar", + " */" + ].join('\n'), { unwrap: true }); + }).should.not.throw(); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @returns {int", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Braces are not balanced'); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @returns {int", + " */" + ].join('\n'), { unwrap: true }); + }).should.not.throw(); + }); + + // https://github.com/Constellation/doctrine/issues/21 + it('incorrect tag starting with @@', function () { + (function () { + doctrine.parse( + [ + "/**", + " * @@version", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Missing or invalid title'); + + (function () { + doctrine.parse( + [ + "/**", + " * @@version", + " */" + ].join('\n'), { unwrap: true }); + }).should.not.throw(); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @@param {string} name Param description", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Missing or invalid title'); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @@param {string} name Param description", + " */" + ].join('\n'), { unwrap: true }); + }).should.not.throw(); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @kind ng", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Invalid kind name \'ng\''); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @variation Animation", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Invalid variation \'Animation\''); + + (function () { + doctrine.parse( + [ + "/**", + " * Description", + " * @access ng", + " */" + ].join('\n'), { unwrap: true, strict: true }); + }).should.throw('Invalid access name \'ng\''); + }); +}); diff --git a/tools/eslint/node_modules/doctrine/test/stringify.js b/tools/eslint/node_modules/doctrine/test/stringify.js new file mode 100644 index 00000000000000..0f3a43ed83e8bd --- /dev/null +++ b/tools/eslint/node_modules/doctrine/test/stringify.js @@ -0,0 +1,413 @@ +/* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*global require describe it*/ +/*jslint node:true */ +'use strict'; + +var fs = require('fs'), + path = require('path'), + root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), + doctrine = require(root), + assert = require('assert'); +require('should'); + +// tests for the stringify function. +// ensure that we can parse and then stringify and the results are identical +describe('stringify', function () { + + function testStringify(text) { + it (text, function() { + var result = doctrine.parse("@param {" + text + "} name"); + // console.log("Parse Tree: " + JSON.stringify(result, null, " ")); + var stringed = doctrine.type.stringify(result.tags[0].type, {compact:true}); + stringed.should.equal(text); + }); + } + + // simple + testStringify("String"); + testStringify("*"); + testStringify("null"); + testStringify("undefined"); + testStringify("void"); + //testStringify("?="); // Failing + + // rest + testStringify("...string"); + testStringify("...[string]"); + testStringify("...[[string]]"); + + // optional, nullable, nonnullable + testStringify("string="); + testStringify("?string"); + testStringify("!string"); + testStringify("!string="); + + // type applications + testStringify("Array."); + testStringify("Array."); + + // union types + testStringify("()"); + testStringify("(String|Number)"); + + // Arrays + testStringify("[String]"); + testStringify("[String,Number]"); + testStringify("[(String|Number)]"); + + // Record types + testStringify("{a}"); + testStringify("{a:String}"); + testStringify("{a:String,b}"); + testStringify("{a:String,b:object}"); + testStringify("{a:String,b:foo.bar.baz}"); + testStringify("{a:(String|Number),b,c:Array.}"); + testStringify("...{a:(String|Number),b,c:Array.}"); + testStringify("{a:(String|Number),b,c:Array.}="); + + // fn types + testStringify("function(a)"); + testStringify("function(a):String"); + testStringify("function(a:number):String"); + testStringify("function(a:number,b:Array.<(String|Number|Object)>):String"); + testStringify("function(a:number,callback:function(a:Array.<(String|Number|Object)>):boolean):String"); + testStringify("function(a:(string|number),this:string,new:true):function():number"); + testStringify("function(a:(string|number),this:string,new:true):function(a:function(val):result):number"); +}); + +describe('literals', function() { + it('NullableLiteral', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.NullableLiteral + }).should.equal('?'); + }); + + it('AllLiteral', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.AllLiteral + }).should.equal('*'); + }); + + it('NullLiteral', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.NullLiteral + }).should.equal('null'); + }); + + it('UndefinedLiteral', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.UndefinedLiteral + }).should.equal('undefined'); + }); +}); + +describe('Expression', function () { + it('NameExpression', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.NameExpression, + name: 'this.is.valid' + }).should.equal('this.is.valid'); + + doctrine.type.stringify({ + type: doctrine.Syntax.NameExpression, + name: 'String' + }).should.equal('String'); + }); + + it('ArrayType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.ArrayType, + elements: [{ + type: doctrine.Syntax.NameExpression, + name: 'String' + }] + }).should.equal('[String]'); + + doctrine.type.stringify({ + type: doctrine.Syntax.ArrayType, + elements: [{ + type: doctrine.Syntax.NameExpression, + name: 'String' + }, { + type: doctrine.Syntax.NameExpression, + name: 'Number' + }] + }).should.equal('[String, Number]'); + + doctrine.type.stringify({ + type: doctrine.Syntax.ArrayType, + elements: [] + }).should.equal('[]'); + }); + + it('RecordType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.RecordType, + fields: [{ + type: doctrine.Syntax.FieldType, + key: 'name', + value: null + }] + }).should.equal('{name}'); + + doctrine.type.stringify({ + type: doctrine.Syntax.RecordType, + fields: [{ + type: doctrine.Syntax.FieldType, + key: 'name', + value: { + type: doctrine.Syntax.NameExpression, + name: 'String' + } + }] + }).should.equal('{name: String}'); + + doctrine.type.stringify({ + type: doctrine.Syntax.RecordType, + fields: [{ + type: doctrine.Syntax.FieldType, + key: 'string', + value: { + type: doctrine.Syntax.NameExpression, + name: 'String' + } + }, { + type: doctrine.Syntax.FieldType, + key: 'number', + value: { + type: doctrine.Syntax.NameExpression, + name: 'Number' + } + }] + }).should.equal('{string: String, number: Number}'); + + doctrine.type.stringify({ + type: doctrine.Syntax.RecordType, + fields: [] + }).should.equal('{}'); + }); + + it('UnionType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.UnionType, + elements: [{ + type: doctrine.Syntax.NameExpression, + name: 'String' + }] + }).should.equal('(String)'); + + doctrine.type.stringify({ + type: doctrine.Syntax.UnionType, + elements: [{ + type: doctrine.Syntax.NameExpression, + name: 'String' + }, { + type: doctrine.Syntax.NameExpression, + name: 'Number' + }] + }).should.equal('(String|Number)'); + + doctrine.type.stringify({ + type: doctrine.Syntax.UnionType, + elements: [{ + type: doctrine.Syntax.NameExpression, + name: 'String' + }, { + type: doctrine.Syntax.NameExpression, + name: 'Number' + }] + }, { topLevel: true }).should.equal('String|Number'); + }); + + it('RestType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.RestType, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'String' + } + }).should.equal('...String'); + }); + + it('NonNullableType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.NonNullableType, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'String' + }, + prefix: true + }).should.equal('!String'); + + doctrine.type.stringify({ + type: doctrine.Syntax.NonNullableType, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'String' + }, + prefix: false + }).should.equal('String!'); + }); + + it('OptionalType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.OptionalType, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'String' + } + }).should.equal('String='); + }); + + it('NullableType', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.NullableType, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'String' + }, + prefix: true + }).should.equal('?String'); + + doctrine.type.stringify({ + type: doctrine.Syntax.NullableType, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'String' + }, + prefix: false + }).should.equal('String?'); + }); + + it('TypeApplication', function () { + doctrine.type.stringify({ + type: doctrine.Syntax.TypeApplication, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'Array' + }, + applications: [ + { + type: doctrine.Syntax.NameExpression, + name: 'String' + } + ] + }).should.equal('Array.'); + + doctrine.type.stringify({ + type: doctrine.Syntax.TypeApplication, + expression: { + type: doctrine.Syntax.NameExpression, + name: 'Array' + }, + applications: [ + { + type: doctrine.Syntax.NameExpression, + name: 'String' + }, + { + type: doctrine.Syntax.AllLiteral + } + ] + }).should.equal('Array.'); + }); +}); + +describe('Complex identity', function () { + it('Functions', function () { + var data01 = 'function (): void'; + doctrine.type.stringify( + doctrine.type.parseType(data01) + ).should.equal(data01); + + var data02 = 'function (): String'; + doctrine.type.stringify( + doctrine.type.parseType(data02) + ).should.equal(data02); + + var data03 = 'function (test: string): String'; + doctrine.type.stringify( + doctrine.type.parseType(data03) + ).should.equal(data03); + + var data04 = 'function (this: Date, test: String): String'; + doctrine.type.stringify( + doctrine.type.parseType(data04) + ).should.equal(data04); + + var data05 = 'function (this: Date, a: String, b: Number): String'; + doctrine.type.stringify( + doctrine.type.parseType(data05) + ).should.equal(data05); + + var data06 = 'function (this: Date, a: Array., b: Number): String'; + doctrine.type.stringify( + doctrine.type.parseType(data06) + ).should.equal(data06); + + var data07 = 'function (new: Date, a: Array., b: Number): HashMap.'; + doctrine.type.stringify( + doctrine.type.parseType(data07) + ).should.equal(data07); + + var data08 = 'function (new: Date, a: Array., b: (Number|String|Date)): HashMap.'; + doctrine.type.stringify( + doctrine.type.parseType(data08) + ).should.equal(data08); + + var data09 = 'function (new: Date)'; + doctrine.type.stringify( + doctrine.type.parseType(data09) + ).should.equal(data09); + + var data10 = 'function (this: Date)'; + doctrine.type.stringify( + doctrine.type.parseType(data10) + ).should.equal(data10); + + var data11 = 'function (this: Date, ...list)'; + doctrine.type.stringify( + doctrine.type.parseType(data11) + ).should.equal(data11); + + var data11a = 'function (this: Date, test: String=)'; + doctrine.type.stringify( + doctrine.type.parseType(data11a) + ).should.equal(data11a); + + // raw ... are not supported +// var data12 = 'function (this: Date, ...)'; +// doctrine.type.stringify( +// doctrine.type.parseType(data12) +// ).should.equal(data12); + + var data12a = 'function (this: Date, ?=)'; + doctrine.type.stringify( + doctrine.type.parseType(data12a) + ).should.equal(data12a); + }); +}); + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/doctrine/test/test.html b/tools/eslint/node_modules/doctrine/test/test.html new file mode 100644 index 00000000000000..3784c2e5e4e1b6 --- /dev/null +++ b/tools/eslint/node_modules/doctrine/test/test.html @@ -0,0 +1,31 @@ + + + + +Doctrine trying + + + + + +
+
+ +
+
+

Parse Tree

+

+	

Stringified

+

+
+
\ No newline at end of file
diff --git a/tools/eslint/node_modules/doctrine/test/unwrap.js b/tools/eslint/node_modules/doctrine/test/unwrap.js
new file mode 100644
index 00000000000000..03d6f6dfe5833f
--- /dev/null
+++ b/tools/eslint/node_modules/doctrine/test/unwrap.js
@@ -0,0 +1,60 @@
+/*
+  Copyright (C) 2012 Yusuke Suzuki 
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+  ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
+  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*jslint node:true */
+'use strict';
+
+var fs = require('fs'),
+    path = require('path'),
+    root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
+    doctrine = require(root);
+require('should');
+
+describe('unwrapComment', function () {
+  it('normal', function () {
+    doctrine.unwrapComment('/**\n * @const\n * @const\n */').should.equal('\n@const\n@const\n');
+  });
+
+  it('single', function () {
+    doctrine.unwrapComment('/**x*/').should.equal('x');
+  });
+
+  it('more stars', function () {
+    doctrine.unwrapComment('/***x*/').should.equal('x');
+    doctrine.unwrapComment('/****x*/').should.equal('*x');
+  });
+
+  it('2 lines', function () {
+    doctrine.unwrapComment('/**x\n * y\n*/').should.equal('x\ny\n');
+  });
+
+  it('2 lines with space', function () {
+    doctrine.unwrapComment('/**x\n *    y\n*/').should.equal('x\n   y\n');
+  });
+
+  it('3 lines with blank line', function () {
+    doctrine.unwrapComment('/**x\n *\n \* y\n*/').should.equal('x\n\ny\n');
+  });
+});
+/* vim: set sw=4 ts=4 et tw=80 : */
diff --git a/tools/eslint/node_modules/escape-string-regexp/index.js b/tools/eslint/node_modules/escape-string-regexp/index.js
new file mode 100644
index 00000000000000..ac6572cabec57d
--- /dev/null
+++ b/tools/eslint/node_modules/escape-string-regexp/index.js
@@ -0,0 +1,11 @@
+'use strict';
+
+var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
+
+module.exports = function (str) {
+	if (typeof str !== 'string') {
+		throw new TypeError('Expected a string');
+	}
+
+	return str.replace(matchOperatorsRe,  '\\$&');
+};
diff --git a/tools/eslint/node_modules/escape-string-regexp/license b/tools/eslint/node_modules/escape-string-regexp/license
new file mode 100644
index 00000000000000..654d0bfe943437
--- /dev/null
+++ b/tools/eslint/node_modules/escape-string-regexp/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus  (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/tools/eslint/node_modules/escape-string-regexp/package.json b/tools/eslint/node_modules/escape-string-regexp/package.json
new file mode 100644
index 00000000000000..813c9089d27760
--- /dev/null
+++ b/tools/eslint/node_modules/escape-string-regexp/package.json
@@ -0,0 +1,70 @@
+{
+  "name": "escape-string-regexp",
+  "version": "1.0.3",
+  "description": "Escape RegExp special characters",
+  "license": "MIT",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/sindresorhus/escape-string-regexp.git"
+  },
+  "author": {
+    "name": "Sindre Sorhus",
+    "email": "sindresorhus@gmail.com",
+    "url": "http://sindresorhus.com"
+  },
+  "maintainers": [
+    {
+      "name": "sindresorhus",
+      "email": "sindresorhus@gmail.com"
+    },
+    {
+      "name": "jbnicolai",
+      "email": "jappelman@xebia.com"
+    }
+  ],
+  "engines": {
+    "node": ">=0.8.0"
+  },
+  "scripts": {
+    "test": "mocha"
+  },
+  "files": [
+    "index.js"
+  ],
+  "keywords": [
+    "regex",
+    "regexp",
+    "re",
+    "regular",
+    "expression",
+    "escape",
+    "string",
+    "str",
+    "special",
+    "characters"
+  ],
+  "devDependencies": {
+    "mocha": "*"
+  },
+  "gitHead": "1e446e6b4449b5f1f8868cd31bf8fd25ee37fb4b",
+  "bugs": {
+    "url": "https://github.com/sindresorhus/escape-string-regexp/issues"
+  },
+  "homepage": "https://github.com/sindresorhus/escape-string-regexp",
+  "_id": "escape-string-regexp@1.0.3",
+  "_shasum": "9e2d8b25bc2555c3336723750e03f099c2735bb5",
+  "_from": "escape-string-regexp@>=1.0.2 <2.0.0",
+  "_npmVersion": "2.1.16",
+  "_nodeVersion": "0.10.35",
+  "_npmUser": {
+    "name": "jbnicolai",
+    "email": "jappelman@xebia.com"
+  },
+  "dist": {
+    "shasum": "9e2d8b25bc2555c3336723750e03f099c2735bb5",
+    "tarball": "http://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.3.tgz"
+  },
+  "directories": {},
+  "_resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.3.tgz",
+  "readme": "ERROR: No README data found!"
+}
diff --git a/tools/eslint/node_modules/escape-string-regexp/readme.md b/tools/eslint/node_modules/escape-string-regexp/readme.md
new file mode 100644
index 00000000000000..808a963a86235e
--- /dev/null
+++ b/tools/eslint/node_modules/escape-string-regexp/readme.md
@@ -0,0 +1,27 @@
+# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
+
+> Escape RegExp special characters
+
+
+## Install
+
+```sh
+$ npm install --save escape-string-regexp
+```
+
+
+## Usage
+
+```js
+var escapeStringRegexp = require('escape-string-regexp');
+
+var escapedString = escapeStringRegexp('how much $ for a unicorn?');
+//=> how much \$ for a unicorn\?
+
+new RegExp(escapedString);
+```
+
+
+## License
+
+MIT © [Sindre Sorhus](http://sindresorhus.com)
diff --git a/tools/eslint/node_modules/escope/.jshintrc b/tools/eslint/node_modules/escope/.jshintrc
new file mode 100644
index 00000000000000..defbf02636c7aa
--- /dev/null
+++ b/tools/eslint/node_modules/escope/.jshintrc
@@ -0,0 +1,20 @@
+{
+    "curly": true,
+    "eqeqeq": true,
+    "immed": true,
+    "indent": 4,
+    "eqnull": true,
+    "latedef": true,
+    "noarg": true,
+    "noempty": true,
+    "quotmark": "single",
+    "undef": true,
+    "unused": true,
+    "strict": true,
+    "trailing": true,
+    "validthis": true,
+
+    "onevar": true,
+
+    "node": true
+}
diff --git a/tools/eslint/node_modules/escope/CONTRIBUTING.md b/tools/eslint/node_modules/escope/CONTRIBUTING.md
new file mode 100644
index 00000000000000..f1ddca9cbdcc30
--- /dev/null
+++ b/tools/eslint/node_modules/escope/CONTRIBUTING.md
@@ -0,0 +1,5 @@
+## Project license:  \
+
+- You will only Submit Contributions where You have authored 100% of the content.
+- You will only Submit Contributions to which You have the necessary rights. This means that if You are employed You have received the necessary permissions from Your employer to make the Contributions.
+- Whatever content You Contribute will be provided under the Project License.
diff --git a/tools/eslint/node_modules/escope/LICENSE.BSD b/tools/eslint/node_modules/escope/LICENSE.BSD
new file mode 100644
index 00000000000000..3e580c355a96e5
--- /dev/null
+++ b/tools/eslint/node_modules/escope/LICENSE.BSD
@@ -0,0 +1,19 @@
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/eslint/node_modules/escope/README.md b/tools/eslint/node_modules/escope/README.md
new file mode 100644
index 00000000000000..7650b24700268c
--- /dev/null
+++ b/tools/eslint/node_modules/escope/README.md
@@ -0,0 +1,77 @@
+Escope ([escope](http://github.com/estools/escope)) is
+[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
+scope analyzer extracted from [esmangle project](http://github.com/estools/esmangle).
+
+[![Build Status](https://travis-ci.org/estools/escope.png?branch=master)](https://travis-ci.org/estools/escope)
+
+### Example
+
+    var escope = require('escope');
+    var esprima = require('esprima');
+    var estraverse = require('estraverse');
+    
+    var ast = esprima.parse(code);
+    var scopeManager = escope.analyze(ast);
+    
+    var currentScope = scopeManager.acquire(ast);   // global scope
+
+    estraverse.traverse(ast, {
+        enter: function(node, parent) {
+            // do stuff
+            
+            if (/Function/.test(node.type)) {
+                currentScope = scopeManager.acquire(node);  // get current function scope
+            }
+        },
+        leave: function(node, parent) {
+            if (/Function/.test(node.type)) {
+                currentScope = currentScope.upper;  // set to parent scope
+            }
+            
+            // do stuff
+        }
+    });
+
+### Document
+
+Generated JSDoc is [here](http://estools.github.io/escope/).
+
+### Demos and Tools
+
+Demonstration is [here](http://mazurov.github.io/escope-demo/) by [Sasha Mazurov](https://github.com/mazurov) (twitter: [@mazurov](http://twitter.com/mazurov)). [issue](https://github.com/estools/escope/issues/14)
+
+![Demo](https://f.cloud.github.com/assets/75759/462920/7aa6dd40-b4f5-11e2-9f07-9f4e8d0415f9.gif)
+
+
+And there are tools constructed on Escope.
+
+- [Esmangle](https://github.com/estools/esmangle) is a minifier / mangler / optimizer.
+- [Eslevels](https://github.com/mazurov/eslevels) is a scope levels analyzer and [SublimeText plugin for scope context coloring](https://github.com/mazurov/sublime-levels) is constructed on it.
+- [Esgoggles](https://github.com/keeyipchan/esgoggles) is JavaScript code browser.
+
+
+### License
+
+Copyright (C) 2012-2013 [Yusuke Suzuki](http://github.com/Constellation)
+ (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+  * Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+
+  * Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in the
+    documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tools/eslint/node_modules/escope/bower.json b/tools/eslint/node_modules/escope/bower.json
new file mode 100644
index 00000000000000..70ad5e5ff3948c
--- /dev/null
+++ b/tools/eslint/node_modules/escope/bower.json
@@ -0,0 +1,13 @@
+{
+  "name": "escope",
+  "version": "2.0.2-dev",
+  "main": "escope.js",
+  "dependencies": {
+    "estraverse": ">= 0.0.2"
+  },
+  "ignore": [
+    "**/.*",
+    "node_modules",
+    "components"
+  ]
+}
diff --git a/tools/eslint/node_modules/escope/gulpfile.js b/tools/eslint/node_modules/escope/gulpfile.js
new file mode 100644
index 00000000000000..f38476b5310fa6
--- /dev/null
+++ b/tools/eslint/node_modules/escope/gulpfile.js
@@ -0,0 +1,145 @@
+/*
+  Copyright (C) 2014 Yusuke Suzuki 
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
+  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+  ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
+  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+'use strict';
+
+var gulp = require('gulp'),
+    mocha = require('gulp-mocha'),
+    babel = require('gulp-babel'),
+    git = require('gulp-git'),
+    bump = require('gulp-bump'),
+    filter = require('gulp-filter'),
+    tagVersion = require('gulp-tag-version'),
+    sourcemaps = require('gulp-sourcemaps'),
+    coffee = require('gulp-coffee'),
+    plumber = require('gulp-plumber'),
+    source = require('vinyl-source-stream'),
+    browserify = require('browserify'),
+    lazypipe = require('lazypipe'),
+    eslint = require('gulp-eslint'),
+    coffee = require('coffee-script/register');
+
+var TEST = [ 'test/*.coffee' ];
+var SOURCE = [ 'src/**/*.js' ];
+
+var ESLINT_OPTION = {
+    rules: {
+        'quotes': 0,
+        'eqeqeq': 0,
+        'no-use-before-define': 0,
+        'no-shadow': 0,
+        'no-new': 0,
+        'no-underscore-dangle': 0,
+        'no-multi-spaces': false,
+        'no-native-reassign': 0,
+        'no-loop-func': 0,
+        'no-lone-blocks': 0
+    },
+    settings: {
+        "ecmascript": 6,
+        "jsx": false
+    },
+    env: {
+        'node': true
+    }
+};
+
+var build = lazypipe()
+    .pipe(sourcemaps.init)
+    .pipe(babel)
+    .pipe(sourcemaps.write)
+    .pipe(gulp.dest, 'lib');
+
+gulp.task('build-for-watch', function () {
+    return gulp.src(SOURCE).pipe(plumber()).pipe(build());
+});
+
+gulp.task('build', function () {
+    return gulp.src(SOURCE).pipe(build());
+});
+
+gulp.task('browserify', [ 'build' ], function () {
+    return browserify({
+        entries: [ './lib/index.js' ]
+    })
+    .bundle()
+    .pipe(source('bundle.js'))
+    .pipe(gulp.dest('build'))
+});
+
+gulp.task('test', [ 'build' ], function () {
+    return gulp.src(TEST)
+        .pipe(mocha({
+            reporter: 'spec',
+            timeout: 100000 // 100s
+        }));
+});
+
+gulp.task('watch', [ 'build-for-watch' ], function () {
+    gulp.watch(SOURCE, [ 'build-for-watch' ]);
+});
+
+// Currently, not works for ES6.
+gulp.task('lint', function () {
+    return gulp.src(SOURCE)
+        .pipe(eslint(ESLINT_OPTION))
+        .pipe(eslint.formatEach('stylish', process.stderr))
+        .pipe(eslint.failOnError());
+});
+
+/**
+ * Bumping version number and tagging the repository with it.
+ * Please read http://semver.org/
+ *
+ * You can use the commands
+ *
+ *     gulp patch     # makes v0.1.0 -> v0.1.1
+ *     gulp feature   # makes v0.1.1 -> v0.2.0
+ *     gulp release   # makes v0.2.1 -> v1.0.0
+ *
+ * To bump the version numbers accordingly after you did a patch,
+ * introduced a feature or made a backwards-incompatible release.
+ */
+
+function inc(importance) {
+    // get all the files to bump version in
+    return gulp.src(['./package.json'])
+        // bump the version number in those files
+        .pipe(bump({type: importance}))
+        // save it back to filesystem
+        .pipe(gulp.dest('./'))
+        // commit the changed version number
+        .pipe(git.commit('Bumps package version'))
+        // read only one file to get the version number
+        .pipe(filter('package.json'))
+        // **tag it in the repository**
+        .pipe(tagVersion());
+}
+
+gulp.task('patch', [ 'build' ], function () { return inc('patch'); })
+gulp.task('minor', [ 'build' ], function () { return inc('minor'); })
+gulp.task('major', [ 'build' ], function () { return inc('major'); })
+
+gulp.task('travis', [ 'test' ]);
+gulp.task('default', [ 'travis' ]);
diff --git a/tools/eslint/node_modules/escope/lib/definition.js b/tools/eslint/node_modules/escope/lib/definition.js
new file mode 100644
index 00000000000000..5ff4f9751547bc
--- /dev/null
+++ b/tools/eslint/node_modules/escope/lib/definition.js
@@ -0,0 +1,100 @@
+"use strict";
+
+var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
+
+var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
+
+var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
+
+var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
+
+Object.defineProperty(exports, "__esModule", {
+  value: true
+});
+/*
+  Copyright (C) 2015 Yusuke Suzuki 
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+  ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
+  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+var Variable = _interopRequire(require("./variable"));
+
+/**
+ * @class Definition
+ */
+
+var Definition = function Definition(type, name, node, parent, index, kind) {
+  _classCallCheck(this, Definition);
+
+  /**
+   * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...).
+   */
+  this.type = type;
+  /**
+   * @member {esprima.Identifier} Definition#name - the identifier AST node of the occurrence.
+   */
+  this.name = name;
+  /**
+   * @member {esprima.Node} Definition#node - the enclosing node of the identifier.
+   */
+  this.node = node;
+  /**
+   * @member {esprima.Node?} Definition#parent - the enclosing statement node of the identifier.
+   */
+  this.parent = parent;
+  /**
+   * @member {Number?} Definition#index - the index in the declaration statement.
+   */
+  this.index = index;
+  /**
+   * @member {String?} Definition#kind - the kind of the declaration statement.
+   */
+  this.kind = kind;
+};
+
+exports["default"] = Definition;
+
+/**
+ * @class ParameterDefinition
+ */
+
+var ParameterDefinition = (function (_Definition) {
+  function ParameterDefinition(name, node, index, rest) {
+    _classCallCheck(this, ParameterDefinition);
+
+    _get(Object.getPrototypeOf(ParameterDefinition.prototype), "constructor", this).call(this, Variable.Parameter, name, node, null, index, null);
+    /**
+     * Whether the parameter definition is a part of a rest parameter.
+     * @member {boolean} ParameterDefinition#rest
+     */
+    this.rest = rest;
+  }
+
+  _inherits(ParameterDefinition, _Definition);
+
+  return ParameterDefinition;
+})(Definition);
+
+exports.ParameterDefinition = ParameterDefinition;
+
+/* vim: set sw=4 ts=4 et tw=80 : */
+exports.Definition = Definition;
+//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImRlZmluaXRpb24uanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztJQXdCTyxRQUFRLDJCQUFNLFlBQVk7Ozs7OztJQUtaLFVBQVUsR0FDaEIsU0FETSxVQUFVLENBQ2YsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsTUFBTSxFQUFFLEtBQUssRUFBRSxJQUFJLEVBQUU7d0JBRGxDLFVBQVU7Ozs7O0FBS3ZCLE1BQUksQ0FBQyxJQUFJLEdBQUcsSUFBSSxDQUFDOzs7O0FBSWpCLE1BQUksQ0FBQyxJQUFJLEdBQUcsSUFBSSxDQUFDOzs7O0FBSWpCLE1BQUksQ0FBQyxJQUFJLEdBQUcsSUFBSSxDQUFDOzs7O0FBSWpCLE1BQUksQ0FBQyxNQUFNLEdBQUcsTUFBTSxDQUFDOzs7O0FBSXJCLE1BQUksQ0FBQyxLQUFLLEdBQUcsS0FBSyxDQUFDOzs7O0FBSW5CLE1BQUksQ0FBQyxJQUFJLEdBQUcsSUFBSSxDQUFDO0NBQ3BCOztxQkExQmdCLFVBQVU7Ozs7OztJQWdDekIsbUJBQW1CO0FBQ1YsV0FEVCxtQkFBbUIsQ0FDVCxJQUFJLEVBQUUsSUFBSSxFQUFFLEtBQUssRUFBRSxJQUFJLEVBQUU7MEJBRG5DLG1CQUFtQjs7QUFFakIsK0JBRkYsbUJBQW1CLDZDQUVYLFFBQVEsQ0FBQyxTQUFTLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxJQUFJLEVBQUUsS0FBSyxFQUFFLElBQUksRUFBRTs7Ozs7QUFLekQsUUFBSSxDQUFDLElBQUksR0FBRyxJQUFJLENBQUM7R0FDcEI7O1lBUkMsbUJBQW1COztTQUFuQixtQkFBbUI7R0FBUyxVQUFVOztRQVl4QyxtQkFBbUIsR0FBbkIsbUJBQW1COzs7UUFDbkIsVUFBVSxHQUFWLFVBQVUiLCJmaWxlIjoiZGVmaW5pdGlvbi5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qXG4gIENvcHlyaWdodCAoQykgMjAxNSBZdXN1a2UgU3V6dWtpIDx1dGF0YW5lLnRlYUBnbWFpbC5jb20+XG5cbiAgUmVkaXN0cmlidXRpb24gYW5kIHVzZSBpbiBzb3VyY2UgYW5kIGJpbmFyeSBmb3Jtcywgd2l0aCBvciB3aXRob3V0XG4gIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmUgbWV0OlxuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICAgICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZSBjb3B5cmlnaHRcbiAgICAgIG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmcgZGlzY2xhaW1lciBpbiB0aGVcbiAgICAgIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZCB3aXRoIHRoZSBkaXN0cmlidXRpb24uXG5cbiAgVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SUyBcIkFTIElTXCJcbiAgQU5EIEFOWSBFWFBSRVNTIE9SIElNUExJRUQgV0FSUkFOVElFUywgSU5DTFVESU5HLCBCVVQgTk9UIExJTUlURUQgVE8sIFRIRVxuICBJTVBMSUVEIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZIEFORCBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRVxuICBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgPENPUFlSSUdIVCBIT0xERVI+IEJFIExJQUJMRSBGT1IgQU5ZXG4gIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsIFNQRUNJQUwsIEVYRU1QTEFSWSwgT1IgQ09OU0VRVUVOVElBTCBEQU1BR0VTXG4gIChJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgUFJPQ1VSRU1FTlQgT0YgU1VCU1RJVFVURSBHT09EUyBPUiBTRVJWSUNFUztcbiAgTE9TUyBPRiBVU0UsIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EXG4gIE9OIEFOWSBUSEVPUlkgT0YgTElBQklMSVRZLCBXSEVUSEVSIElOIENPTlRSQUNULCBTVFJJQ1QgTElBQklMSVRZLCBPUiBUT1JUXG4gIChJTkNMVURJTkcgTkVHTElHRU5DRSBPUiBPVEhFUldJU0UpIEFSSVNJTkcgSU4gQU5ZIFdBWSBPVVQgT0YgVEhFIFVTRSBPRlxuICBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuKi9cblxuaW1wb3J0IFZhcmlhYmxlIGZyb20gJy4vdmFyaWFibGUnO1xuXG4vKipcbiAqIEBjbGFzcyBEZWZpbml0aW9uXG4gKi9cbmV4cG9ydCBkZWZhdWx0IGNsYXNzIERlZmluaXRpb24ge1xuICAgIGNvbnN0cnVjdG9yKHR5cGUsIG5hbWUsIG5vZGUsIHBhcmVudCwgaW5kZXgsIGtpbmQpIHtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gRGVmaW5pdGlvbiN0eXBlIC0gdHlwZSBvZiB0aGUgb2NjdXJyZW5jZSAoZS5nLiBcIlBhcmFtZXRlclwiLCBcIlZhcmlhYmxlXCIsIC4uLikuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnR5cGUgPSB0eXBlO1xuICAgICAgICAvKipcbiAgICAgICAgICogQG1lbWJlciB7ZXNwcmltYS5JZGVudGlmaWVyfSBEZWZpbml0aW9uI25hbWUgLSB0aGUgaWRlbnRpZmllciBBU1Qgbm9kZSBvZiB0aGUgb2NjdXJyZW5jZS5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMubmFtZSA9IG5hbWU7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtlc3ByaW1hLk5vZGV9IERlZmluaXRpb24jbm9kZSAtIHRoZSBlbmNsb3Npbmcgbm9kZSBvZiB0aGUgaWRlbnRpZmllci5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMubm9kZSA9IG5vZGU7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtlc3ByaW1hLk5vZGU/fSBEZWZpbml0aW9uI3BhcmVudCAtIHRoZSBlbmNsb3Npbmcgc3RhdGVtZW50IG5vZGUgb2YgdGhlIGlkZW50aWZpZXIuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnBhcmVudCA9IHBhcmVudDtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge051bWJlcj99IERlZmluaXRpb24jaW5kZXggLSB0aGUgaW5kZXggaW4gdGhlIGRlY2xhcmF0aW9uIHN0YXRlbWVudC5cbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuaW5kZXggPSBpbmRleDtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZz99IERlZmluaXRpb24ja2luZCAtIHRoZSBraW5kIG9mIHRoZSBkZWNsYXJhdGlvbiBzdGF0ZW1lbnQuXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmtpbmQgPSBraW5kO1xuICAgIH1cbn1cblxuLyoqXG4gKiBAY2xhc3MgUGFyYW1ldGVyRGVmaW5pdGlvblxuICovXG5jbGFzcyBQYXJhbWV0ZXJEZWZpbml0aW9uIGV4dGVuZHMgRGVmaW5pdGlvbiB7XG4gICAgY29uc3RydWN0b3IobmFtZSwgbm9kZSwgaW5kZXgsIHJlc3QpIHtcbiAgICAgICAgc3VwZXIoVmFyaWFibGUuUGFyYW1ldGVyLCBuYW1lLCBub2RlLCBudWxsLCBpbmRleCwgbnVsbCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBXaGV0aGVyIHRoZSBwYXJhbWV0ZXIgZGVmaW5pdGlvbiBpcyBhIHBhcnQgb2YgYSByZXN0IHBhcmFtZXRlci5cbiAgICAgICAgICogQG1lbWJlciB7Ym9vbGVhbn0gUGFyYW1ldGVyRGVmaW5pdGlvbiNyZXN0XG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnJlc3QgPSByZXN0O1xuICAgIH1cbn1cblxuZXhwb3J0IHtcbiAgICBQYXJhbWV0ZXJEZWZpbml0aW9uLFxuICAgIERlZmluaXRpb25cbn1cblxuLyogdmltOiBzZXQgc3c9NCB0cz00IGV0IHR3PTgwIDogKi9cbiJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ==
\ No newline at end of file
diff --git a/tools/eslint/node_modules/escope/lib/index.js b/tools/eslint/node_modules/escope/lib/index.js
new file mode 100644
index 00000000000000..58964e061b8c19
--- /dev/null
+++ b/tools/eslint/node_modules/escope/lib/index.js
@@ -0,0 +1,154 @@
+"use strict";
+
+var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
+
+/**
+ * Main interface function. Takes an Esprima syntax tree and returns the
+ * analyzed scopes.
+ * @function analyze
+ * @param {esprima.Tree} tree
+ * @param {Object} providedOptions - Options that tailor the scope analysis
+ * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag
+ * @param {boolean} [providedOptions.directive=false]- the directive flag
+ * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls
+ * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole
+ * script is executed under node.js environment. When enabled, escope adds
+ * a function scope immediately following the global scope.
+ * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module'
+ * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered
+ * @return {ScopeManager}
+ */
+exports.analyze = analyze;
+Object.defineProperty(exports, "__esModule", {
+    value: true
+});
+/*
+  Copyright (C) 2012-2014 Yusuke Suzuki 
+  Copyright (C) 2013 Alex Seville 
+  Copyright (C) 2014 Thiago de Arruda 
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+  ARE DISCLAIMED. IN NO EVENT SHALL  BE LIABLE FOR ANY
+  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * Escope (escope) is an ECMAScript
+ * scope analyzer extracted from the esmangle project.
+ * 

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. esprima is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ + +/*jslint bitwise:true */ + +var assert = _interopRequire(require("assert")); + +var ScopeManager = _interopRequire(require("./scope-manager")); + +var Referencer = _interopRequire(require("./referencer")); + +var Reference = _interopRequire(require("./reference")); + +var Variable = _interopRequire(require("./variable")); + +var Scope = _interopRequire(require("./scope")); + +var version = require("../package.json").version; + +function defaultOptions() { + return { + optimistic: false, + directive: false, + nodejsScope: false, + sourceType: "script", // one of ['script', 'module'] + ecmaVersion: 5 + }; +} + +function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === "object" && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} +function analyze(tree, providedOptions) { + var scopeManager, referencer, options; + + options = updateDeeply(defaultOptions(), providedOptions); + + scopeManager = new ScopeManager(options); + + referencer = new Referencer(scopeManager); + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, "currentScope should be null."); + + return scopeManager; +} + +exports.version = version; + +/* vim: set sw=4 ts=4 et tw=80 : */ +exports.Reference = Reference; +exports.Variable = Variable; +exports.Scope = Scope; +exports.ScopeManager = ScopeManager; + +/** @name module:escope.version */ + +/** @name module:escope.Reference */ + +/** @name module:escope.Variable */ + +/** @name module:escope.Scope */ + +/** @name module:escope.ScopeManager */ +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O1FBNkdnQixPQUFPLEdBQVAsT0FBTzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0lBM0RoQixNQUFNLDJCQUFNLFFBQVE7O0lBRXBCLFlBQVksMkJBQU0saUJBQWlCOztJQUNuQyxVQUFVLDJCQUFNLGNBQWM7O0lBQzlCLFNBQVMsMkJBQU0sYUFBYTs7SUFDNUIsUUFBUSwyQkFBTSxZQUFZOztJQUMxQixLQUFLLDJCQUFNLFNBQVM7O0lBQ2xCLE9BQU8sV0FBUSxpQkFBaUIsRUFBaEMsT0FBTzs7QUFFaEIsU0FBUyxjQUFjLEdBQUc7QUFDdEIsV0FBTztBQUNILGtCQUFVLEVBQUUsS0FBSztBQUNqQixpQkFBUyxFQUFFLEtBQUs7QUFDaEIsbUJBQVcsRUFBRSxLQUFLO0FBQ2xCLGtCQUFVLEVBQUUsUUFBUTtBQUNwQixtQkFBVyxFQUFFLENBQUM7S0FDakIsQ0FBQztDQUNMOztBQUVELFNBQVMsWUFBWSxDQUFDLE1BQU0sRUFBRSxRQUFRLEVBQUU7QUFDcEMsUUFBSSxHQUFHLEVBQUUsR0FBRyxDQUFDOztBQUViLGFBQVMsWUFBWSxDQUFDLE1BQU0sRUFBRTtBQUMxQixlQUFPLE9BQU8sTUFBTSxLQUFLLFFBQVEsSUFBSSxNQUFNLFlBQVksTUFBTSxJQUFJLEVBQUUsTUFBTSxZQUFZLE1BQU0sQ0FBQSxBQUFDLENBQUM7S0FDaEc7O0FBRUQsU0FBSyxHQUFHLElBQUksUUFBUSxFQUFFO0FBQ2xCLFlBQUksUUFBUSxDQUFDLGNBQWMsQ0FBQyxHQUFHLENBQUMsRUFBRTtBQUM5QixlQUFHLEdBQUcsUUFBUSxDQUFDLEdBQUcsQ0FBQyxDQUFDO0FBQ3BCLGdCQUFJLFlBQVksQ0FBQyxHQUFHLENBQUMsRUFBRTtBQUNuQixvQkFBSSxZQUFZLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLEVBQUU7QUFDM0IsZ0NBQVksQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsR0FBRyxDQUFDLENBQUM7aUJBQ2xDLE1BQU07QUFDSCwwQkFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLFlBQVksQ0FBQyxFQUFFLEVBQUUsR0FBRyxDQUFDLENBQUM7aUJBQ3ZDO2FBQ0osTUFBTTtBQUNILHNCQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsR0FBRyxDQUFDO2FBQ3JCO1NBQ0o7S0FDSjtBQUNELFdBQU8sTUFBTSxDQUFDO0NBQ2pCO0FBa0JNLFNBQVMsT0FBTyxDQUFDLElBQUksRUFBRSxlQUFlLEVBQUU7QUFDM0MsUUFBSSxZQUFZLEVBQUUsVUFBVSxFQUFFLE9BQU8sQ0FBQzs7QUFFdEMsV0FBTyxHQUFHLFlBQVksQ0FBQyxjQUFjLEVBQUUsRUFBRSxlQUFlLENBQUMsQ0FBQzs7QUFFMUQsZ0JBQVksR0FBRyxJQUFJLFlBQVksQ0FBQyxPQUFPLENBQUMsQ0FBQzs7QUFFekMsY0FBVSxHQUFHLElBQUksVUFBVSxDQUFDLFlBQVksQ0FBQyxDQUFDO0FBQzFDLGNBQVUsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7O0FBRXZCLFVBQU0sQ0FBQyxZQUFZLENBQUMsY0FBYyxLQUFLLElBQUksRUFBRSw4QkFBOEIsQ0FBQyxDQUFDOztBQUU3RSxXQUFPLFlBQVksQ0FBQztDQUN2Qjs7UUFJRyxPQUFPLEdBQVAsT0FBTzs7O1FBRVAsU0FBUyxHQUFULFNBQVM7UUFFVCxRQUFRLEdBQVIsUUFBUTtRQUVSLEtBQUssR0FBTCxLQUFLO1FBRUwsWUFBWSxHQUFaLFlBQVkiLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VzQ29udGVudCI6WyIvKlxuICBDb3B5cmlnaHQgKEMpIDIwMTItMjAxNCBZdXN1a2UgU3V6dWtpIDx1dGF0YW5lLnRlYUBnbWFpbC5jb20+XG4gIENvcHlyaWdodCAoQykgMjAxMyBBbGV4IFNldmlsbGUgPGhpQGFsZXhhbmRlcnNldmlsbGUuY29tPlxuICBDb3B5cmlnaHQgKEMpIDIwMTQgVGhpYWdvIGRlIEFycnVkYSA8dHBhZGlsaGE4NEBnbWFpbC5jb20+XG5cbiAgUmVkaXN0cmlidXRpb24gYW5kIHVzZSBpbiBzb3VyY2UgYW5kIGJpbmFyeSBmb3Jtcywgd2l0aCBvciB3aXRob3V0XG4gIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmUgbWV0OlxuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICAgICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZSBjb3B5cmlnaHRcbiAgICAgIG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmcgZGlzY2xhaW1lciBpbiB0aGVcbiAgICAgIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZCB3aXRoIHRoZSBkaXN0cmlidXRpb24uXG5cbiAgVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SUyBcIkFTIElTXCJcbiAgQU5EIEFOWSBFWFBSRVNTIE9SIElNUExJRUQgV0FSUkFOVElFUywgSU5DTFVESU5HLCBCVVQgTk9UIExJTUlURUQgVE8sIFRIRVxuICBJTVBMSUVEIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZIEFORCBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRVxuICBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgPENPUFlSSUdIVCBIT0xERVI+IEJFIExJQUJMRSBGT1IgQU5ZXG4gIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsIFNQRUNJQUwsIEVYRU1QTEFSWSwgT1IgQ09OU0VRVUVOVElBTCBEQU1BR0VTXG4gIChJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgUFJPQ1VSRU1FTlQgT0YgU1VCU1RJVFVURSBHT09EUyBPUiBTRVJWSUNFUztcbiAgTE9TUyBPRiBVU0UsIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EXG4gIE9OIEFOWSBUSEVPUlkgT0YgTElBQklMSVRZLCBXSEVUSEVSIElOIENPTlRSQUNULCBTVFJJQ1QgTElBQklMSVRZLCBPUiBUT1JUXG4gIChJTkNMVURJTkcgTkVHTElHRU5DRSBPUiBPVEhFUldJU0UpIEFSSVNJTkcgSU4gQU5ZIFdBWSBPVVQgT0YgVEhFIFVTRSBPRlxuICBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuKi9cblxuLyoqXG4gKiBFc2NvcGUgKDxhIGhyZWY9XCJodHRwOi8vZ2l0aHViLmNvbS9lc3Rvb2xzL2VzY29wZVwiPmVzY29wZTwvYT4pIGlzIGFuIDxhXG4gKiBocmVmPVwiaHR0cDovL3d3dy5lY21hLWludGVybmF0aW9uYWwub3JnL3B1YmxpY2F0aW9ucy9zdGFuZGFyZHMvRWNtYS0yNjIuaHRtXCI+RUNNQVNjcmlwdDwvYT5cbiAqIHNjb3BlIGFuYWx5emVyIGV4dHJhY3RlZCBmcm9tIHRoZSA8YVxuICogaHJlZj1cImh0dHA6Ly9naXRodWIuY29tL2VzdG9vbHMvZXNtYW5nbGVcIj5lc21hbmdsZSBwcm9qZWN0PC9hLz4uXG4gKiA8cD5cbiAqIDxlbT5lc2NvcGU8L2VtPiBmaW5kcyBsZXhpY2FsIHNjb3BlcyBpbiBhIHNvdXJjZSBwcm9ncmFtLCBpLmUuIGFyZWFzIG9mIHRoYXRcbiAqIHByb2dyYW0gd2hlcmUgZGlmZmVyZW50IG9jY3VycmVuY2VzIG9mIHRoZSBzYW1lIGlkZW50aWZpZXIgcmVmZXIgdG8gdGhlIHNhbWVcbiAqIHZhcmlhYmxlLiBXaXRoIGVhY2ggc2NvcGUgdGhlIGNvbnRhaW5lZCB2YXJpYWJsZXMgYXJlIGNvbGxlY3RlZCwgYW5kIGVhY2hcbiAqIGlkZW50aWZpZXIgcmVmZXJlbmNlIGluIGNvZGUgaXMgbGlua2VkIHRvIGl0cyBjb3JyZXNwb25kaW5nIHZhcmlhYmxlIChpZlxuICogcG9zc2libGUpLlxuICogPHA+XG4gKiA8ZW0+ZXNjb3BlPC9lbT4gd29ya3Mgb24gYSBzeW50YXggdHJlZSBvZiB0aGUgcGFyc2VkIHNvdXJjZSBjb2RlIHdoaWNoIGhhc1xuICogdG8gYWRoZXJlIHRvIHRoZSA8YVxuICogaHJlZj1cImh0dHBzOi8vZGV2ZWxvcGVyLm1vemlsbGEub3JnL2VuLVVTL2RvY3MvU3BpZGVyTW9ua2V5L1BhcnNlcl9BUElcIj5cbiAqIE1vemlsbGEgUGFyc2VyIEFQSTwvYT4uIEUuZy4gPGEgaHJlZj1cImh0dHA6Ly9lc3ByaW1hLm9yZ1wiPmVzcHJpbWE8L2E+IGlzIGEgcGFyc2VyXG4gKiB0aGF0IHByb2R1Y2VzIHN1Y2ggc3ludGF4IHRyZWVzLlxuICogPHA+XG4gKiBUaGUgbWFpbiBpbnRlcmZhY2UgaXMgdGhlIHtAbGluayBhbmFseXplfSBmdW5jdGlvbi5cbiAqIEBtb2R1bGUgZXNjb3BlXG4gKi9cblxuLypqc2xpbnQgYml0d2lzZTp0cnVlICovXG5cbmltcG9ydCBhc3NlcnQgZnJvbSAnYXNzZXJ0JztcblxuaW1wb3J0IFNjb3BlTWFuYWdlciBmcm9tICcuL3Njb3BlLW1hbmFnZXInO1xuaW1wb3J0IFJlZmVyZW5jZXIgZnJvbSAnLi9yZWZlcmVuY2VyJztcbmltcG9ydCBSZWZlcmVuY2UgZnJvbSAnLi9yZWZlcmVuY2UnO1xuaW1wb3J0IFZhcmlhYmxlIGZyb20gJy4vdmFyaWFibGUnO1xuaW1wb3J0IFNjb3BlIGZyb20gJy4vc2NvcGUnO1xuaW1wb3J0IHsgdmVyc2lvbiB9IGZyb20gJy4uL3BhY2thZ2UuanNvbic7XG5cbmZ1bmN0aW9uIGRlZmF1bHRPcHRpb25zKCkge1xuICAgIHJldHVybiB7XG4gICAgICAgIG9wdGltaXN0aWM6IGZhbHNlLFxuICAgICAgICBkaXJlY3RpdmU6IGZhbHNlLFxuICAgICAgICBub2RlanNTY29wZTogZmFsc2UsXG4gICAgICAgIHNvdXJjZVR5cGU6ICdzY3JpcHQnLCAgLy8gb25lIG9mIFsnc2NyaXB0JywgJ21vZHVsZSddXG4gICAgICAgIGVjbWFWZXJzaW9uOiA1XG4gICAgfTtcbn1cblxuZnVuY3Rpb24gdXBkYXRlRGVlcGx5KHRhcmdldCwgb3ZlcnJpZGUpIHtcbiAgICB2YXIga2V5LCB2YWw7XG5cbiAgICBmdW5jdGlvbiBpc0hhc2hPYmplY3QodGFyZ2V0KSB7XG4gICAgICAgIHJldHVybiB0eXBlb2YgdGFyZ2V0ID09PSAnb2JqZWN0JyAmJiB0YXJnZXQgaW5zdGFuY2VvZiBPYmplY3QgJiYgISh0YXJnZXQgaW5zdGFuY2VvZiBSZWdFeHApO1xuICAgIH1cblxuICAgIGZvciAoa2V5IGluIG92ZXJyaWRlKSB7XG4gICAgICAgIGlmIChvdmVycmlkZS5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICAgICAgICB2YWwgPSBvdmVycmlkZVtrZXldO1xuICAgICAgICAgICAgaWYgKGlzSGFzaE9iamVjdCh2YWwpKSB7XG4gICAgICAgICAgICAgICAgaWYgKGlzSGFzaE9iamVjdCh0YXJnZXRba2V5XSkpIHtcbiAgICAgICAgICAgICAgICAgICAgdXBkYXRlRGVlcGx5KHRhcmdldFtrZXldLCB2YWwpO1xuICAgICAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgIHRhcmdldFtrZXldID0gdXBkYXRlRGVlcGx5KHt9LCB2YWwpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgdGFyZ2V0W2tleV0gPSB2YWw7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICB9XG4gICAgcmV0dXJuIHRhcmdldDtcbn1cblxuLyoqXG4gKiBNYWluIGludGVyZmFjZSBmdW5jdGlvbi4gVGFrZXMgYW4gRXNwcmltYSBzeW50YXggdHJlZSBhbmQgcmV0dXJucyB0aGVcbiAqIGFuYWx5emVkIHNjb3Blcy5cbiAqIEBmdW5jdGlvbiBhbmFseXplXG4gKiBAcGFyYW0ge2VzcHJpbWEuVHJlZX0gdHJlZVxuICogQHBhcmFtIHtPYmplY3R9IHByb3ZpZGVkT3B0aW9ucyAtIE9wdGlvbnMgdGhhdCB0YWlsb3IgdGhlIHNjb3BlIGFuYWx5c2lzXG4gKiBAcGFyYW0ge2Jvb2xlYW59IFtwcm92aWRlZE9wdGlvbnMub3B0aW1pc3RpYz1mYWxzZV0gLSB0aGUgb3B0aW1pc3RpYyBmbGFnXG4gKiBAcGFyYW0ge2Jvb2xlYW59IFtwcm92aWRlZE9wdGlvbnMuZGlyZWN0aXZlPWZhbHNlXS0gdGhlIGRpcmVjdGl2ZSBmbGFnXG4gKiBAcGFyYW0ge2Jvb2xlYW59IFtwcm92aWRlZE9wdGlvbnMuaWdub3JlRXZhbD1mYWxzZV0tIHdoZXRoZXIgdG8gY2hlY2sgJ2V2YWwoKScgY2FsbHNcbiAqIEBwYXJhbSB7Ym9vbGVhbn0gW3Byb3ZpZGVkT3B0aW9ucy5ub2RlanNTY29wZT1mYWxzZV0tIHdoZXRoZXIgdGhlIHdob2xlXG4gKiBzY3JpcHQgaXMgZXhlY3V0ZWQgdW5kZXIgbm9kZS5qcyBlbnZpcm9ubWVudC4gV2hlbiBlbmFibGVkLCBlc2NvcGUgYWRkc1xuICogYSBmdW5jdGlvbiBzY29wZSBpbW1lZGlhdGVseSBmb2xsb3dpbmcgdGhlIGdsb2JhbCBzY29wZS5cbiAqIEBwYXJhbSB7c3RyaW5nfSBbcHJvdmlkZWRPcHRpb25zLnNvdXJjZVR5cGU9J3NjcmlwdCddLSB0aGUgc291cmNlIHR5cGUgb2YgdGhlIHNjcmlwdC4gb25lIG9mICdzY3JpcHQnIGFuZCAnbW9kdWxlJ1xuICogQHBhcmFtIHtudW1iZXJ9IFtwcm92aWRlZE9wdGlvbnMuZWNtYVZlcnNpb249NV0tIHdoaWNoIEVDTUFTY3JpcHQgdmVyc2lvbiBpcyBjb25zaWRlcmVkXG4gKiBAcmV0dXJuIHtTY29wZU1hbmFnZXJ9XG4gKi9cbmV4cG9ydCBmdW5jdGlvbiBhbmFseXplKHRyZWUsIHByb3ZpZGVkT3B0aW9ucykge1xuICAgIHZhciBzY29wZU1hbmFnZXIsIHJlZmVyZW5jZXIsIG9wdGlvbnM7XG5cbiAgICBvcHRpb25zID0gdXBkYXRlRGVlcGx5KGRlZmF1bHRPcHRpb25zKCksIHByb3ZpZGVkT3B0aW9ucyk7XG5cbiAgICBzY29wZU1hbmFnZXIgPSBuZXcgU2NvcGVNYW5hZ2VyKG9wdGlvbnMpO1xuXG4gICAgcmVmZXJlbmNlciA9IG5ldyBSZWZlcmVuY2VyKHNjb3BlTWFuYWdlcik7XG4gICAgcmVmZXJlbmNlci52aXNpdCh0cmVlKTtcblxuICAgIGFzc2VydChzY29wZU1hbmFnZXIuX19jdXJyZW50U2NvcGUgPT09IG51bGwsICdjdXJyZW50U2NvcGUgc2hvdWxkIGJlIG51bGwuJyk7XG5cbiAgICByZXR1cm4gc2NvcGVNYW5hZ2VyO1xufVxuXG5leHBvcnQge1xuICAgIC8qKiBAbmFtZSBtb2R1bGU6ZXNjb3BlLnZlcnNpb24gKi9cbiAgICB2ZXJzaW9uLFxuICAgIC8qKiBAbmFtZSBtb2R1bGU6ZXNjb3BlLlJlZmVyZW5jZSAqL1xuICAgIFJlZmVyZW5jZSxcbiAgICAvKiogQG5hbWUgbW9kdWxlOmVzY29wZS5WYXJpYWJsZSAqL1xuICAgIFZhcmlhYmxlLFxuICAgIC8qKiBAbmFtZSBtb2R1bGU6ZXNjb3BlLlNjb3BlICovXG4gICAgU2NvcGUsXG4gICAgLyoqIEBuYW1lIG1vZHVsZTplc2NvcGUuU2NvcGVNYW5hZ2VyICovXG4gICAgU2NvcGVNYW5hZ2VyXG59O1xuXG5cbi8qIHZpbTogc2V0IHN3PTQgdHM9NCBldCB0dz04MCA6ICovXG4iXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0= \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/lib/reference.js b/tools/eslint/node_modules/escope/lib/reference.js new file mode 100644 index 00000000000000..65f45d78dfebeb --- /dev/null +++ b/tools/eslint/node_modules/escope/lib/reference.js @@ -0,0 +1,184 @@ +"use strict"; + +var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +var READ = 1; +var WRITE = 2; +var RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ + +var Reference = (function () { + function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial) { + _classCallCheck(this, Reference); + + /** + * Identifier syntax node. + * @member {esprima#Identifier} Reference#identifier + */ + this.identifier = ident; + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + /** + * If reference is writeable, this is the tree being written to it. + * @member {esprima#Node} Reference#writeExpr + */ + this.writeExpr = writeExpr; + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + _createClass(Reference, { + isStatic: { + + /** + * Whether the reference is static. + * @method Reference#isStatic + * @return {boolean} + */ + + value: function isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + }, + isWrite: { + + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @return {boolean} + */ + + value: function isWrite() { + return !!(this.flag & Reference.WRITE); + } + }, + isRead: { + + /** + * Whether the reference is readable. + * @method Reference#isRead + * @return {boolean} + */ + + value: function isRead() { + return !!(this.flag & Reference.READ); + } + }, + isReadOnly: { + + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @return {boolean} + */ + + value: function isReadOnly() { + return this.flag === Reference.READ; + } + }, + isWriteOnly: { + + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @return {boolean} + */ + + value: function isWriteOnly() { + return this.flag === Reference.WRITE; + } + }, + isReadWrite: { + + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @return {boolean} + */ + + value: function isReadWrite() { + return this.flag === Reference.RW; + } + } + }); + + return Reference; +})(); + +module.exports = Reference; + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +/* vim: set sw=4 ts=4 et tw=80 : */ +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInJlZmVyZW5jZS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUF3QkEsSUFBTSxJQUFJLEdBQUcsQ0FBRyxDQUFDO0FBQ2pCLElBQU0sS0FBSyxHQUFHLENBQUcsQ0FBQztBQUNsQixJQUFNLEVBQUUsR0FBRyxJQUFJLEdBQUcsS0FBSyxDQUFDOzs7Ozs7O0lBTUgsU0FBUztBQUNmLFdBRE0sU0FBUyxDQUNkLEtBQUssRUFBRSxLQUFLLEVBQUUsSUFBSSxFQUFHLFNBQVMsRUFBRSxtQkFBbUIsRUFBRSxPQUFPLEVBQUU7MEJBRHpELFNBQVM7Ozs7OztBQU10QixRQUFJLENBQUMsVUFBVSxHQUFHLEtBQUssQ0FBQzs7Ozs7QUFLeEIsUUFBSSxDQUFDLElBQUksR0FBRyxLQUFLLENBQUM7Ozs7OztBQU1sQixRQUFJLENBQUMsT0FBTyxHQUFHLEtBQUssQ0FBQzs7Ozs7QUFLckIsUUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLENBQUM7Ozs7Ozs7QUFPckIsUUFBSSxDQUFDLElBQUksR0FBRyxJQUFJLENBQUM7QUFDakIsUUFBSSxJQUFJLENBQUMsT0FBTyxFQUFFLEVBQUU7Ozs7O0FBS2hCLFVBQUksQ0FBQyxTQUFTLEdBQUcsU0FBUyxDQUFDOzs7OztBQUszQixVQUFJLENBQUMsT0FBTyxHQUFHLE9BQU8sQ0FBQztLQUMxQjtBQUNELFFBQUksQ0FBQyxxQkFBcUIsR0FBRyxtQkFBbUIsQ0FBQztHQUNwRDs7ZUEzQ2dCLFNBQVM7QUFrRDFCLFlBQVE7Ozs7Ozs7O2FBQUEsb0JBQUc7QUFDUCxlQUFPLENBQUMsSUFBSSxDQUFDLE9BQU8sSUFBSSxJQUFJLENBQUMsUUFBUSxJQUFJLElBQUksQ0FBQyxRQUFRLENBQUMsS0FBSyxDQUFDLFFBQVEsRUFBRSxDQUFDO09BQzNFOztBQU9ELFdBQU87Ozs7Ozs7O2FBQUEsbUJBQUc7QUFDTixlQUFPLENBQUMsRUFBRSxJQUFJLENBQUMsSUFBSSxHQUFHLFNBQVMsQ0FBQyxLQUFLLENBQUEsQUFBQyxDQUFDO09BQzFDOztBQU9ELFVBQU07Ozs7Ozs7O2FBQUEsa0JBQUc7QUFDTCxlQUFPLENBQUMsRUFBRSxJQUFJLENBQUMsSUFBSSxHQUFHLFNBQVMsQ0FBQyxJQUFJLENBQUEsQUFBQyxDQUFDO09BQ3pDOztBQU9ELGNBQVU7Ozs7Ozs7O2FBQUEsc0JBQUc7QUFDVCxlQUFPLElBQUksQ0FBQyxJQUFJLEtBQUssU0FBUyxDQUFDLElBQUksQ0FBQztPQUN2Qzs7QUFPRCxlQUFXOzs7Ozs7OzthQUFBLHVCQUFHO0FBQ1YsZUFBTyxJQUFJLENBQUMsSUFBSSxLQUFLLFNBQVMsQ0FBQyxLQUFLLENBQUM7T0FDeEM7O0FBT0QsZUFBVzs7Ozs7Ozs7YUFBQSx1QkFBRztBQUNWLGVBQU8sSUFBSSxDQUFDLElBQUksS0FBSyxTQUFTLENBQUMsRUFBRSxDQUFDO09BQ3JDOzs7O1NBakdnQixTQUFTOzs7aUJBQVQsU0FBUzs7Ozs7O0FBd0c5QixTQUFTLENBQUMsSUFBSSxHQUFHLElBQUksQ0FBQzs7Ozs7QUFLdEIsU0FBUyxDQUFDLEtBQUssR0FBRyxLQUFLLENBQUM7Ozs7O0FBS3hCLFNBQVMsQ0FBQyxFQUFFLEdBQUcsRUFBRSxDQUFDIiwiZmlsZSI6InJlZmVyZW5jZS5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qXG4gIENvcHlyaWdodCAoQykgMjAxNSBZdXN1a2UgU3V6dWtpIDx1dGF0YW5lLnRlYUBnbWFpbC5jb20+XG5cbiAgUmVkaXN0cmlidXRpb24gYW5kIHVzZSBpbiBzb3VyY2UgYW5kIGJpbmFyeSBmb3Jtcywgd2l0aCBvciB3aXRob3V0XG4gIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmUgbWV0OlxuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICAgICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZSBjb3B5cmlnaHRcbiAgICAgIG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmcgZGlzY2xhaW1lciBpbiB0aGVcbiAgICAgIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZCB3aXRoIHRoZSBkaXN0cmlidXRpb24uXG5cbiAgVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SUyBcIkFTIElTXCJcbiAgQU5EIEFOWSBFWFBSRVNTIE9SIElNUExJRUQgV0FSUkFOVElFUywgSU5DTFVESU5HLCBCVVQgTk9UIExJTUlURUQgVE8sIFRIRVxuICBJTVBMSUVEIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZIEFORCBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRVxuICBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgPENPUFlSSUdIVCBIT0xERVI+IEJFIExJQUJMRSBGT1IgQU5ZXG4gIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsIFNQRUNJQUwsIEVYRU1QTEFSWSwgT1IgQ09OU0VRVUVOVElBTCBEQU1BR0VTXG4gIChJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgUFJPQ1VSRU1FTlQgT0YgU1VCU1RJVFVURSBHT09EUyBPUiBTRVJWSUNFUztcbiAgTE9TUyBPRiBVU0UsIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EXG4gIE9OIEFOWSBUSEVPUlkgT0YgTElBQklMSVRZLCBXSEVUSEVSIElOIENPTlRSQUNULCBTVFJJQ1QgTElBQklMSVRZLCBPUiBUT1JUXG4gIChJTkNMVURJTkcgTkVHTElHRU5DRSBPUiBPVEhFUldJU0UpIEFSSVNJTkcgSU4gQU5ZIFdBWSBPVVQgT0YgVEhFIFVTRSBPRlxuICBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuKi9cblxuY29uc3QgUkVBRCA9IDB4MTtcbmNvbnN0IFdSSVRFID0gMHgyO1xuY29uc3QgUlcgPSBSRUFEIHwgV1JJVEU7XG5cbi8qKlxuICogQSBSZWZlcmVuY2UgcmVwcmVzZW50cyBhIHNpbmdsZSBvY2N1cnJlbmNlIG9mIGFuIGlkZW50aWZpZXIgaW4gY29kZS5cbiAqIEBjbGFzcyBSZWZlcmVuY2VcbiAqL1xuZXhwb3J0IGRlZmF1bHQgY2xhc3MgUmVmZXJlbmNlIHtcbiAgICBjb25zdHJ1Y3RvcihpZGVudCwgc2NvcGUsIGZsYWcsICB3cml0ZUV4cHIsIG1heWJlSW1wbGljaXRHbG9iYWwsIHBhcnRpYWwpIHtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIElkZW50aWZpZXIgc3ludGF4IG5vZGUuXG4gICAgICAgICAqIEBtZW1iZXIge2VzcHJpbWEjSWRlbnRpZmllcn0gUmVmZXJlbmNlI2lkZW50aWZpZXJcbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuaWRlbnRpZmllciA9IGlkZW50O1xuICAgICAgICAvKipcbiAgICAgICAgICogUmVmZXJlbmNlIHRvIHRoZSBlbmNsb3NpbmcgU2NvcGUuXG4gICAgICAgICAqIEBtZW1iZXIge1Njb3BlfSBSZWZlcmVuY2UjZnJvbVxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5mcm9tID0gc2NvcGU7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBXaGV0aGVyIHRoZSByZWZlcmVuY2UgY29tZXMgZnJvbSBhIGR5bmFtaWMgc2NvcGUgKHN1Y2ggYXMgJ2V2YWwnLFxuICAgICAgICAgKiAnd2l0aCcsIGV0Yy4pLCBhbmQgbWF5IGJlIHRyYXBwZWQgYnkgZHluYW1pYyBzY29wZXMuXG4gICAgICAgICAqIEBtZW1iZXIge2Jvb2xlYW59IFJlZmVyZW5jZSN0YWludGVkXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnRhaW50ZWQgPSBmYWxzZTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoZSB2YXJpYWJsZSB0aGlzIHJlZmVyZW5jZSBpcyByZXNvbHZlZCB3aXRoLlxuICAgICAgICAgKiBAbWVtYmVyIHtWYXJpYWJsZX0gUmVmZXJlbmNlI3Jlc29sdmVkXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnJlc29sdmVkID0gbnVsbDtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFRoZSByZWFkLXdyaXRlIG1vZGUgb2YgdGhlIHJlZmVyZW5jZS4gKFZhbHVlIGlzIG9uZSBvZiB7QGxpbmtcbiAgICAgICAgICogUmVmZXJlbmNlLlJFQUR9LCB7QGxpbmsgUmVmZXJlbmNlLlJXfSwge0BsaW5rIFJlZmVyZW5jZS5XUklURX0pLlxuICAgICAgICAgKiBAbWVtYmVyIHtudW1iZXJ9IFJlZmVyZW5jZSNmbGFnXG4gICAgICAgICAqIEBwcml2YXRlXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmZsYWcgPSBmbGFnO1xuICAgICAgICBpZiAodGhpcy5pc1dyaXRlKCkpIHtcbiAgICAgICAgICAgIC8qKlxuICAgICAgICAgICAgICogSWYgcmVmZXJlbmNlIGlzIHdyaXRlYWJsZSwgdGhpcyBpcyB0aGUgdHJlZSBiZWluZyB3cml0dGVuIHRvIGl0LlxuICAgICAgICAgICAgICogQG1lbWJlciB7ZXNwcmltYSNOb2RlfSBSZWZlcmVuY2Ujd3JpdGVFeHByXG4gICAgICAgICAgICAgKi9cbiAgICAgICAgICAgIHRoaXMud3JpdGVFeHByID0gd3JpdGVFeHByO1xuICAgICAgICAgICAgLyoqXG4gICAgICAgICAgICAgKiBXaGV0aGVyIHRoZSBSZWZlcmVuY2UgbWlnaHQgcmVmZXIgdG8gYSBwYXJ0aWFsIHZhbHVlIG9mIHdyaXRlRXhwci5cbiAgICAgICAgICAgICAqIEBtZW1iZXIge2Jvb2xlYW59IFJlZmVyZW5jZSNwYXJ0aWFsXG4gICAgICAgICAgICAgKi9cbiAgICAgICAgICAgIHRoaXMucGFydGlhbCA9IHBhcnRpYWw7XG4gICAgICAgIH1cbiAgICAgICAgdGhpcy5fX21heWJlSW1wbGljaXRHbG9iYWwgPSBtYXliZUltcGxpY2l0R2xvYmFsO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFdoZXRoZXIgdGhlIHJlZmVyZW5jZSBpcyBzdGF0aWMuXG4gICAgICogQG1ldGhvZCBSZWZlcmVuY2UjaXNTdGF0aWNcbiAgICAgKiBAcmV0dXJuIHtib29sZWFufVxuICAgICAqL1xuICAgIGlzU3RhdGljKCkge1xuICAgICAgICByZXR1cm4gIXRoaXMudGFpbnRlZCAmJiB0aGlzLnJlc29sdmVkICYmIHRoaXMucmVzb2x2ZWQuc2NvcGUuaXNTdGF0aWMoKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBXaGV0aGVyIHRoZSByZWZlcmVuY2UgaXMgd3JpdGVhYmxlLlxuICAgICAqIEBtZXRob2QgUmVmZXJlbmNlI2lzV3JpdGVcbiAgICAgKiBAcmV0dXJuIHtib29sZWFufVxuICAgICAqL1xuICAgIGlzV3JpdGUoKSB7XG4gICAgICAgIHJldHVybiAhISh0aGlzLmZsYWcgJiBSZWZlcmVuY2UuV1JJVEUpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFdoZXRoZXIgdGhlIHJlZmVyZW5jZSBpcyByZWFkYWJsZS5cbiAgICAgKiBAbWV0aG9kIFJlZmVyZW5jZSNpc1JlYWRcbiAgICAgKiBAcmV0dXJuIHtib29sZWFufVxuICAgICAqL1xuICAgIGlzUmVhZCgpIHtcbiAgICAgICAgcmV0dXJuICEhKHRoaXMuZmxhZyAmIFJlZmVyZW5jZS5SRUFEKTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiBXaGV0aGVyIHRoZSByZWZlcmVuY2UgaXMgcmVhZC1vbmx5LlxuICAgICAqIEBtZXRob2QgUmVmZXJlbmNlI2lzUmVhZE9ubHlcbiAgICAgKiBAcmV0dXJuIHtib29sZWFufVxuICAgICAqL1xuICAgIGlzUmVhZE9ubHkoKSB7XG4gICAgICAgIHJldHVybiB0aGlzLmZsYWcgPT09IFJlZmVyZW5jZS5SRUFEO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFdoZXRoZXIgdGhlIHJlZmVyZW5jZSBpcyB3cml0ZS1vbmx5LlxuICAgICAqIEBtZXRob2QgUmVmZXJlbmNlI2lzV3JpdGVPbmx5XG4gICAgICogQHJldHVybiB7Ym9vbGVhbn1cbiAgICAgKi9cbiAgICBpc1dyaXRlT25seSgpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuZmxhZyA9PT0gUmVmZXJlbmNlLldSSVRFO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIFdoZXRoZXIgdGhlIHJlZmVyZW5jZSBpcyByZWFkLXdyaXRlLlxuICAgICAqIEBtZXRob2QgUmVmZXJlbmNlI2lzUmVhZFdyaXRlXG4gICAgICogQHJldHVybiB7Ym9vbGVhbn1cbiAgICAgKi9cbiAgICBpc1JlYWRXcml0ZSgpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuZmxhZyA9PT0gUmVmZXJlbmNlLlJXO1xuICAgIH1cbn1cblxuLyoqXG4gKiBAY29uc3RhbnQgUmVmZXJlbmNlLlJFQURcbiAqIEBwcml2YXRlXG4gKi9cblJlZmVyZW5jZS5SRUFEID0gUkVBRDtcbi8qKlxuICogQGNvbnN0YW50IFJlZmVyZW5jZS5XUklURVxuICogQHByaXZhdGVcbiAqL1xuUmVmZXJlbmNlLldSSVRFID0gV1JJVEU7XG4vKipcbiAqIEBjb25zdGFudCBSZWZlcmVuY2UuUldcbiAqIEBwcml2YXRlXG4gKi9cblJlZmVyZW5jZS5SVyA9IFJXO1xuXG4vKiB2aW06IHNldCBzdz00IHRzPTQgZXQgdHc9ODAgOiAqL1xuIl0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9 \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/lib/referencer.js b/tools/eslint/node_modules/escope/lib/referencer.js new file mode 100644 index 00000000000000..91d658dc789944 --- /dev/null +++ b/tools/eslint/node_modules/escope/lib/referencer.js @@ -0,0 +1,655 @@ +"use strict"; + +var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; + +var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; + +var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +var Syntax = require("estraverse").Syntax; + +var esrecurse = _interopRequire(require("esrecurse")); + +var Reference = _interopRequire(require("./reference")); + +var Variable = _interopRequire(require("./variable")); + +var _definition = require("./definition"); + +var ParameterDefinition = _definition.ParameterDefinition; +var Definition = _definition.Definition; + +var assert = _interopRequire(require("assert")); + +var PatternVisitor = (function (_esrecurse$Visitor) { + function PatternVisitor(rootPattern, referencer, callback) { + _classCallCheck(this, PatternVisitor); + + _get(Object.getPrototypeOf(PatternVisitor.prototype), "constructor", this).call(this); + this.referencer = referencer; + this.callback = callback; + } + + _inherits(PatternVisitor, _esrecurse$Visitor); + + _createClass(PatternVisitor, { + perform: { + value: function perform(pattern) { + if (pattern.type === Syntax.Identifier) { + this.callback(pattern, true); + return; + } + this.visit(pattern); + } + }, + Identifier: { + value: function Identifier(pattern) { + this.callback(pattern, false); + } + }, + ObjectPattern: { + value: function ObjectPattern(pattern) { + var i, iz, property; + for (i = 0, iz = pattern.properties.length; i < iz; ++i) { + property = pattern.properties[i]; + if (property.shorthand) { + this.visit(property.key); + continue; + } + this.visit(property.value); + } + } + }, + ArrayPattern: { + value: function ArrayPattern(pattern) { + var i, iz, element; + for (i = 0, iz = pattern.elements.length; i < iz; ++i) { + element = pattern.elements[i]; + if (element) { + this.visit(element); + } + } + } + }, + AssignmentPattern: { + value: function AssignmentPattern(pattern) { + this.visit(pattern.left); + // FIXME: Condier TDZ scope. + this.referencer.visit(pattern.right); + } + } + }); + + return PatternVisitor; +})(esrecurse.Visitor); + +function traverseIdentifierInPattern(rootPattern, referencer, callback) { + var visitor = new PatternVisitor(rootPattern, referencer, callback); + visitor.perform(rootPattern); +} + +function isPattern(node) { + var nodeType = node.type; + return nodeType === Syntax.Identifier || nodeType === Syntax.ObjectPattern || nodeType === Syntax.ArrayPattern || nodeType === Syntax.SpreadElement || nodeType === Syntax.RestElement || nodeType === Syntax.AssignmentPattern; +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +var Importer = (function (_esrecurse$Visitor2) { + function Importer(declaration, referencer) { + _classCallCheck(this, Importer); + + _get(Object.getPrototypeOf(Importer.prototype), "constructor", this).call(this); + this.declaration = declaration; + this.referencer = referencer; + } + + _inherits(Importer, _esrecurse$Visitor2); + + _createClass(Importer, { + visitImport: { + value: function visitImport(id, specifier) { + var _this = this; + + this.referencer.visitPattern(id, function (pattern) { + _this.referencer.currentScope().__define(pattern, new Definition(Variable.ImportBinding, pattern, specifier, _this.declaration, null, null)); + }); + } + }, + ImportNamespaceSpecifier: { + value: function ImportNamespaceSpecifier(node) { + var local = node.local || node.id; + if (local) { + this.visitImport(local, node); + } + } + }, + ImportDefaultSpecifier: { + value: function ImportDefaultSpecifier(node) { + var local = node.local || node.id; + this.visitImport(local, node); + } + }, + ImportSpecifier: { + value: function ImportSpecifier(node) { + var local = node.local || node.id; + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } + } + }); + + return Importer; +})(esrecurse.Visitor); + +// Referencing variables and creating bindings. + +var Referencer = (function (_esrecurse$Visitor3) { + function Referencer(scopeManager) { + _classCallCheck(this, Referencer); + + _get(Object.getPrototypeOf(Referencer.prototype), "constructor", this).call(this); + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + _inherits(Referencer, _esrecurse$Visitor3); + + _createClass(Referencer, { + currentScope: { + value: function currentScope() { + return this.scopeManager.__currentScope; + } + }, + close: { + value: function close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + }, + pushInnerMethodDefinition: { + value: function pushInnerMethodDefinition(isInnerMethodDefinition) { + var previous = this.isInnerMethodDefinition; + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + }, + popInnerMethodDefinition: { + value: function popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + }, + materializeTDZScope: { + value: function materializeTDZScope(node, iterationNode) { + // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation + // TDZ scope hides the declaration's names. + this.scopeManager.__nestTDZScope(node, iterationNode); + this.visitVariableDeclaration(this.currentScope(), Variable.TDZ, iterationNode.left, 0); + } + }, + materializeIterationScope: { + value: function materializeIterationScope(node) { + var _this = this; + + // Generate iteration scope for upper ForIn/ForOf Statements. + var letOrConstDecl; + this.scopeManager.__nestForScope(node); + letOrConstDecl = node.left; + this.visitVariableDeclaration(this.currentScope(), Variable.Variable, letOrConstDecl, 0); + this.visitPattern(letOrConstDecl.declarations[0].id, function (pattern) { + _this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true); + }); + } + }, + visitPattern: { + value: function visitPattern(node, callback) { + traverseIdentifierInPattern(node, this, callback); + } + }, + visitFunction: { + value: function visitFunction(node) { + var _this = this; + + var i, iz; + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + if (node.type === Syntax.FunctionDeclaration) { + // id is defined in upper scope + this.currentScope().__define(node.id, new Definition(Variable.FunctionName, node.id, node, null, null, null)); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], function (pattern) { + _this.currentScope().__define(pattern, new ParameterDefinition(pattern, node, i, false)); + }); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, function (pattern) { + _this.currentScope().__define(pattern, new ParameterDefinition(pattern, node, node.params.length, true)); + }); + } + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + + this.close(node); + } + }, + visitClass: { + value: function visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, new Definition(Variable.ClassName, node.id, node, null, null, null)); + } + + // FIXME: Maybe consider TDZ. + this.visit(node.superClass); + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, new Definition(Variable.ClassName, node.id, node)); + } + this.visit(node.body); + + this.close(node); + } + }, + visitProperty: { + value: function visitProperty(node) { + var previous, isMethodDefinition; + if (node.computed) { + this.visit(node.key); + } + + isMethodDefinition = node.type === Syntax.MethodDefinition || node.method; + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + }, + visitForIn: { + value: function visitForIn(node) { + var _this = this; + + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.materializeTDZScope(node.right, node); + this.visit(node.right); + this.close(node.right); + + this.materializeIterationScope(node); + this.visit(node.body); + this.close(node); + } else { + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, function (pattern) { + _this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true); + }); + } else { + if (!isPattern(node.left)) { + this.visit(node.left); + } + this.visitPattern(node.left, function (pattern) { + var maybeImplicitGlobal = null; + if (!_this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern: pattern, + node: node + }; + } + _this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true); + }); + } + this.visit(node.right); + this.visit(node.body); + } + } + }, + visitVariableDeclaration: { + value: function visitVariableDeclaration(variableTargetScope, type, node, index) { + var _this = this; + + var decl, init; + + decl = node.declarations[index]; + init = decl.init; + this.visitPattern(decl.id, function (pattern, toplevel) { + variableTargetScope.__define(pattern, new Definition(type, pattern, decl, node, index, node.kind)); + + if (init) { + _this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !toplevel); + } + }); + } + }, + AssignmentExpression: { + value: function AssignmentExpression(node) { + var _this = this; + + if (isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, function (pattern, toplevel) { + var maybeImplicitGlobal = null; + if (!_this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern: pattern, + node: node + }; + } + _this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !toplevel); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + }, + CatchClause: { + value: function CatchClause(node) { + var _this = this; + + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, function (pattern) { + _this.currentScope().__define(pattern, new Definition(Variable.CatchClause, node.param, node, null, null, null)); + }); + this.visit(node.body); + + this.close(node); + } + }, + Program: { + value: function Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.__isNodejsScope()) { + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + this.visitChildren(node); + this.close(node); + } + }, + Identifier: { + value: function Identifier(node) { + this.currentScope().__referencing(node); + } + }, + UpdateExpression: { + value: function UpdateExpression(node) { + if (isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + }, + MemberExpression: { + value: function MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + }, + Property: { + value: function Property(node) { + this.visitProperty(node); + } + }, + MethodDefinition: { + value: function MethodDefinition(node) { + this.visitProperty(node); + } + }, + BreakStatement: { + value: function BreakStatement() {} + }, + ContinueStatement: { + value: function ContinueStatement() {} + }, + LabeledStatement: { + value: function LabeledStatement(node) { + this.visit(node.body); + } + }, + ForStatement: { + value: function ForStatement(node) { + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + }, + ClassExpression: { + value: function ClassExpression(node) { + this.visitClass(node); + } + }, + ClassDeclaration: { + value: function ClassDeclaration(node) { + this.visitClass(node); + } + }, + CallExpression: { + value: function CallExpression(node) { + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + }, + BlockStatement: { + value: function BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + }, + ThisExpression: { + value: function ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + }, + WithStatement: { + value: function WithStatement(node) { + this.visit(node.object); + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + }, + VariableDeclaration: { + value: function VariableDeclaration(node) { + var variableTargetScope, i, iz, decl; + variableTargetScope = node.kind === "var" ? this.currentScope().variableScope : this.currentScope(); + for (i = 0, iz = node.declarations.length; i < iz; ++i) { + decl = node.declarations[i]; + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + }, + SwitchStatement: { + + // sec 13.11.8 + + value: function SwitchStatement(node) { + var i, iz; + + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + }, + FunctionDeclaration: { + value: function FunctionDeclaration(node) { + this.visitFunction(node); + } + }, + FunctionExpression: { + value: function FunctionExpression(node) { + this.visitFunction(node); + } + }, + ForOfStatement: { + value: function ForOfStatement(node) { + this.visitForIn(node); + } + }, + ForInStatement: { + value: function ForInStatement(node) { + this.visitForIn(node); + } + }, + ArrowFunctionExpression: { + value: function ArrowFunctionExpression(node) { + this.visitFunction(node); + } + }, + ImportDeclaration: { + value: function ImportDeclaration(node) { + var importer; + + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + + importer = new Importer(node, this); + importer.visit(node); + } + }, + visitExportDeclaration: { + value: function visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + }, + ExportDeclaration: { + value: function ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + }, + ExportNamedDeclaration: { + value: function ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + }, + ExportSpecifier: { + value: function ExportSpecifier(node) { + var local = node.id || node.local; + this.visit(local); + } + } + }); + + return Referencer; +})(esrecurse.Visitor); + +module.exports = Referencer; + +/* vim: set sw=4 ts=4 et tw=80 : */ +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInJlZmVyZW5jZXIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0lBdUJTLE1BQU0sV0FBUSxZQUFZLEVBQTFCLE1BQU07O0lBQ1IsU0FBUywyQkFBTSxXQUFXOztJQUMxQixTQUFTLDJCQUFNLGFBQWE7O0lBQzVCLFFBQVEsMkJBQU0sWUFBWTs7MEJBQ2UsY0FBYzs7SUFBckQsbUJBQW1CLGVBQW5CLG1CQUFtQjtJQUFFLFVBQVUsZUFBVixVQUFVOztJQUNqQyxNQUFNLDJCQUFNLFFBQVE7O0lBRXJCLGNBQWM7QUFDTCxhQURULGNBQWMsQ0FDSixXQUFXLEVBQUUsVUFBVSxFQUFFLFFBQVEsRUFBRTs4QkFEN0MsY0FBYzs7QUFFWixtQ0FGRixjQUFjLDZDQUVKO0FBQ1IsWUFBSSxDQUFDLFVBQVUsR0FBRyxVQUFVLENBQUM7QUFDN0IsWUFBSSxDQUFDLFFBQVEsR0FBRyxRQUFRLENBQUM7S0FDNUI7O2NBTEMsY0FBYzs7aUJBQWQsY0FBYztBQU9oQixlQUFPO21CQUFBLGlCQUFDLE9BQU8sRUFBRTtBQUNiLG9CQUFJLE9BQU8sQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLFVBQVUsRUFBRTtBQUNwQyx3QkFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLEVBQUUsSUFBSSxDQUFDLENBQUM7QUFDN0IsMkJBQU87aUJBQ1Y7QUFDRCxvQkFBSSxDQUFDLEtBQUssQ0FBQyxPQUFPLENBQUMsQ0FBQzthQUN2Qjs7QUFFRCxrQkFBVTttQkFBQSxvQkFBQyxPQUFPLEVBQUU7QUFDaEIsb0JBQUksQ0FBQyxRQUFRLENBQUMsT0FBTyxFQUFFLEtBQUssQ0FBQyxDQUFDO2FBQ2pDOztBQUVELHFCQUFhO21CQUFBLHVCQUFDLE9BQU8sRUFBRTtBQUNuQixvQkFBSSxDQUFDLEVBQUUsRUFBRSxFQUFFLFFBQVEsQ0FBQztBQUNwQixxQkFBSyxDQUFDLEdBQUcsQ0FBQyxFQUFFLEVBQUUsR0FBRyxPQUFPLENBQUMsVUFBVSxDQUFDLE1BQU0sRUFBRSxDQUFDLEdBQUcsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFO0FBQ3JELDRCQUFRLEdBQUcsT0FBTyxDQUFDLFVBQVUsQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUNqQyx3QkFBSSxRQUFRLENBQUMsU0FBUyxFQUFFO0FBQ3BCLDRCQUFJLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxHQUFHLENBQUMsQ0FBQztBQUN6QixpQ0FBUztxQkFDWjtBQUNELHdCQUFJLENBQUMsS0FBSyxDQUFDLFFBQVEsQ0FBQyxLQUFLLENBQUMsQ0FBQztpQkFDOUI7YUFDSjs7QUFFRCxvQkFBWTttQkFBQSxzQkFBQyxPQUFPLEVBQUU7QUFDbEIsb0JBQUksQ0FBQyxFQUFFLEVBQUUsRUFBRSxPQUFPLENBQUM7QUFDbkIscUJBQUssQ0FBQyxHQUFHLENBQUMsRUFBRSxFQUFFLEdBQUcsT0FBTyxDQUFDLFFBQVEsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTtBQUNuRCwyQkFBTyxHQUFHLE9BQU8sQ0FBQyxRQUFRLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDOUIsd0JBQUksT0FBTyxFQUFFO0FBQ1QsNEJBQUksQ0FBQyxLQUFLLENBQUMsT0FBTyxDQUFDLENBQUM7cUJBQ3ZCO2lCQUNKO2FBQ0o7O0FBRUQseUJBQWlCO21CQUFBLDJCQUFDLE9BQU8sRUFBRTtBQUN2QixvQkFBSSxDQUFDLEtBQUssQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUM7O0FBRXpCLG9CQUFJLENBQUMsVUFBVSxDQUFDLEtBQUssQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLENBQUM7YUFDeEM7Ozs7V0E3Q0MsY0FBYztHQUFTLFNBQVMsQ0FBQyxPQUFPOztBQWdEOUMsU0FBUywyQkFBMkIsQ0FBQyxXQUFXLEVBQUUsVUFBVSxFQUFFLFFBQVEsRUFBRTtBQUNwRSxRQUFJLE9BQU8sR0FBRyxJQUFJLGNBQWMsQ0FBQyxXQUFXLEVBQUUsVUFBVSxFQUFFLFFBQVEsQ0FBQyxDQUFDO0FBQ3BFLFdBQU8sQ0FBQyxPQUFPLENBQUMsV0FBVyxDQUFDLENBQUM7Q0FDaEM7O0FBRUQsU0FBUyxTQUFTLENBQUMsSUFBSSxFQUFFO0FBQ3JCLFFBQUksUUFBUSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUM7QUFDekIsV0FBTyxRQUFRLEtBQUssTUFBTSxDQUFDLFVBQVUsSUFBSSxRQUFRLEtBQUssTUFBTSxDQUFDLGFBQWEsSUFBSSxRQUFRLEtBQUssTUFBTSxDQUFDLFlBQVksSUFBSSxRQUFRLEtBQUssTUFBTSxDQUFDLGFBQWEsSUFBSSxRQUFRLEtBQUssTUFBTSxDQUFDLFdBQVcsSUFBSSxRQUFRLEtBQUssTUFBTSxDQUFDLGlCQUFpQixDQUFDO0NBQ25POzs7Ozs7OztJQVFLLFFBQVE7QUFDQyxhQURULFFBQVEsQ0FDRSxXQUFXLEVBQUUsVUFBVSxFQUFFOzhCQURuQyxRQUFROztBQUVOLG1DQUZGLFFBQVEsNkNBRUU7QUFDUixZQUFJLENBQUMsV0FBVyxHQUFHLFdBQVcsQ0FBQztBQUMvQixZQUFJLENBQUMsVUFBVSxHQUFHLFVBQVUsQ0FBQztLQUNoQzs7Y0FMQyxRQUFROztpQkFBUixRQUFRO0FBT1YsbUJBQVc7bUJBQUEscUJBQUMsRUFBRSxFQUFFLFNBQVMsRUFBRTs7O0FBQ3ZCLG9CQUFJLENBQUMsVUFBVSxDQUFDLFlBQVksQ0FBQyxFQUFFLEVBQUUsVUFBQyxPQUFPLEVBQUs7QUFDMUMsMEJBQUssVUFBVSxDQUFDLFlBQVksRUFBRSxDQUFDLFFBQVEsQ0FBQyxPQUFPLEVBQzNDLElBQUksVUFBVSxDQUNWLFFBQVEsQ0FBQyxhQUFhLEVBQ3RCLE9BQU8sRUFDUCxTQUFTLEVBQ1QsTUFBSyxXQUFXLEVBQ2hCLElBQUksRUFDSixJQUFJLENBQ0gsQ0FBQyxDQUFDO2lCQUNkLENBQUMsQ0FBQzthQUNOOztBQUVELGdDQUF3QjttQkFBQSxrQ0FBQyxJQUFJLEVBQUU7QUFDM0Isb0JBQUksS0FBSyxHQUFJLElBQUksQ0FBQyxLQUFLLElBQUksSUFBSSxDQUFDLEVBQUUsQUFBQyxDQUFDO0FBQ3BDLG9CQUFJLEtBQUssRUFBRTtBQUNQLHdCQUFJLENBQUMsV0FBVyxDQUFDLEtBQUssRUFBRSxJQUFJLENBQUMsQ0FBQztpQkFDakM7YUFDSjs7QUFFRCw4QkFBc0I7bUJBQUEsZ0NBQUMsSUFBSSxFQUFFO0FBQ3pCLG9CQUFJLEtBQUssR0FBSSxJQUFJLENBQUMsS0FBSyxJQUFJLElBQUksQ0FBQyxFQUFFLEFBQUMsQ0FBQztBQUNwQyxvQkFBSSxDQUFDLFdBQVcsQ0FBQyxLQUFLLEVBQUUsSUFBSSxDQUFDLENBQUM7YUFDakM7O0FBRUQsdUJBQWU7bUJBQUEseUJBQUMsSUFBSSxFQUFFO0FBQ2xCLG9CQUFJLEtBQUssR0FBSSxJQUFJLENBQUMsS0FBSyxJQUFJLElBQUksQ0FBQyxFQUFFLEFBQUMsQ0FBQztBQUNwQyxvQkFBSSxJQUFJLENBQUMsSUFBSSxFQUFFO0FBQ1gsd0JBQUksQ0FBQyxXQUFXLENBQUMsSUFBSSxDQUFDLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztpQkFDckMsTUFBTTtBQUNILHdCQUFJLENBQUMsV0FBVyxDQUFDLEtBQUssRUFBRSxJQUFJLENBQUMsQ0FBQztpQkFDakM7YUFDSjs7OztXQXhDQyxRQUFRO0dBQVMsU0FBUyxDQUFDLE9BQU87Ozs7SUE0Q25CLFVBQVU7QUFDaEIsYUFETSxVQUFVLENBQ2YsWUFBWSxFQUFFOzhCQURULFVBQVU7O0FBRXZCLG1DQUZhLFVBQVUsNkNBRWY7QUFDUixZQUFJLENBQUMsWUFBWSxHQUFHLFlBQVksQ0FBQztBQUNqQyxZQUFJLENBQUMsTUFBTSxHQUFHLElBQUksQ0FBQztBQUNuQixZQUFJLENBQUMsdUJBQXVCLEdBQUcsS0FBSyxDQUFDO0tBQ3hDOztjQU5nQixVQUFVOztpQkFBVixVQUFVO0FBUTNCLG9CQUFZO21CQUFBLHdCQUFHO0FBQ1gsdUJBQU8sSUFBSSxDQUFDLFlBQVksQ0FBQyxjQUFjLENBQUM7YUFDM0M7O0FBRUQsYUFBSzttQkFBQSxlQUFDLElBQUksRUFBRTtBQUNSLHVCQUFPLElBQUksQ0FBQyxZQUFZLEVBQUUsSUFBSSxJQUFJLEtBQUssSUFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLEtBQUssRUFBRTtBQUM5RCx3QkFBSSxDQUFDLFlBQVksQ0FBQyxjQUFjLEdBQUcsSUFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsWUFBWSxDQUFDLENBQUM7aUJBQ3JGO2FBQ0o7O0FBRUQsaUNBQXlCO21CQUFBLG1DQUFDLHVCQUF1QixFQUFFO0FBQy9DLG9CQUFJLFFBQVEsR0FBRyxJQUFJLENBQUMsdUJBQXVCLENBQUM7QUFDNUMsb0JBQUksQ0FBQyx1QkFBdUIsR0FBRyx1QkFBdUIsQ0FBQztBQUN2RCx1QkFBTyxRQUFRLENBQUM7YUFDbkI7O0FBRUQsZ0NBQXdCO21CQUFBLGtDQUFDLHVCQUF1QixFQUFFO0FBQzlDLG9CQUFJLENBQUMsdUJBQXVCLEdBQUcsdUJBQXVCLENBQUM7YUFDMUQ7O0FBRUQsMkJBQW1CO21CQUFBLDZCQUFDLElBQUksRUFBRSxhQUFhLEVBQUU7OztBQUdyQyxvQkFBSSxDQUFDLFlBQVksQ0FBQyxjQUFjLENBQUMsSUFBSSxFQUFFLGFBQWEsQ0FBQyxDQUFDO0FBQ3RELG9CQUFJLENBQUMsd0JBQXdCLENBQUMsSUFBSSxDQUFDLFlBQVksRUFBRSxFQUFFLFFBQVEsQ0FBQyxHQUFHLEVBQUUsYUFBYSxDQUFDLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQzthQUMzRjs7QUFFRCxpQ0FBeUI7bUJBQUEsbUNBQUMsSUFBSSxFQUFFOzs7O0FBRTVCLG9CQUFJLGNBQWMsQ0FBQztBQUNuQixvQkFBSSxDQUFDLFlBQVksQ0FBQyxjQUFjLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkMsOEJBQWMsR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDO0FBQzNCLG9CQUFJLENBQUMsd0JBQXdCLENBQUMsSUFBSSxDQUFDLFlBQVksRUFBRSxFQUFFLFFBQVEsQ0FBQyxRQUFRLEVBQUUsY0FBYyxFQUFFLENBQUMsQ0FBQyxDQUFDO0FBQ3pGLG9CQUFJLENBQUMsWUFBWSxDQUFDLGNBQWMsQ0FBQyxZQUFZLENBQUMsQ0FBQyxDQUFDLENBQUMsRUFBRSxFQUFFLFVBQUMsT0FBTyxFQUFLO0FBQzlELDBCQUFLLFlBQVksRUFBRSxDQUFDLGFBQWEsQ0FBQyxPQUFPLEVBQUUsU0FBUyxDQUFDLEtBQUssRUFBRSxJQUFJLENBQUMsS0FBSyxFQUFFLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQztpQkFDdkYsQ0FBQyxDQUFDO2FBQ047O0FBRUQsb0JBQVk7bUJBQUEsc0JBQUMsSUFBSSxFQUFFLFFBQVEsRUFBRTtBQUN6QiwyQ0FBMkIsQ0FBQyxJQUFJLEVBQUUsSUFBSSxFQUFFLFFBQVEsQ0FBQyxDQUFDO2FBQ3JEOztBQUVELHFCQUFhO21CQUFBLHVCQUFDLElBQUksRUFBRTs7O0FBQ2hCLG9CQUFJLENBQUMsRUFBRSxFQUFFLENBQUM7Ozs7OztBQU1WLG9CQUFJLElBQUksQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLG1CQUFtQixFQUFFOztBQUUxQyx3QkFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsRUFBRSxFQUM1QixJQUFJLFVBQVUsQ0FDVixRQUFRLENBQUMsWUFBWSxFQUNyQixJQUFJLENBQUMsRUFBRSxFQUNQLElBQUksRUFDSixJQUFJLEVBQ0osSUFBSSxFQUNKLElBQUksQ0FDUCxDQUFDLENBQUM7aUJBQ2Q7Ozs7QUFJRCxvQkFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxrQkFBa0IsSUFBSSxJQUFJLENBQUMsRUFBRSxFQUFFO0FBQ3BELHdCQUFJLENBQUMsWUFBWSxDQUFDLGlDQUFpQyxDQUFDLElBQUksQ0FBQyxDQUFDO2lCQUM3RDs7O0FBR0Qsb0JBQUksQ0FBQyxZQUFZLENBQUMsbUJBQW1CLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyx1QkFBdUIsQ0FBQyxDQUFDOztBQUUxRSxxQkFBSyxDQUFDLEdBQUcsQ0FBQyxFQUFFLEVBQUUsR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLE1BQU0sRUFBRSxDQUFDLEdBQUcsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFO0FBQzlDLHdCQUFJLENBQUMsWUFBWSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLEVBQUUsVUFBQyxPQUFPLEVBQUs7QUFDM0MsOEJBQUssWUFBWSxFQUFFLENBQUMsUUFBUSxDQUFDLE9BQU8sRUFDaEMsSUFBSSxtQkFBbUIsQ0FDbkIsT0FBTyxFQUNQLElBQUksRUFDSixDQUFDLEVBQ0QsS0FBSyxDQUNSLENBQUMsQ0FBQztxQkFDVixDQUFDLENBQUM7aUJBQ047OztBQUdELG9CQUFJLElBQUksQ0FBQyxJQUFJLEVBQUU7QUFDWCx3QkFBSSxDQUFDLFlBQVksQ0FBQztBQUNkLDRCQUFJLEVBQUUsYUFBYTtBQUNuQixnQ0FBUSxFQUFFLElBQUksQ0FBQyxJQUFJO3FCQUN0QixFQUFFLFVBQUMsT0FBTyxFQUFLO0FBQ1osOEJBQUssWUFBWSxFQUFFLENBQUMsUUFBUSxDQUFDLE9BQU8sRUFDaEMsSUFBSSxtQkFBbUIsQ0FDbkIsT0FBTyxFQUNQLElBQUksRUFDSixJQUFJLENBQUMsTUFBTSxDQUFDLE1BQU0sRUFDbEIsSUFBSSxDQUNQLENBQUMsQ0FBQztxQkFDVixDQUFDLENBQUM7aUJBQ047OztBQUdELG9CQUFJLElBQUksQ0FBQyxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxjQUFjLEVBQUU7QUFDMUMsd0JBQUksQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO2lCQUNqQyxNQUFNO0FBQ0gsd0JBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO2lCQUN6Qjs7QUFFRCxvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUNwQjs7QUFFRCxrQkFBVTttQkFBQSxvQkFBQyxJQUFJLEVBQUU7QUFDYixvQkFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxnQkFBZ0IsRUFBRTtBQUN2Qyx3QkFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsRUFBRSxFQUM1QixJQUFJLFVBQVUsQ0FDVixRQUFRLENBQUMsU0FBUyxFQUNsQixJQUFJLENBQUMsRUFBRSxFQUNQLElBQUksRUFDSixJQUFJLEVBQ0osSUFBSSxFQUNKLElBQUksQ0FDUCxDQUFDLENBQUM7aUJBQ2Q7OztBQUdELG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsQ0FBQzs7QUFFNUIsb0JBQUksQ0FBQyxZQUFZLENBQUMsZ0JBQWdCLENBQUMsSUFBSSxDQUFDLENBQUM7O0FBRXpDLG9CQUFJLElBQUksQ0FBQyxFQUFFLEVBQUU7QUFDVCx3QkFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsRUFBRSxFQUM1QixJQUFJLFVBQVUsQ0FDVixRQUFRLENBQUMsU0FBUyxFQUNsQixJQUFJLENBQUMsRUFBRSxFQUNQLElBQUksQ0FDUCxDQUFDLENBQUM7aUJBQ2Q7QUFDRCxvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7O0FBRXRCLG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3BCOztBQUVELHFCQUFhO21CQUFBLHVCQUFDLElBQUksRUFBRTtBQUNoQixvQkFBSSxRQUFRLEVBQUUsa0JBQWtCLENBQUM7QUFDakMsb0JBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtBQUNmLHdCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQztpQkFDeEI7O0FBRUQsa0NBQWtCLEdBQUcsSUFBSSxDQUFDLElBQUksS0FBSyxNQUFNLENBQUMsZ0JBQWdCLElBQUksSUFBSSxDQUFDLE1BQU0sQ0FBQztBQUMxRSxvQkFBSSxrQkFBa0IsRUFBRTtBQUNwQiw0QkFBUSxHQUFHLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxJQUFJLENBQUMsQ0FBQztpQkFDbkQ7QUFDRCxvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUM7QUFDdkIsb0JBQUksa0JBQWtCLEVBQUU7QUFDcEIsd0JBQUksQ0FBQyx3QkFBd0IsQ0FBQyxRQUFRLENBQUMsQ0FBQztpQkFDM0M7YUFDSjs7QUFFRCxrQkFBVTttQkFBQSxvQkFBQyxJQUFJLEVBQUU7OztBQUNiLG9CQUFJLElBQUksQ0FBQyxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxtQkFBbUIsSUFBSSxJQUFJLENBQUMsSUFBSSxDQUFDLElBQUksS0FBSyxLQUFLLEVBQUU7QUFDM0Usd0JBQUksQ0FBQyxtQkFBbUIsQ0FBQyxJQUFJLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0FBQzNDLHdCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsQ0FBQztBQUN2Qix3QkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUM7O0FBRXZCLHdCQUFJLENBQUMseUJBQXlCLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDckMsd0JBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQ3RCLHdCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDO2lCQUNwQixNQUFNO0FBQ0gsd0JBQUksSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLG1CQUFtQixFQUFFO0FBQy9DLDRCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUN0Qiw0QkFBSSxDQUFDLFlBQVksQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLFlBQVksQ0FBQyxDQUFDLENBQUMsQ0FBQyxFQUFFLEVBQUUsVUFBQyxPQUFPLEVBQUs7QUFDekQsa0NBQUssWUFBWSxFQUFFLENBQUMsYUFBYSxDQUFDLE9BQU8sRUFBRSxTQUFTLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxLQUFLLEVBQUUsSUFBSSxFQUFFLElBQUksQ0FBQyxDQUFDO3lCQUN2RixDQUFDLENBQUM7cUJBQ04sTUFBTTtBQUNILDRCQUFJLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsRUFBRTtBQUN2QixnQ0FBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7eUJBQ3pCO0FBQ0QsNEJBQUksQ0FBQyxZQUFZLENBQUMsSUFBSSxDQUFDLElBQUksRUFBRSxVQUFDLE9BQU8sRUFBSztBQUN0QyxnQ0FBSSxtQkFBbUIsR0FBRyxJQUFJLENBQUM7QUFDL0IsZ0NBQUksQ0FBQyxNQUFLLFlBQVksRUFBRSxDQUFDLFFBQVEsRUFBRTtBQUMvQixtREFBbUIsR0FBRztBQUNsQiwyQ0FBTyxFQUFFLE9BQU87QUFDaEIsd0NBQUksRUFBRSxJQUFJO2lDQUNiLENBQUM7NkJBQ0w7QUFDRCxrQ0FBSyxZQUFZLEVBQUUsQ0FBQyxhQUFhLENBQUMsT0FBTyxFQUFFLFNBQVMsQ0FBQyxLQUFLLEVBQUUsSUFBSSxDQUFDLEtBQUssRUFBRSxtQkFBbUIsRUFBRSxJQUFJLENBQUMsQ0FBQzt5QkFDdEcsQ0FBQyxDQUFDO3FCQUNOO0FBQ0Qsd0JBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDO0FBQ3ZCLHdCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztpQkFDekI7YUFDSjs7QUFFRCxnQ0FBd0I7bUJBQUEsa0NBQUMsbUJBQW1CLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxLQUFLLEVBQUU7OztBQUM3RCxvQkFBSSxJQUFJLEVBQUUsSUFBSSxDQUFDOztBQUVmLG9CQUFJLEdBQUcsSUFBSSxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsQ0FBQztBQUNoQyxvQkFBSSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUM7QUFDakIsb0JBQUksQ0FBQyxZQUFZLENBQUMsSUFBSSxDQUFDLEVBQUUsRUFBRSxVQUFDLE9BQU8sRUFBRSxRQUFRLEVBQUs7QUFDOUMsdUNBQW1CLENBQUMsUUFBUSxDQUFDLE9BQU8sRUFDaEMsSUFBSSxVQUFVLENBQ1YsSUFBSSxFQUNKLE9BQU8sRUFDUCxJQUFJLEVBQ0osSUFBSSxFQUNKLEtBQUssRUFDTCxJQUFJLENBQUMsSUFBSSxDQUNaLENBQUMsQ0FBQzs7QUFFUCx3QkFBSSxJQUFJLEVBQUU7QUFDTiw4QkFBSyxZQUFZLEVBQUUsQ0FBQyxhQUFhLENBQUMsT0FBTyxFQUFFLFNBQVMsQ0FBQyxLQUFLLEVBQUUsSUFBSSxFQUFFLElBQUksRUFBRSxDQUFDLFFBQVEsQ0FBQyxDQUFDO3FCQUN0RjtpQkFDSixDQUFDLENBQUM7YUFDTjs7QUFFRCw0QkFBb0I7bUJBQUEsOEJBQUMsSUFBSSxFQUFFOzs7QUFDdkIsb0JBQUksU0FBUyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsRUFBRTtBQUN0Qix3QkFBSSxJQUFJLENBQUMsUUFBUSxLQUFLLEdBQUcsRUFBRTtBQUN2Qiw0QkFBSSxDQUFDLFlBQVksQ0FBQyxJQUFJLENBQUMsSUFBSSxFQUFFLFVBQUMsT0FBTyxFQUFFLFFBQVEsRUFBSztBQUNoRCxnQ0FBSSxtQkFBbUIsR0FBRyxJQUFJLENBQUM7QUFDL0IsZ0NBQUksQ0FBQyxNQUFLLFlBQVksRUFBRSxDQUFDLFFBQVEsRUFBRTtBQUMvQixtREFBbUIsR0FBRztBQUNsQiwyQ0FBTyxFQUFFLE9BQU87QUFDaEIsd0NBQUksRUFBRSxJQUFJO2lDQUNiLENBQUM7NkJBQ0w7QUFDRCxrQ0FBSyxZQUFZLEVBQUUsQ0FBQyxhQUFhLENBQUMsT0FBTyxFQUFFLFNBQVMsQ0FBQyxLQUFLLEVBQUUsSUFBSSxDQUFDLEtBQUssRUFBRSxtQkFBbUIsRUFBRSxDQUFDLFFBQVEsQ0FBQyxDQUFDO3lCQUMzRyxDQUFDLENBQUM7cUJBQ04sTUFBTTtBQUNILDRCQUFJLENBQUMsWUFBWSxFQUFFLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxJQUFJLEVBQUUsU0FBUyxDQUFDLEVBQUUsRUFBRSxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUM7cUJBQzFFO2lCQUNKLE1BQU07QUFDSCx3QkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7aUJBQ3pCO0FBQ0Qsb0JBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDO2FBQzFCOztBQUVELG1CQUFXO21CQUFBLHFCQUFDLElBQUksRUFBRTs7O0FBQ2Qsb0JBQUksQ0FBQyxZQUFZLENBQUMsZ0JBQWdCLENBQUMsSUFBSSxDQUFDLENBQUM7O0FBRXpDLG9CQUFJLENBQUMsWUFBWSxDQUFDLElBQUksQ0FBQyxLQUFLLEVBQUUsVUFBQyxPQUFPLEVBQUs7QUFDdkMsMEJBQUssWUFBWSxFQUFFLENBQUMsUUFBUSxDQUFDLE9BQU8sRUFDaEMsSUFBSSxVQUFVLENBQ1YsUUFBUSxDQUFDLFdBQVcsRUFDcEIsSUFBSSxDQUFDLEtBQUssRUFDVixJQUFJLEVBQ0osSUFBSSxFQUNKLElBQUksRUFDSixJQUFJLENBQ1AsQ0FBQyxDQUFDO2lCQUNWLENBQUMsQ0FBQztBQUNILG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQzs7QUFFdEIsb0JBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDcEI7O0FBRUQsZUFBTzttQkFBQSxpQkFBQyxJQUFJLEVBQUU7QUFDVixvQkFBSSxDQUFDLFlBQVksQ0FBQyxpQkFBaUIsQ0FBQyxJQUFJLENBQUMsQ0FBQzs7QUFFMUMsb0JBQUksSUFBSSxDQUFDLFlBQVksQ0FBQyxlQUFlLEVBQUUsRUFBRTs7QUFFckMsd0JBQUksQ0FBQyxZQUFZLEVBQUUsQ0FBQyxRQUFRLEdBQUcsS0FBSyxDQUFDO0FBQ3JDLHdCQUFJLENBQUMsWUFBWSxDQUFDLG1CQUFtQixDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQztpQkFDdEQ7O0FBRUQsb0JBQUksSUFBSSxDQUFDLFlBQVksQ0FBQyxPQUFPLEVBQUUsSUFBSSxJQUFJLENBQUMsWUFBWSxDQUFDLFFBQVEsRUFBRSxFQUFFO0FBQzdELHdCQUFJLENBQUMsWUFBWSxDQUFDLGlCQUFpQixDQUFDLElBQUksQ0FBQyxDQUFDO2lCQUM3Qzs7QUFFRCxvQkFBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUN6QixvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUNwQjs7QUFFRCxrQkFBVTttQkFBQSxvQkFBQyxJQUFJLEVBQUU7QUFDYixvQkFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUMzQzs7QUFFRCx3QkFBZ0I7bUJBQUEsMEJBQUMsSUFBSSxFQUFFO0FBQ25CLG9CQUFJLFNBQVMsQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLEVBQUU7QUFDMUIsd0JBQUksQ0FBQyxZQUFZLEVBQUUsQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLFFBQVEsRUFBRSxTQUFTLENBQUMsRUFBRSxFQUFFLElBQUksQ0FBQyxDQUFDO2lCQUN4RSxNQUFNO0FBQ0gsd0JBQUksQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLENBQUM7aUJBQzVCO2FBQ0o7O0FBRUQsd0JBQWdCO21CQUFBLDBCQUFDLElBQUksRUFBRTtBQUNuQixvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUM7QUFDeEIsb0JBQUksSUFBSSxDQUFDLFFBQVEsRUFBRTtBQUNmLHdCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxRQUFRLENBQUMsQ0FBQztpQkFDN0I7YUFDSjs7QUFFRCxnQkFBUTttQkFBQSxrQkFBQyxJQUFJLEVBQUU7QUFDWCxvQkFBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUM1Qjs7QUFFRCx3QkFBZ0I7bUJBQUEsMEJBQUMsSUFBSSxFQUFFO0FBQ25CLG9CQUFJLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQzVCOztBQUVELHNCQUFjO21CQUFBLDBCQUFHLEVBQUU7O0FBRW5CLHlCQUFpQjttQkFBQSw2QkFBRyxFQUFFOztBQUV0Qix3QkFBZ0I7bUJBQUEsMEJBQUMsSUFBSSxFQUFFO0FBQ25CLG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUN6Qjs7QUFFRCxvQkFBWTttQkFBQSxzQkFBQyxJQUFJLEVBQUU7Ozs7O0FBS2Ysb0JBQUksSUFBSSxDQUFDLElBQUksSUFBSSxJQUFJLENBQUMsSUFBSSxDQUFDLElBQUksS0FBSyxNQUFNLENBQUMsbUJBQW1CLElBQUksSUFBSSxDQUFDLElBQUksQ0FBQyxJQUFJLEtBQUssS0FBSyxFQUFFO0FBQ3hGLHdCQUFJLENBQUMsWUFBWSxDQUFDLGNBQWMsQ0FBQyxJQUFJLENBQUMsQ0FBQztpQkFDMUM7O0FBRUQsb0JBQUksQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLENBQUM7O0FBRXpCLG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3BCOztBQUVELHVCQUFlO21CQUFBLHlCQUFDLElBQUksRUFBRTtBQUNsQixvQkFBSSxDQUFDLFVBQVUsQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUN6Qjs7QUFFRCx3QkFBZ0I7bUJBQUEsMEJBQUMsSUFBSSxFQUFFO0FBQ25CLG9CQUFJLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3pCOztBQUVELHNCQUFjO21CQUFBLHdCQUFDLElBQUksRUFBRTs7QUFFakIsb0JBQUksQ0FBQyxJQUFJLENBQUMsWUFBWSxDQUFDLFlBQVksRUFBRSxJQUFJLElBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxVQUFVLElBQUksSUFBSSxDQUFDLE1BQU0sQ0FBQyxJQUFJLEtBQUssTUFBTSxFQUFFOzs7QUFHNUcsd0JBQUksQ0FBQyxZQUFZLEVBQUUsQ0FBQyxhQUFhLENBQUMsWUFBWSxFQUFFLENBQUM7aUJBQ3BEO0FBQ0Qsb0JBQUksQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDNUI7O0FBRUQsc0JBQWM7bUJBQUEsd0JBQUMsSUFBSSxFQUFFO0FBQ2pCLG9CQUFJLElBQUksQ0FBQyxZQUFZLENBQUMsT0FBTyxFQUFFLEVBQUU7QUFDN0Isd0JBQUksQ0FBQyxZQUFZLENBQUMsZ0JBQWdCLENBQUMsSUFBSSxDQUFDLENBQUM7aUJBQzVDOztBQUVELG9CQUFJLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxDQUFDOztBQUV6QixvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUNwQjs7QUFFRCxzQkFBYzttQkFBQSwwQkFBRztBQUNiLG9CQUFJLENBQUMsWUFBWSxFQUFFLENBQUMsYUFBYSxDQUFDLFlBQVksRUFBRSxDQUFDO2FBQ3BEOztBQUVELHFCQUFhO21CQUFBLHVCQUFDLElBQUksRUFBRTtBQUNoQixvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUM7O0FBRXhCLG9CQUFJLENBQUMsWUFBWSxDQUFDLGVBQWUsQ0FBQyxJQUFJLENBQUMsQ0FBQzs7QUFFeEMsb0JBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDOztBQUV0QixvQkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUNwQjs7QUFFRCwyQkFBbUI7bUJBQUEsNkJBQUMsSUFBSSxFQUFFO0FBQ3RCLG9CQUFJLG1CQUFtQixFQUFFLENBQUMsRUFBRSxFQUFFLEVBQUUsSUFBSSxDQUFDO0FBQ3JDLG1DQUFtQixHQUFHLEFBQUMsSUFBSSxDQUFDLElBQUksS0FBSyxLQUFLLEdBQUksSUFBSSxDQUFDLFlBQVksRUFBRSxDQUFDLGFBQWEsR0FBRyxJQUFJLENBQUMsWUFBWSxFQUFFLENBQUM7QUFDdEcscUJBQUssQ0FBQyxHQUFHLENBQUMsRUFBRSxFQUFFLEdBQUcsSUFBSSxDQUFDLFlBQVksQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTtBQUNwRCx3QkFBSSxHQUFHLElBQUksQ0FBQyxZQUFZLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDNUIsd0JBQUksQ0FBQyx3QkFBd0IsQ0FBQyxtQkFBbUIsRUFBRSxRQUFRLENBQUMsUUFBUSxFQUFFLElBQUksRUFBRSxDQUFDLENBQUMsQ0FBQztBQUMvRSx3QkFBSSxJQUFJLENBQUMsSUFBSSxFQUFFO0FBQ1gsNEJBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO3FCQUN6QjtpQkFDSjthQUNKOztBQUdELHVCQUFlOzs7O21CQUFBLHlCQUFDLElBQUksRUFBRTtBQUNsQixvQkFBSSxDQUFDLEVBQUUsRUFBRSxDQUFDOztBQUVWLG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxZQUFZLENBQUMsQ0FBQzs7QUFFOUIsb0JBQUksSUFBSSxDQUFDLFlBQVksQ0FBQyxPQUFPLEVBQUUsRUFBRTtBQUM3Qix3QkFBSSxDQUFDLFlBQVksQ0FBQyxpQkFBaUIsQ0FBQyxJQUFJLENBQUMsQ0FBQztpQkFDN0M7O0FBRUQscUJBQUssQ0FBQyxHQUFHLENBQUMsRUFBRSxFQUFFLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTtBQUM3Qyx3QkFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7aUJBQzdCOztBQUVELG9CQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3BCOztBQUVELDJCQUFtQjttQkFBQSw2QkFBQyxJQUFJLEVBQUU7QUFDdEIsb0JBQUksQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDNUI7O0FBRUQsMEJBQWtCO21CQUFBLDRCQUFDLElBQUksRUFBRTtBQUNyQixvQkFBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUM1Qjs7QUFFRCxzQkFBYzttQkFBQSx3QkFBQyxJQUFJLEVBQUU7QUFDakIsb0JBQUksQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDekI7O0FBRUQsc0JBQWM7bUJBQUEsd0JBQUMsSUFBSSxFQUFFO0FBQ2pCLG9CQUFJLENBQUMsVUFBVSxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3pCOztBQUVELCtCQUF1QjttQkFBQSxpQ0FBQyxJQUFJLEVBQUU7QUFDMUIsb0JBQUksQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDNUI7O0FBRUQseUJBQWlCO21CQUFBLDJCQUFDLElBQUksRUFBRTtBQUNwQixvQkFBSSxRQUFRLENBQUM7O0FBRWIsc0JBQU0sQ0FBQyxJQUFJLENBQUMsWUFBWSxDQUFDLE9BQU8sRUFBRSxJQUFJLElBQUksQ0FBQyxZQUFZLENBQUMsUUFBUSxFQUFFLEVBQUUsaUZBQWlGLENBQUMsQ0FBQzs7QUFFdkosd0JBQVEsR0FBRyxJQUFJLFFBQVEsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLENBQUM7QUFDcEMsd0JBQVEsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDeEI7O0FBRUQsOEJBQXNCO21CQUFBLGdDQUFDLElBQUksRUFBRTtBQUN6QixvQkFBSSxJQUFJLENBQUMsTUFBTSxFQUFFO0FBQ2IsMkJBQU87aUJBQ1Y7QUFDRCxvQkFBSSxJQUFJLENBQUMsV0FBVyxFQUFFO0FBQ2xCLHdCQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUMsQ0FBQztBQUM3QiwyQkFBTztpQkFDVjs7QUFFRCxvQkFBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsQ0FBQzthQUM1Qjs7QUFFRCx5QkFBaUI7bUJBQUEsMkJBQUMsSUFBSSxFQUFFO0FBQ3BCLG9CQUFJLENBQUMsc0JBQXNCLENBQUMsSUFBSSxDQUFDLENBQUM7YUFDckM7O0FBRUQsOEJBQXNCO21CQUFBLGdDQUFDLElBQUksRUFBRTtBQUN6QixvQkFBSSxDQUFDLHNCQUFzQixDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3JDOztBQUVELHVCQUFlO21CQUFBLHlCQUFDLElBQUksRUFBRTtBQUNsQixvQkFBSSxLQUFLLEdBQUksSUFBSSxDQUFDLEVBQUUsSUFBSSxJQUFJLENBQUMsS0FBSyxBQUFDLENBQUM7QUFDcEMsb0JBQUksQ0FBQyxLQUFLLENBQUMsS0FBSyxDQUFDLENBQUM7YUFDckI7Ozs7V0FuY2dCLFVBQVU7R0FBUyxTQUFTLENBQUMsT0FBTzs7aUJBQXBDLFVBQVUiLCJmaWxlIjoicmVmZXJlbmNlci5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qXG4gIENvcHlyaWdodCAoQykgMjAxNSBZdXN1a2UgU3V6dWtpIDx1dGF0YW5lLnRlYUBnbWFpbC5jb20+XG5cbiAgUmVkaXN0cmlidXRpb24gYW5kIHVzZSBpbiBzb3VyY2UgYW5kIGJpbmFyeSBmb3Jtcywgd2l0aCBvciB3aXRob3V0XG4gIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmUgbWV0OlxuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICAgICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZSBjb3B5cmlnaHRcbiAgICAgIG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmcgZGlzY2xhaW1lciBpbiB0aGVcbiAgICAgIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZCB3aXRoIHRoZSBkaXN0cmlidXRpb24uXG5cbiAgVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SUyBcIkFTIElTXCJcbiAgQU5EIEFOWSBFWFBSRVNTIE9SIElNUExJRUQgV0FSUkFOVElFUywgSU5DTFVESU5HLCBCVVQgTk9UIExJTUlURUQgVE8sIFRIRVxuICBJTVBMSUVEIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZIEFORCBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRVxuICBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgPENPUFlSSUdIVCBIT0xERVI+IEJFIExJQUJMRSBGT1IgQU5ZXG4gIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsIFNQRUNJQUwsIEVYRU1QTEFSWSwgT1IgQ09OU0VRVUVOVElBTCBEQU1BR0VTXG4gIChJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgUFJPQ1VSRU1FTlQgT0YgU1VCU1RJVFVURSBHT09EUyBPUiBTRVJWSUNFUztcbiAgTE9TUyBPRiBVU0UsIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EXG4gIE9OIEFOWSBUSEVPUlkgT0YgTElBQklMSVRZLCBXSEVUSEVSIElOIENPTlRSQUNULCBTVFJJQ1QgTElBQklMSVRZLCBPUiBUT1JUXG4gIChJTkNMVURJTkcgTkVHTElHRU5DRSBPUiBPVEhFUldJU0UpIEFSSVNJTkcgSU4gQU5ZIFdBWSBPVVQgT0YgVEhFIFVTRSBPRlxuICBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuKi9cbmltcG9ydCB7IFN5bnRheCB9IGZyb20gJ2VzdHJhdmVyc2UnO1xuaW1wb3J0IGVzcmVjdXJzZSBmcm9tICdlc3JlY3Vyc2UnO1xuaW1wb3J0IFJlZmVyZW5jZSBmcm9tICcuL3JlZmVyZW5jZSc7XG5pbXBvcnQgVmFyaWFibGUgZnJvbSAnLi92YXJpYWJsZSc7XG5pbXBvcnQgeyBQYXJhbWV0ZXJEZWZpbml0aW9uLCBEZWZpbml0aW9uIH0gZnJvbSAnLi9kZWZpbml0aW9uJztcbmltcG9ydCBhc3NlcnQgZnJvbSAnYXNzZXJ0JztcblxuY2xhc3MgUGF0dGVyblZpc2l0b3IgZXh0ZW5kcyBlc3JlY3Vyc2UuVmlzaXRvciB7XG4gICAgY29uc3RydWN0b3Iocm9vdFBhdHRlcm4sIHJlZmVyZW5jZXIsIGNhbGxiYWNrKSB7XG4gICAgICAgIHN1cGVyKCk7XG4gICAgICAgIHRoaXMucmVmZXJlbmNlciA9IHJlZmVyZW5jZXI7XG4gICAgICAgIHRoaXMuY2FsbGJhY2sgPSBjYWxsYmFjaztcbiAgICB9XG5cbiAgICBwZXJmb3JtKHBhdHRlcm4pIHtcbiAgICAgICAgaWYgKHBhdHRlcm4udHlwZSA9PT0gU3ludGF4LklkZW50aWZpZXIpIHtcbiAgICAgICAgICAgIHRoaXMuY2FsbGJhY2socGF0dGVybiwgdHJ1ZSk7XG4gICAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cbiAgICAgICAgdGhpcy52aXNpdChwYXR0ZXJuKTtcbiAgICB9XG5cbiAgICBJZGVudGlmaWVyKHBhdHRlcm4pIHtcbiAgICAgICAgdGhpcy5jYWxsYmFjayhwYXR0ZXJuLCBmYWxzZSk7XG4gICAgfVxuXG4gICAgT2JqZWN0UGF0dGVybihwYXR0ZXJuKSB7XG4gICAgICAgIHZhciBpLCBpeiwgcHJvcGVydHk7XG4gICAgICAgIGZvciAoaSA9IDAsIGl6ID0gcGF0dGVybi5wcm9wZXJ0aWVzLmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgIHByb3BlcnR5ID0gcGF0dGVybi5wcm9wZXJ0aWVzW2ldO1xuICAgICAgICAgICAgaWYgKHByb3BlcnR5LnNob3J0aGFuZCkge1xuICAgICAgICAgICAgICAgIHRoaXMudmlzaXQocHJvcGVydHkua2V5KTtcbiAgICAgICAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIHRoaXMudmlzaXQocHJvcGVydHkudmFsdWUpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgQXJyYXlQYXR0ZXJuKHBhdHRlcm4pIHtcbiAgICAgICAgdmFyIGksIGl6LCBlbGVtZW50O1xuICAgICAgICBmb3IgKGkgPSAwLCBpeiA9IHBhdHRlcm4uZWxlbWVudHMubGVuZ3RoOyBpIDwgaXo7ICsraSkge1xuICAgICAgICAgICAgZWxlbWVudCA9IHBhdHRlcm4uZWxlbWVudHNbaV07XG4gICAgICAgICAgICBpZiAoZWxlbWVudCkge1xuICAgICAgICAgICAgICAgIHRoaXMudmlzaXQoZWxlbWVudCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICBBc3NpZ25tZW50UGF0dGVybihwYXR0ZXJuKSB7XG4gICAgICAgIHRoaXMudmlzaXQocGF0dGVybi5sZWZ0KTtcbiAgICAgICAgLy8gRklYTUU6IENvbmRpZXIgVERaIHNjb3BlLlxuICAgICAgICB0aGlzLnJlZmVyZW5jZXIudmlzaXQocGF0dGVybi5yaWdodCk7XG4gICAgfVxufVxuXG5mdW5jdGlvbiB0cmF2ZXJzZUlkZW50aWZpZXJJblBhdHRlcm4ocm9vdFBhdHRlcm4sIHJlZmVyZW5jZXIsIGNhbGxiYWNrKSB7XG4gICAgdmFyIHZpc2l0b3IgPSBuZXcgUGF0dGVyblZpc2l0b3Iocm9vdFBhdHRlcm4sIHJlZmVyZW5jZXIsIGNhbGxiYWNrKTtcbiAgICB2aXNpdG9yLnBlcmZvcm0ocm9vdFBhdHRlcm4pO1xufVxuXG5mdW5jdGlvbiBpc1BhdHRlcm4obm9kZSkge1xuICAgIHZhciBub2RlVHlwZSA9IG5vZGUudHlwZTtcbiAgICByZXR1cm4gbm9kZVR5cGUgPT09IFN5bnRheC5JZGVudGlmaWVyIHx8IG5vZGVUeXBlID09PSBTeW50YXguT2JqZWN0UGF0dGVybiB8fCBub2RlVHlwZSA9PT0gU3ludGF4LkFycmF5UGF0dGVybiB8fCBub2RlVHlwZSA9PT0gU3ludGF4LlNwcmVhZEVsZW1lbnQgfHwgbm9kZVR5cGUgPT09IFN5bnRheC5SZXN0RWxlbWVudCB8fCBub2RlVHlwZSA9PT0gU3ludGF4LkFzc2lnbm1lbnRQYXR0ZXJuO1xufVxuXG4vLyBJbXBvcnRpbmcgSW1wb3J0RGVjbGFyYXRpb24uXG4vLyBodHRwOi8vcGVvcGxlLm1vemlsbGEub3JnL35qb3JlbmRvcmZmL2VzNi1kcmFmdC5odG1sI3NlYy1tb2R1bGVkZWNsYXJhdGlvbmluc3RhbnRpYXRpb25cbi8vIGh0dHBzOi8vZ2l0aHViLmNvbS9lc3RyZWUvZXN0cmVlL2Jsb2IvbWFzdGVyL2VzNi5tZCNpbXBvcnRkZWNsYXJhdGlvblxuLy8gRklYTUU6IE5vdywgd2UgZG9uJ3QgY3JlYXRlIG1vZHVsZSBlbnZpcm9ubWVudCwgYmVjYXVzZSB0aGUgY29udGV4dCBpc1xuLy8gaW1wbGVtZW50YXRpb24gZGVwZW5kZW50LlxuXG5jbGFzcyBJbXBvcnRlciBleHRlbmRzIGVzcmVjdXJzZS5WaXNpdG9yIHtcbiAgICBjb25zdHJ1Y3RvcihkZWNsYXJhdGlvbiwgcmVmZXJlbmNlcikge1xuICAgICAgICBzdXBlcigpO1xuICAgICAgICB0aGlzLmRlY2xhcmF0aW9uID0gZGVjbGFyYXRpb247XG4gICAgICAgIHRoaXMucmVmZXJlbmNlciA9IHJlZmVyZW5jZXI7XG4gICAgfVxuXG4gICAgdmlzaXRJbXBvcnQoaWQsIHNwZWNpZmllcikge1xuICAgICAgICB0aGlzLnJlZmVyZW5jZXIudmlzaXRQYXR0ZXJuKGlkLCAocGF0dGVybikgPT4ge1xuICAgICAgICAgICAgdGhpcy5yZWZlcmVuY2VyLmN1cnJlbnRTY29wZSgpLl9fZGVmaW5lKHBhdHRlcm4sXG4gICAgICAgICAgICAgICAgbmV3IERlZmluaXRpb24oXG4gICAgICAgICAgICAgICAgICAgIFZhcmlhYmxlLkltcG9ydEJpbmRpbmcsXG4gICAgICAgICAgICAgICAgICAgIHBhdHRlcm4sXG4gICAgICAgICAgICAgICAgICAgIHNwZWNpZmllcixcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5kZWNsYXJhdGlvbixcbiAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgbnVsbFxuICAgICAgICAgICAgICAgICAgICApKTtcbiAgICAgICAgfSk7XG4gICAgfVxuXG4gICAgSW1wb3J0TmFtZXNwYWNlU3BlY2lmaWVyKG5vZGUpIHtcbiAgICAgICAgbGV0IGxvY2FsID0gKG5vZGUubG9jYWwgfHwgbm9kZS5pZCk7XG4gICAgICAgIGlmIChsb2NhbCkge1xuICAgICAgICAgICAgdGhpcy52aXNpdEltcG9ydChsb2NhbCwgbm9kZSk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICBJbXBvcnREZWZhdWx0U3BlY2lmaWVyKG5vZGUpIHtcbiAgICAgICAgbGV0IGxvY2FsID0gKG5vZGUubG9jYWwgfHwgbm9kZS5pZCk7XG4gICAgICAgIHRoaXMudmlzaXRJbXBvcnQobG9jYWwsIG5vZGUpO1xuICAgIH1cblxuICAgIEltcG9ydFNwZWNpZmllcihub2RlKSB7XG4gICAgICAgIGxldCBsb2NhbCA9IChub2RlLmxvY2FsIHx8IG5vZGUuaWQpO1xuICAgICAgICBpZiAobm9kZS5uYW1lKSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0SW1wb3J0KG5vZGUubmFtZSwgbm9kZSk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0SW1wb3J0KGxvY2FsLCBub2RlKTtcbiAgICAgICAgfVxuICAgIH1cbn1cblxuLy8gUmVmZXJlbmNpbmcgdmFyaWFibGVzIGFuZCBjcmVhdGluZyBiaW5kaW5ncy5cbmV4cG9ydCBkZWZhdWx0IGNsYXNzIFJlZmVyZW5jZXIgZXh0ZW5kcyBlc3JlY3Vyc2UuVmlzaXRvciB7XG4gICAgY29uc3RydWN0b3Ioc2NvcGVNYW5hZ2VyKSB7XG4gICAgICAgIHN1cGVyKCk7XG4gICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyID0gc2NvcGVNYW5hZ2VyO1xuICAgICAgICB0aGlzLnBhcmVudCA9IG51bGw7XG4gICAgICAgIHRoaXMuaXNJbm5lck1ldGhvZERlZmluaXRpb24gPSBmYWxzZTtcbiAgICB9XG5cbiAgICBjdXJyZW50U2NvcGUoKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNjb3BlTWFuYWdlci5fX2N1cnJlbnRTY29wZTtcbiAgICB9XG5cbiAgICBjbG9zZShub2RlKSB7XG4gICAgICAgIHdoaWxlICh0aGlzLmN1cnJlbnRTY29wZSgpICYmIG5vZGUgPT09IHRoaXMuY3VycmVudFNjb3BlKCkuYmxvY2spIHtcbiAgICAgICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyLl9fY3VycmVudFNjb3BlID0gdGhpcy5jdXJyZW50U2NvcGUoKS5fX2Nsb3NlKHRoaXMuc2NvcGVNYW5hZ2VyKTtcbiAgICAgICAgfVxuICAgIH1cblxuICAgIHB1c2hJbm5lck1ldGhvZERlZmluaXRpb24oaXNJbm5lck1ldGhvZERlZmluaXRpb24pIHtcbiAgICAgICAgdmFyIHByZXZpb3VzID0gdGhpcy5pc0lubmVyTWV0aG9kRGVmaW5pdGlvbjtcbiAgICAgICAgdGhpcy5pc0lubmVyTWV0aG9kRGVmaW5pdGlvbiA9IGlzSW5uZXJNZXRob2REZWZpbml0aW9uO1xuICAgICAgICByZXR1cm4gcHJldmlvdXM7XG4gICAgfVxuXG4gICAgcG9wSW5uZXJNZXRob2REZWZpbml0aW9uKGlzSW5uZXJNZXRob2REZWZpbml0aW9uKSB7XG4gICAgICAgIHRoaXMuaXNJbm5lck1ldGhvZERlZmluaXRpb24gPSBpc0lubmVyTWV0aG9kRGVmaW5pdGlvbjtcbiAgICB9XG5cbiAgICBtYXRlcmlhbGl6ZVREWlNjb3BlKG5vZGUsIGl0ZXJhdGlvbk5vZGUpIHtcbiAgICAgICAgLy8gaHR0cDovL3Blb3BsZS5tb3ppbGxhLm9yZy9+am9yZW5kb3JmZi9lczYtZHJhZnQuaHRtbCNzZWMtcnVudGltZS1zZW1hbnRpY3MtZm9yaW4tZGl2LW9mZXhwcmVzc2lvbmV2YWx1YXRpb24tYWJzdHJhY3Qtb3BlcmF0aW9uXG4gICAgICAgIC8vIFREWiBzY29wZSBoaWRlcyB0aGUgZGVjbGFyYXRpb24ncyBuYW1lcy5cbiAgICAgICAgdGhpcy5zY29wZU1hbmFnZXIuX19uZXN0VERaU2NvcGUobm9kZSwgaXRlcmF0aW9uTm9kZSk7XG4gICAgICAgIHRoaXMudmlzaXRWYXJpYWJsZURlY2xhcmF0aW9uKHRoaXMuY3VycmVudFNjb3BlKCksIFZhcmlhYmxlLlREWiwgaXRlcmF0aW9uTm9kZS5sZWZ0LCAwKTtcbiAgICB9XG5cbiAgICBtYXRlcmlhbGl6ZUl0ZXJhdGlvblNjb3BlKG5vZGUpIHtcbiAgICAgICAgLy8gR2VuZXJhdGUgaXRlcmF0aW9uIHNjb3BlIGZvciB1cHBlciBGb3JJbi9Gb3JPZiBTdGF0ZW1lbnRzLlxuICAgICAgICB2YXIgbGV0T3JDb25zdERlY2w7XG4gICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyLl9fbmVzdEZvclNjb3BlKG5vZGUpO1xuICAgICAgICBsZXRPckNvbnN0RGVjbCA9IG5vZGUubGVmdDtcbiAgICAgICAgdGhpcy52aXNpdFZhcmlhYmxlRGVjbGFyYXRpb24odGhpcy5jdXJyZW50U2NvcGUoKSwgVmFyaWFibGUuVmFyaWFibGUsIGxldE9yQ29uc3REZWNsLCAwKTtcbiAgICAgICAgdGhpcy52aXNpdFBhdHRlcm4obGV0T3JDb25zdERlY2wuZGVjbGFyYXRpb25zWzBdLmlkLCAocGF0dGVybikgPT4ge1xuICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX3JlZmVyZW5jaW5nKHBhdHRlcm4sIFJlZmVyZW5jZS5XUklURSwgbm9kZS5yaWdodCwgbnVsbCwgdHJ1ZSk7XG4gICAgICAgIH0pO1xuICAgIH1cblxuICAgIHZpc2l0UGF0dGVybihub2RlLCBjYWxsYmFjaykge1xuICAgICAgICB0cmF2ZXJzZUlkZW50aWZpZXJJblBhdHRlcm4obm9kZSwgdGhpcywgY2FsbGJhY2spO1xuICAgIH1cblxuICAgIHZpc2l0RnVuY3Rpb24obm9kZSkge1xuICAgICAgICB2YXIgaSwgaXo7XG4gICAgICAgIC8vIEZ1bmN0aW9uRGVjbGFyYXRpb24gbmFtZSBpcyBkZWZpbmVkIGluIHVwcGVyIHNjb3BlXG4gICAgICAgIC8vIE5PVEU6IE5vdCByZWZlcnJpbmcgdmFyaWFibGVTY29wZS4gSXQgaXMgaW50ZW5kZWQuXG4gICAgICAgIC8vIFNpbmNlXG4gICAgICAgIC8vICBpbiBFUzUsIEZ1bmN0aW9uRGVjbGFyYXRpb24gc2hvdWxkIGJlIGluIEZ1bmN0aW9uQm9keS5cbiAgICAgICAgLy8gIGluIEVTNiwgRnVuY3Rpb25EZWNsYXJhdGlvbiBzaG91bGQgYmUgYmxvY2sgc2NvcGVkLlxuICAgICAgICBpZiAobm9kZS50eXBlID09PSBTeW50YXguRnVuY3Rpb25EZWNsYXJhdGlvbikge1xuICAgICAgICAgICAgLy8gaWQgaXMgZGVmaW5lZCBpbiB1cHBlciBzY29wZVxuICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX2RlZmluZShub2RlLmlkLFxuICAgICAgICAgICAgICAgICAgICBuZXcgRGVmaW5pdGlvbihcbiAgICAgICAgICAgICAgICAgICAgICAgIFZhcmlhYmxlLkZ1bmN0aW9uTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuaWQsXG4gICAgICAgICAgICAgICAgICAgICAgICBub2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgICAgIG51bGwsXG4gICAgICAgICAgICAgICAgICAgICAgICBudWxsXG4gICAgICAgICAgICAgICAgICAgICkpO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gRnVuY3Rpb25FeHByZXNzaW9uIHdpdGggbmFtZSBjcmVhdGVzIGl0cyBzcGVjaWFsIHNjb3BlO1xuICAgICAgICAvLyBGdW5jdGlvbkV4cHJlc3Npb25OYW1lU2NvcGUuXG4gICAgICAgIGlmIChub2RlLnR5cGUgPT09IFN5bnRheC5GdW5jdGlvbkV4cHJlc3Npb24gJiYgbm9kZS5pZCkge1xuICAgICAgICAgICAgdGhpcy5zY29wZU1hbmFnZXIuX19uZXN0RnVuY3Rpb25FeHByZXNzaW9uTmFtZVNjb3BlKG5vZGUpO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gQ29uc2lkZXIgdGhpcyBmdW5jdGlvbiBpcyBpbiB0aGUgTWV0aG9kRGVmaW5pdGlvbi5cbiAgICAgICAgdGhpcy5zY29wZU1hbmFnZXIuX19uZXN0RnVuY3Rpb25TY29wZShub2RlLCB0aGlzLmlzSW5uZXJNZXRob2REZWZpbml0aW9uKTtcblxuICAgICAgICBmb3IgKGkgPSAwLCBpeiA9IG5vZGUucGFyYW1zLmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgIHRoaXMudmlzaXRQYXR0ZXJuKG5vZGUucGFyYW1zW2ldLCAocGF0dGVybikgPT4ge1xuICAgICAgICAgICAgICAgIHRoaXMuY3VycmVudFNjb3BlKCkuX19kZWZpbmUocGF0dGVybixcbiAgICAgICAgICAgICAgICAgICAgbmV3IFBhcmFtZXRlckRlZmluaXRpb24oXG4gICAgICAgICAgICAgICAgICAgICAgICBwYXR0ZXJuLFxuICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSxcbiAgICAgICAgICAgICAgICAgICAgICAgIGksXG4gICAgICAgICAgICAgICAgICAgICAgICBmYWxzZVxuICAgICAgICAgICAgICAgICAgICApKTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gaWYgdGhlcmUncyBhIHJlc3QgYXJndW1lbnQsIGFkZCB0aGF0XG4gICAgICAgIGlmIChub2RlLnJlc3QpIHtcbiAgICAgICAgICAgIHRoaXMudmlzaXRQYXR0ZXJuKHtcbiAgICAgICAgICAgICAgICB0eXBlOiAnUmVzdEVsZW1lbnQnLFxuICAgICAgICAgICAgICAgIGFyZ3VtZW50OiBub2RlLnJlc3RcbiAgICAgICAgICAgIH0sIChwYXR0ZXJuKSA9PiB7XG4gICAgICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX2RlZmluZShwYXR0ZXJuLFxuICAgICAgICAgICAgICAgICAgICBuZXcgUGFyYW1ldGVyRGVmaW5pdGlvbihcbiAgICAgICAgICAgICAgICAgICAgICAgIHBhdHRlcm4sXG4gICAgICAgICAgICAgICAgICAgICAgICBub2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5wYXJhbXMubGVuZ3RoLFxuICAgICAgICAgICAgICAgICAgICAgICAgdHJ1ZVxuICAgICAgICAgICAgICAgICAgICApKTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gU2tpcCBCbG9ja1N0YXRlbWVudCB0byBwcmV2ZW50IGNyZWF0aW5nIEJsb2NrU3RhdGVtZW50IHNjb3BlLlxuICAgICAgICBpZiAobm9kZS5ib2R5LnR5cGUgPT09IFN5bnRheC5CbG9ja1N0YXRlbWVudCkge1xuICAgICAgICAgICAgdGhpcy52aXNpdENoaWxkcmVuKG5vZGUuYm9keSk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0KG5vZGUuYm9keSk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLmNsb3NlKG5vZGUpO1xuICAgIH1cblxuICAgIHZpc2l0Q2xhc3Mobm9kZSkge1xuICAgICAgICBpZiAobm9kZS50eXBlID09PSBTeW50YXguQ2xhc3NEZWNsYXJhdGlvbikge1xuICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX2RlZmluZShub2RlLmlkLFxuICAgICAgICAgICAgICAgICAgICBuZXcgRGVmaW5pdGlvbihcbiAgICAgICAgICAgICAgICAgICAgICAgIFZhcmlhYmxlLkNsYXNzTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuaWQsXG4gICAgICAgICAgICAgICAgICAgICAgICBub2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgICAgIG51bGwsXG4gICAgICAgICAgICAgICAgICAgICAgICBudWxsXG4gICAgICAgICAgICAgICAgICAgICkpO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gRklYTUU6IE1heWJlIGNvbnNpZGVyIFREWi5cbiAgICAgICAgdGhpcy52aXNpdChub2RlLnN1cGVyQ2xhc3MpO1xuXG4gICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyLl9fbmVzdENsYXNzU2NvcGUobm9kZSk7XG5cbiAgICAgICAgaWYgKG5vZGUuaWQpIHtcbiAgICAgICAgICAgIHRoaXMuY3VycmVudFNjb3BlKCkuX19kZWZpbmUobm9kZS5pZCxcbiAgICAgICAgICAgICAgICAgICAgbmV3IERlZmluaXRpb24oXG4gICAgICAgICAgICAgICAgICAgICAgICBWYXJpYWJsZS5DbGFzc05hbWUsXG4gICAgICAgICAgICAgICAgICAgICAgICBub2RlLmlkLFxuICAgICAgICAgICAgICAgICAgICAgICAgbm9kZVxuICAgICAgICAgICAgICAgICAgICApKTtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLnZpc2l0KG5vZGUuYm9keSk7XG5cbiAgICAgICAgdGhpcy5jbG9zZShub2RlKTtcbiAgICB9XG5cbiAgICB2aXNpdFByb3BlcnR5KG5vZGUpIHtcbiAgICAgICAgdmFyIHByZXZpb3VzLCBpc01ldGhvZERlZmluaXRpb247XG4gICAgICAgIGlmIChub2RlLmNvbXB1dGVkKSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0KG5vZGUua2V5KTtcbiAgICAgICAgfVxuXG4gICAgICAgIGlzTWV0aG9kRGVmaW5pdGlvbiA9IG5vZGUudHlwZSA9PT0gU3ludGF4Lk1ldGhvZERlZmluaXRpb24gfHwgbm9kZS5tZXRob2Q7XG4gICAgICAgIGlmIChpc01ldGhvZERlZmluaXRpb24pIHtcbiAgICAgICAgICAgIHByZXZpb3VzID0gdGhpcy5wdXNoSW5uZXJNZXRob2REZWZpbml0aW9uKHRydWUpO1xuICAgICAgICB9XG4gICAgICAgIHRoaXMudmlzaXQobm9kZS52YWx1ZSk7XG4gICAgICAgIGlmIChpc01ldGhvZERlZmluaXRpb24pIHtcbiAgICAgICAgICAgIHRoaXMucG9wSW5uZXJNZXRob2REZWZpbml0aW9uKHByZXZpb3VzKTtcbiAgICAgICAgfVxuICAgIH1cblxuICAgIHZpc2l0Rm9ySW4obm9kZSkge1xuICAgICAgICBpZiAobm9kZS5sZWZ0LnR5cGUgPT09IFN5bnRheC5WYXJpYWJsZURlY2xhcmF0aW9uICYmIG5vZGUubGVmdC5raW5kICE9PSAndmFyJykge1xuICAgICAgICAgICAgdGhpcy5tYXRlcmlhbGl6ZVREWlNjb3BlKG5vZGUucmlnaHQsIG5vZGUpO1xuICAgICAgICAgICAgdGhpcy52aXNpdChub2RlLnJpZ2h0KTtcbiAgICAgICAgICAgIHRoaXMuY2xvc2Uobm9kZS5yaWdodCk7XG5cbiAgICAgICAgICAgIHRoaXMubWF0ZXJpYWxpemVJdGVyYXRpb25TY29wZShub2RlKTtcbiAgICAgICAgICAgIHRoaXMudmlzaXQobm9kZS5ib2R5KTtcbiAgICAgICAgICAgIHRoaXMuY2xvc2Uobm9kZSk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICBpZiAobm9kZS5sZWZ0LnR5cGUgPT09IFN5bnRheC5WYXJpYWJsZURlY2xhcmF0aW9uKSB7XG4gICAgICAgICAgICAgICAgdGhpcy52aXNpdChub2RlLmxlZnQpO1xuICAgICAgICAgICAgICAgIHRoaXMudmlzaXRQYXR0ZXJuKG5vZGUubGVmdC5kZWNsYXJhdGlvbnNbMF0uaWQsIChwYXR0ZXJuKSA9PiB7XG4gICAgICAgICAgICAgICAgICAgIHRoaXMuY3VycmVudFNjb3BlKCkuX19yZWZlcmVuY2luZyhwYXR0ZXJuLCBSZWZlcmVuY2UuV1JJVEUsIG5vZGUucmlnaHQsIG51bGwsIHRydWUpO1xuICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICBpZiAoIWlzUGF0dGVybihub2RlLmxlZnQpKSB7XG4gICAgICAgICAgICAgICAgICAgIHRoaXMudmlzaXQobm9kZS5sZWZ0KTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgdGhpcy52aXNpdFBhdHRlcm4obm9kZS5sZWZ0LCAocGF0dGVybikgPT4ge1xuICAgICAgICAgICAgICAgICAgICB2YXIgbWF5YmVJbXBsaWNpdEdsb2JhbCA9IG51bGw7XG4gICAgICAgICAgICAgICAgICAgIGlmICghdGhpcy5jdXJyZW50U2NvcGUoKS5pc1N0cmljdCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgbWF5YmVJbXBsaWNpdEdsb2JhbCA9IHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBwYXR0ZXJuOiBwYXR0ZXJuLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGU6IG5vZGVcbiAgICAgICAgICAgICAgICAgICAgICAgIH07XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX3JlZmVyZW5jaW5nKHBhdHRlcm4sIFJlZmVyZW5jZS5XUklURSwgbm9kZS5yaWdodCwgbWF5YmVJbXBsaWNpdEdsb2JhbCwgdHJ1ZSk7XG4gICAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICB0aGlzLnZpc2l0KG5vZGUucmlnaHQpO1xuICAgICAgICAgICAgdGhpcy52aXNpdChub2RlLmJvZHkpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgdmlzaXRWYXJpYWJsZURlY2xhcmF0aW9uKHZhcmlhYmxlVGFyZ2V0U2NvcGUsIHR5cGUsIG5vZGUsIGluZGV4KSB7XG4gICAgICAgIHZhciBkZWNsLCBpbml0O1xuXG4gICAgICAgIGRlY2wgPSBub2RlLmRlY2xhcmF0aW9uc1tpbmRleF07XG4gICAgICAgIGluaXQgPSBkZWNsLmluaXQ7XG4gICAgICAgIHRoaXMudmlzaXRQYXR0ZXJuKGRlY2wuaWQsIChwYXR0ZXJuLCB0b3BsZXZlbCkgPT4ge1xuICAgICAgICAgICAgdmFyaWFibGVUYXJnZXRTY29wZS5fX2RlZmluZShwYXR0ZXJuLFxuICAgICAgICAgICAgICAgIG5ldyBEZWZpbml0aW9uKFxuICAgICAgICAgICAgICAgICAgICB0eXBlLFxuICAgICAgICAgICAgICAgICAgICBwYXR0ZXJuLFxuICAgICAgICAgICAgICAgICAgICBkZWNsLFxuICAgICAgICAgICAgICAgICAgICBub2RlLFxuICAgICAgICAgICAgICAgICAgICBpbmRleCxcbiAgICAgICAgICAgICAgICAgICAgbm9kZS5raW5kXG4gICAgICAgICAgICAgICAgKSk7XG5cbiAgICAgICAgICAgIGlmIChpbml0KSB7XG4gICAgICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX3JlZmVyZW5jaW5nKHBhdHRlcm4sIFJlZmVyZW5jZS5XUklURSwgaW5pdCwgbnVsbCwgIXRvcGxldmVsKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgfVxuXG4gICAgQXNzaWdubWVudEV4cHJlc3Npb24obm9kZSkge1xuICAgICAgICBpZiAoaXNQYXR0ZXJuKG5vZGUubGVmdCkpIHtcbiAgICAgICAgICAgIGlmIChub2RlLm9wZXJhdG9yID09PSAnPScpIHtcbiAgICAgICAgICAgICAgICB0aGlzLnZpc2l0UGF0dGVybihub2RlLmxlZnQsIChwYXR0ZXJuLCB0b3BsZXZlbCkgPT4ge1xuICAgICAgICAgICAgICAgICAgICB2YXIgbWF5YmVJbXBsaWNpdEdsb2JhbCA9IG51bGw7XG4gICAgICAgICAgICAgICAgICAgIGlmICghdGhpcy5jdXJyZW50U2NvcGUoKS5pc1N0cmljdCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgbWF5YmVJbXBsaWNpdEdsb2JhbCA9IHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBwYXR0ZXJuOiBwYXR0ZXJuLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGU6IG5vZGVcbiAgICAgICAgICAgICAgICAgICAgICAgIH07XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX3JlZmVyZW5jaW5nKHBhdHRlcm4sIFJlZmVyZW5jZS5XUklURSwgbm9kZS5yaWdodCwgbWF5YmVJbXBsaWNpdEdsb2JhbCwgIXRvcGxldmVsKTtcbiAgICAgICAgICAgICAgICB9KTtcbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX3JlZmVyZW5jaW5nKG5vZGUubGVmdCwgUmVmZXJlbmNlLlJXLCBub2RlLnJpZ2h0KTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIHRoaXMudmlzaXQobm9kZS5sZWZ0KTtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLnZpc2l0KG5vZGUucmlnaHQpO1xuICAgIH1cblxuICAgIENhdGNoQ2xhdXNlKG5vZGUpIHtcbiAgICAgICAgdGhpcy5zY29wZU1hbmFnZXIuX19uZXN0Q2F0Y2hTY29wZShub2RlKTtcblxuICAgICAgICB0aGlzLnZpc2l0UGF0dGVybihub2RlLnBhcmFtLCAocGF0dGVybikgPT4ge1xuICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX2RlZmluZShwYXR0ZXJuLFxuICAgICAgICAgICAgICAgIG5ldyBEZWZpbml0aW9uKFxuICAgICAgICAgICAgICAgICAgICBWYXJpYWJsZS5DYXRjaENsYXVzZSxcbiAgICAgICAgICAgICAgICAgICAgbm9kZS5wYXJhbSxcbiAgICAgICAgICAgICAgICAgICAgbm9kZSxcbiAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgbnVsbFxuICAgICAgICAgICAgICAgICkpO1xuICAgICAgICB9KTtcbiAgICAgICAgdGhpcy52aXNpdChub2RlLmJvZHkpO1xuXG4gICAgICAgIHRoaXMuY2xvc2Uobm9kZSk7XG4gICAgfVxuXG4gICAgUHJvZ3JhbShub2RlKSB7XG4gICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyLl9fbmVzdEdsb2JhbFNjb3BlKG5vZGUpO1xuXG4gICAgICAgIGlmICh0aGlzLnNjb3BlTWFuYWdlci5fX2lzTm9kZWpzU2NvcGUoKSkge1xuICAgICAgICAgICAgLy8gRm9yY2Ugc3RyaWN0bmVzcyBvZiBHbG9iYWxTY29wZSB0byBmYWxzZSB3aGVuIHVzaW5nIG5vZGUuanMgc2NvcGUuXG4gICAgICAgICAgICB0aGlzLmN1cnJlbnRTY29wZSgpLmlzU3RyaWN0ID0gZmFsc2U7XG4gICAgICAgICAgICB0aGlzLnNjb3BlTWFuYWdlci5fX25lc3RGdW5jdGlvblNjb3BlKG5vZGUsIGZhbHNlKTtcbiAgICAgICAgfVxuXG4gICAgICAgIGlmICh0aGlzLnNjb3BlTWFuYWdlci5fX2lzRVM2KCkgJiYgdGhpcy5zY29wZU1hbmFnZXIuaXNNb2R1bGUoKSkge1xuICAgICAgICAgICAgdGhpcy5zY29wZU1hbmFnZXIuX19uZXN0TW9kdWxlU2NvcGUobm9kZSk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLnZpc2l0Q2hpbGRyZW4obm9kZSk7XG4gICAgICAgIHRoaXMuY2xvc2Uobm9kZSk7XG4gICAgfVxuXG4gICAgSWRlbnRpZmllcihub2RlKSB7XG4gICAgICAgIHRoaXMuY3VycmVudFNjb3BlKCkuX19yZWZlcmVuY2luZyhub2RlKTtcbiAgICB9XG5cbiAgICBVcGRhdGVFeHByZXNzaW9uKG5vZGUpIHtcbiAgICAgICAgaWYgKGlzUGF0dGVybihub2RlLmFyZ3VtZW50KSkge1xuICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS5fX3JlZmVyZW5jaW5nKG5vZGUuYXJndW1lbnQsIFJlZmVyZW5jZS5SVywgbnVsbCk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0Q2hpbGRyZW4obm9kZSk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICBNZW1iZXJFeHByZXNzaW9uKG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdChub2RlLm9iamVjdCk7XG4gICAgICAgIGlmIChub2RlLmNvbXB1dGVkKSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0KG5vZGUucHJvcGVydHkpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgUHJvcGVydHkobm9kZSkge1xuICAgICAgICB0aGlzLnZpc2l0UHJvcGVydHkobm9kZSk7XG4gICAgfVxuXG4gICAgTWV0aG9kRGVmaW5pdGlvbihub2RlKSB7XG4gICAgICAgIHRoaXMudmlzaXRQcm9wZXJ0eShub2RlKTtcbiAgICB9XG5cbiAgICBCcmVha1N0YXRlbWVudCgpIHt9XG5cbiAgICBDb250aW51ZVN0YXRlbWVudCgpIHt9XG5cbiAgICBMYWJlbGVkU3RhdGVtZW50KG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdChub2RlLmJvZHkpO1xuICAgIH1cblxuICAgIEZvclN0YXRlbWVudChub2RlKSB7XG4gICAgICAgIC8vIENyZWF0ZSBGb3JTdGF0ZW1lbnQgZGVjbGFyYXRpb24uXG4gICAgICAgIC8vIE5PVEU6IEluIEVTNiwgRm9yU3RhdGVtZW50IGR5bmFtaWNhbGx5IGdlbmVyYXRlc1xuICAgICAgICAvLyBwZXIgaXRlcmF0aW9uIGVudmlyb25tZW50LiBIb3dldmVyLCBlc2NvcGUgaXNcbiAgICAgICAgLy8gYSBzdGF0aWMgYW5hbHl6ZXIsIHdlIG9ubHkgZ2VuZXJhdGUgb25lIHNjb3BlIGZvciBGb3JTdGF0ZW1lbnQuXG4gICAgICAgIGlmIChub2RlLmluaXQgJiYgbm9kZS5pbml0LnR5cGUgPT09IFN5bnRheC5WYXJpYWJsZURlY2xhcmF0aW9uICYmIG5vZGUuaW5pdC5raW5kICE9PSAndmFyJykge1xuICAgICAgICAgICAgdGhpcy5zY29wZU1hbmFnZXIuX19uZXN0Rm9yU2NvcGUobm9kZSk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLnZpc2l0Q2hpbGRyZW4obm9kZSk7XG5cbiAgICAgICAgdGhpcy5jbG9zZShub2RlKTtcbiAgICB9XG5cbiAgICBDbGFzc0V4cHJlc3Npb24obm9kZSkge1xuICAgICAgICB0aGlzLnZpc2l0Q2xhc3Mobm9kZSk7XG4gICAgfVxuXG4gICAgQ2xhc3NEZWNsYXJhdGlvbihub2RlKSB7XG4gICAgICAgIHRoaXMudmlzaXRDbGFzcyhub2RlKTtcbiAgICB9XG5cbiAgICBDYWxsRXhwcmVzc2lvbihub2RlKSB7XG4gICAgICAgIC8vIENoZWNrIHRoaXMgaXMgZGlyZWN0IGNhbGwgdG8gZXZhbFxuICAgICAgICBpZiAoIXRoaXMuc2NvcGVNYW5hZ2VyLl9faWdub3JlRXZhbCgpICYmIG5vZGUuY2FsbGVlLnR5cGUgPT09IFN5bnRheC5JZGVudGlmaWVyICYmIG5vZGUuY2FsbGVlLm5hbWUgPT09ICdldmFsJykge1xuICAgICAgICAgICAgLy8gTk9URTogVGhpcyBzaG91bGQgYmUgYHZhcmlhYmxlU2NvcGVgLiBTaW5jZSBkaXJlY3QgZXZhbCBjYWxsIGFsd2F5cyBjcmVhdGVzIExleGljYWwgZW52aXJvbm1lbnQgYW5kXG4gICAgICAgICAgICAvLyBsZXQgLyBjb25zdCBzaG91bGQgYmUgZW5jbG9zZWQgaW50byBpdC4gT25seSBWYXJpYWJsZURlY2xhcmF0aW9uIGFmZmVjdHMgb24gdGhlIGNhbGxlcidzIGVudmlyb25tZW50LlxuICAgICAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS52YXJpYWJsZVNjb3BlLl9fZGV0ZWN0RXZhbCgpO1xuICAgICAgICB9XG4gICAgICAgIHRoaXMudmlzaXRDaGlsZHJlbihub2RlKTtcbiAgICB9XG5cbiAgICBCbG9ja1N0YXRlbWVudChub2RlKSB7XG4gICAgICAgIGlmICh0aGlzLnNjb3BlTWFuYWdlci5fX2lzRVM2KCkpIHtcbiAgICAgICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyLl9fbmVzdEJsb2NrU2NvcGUobm9kZSk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLnZpc2l0Q2hpbGRyZW4obm9kZSk7XG5cbiAgICAgICAgdGhpcy5jbG9zZShub2RlKTtcbiAgICB9XG5cbiAgICBUaGlzRXhwcmVzc2lvbigpIHtcbiAgICAgICAgdGhpcy5jdXJyZW50U2NvcGUoKS52YXJpYWJsZVNjb3BlLl9fZGV0ZWN0VGhpcygpO1xuICAgIH1cblxuICAgIFdpdGhTdGF0ZW1lbnQobm9kZSkge1xuICAgICAgICB0aGlzLnZpc2l0KG5vZGUub2JqZWN0KTtcbiAgICAgICAgLy8gVGhlbiBuZXN0IHNjb3BlIGZvciBXaXRoU3RhdGVtZW50LlxuICAgICAgICB0aGlzLnNjb3BlTWFuYWdlci5fX25lc3RXaXRoU2NvcGUobm9kZSk7XG5cbiAgICAgICAgdGhpcy52aXNpdChub2RlLmJvZHkpO1xuXG4gICAgICAgIHRoaXMuY2xvc2Uobm9kZSk7XG4gICAgfVxuXG4gICAgVmFyaWFibGVEZWNsYXJhdGlvbihub2RlKSB7XG4gICAgICAgIHZhciB2YXJpYWJsZVRhcmdldFNjb3BlLCBpLCBpeiwgZGVjbDtcbiAgICAgICAgdmFyaWFibGVUYXJnZXRTY29wZSA9IChub2RlLmtpbmQgPT09ICd2YXInKSA/IHRoaXMuY3VycmVudFNjb3BlKCkudmFyaWFibGVTY29wZSA6IHRoaXMuY3VycmVudFNjb3BlKCk7XG4gICAgICAgIGZvciAoaSA9IDAsIGl6ID0gbm9kZS5kZWNsYXJhdGlvbnMubGVuZ3RoOyBpIDwgaXo7ICsraSkge1xuICAgICAgICAgICAgZGVjbCA9IG5vZGUuZGVjbGFyYXRpb25zW2ldO1xuICAgICAgICAgICAgdGhpcy52aXNpdFZhcmlhYmxlRGVjbGFyYXRpb24odmFyaWFibGVUYXJnZXRTY29wZSwgVmFyaWFibGUuVmFyaWFibGUsIG5vZGUsIGkpO1xuICAgICAgICAgICAgaWYgKGRlY2wuaW5pdCkge1xuICAgICAgICAgICAgICAgIHRoaXMudmlzaXQoZGVjbC5pbml0KTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cblxuICAgIC8vIHNlYyAxMy4xMS44XG4gICAgU3dpdGNoU3RhdGVtZW50KG5vZGUpIHtcbiAgICAgICAgdmFyIGksIGl6O1xuXG4gICAgICAgIHRoaXMudmlzaXQobm9kZS5kaXNjcmltaW5hbnQpO1xuXG4gICAgICAgIGlmICh0aGlzLnNjb3BlTWFuYWdlci5fX2lzRVM2KCkpIHtcbiAgICAgICAgICAgIHRoaXMuc2NvcGVNYW5hZ2VyLl9fbmVzdFN3aXRjaFNjb3BlKG5vZGUpO1xuICAgICAgICB9XG5cbiAgICAgICAgZm9yIChpID0gMCwgaXogPSBub2RlLmNhc2VzLmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgIHRoaXMudmlzaXQobm9kZS5jYXNlc1tpXSk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLmNsb3NlKG5vZGUpO1xuICAgIH1cblxuICAgIEZ1bmN0aW9uRGVjbGFyYXRpb24obm9kZSkge1xuICAgICAgICB0aGlzLnZpc2l0RnVuY3Rpb24obm9kZSk7XG4gICAgfVxuXG4gICAgRnVuY3Rpb25FeHByZXNzaW9uKG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdEZ1bmN0aW9uKG5vZGUpO1xuICAgIH1cblxuICAgIEZvck9mU3RhdGVtZW50KG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdEZvckluKG5vZGUpO1xuICAgIH1cblxuICAgIEZvckluU3RhdGVtZW50KG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdEZvckluKG5vZGUpO1xuICAgIH1cblxuICAgIEFycm93RnVuY3Rpb25FeHByZXNzaW9uKG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdEZ1bmN0aW9uKG5vZGUpO1xuICAgIH1cblxuICAgIEltcG9ydERlY2xhcmF0aW9uKG5vZGUpIHtcbiAgICAgICAgdmFyIGltcG9ydGVyO1xuXG4gICAgICAgIGFzc2VydCh0aGlzLnNjb3BlTWFuYWdlci5fX2lzRVM2KCkgJiYgdGhpcy5zY29wZU1hbmFnZXIuaXNNb2R1bGUoKSwgJ0ltcG9ydERlY2xhcmF0aW9uIHNob3VsZCBhcHBlYXIgd2hlbiB0aGUgbW9kZSBpcyBFUzYgYW5kIGluIHRoZSBtb2R1bGUgY29udGV4dC4nKTtcblxuICAgICAgICBpbXBvcnRlciA9IG5ldyBJbXBvcnRlcihub2RlLCB0aGlzKTtcbiAgICAgICAgaW1wb3J0ZXIudmlzaXQobm9kZSk7XG4gICAgfVxuXG4gICAgdmlzaXRFeHBvcnREZWNsYXJhdGlvbihub2RlKSB7XG4gICAgICAgIGlmIChub2RlLnNvdXJjZSkge1xuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG4gICAgICAgIGlmIChub2RlLmRlY2xhcmF0aW9uKSB7XG4gICAgICAgICAgICB0aGlzLnZpc2l0KG5vZGUuZGVjbGFyYXRpb24pO1xuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG5cbiAgICAgICAgdGhpcy52aXNpdENoaWxkcmVuKG5vZGUpO1xuICAgIH1cblxuICAgIEV4cG9ydERlY2xhcmF0aW9uKG5vZGUpIHtcbiAgICAgICAgdGhpcy52aXNpdEV4cG9ydERlY2xhcmF0aW9uKG5vZGUpO1xuICAgIH1cblxuICAgIEV4cG9ydE5hbWVkRGVjbGFyYXRpb24obm9kZSkge1xuICAgICAgICB0aGlzLnZpc2l0RXhwb3J0RGVjbGFyYXRpb24obm9kZSk7XG4gICAgfVxuXG4gICAgRXhwb3J0U3BlY2lmaWVyKG5vZGUpIHtcbiAgICAgICAgbGV0IGxvY2FsID0gKG5vZGUuaWQgfHwgbm9kZS5sb2NhbCk7XG4gICAgICAgIHRoaXMudmlzaXQobG9jYWwpO1xuICAgIH1cbn1cblxuLyogdmltOiBzZXQgc3c9NCB0cz00IGV0IHR3PTgwIDogKi9cbiJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ== \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/lib/scope-manager.js b/tools/eslint/node_modules/escope/lib/scope-manager.js new file mode 100644 index 00000000000000..bb64896f007223 --- /dev/null +++ b/tools/eslint/node_modules/escope/lib/scope-manager.js @@ -0,0 +1,275 @@ +"use strict"; + +var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; + +var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +var WeakMap = _interopRequire(require("es6-weak-map")); + +var _scope = require("./scope"); + +var Scope = _interopRequire(_scope); + +var assert = _interopRequire(require("assert")); + +var GlobalScope = _scope.GlobalScope; +var CatchScope = _scope.CatchScope; +var WithScope = _scope.WithScope; +var ModuleScope = _scope.ModuleScope; +var ClassScope = _scope.ClassScope; +var SwitchScope = _scope.SwitchScope; +var FunctionScope = _scope.FunctionScope; +var ForScope = _scope.ForScope; +var TDZScope = _scope.TDZScope; +var FunctionExpressionNameScope = _scope.FunctionExpressionNameScope; +var BlockScope = _scope.BlockScope; + +/** + * @class ScopeManager + */ + +var ScopeManager = (function () { + function ScopeManager(options) { + _classCallCheck(this, ScopeManager); + + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + } + + _createClass(ScopeManager, { + __useDirective: { + value: function __useDirective() { + return this.__options.directive; + } + }, + __isOptimistic: { + value: function __isOptimistic() { + return this.__options.optimistic; + } + }, + __ignoreEval: { + value: function __ignoreEval() { + return this.__options.ignoreEval; + } + }, + __isNodejsScope: { + value: function __isNodejsScope() { + return this.__options.nodejsScope; + } + }, + isModule: { + value: function isModule() { + return this.__options.sourceType === "module"; + } + }, + __get: { + + // Returns appropliate scope for this node. + + value: function __get(node) { + return this.__nodeToScope.get(node); + } + }, + acquire: { + + /** + * acquire scope from node. + * @method ScopeManager#acquire + * @param {Esprima.Node} node - node for the acquired scope. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @return {Scope?} + */ + + value: function acquire(node, inner) { + var scopes, scope, i, iz; + + function predicate(scope) { + if (scope.type === "function" && scope.functionExpressionScope) { + return false; + } + if (scope.type === "TDZ") { + return false; + } + return true; + } + + scopes = this.__get(node); + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (i = scopes.length - 1; i >= 0; --i) { + scope = scopes[i]; + if (predicate(scope)) { + return scope; + } + } + } else { + for (i = 0, iz = scopes.length; i < iz; ++i) { + scope = scopes[i]; + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + }, + acquireAll: { + + /** + * acquire all scopes from node. + * @method ScopeManager#acquireAll + * @param {Esprima.Node} node - node for the acquired scope. + * @return {Scope[]?} + */ + + value: function acquireAll(node) { + return this.__get(node); + } + }, + release: { + + /** + * release the node. + * @method ScopeManager#release + * @param {Esprima.Node} node - releasing node. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @return {Scope?} upper scope for the node. + */ + + value: function release(node, inner) { + var scopes, scope; + scopes = this.__get(node); + if (scopes && scopes.length) { + scope = scopes[0].upper; + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + }, + attach: { + value: function attach() {} + }, + detach: { + value: function detach() {} + }, + __nestScope: { + value: function __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + }, + __nestGlobalScope: { + value: function __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + }, + __nestBlockScope: { + value: function __nestBlockScope(node, isMethodDefinition) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + }, + __nestFunctionScope: { + value: function __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + }, + __nestForScope: { + value: function __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + }, + __nestCatchScope: { + value: function __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + }, + __nestWithScope: { + value: function __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + }, + __nestClassScope: { + value: function __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + }, + __nestSwitchScope: { + value: function __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + }, + __nestModuleScope: { + value: function __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + }, + __nestTDZScope: { + value: function __nestTDZScope(node) { + return this.__nestScope(new TDZScope(this, this.__currentScope, node)); + } + }, + __nestFunctionExpressionNameScope: { + value: function __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + }, + __isES6: { + value: function __isES6() { + return this.__options.ecmaVersion >= 6; + } + } + }); + + return ScopeManager; +})(); + +module.exports = ScopeManager; + +/* vim: set sw=4 ts=4 et tw=80 : */ +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjb3BlLW1hbmFnZXIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7SUF3Qk8sT0FBTywyQkFBTSxjQUFjOztxQkFDaEIsU0FBUzs7SUFBcEIsS0FBSzs7SUFDTCxNQUFNLDJCQUFNLFFBQVE7O0lBR3ZCLFdBQVcsVUFBWCxXQUFXO0lBQ1gsVUFBVSxVQUFWLFVBQVU7SUFDVixTQUFTLFVBQVQsU0FBUztJQUNULFdBQVcsVUFBWCxXQUFXO0lBQ1gsVUFBVSxVQUFWLFVBQVU7SUFDVixXQUFXLFVBQVgsV0FBVztJQUNYLGFBQWEsVUFBYixhQUFhO0lBQ2IsUUFBUSxVQUFSLFFBQVE7SUFDUixRQUFRLFVBQVIsUUFBUTtJQUNSLDJCQUEyQixVQUEzQiwyQkFBMkI7SUFDM0IsVUFBVSxVQUFWLFVBQVU7Ozs7OztJQU1PLFlBQVk7QUFDbEIsYUFETSxZQUFZLENBQ2pCLE9BQU8sRUFBRTs4QkFESixZQUFZOztBQUV6QixZQUFJLENBQUMsTUFBTSxHQUFHLEVBQUUsQ0FBQztBQUNqQixZQUFJLENBQUMsV0FBVyxHQUFHLElBQUksQ0FBQztBQUN4QixZQUFJLENBQUMsYUFBYSxHQUFHLElBQUksT0FBTyxFQUFFLENBQUM7QUFDbkMsWUFBSSxDQUFDLGNBQWMsR0FBRyxJQUFJLENBQUM7QUFDM0IsWUFBSSxDQUFDLFNBQVMsR0FBRyxPQUFPLENBQUM7S0FDNUI7O2lCQVBnQixZQUFZO0FBUzdCLHNCQUFjO21CQUFBLDBCQUFHO0FBQ2IsdUJBQU8sSUFBSSxDQUFDLFNBQVMsQ0FBQyxTQUFTLENBQUM7YUFDbkM7O0FBRUQsc0JBQWM7bUJBQUEsMEJBQUc7QUFDYix1QkFBTyxJQUFJLENBQUMsU0FBUyxDQUFDLFVBQVUsQ0FBQzthQUNwQzs7QUFFRCxvQkFBWTttQkFBQSx3QkFBRztBQUNYLHVCQUFPLElBQUksQ0FBQyxTQUFTLENBQUMsVUFBVSxDQUFDO2FBQ3BDOztBQUVELHVCQUFlO21CQUFBLDJCQUFHO0FBQ2QsdUJBQU8sSUFBSSxDQUFDLFNBQVMsQ0FBQyxXQUFXLENBQUM7YUFDckM7O0FBRUQsZ0JBQVE7bUJBQUEsb0JBQUc7QUFDUCx1QkFBTyxJQUFJLENBQUMsU0FBUyxDQUFDLFVBQVUsS0FBSyxRQUFRLENBQUM7YUFDakQ7O0FBR0QsYUFBSzs7OzttQkFBQSxlQUFDLElBQUksRUFBRTtBQUNSLHVCQUFPLElBQUksQ0FBQyxhQUFhLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQ3ZDOztBQVNELGVBQU87Ozs7Ozs7Ozs7bUJBQUEsaUJBQUMsSUFBSSxFQUFFLEtBQUssRUFBRTtBQUNqQixvQkFBSSxNQUFNLEVBQUUsS0FBSyxFQUFFLENBQUMsRUFBRSxFQUFFLENBQUM7O0FBRXpCLHlCQUFTLFNBQVMsQ0FBQyxLQUFLLEVBQUU7QUFDdEIsd0JBQUksS0FBSyxDQUFDLElBQUksS0FBSyxVQUFVLElBQUksS0FBSyxDQUFDLHVCQUF1QixFQUFFO0FBQzVELCtCQUFPLEtBQUssQ0FBQztxQkFDaEI7QUFDRCx3QkFBSSxLQUFLLENBQUMsSUFBSSxLQUFLLEtBQUssRUFBRTtBQUN0QiwrQkFBTyxLQUFLLENBQUM7cUJBQ2hCO0FBQ0QsMkJBQU8sSUFBSSxDQUFDO2lCQUNmOztBQUVELHNCQUFNLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUMxQixvQkFBSSxDQUFDLE1BQU0sSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsRUFBRTtBQUNoQywyQkFBTyxJQUFJLENBQUM7aUJBQ2Y7Ozs7QUFJRCxvQkFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsRUFBRTtBQUNyQiwyQkFBTyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7aUJBQ3BCOztBQUVELG9CQUFJLEtBQUssRUFBRTtBQUNQLHlCQUFLLENBQUMsR0FBRyxNQUFNLENBQUMsTUFBTSxHQUFHLENBQUMsRUFBRSxDQUFDLElBQUksQ0FBQyxFQUFFLEVBQUUsQ0FBQyxFQUFFO0FBQ3JDLDZCQUFLLEdBQUcsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ2xCLDRCQUFJLFNBQVMsQ0FBQyxLQUFLLENBQUMsRUFBRTtBQUNsQixtQ0FBTyxLQUFLLENBQUM7eUJBQ2hCO3FCQUNKO2lCQUNKLE1BQU07QUFDSCx5QkFBSyxDQUFDLEdBQUcsQ0FBQyxFQUFFLEVBQUUsR0FBRyxNQUFNLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUU7QUFDekMsNkJBQUssR0FBRyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDbEIsNEJBQUksU0FBUyxDQUFDLEtBQUssQ0FBQyxFQUFFO0FBQ2xCLG1DQUFPLEtBQUssQ0FBQzt5QkFDaEI7cUJBQ0o7aUJBQ0o7O0FBRUQsdUJBQU8sSUFBSSxDQUFDO2FBQ2Y7O0FBUUQsa0JBQVU7Ozs7Ozs7OzttQkFBQSxvQkFBQyxJQUFJLEVBQUU7QUFDYix1QkFBTyxJQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDO2FBQzNCOztBQVNELGVBQU87Ozs7Ozs7Ozs7bUJBQUEsaUJBQUMsSUFBSSxFQUFFLEtBQUssRUFBRTtBQUNqQixvQkFBSSxNQUFNLEVBQUUsS0FBSyxDQUFDO0FBQ2xCLHNCQUFNLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUMxQixvQkFBSSxNQUFNLElBQUksTUFBTSxDQUFDLE1BQU0sRUFBRTtBQUN6Qix5QkFBSyxHQUFHLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxLQUFLLENBQUM7QUFDeEIsd0JBQUksQ0FBQyxLQUFLLEVBQUU7QUFDUiwrQkFBTyxJQUFJLENBQUM7cUJBQ2Y7QUFDRCwyQkFBTyxJQUFJLENBQUMsT0FBTyxDQUFDLEtBQUssQ0FBQyxLQUFLLEVBQUUsS0FBSyxDQUFDLENBQUM7aUJBQzNDO0FBQ0QsdUJBQU8sSUFBSSxDQUFDO2FBQ2Y7O0FBRUQsY0FBTTttQkFBQSxrQkFBRyxFQUFHOztBQUVaLGNBQU07bUJBQUEsa0JBQUcsRUFBRzs7QUFFWixtQkFBVzttQkFBQSxxQkFBQyxLQUFLLEVBQUU7QUFDZixvQkFBSSxLQUFLLFlBQVksV0FBVyxFQUFFO0FBQzlCLDBCQUFNLENBQUMsSUFBSSxDQUFDLGNBQWMsS0FBSyxJQUFJLENBQUMsQ0FBQztBQUNyQyx3QkFBSSxDQUFDLFdBQVcsR0FBRyxLQUFLLENBQUM7aUJBQzVCO0FBQ0Qsb0JBQUksQ0FBQyxjQUFjLEdBQUcsS0FBSyxDQUFDO0FBQzVCLHVCQUFPLEtBQUssQ0FBQzthQUNoQjs7QUFFRCx5QkFBaUI7bUJBQUEsMkJBQUMsSUFBSSxFQUFFO0FBQ3BCLHVCQUFPLElBQUksQ0FBQyxXQUFXLENBQUMsSUFBSSxXQUFXLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxDQUFDLENBQUM7YUFDeEQ7O0FBRUQsd0JBQWdCO21CQUFBLDBCQUFDLElBQUksRUFBRSxrQkFBa0IsRUFBRTtBQUN2Qyx1QkFBTyxJQUFJLENBQUMsV0FBVyxDQUFDLElBQUksVUFBVSxDQUFDLElBQUksRUFBRSxJQUFJLENBQUMsY0FBYyxFQUFFLElBQUksQ0FBQyxDQUFDLENBQUM7YUFDNUU7O0FBRUQsMkJBQW1CO21CQUFBLDZCQUFDLElBQUksRUFBRSxrQkFBa0IsRUFBRTtBQUMxQyx1QkFBTyxJQUFJLENBQUMsV0FBVyxDQUFDLElBQUksYUFBYSxDQUFDLElBQUksRUFBRSxJQUFJLENBQUMsY0FBYyxFQUFFLElBQUksRUFBRSxrQkFBa0IsQ0FBQyxDQUFDLENBQUM7YUFDbkc7O0FBRUQsc0JBQWM7bUJBQUEsd0JBQUMsSUFBSSxFQUFFO0FBQ2pCLHVCQUFPLElBQUksQ0FBQyxXQUFXLENBQUMsSUFBSSxRQUFRLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxjQUFjLEVBQUUsSUFBSSxDQUFDLENBQUMsQ0FBQzthQUMxRTs7QUFFRCx3QkFBZ0I7bUJBQUEsMEJBQUMsSUFBSSxFQUFFO0FBQ25CLHVCQUFPLElBQUksQ0FBQyxXQUFXLENBQUMsSUFBSSxVQUFVLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxjQUFjLEVBQUUsSUFBSSxDQUFDLENBQUMsQ0FBQzthQUM1RTs7QUFFRCx1QkFBZTttQkFBQSx5QkFBQyxJQUFJLEVBQUU7QUFDbEIsdUJBQU8sSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLFNBQVMsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLGNBQWMsRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO2FBQzNFOztBQUVELHdCQUFnQjttQkFBQSwwQkFBQyxJQUFJLEVBQUU7QUFDbkIsdUJBQU8sSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLFVBQVUsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLGNBQWMsRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO2FBQzVFOztBQUVELHlCQUFpQjttQkFBQSwyQkFBQyxJQUFJLEVBQUU7QUFDcEIsdUJBQU8sSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLFdBQVcsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLGNBQWMsRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO2FBQzdFOztBQUVELHlCQUFpQjttQkFBQSwyQkFBQyxJQUFJLEVBQUU7QUFDcEIsdUJBQU8sSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLFdBQVcsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLGNBQWMsRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDO2FBQzdFOztBQUVELHNCQUFjO21CQUFBLHdCQUFDLElBQUksRUFBRTtBQUNqQix1QkFBTyxJQUFJLENBQUMsV0FBVyxDQUFDLElBQUksUUFBUSxDQUFDLElBQUksRUFBRSxJQUFJLENBQUMsY0FBYyxFQUFFLElBQUksQ0FBQyxDQUFDLENBQUM7YUFDMUU7O0FBRUQseUNBQWlDO21CQUFBLDJDQUFDLElBQUksRUFBRTtBQUNwQyx1QkFBTyxJQUFJLENBQUMsV0FBVyxDQUFDLElBQUksMkJBQTJCLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxjQUFjLEVBQUUsSUFBSSxDQUFDLENBQUMsQ0FBQzthQUM3Rjs7QUFFRCxlQUFPO21CQUFBLG1CQUFHO0FBQ04sdUJBQU8sSUFBSSxDQUFDLFNBQVMsQ0FBQyxXQUFXLElBQUksQ0FBQyxDQUFDO2FBQzFDOzs7O1dBN0tnQixZQUFZOzs7aUJBQVosWUFBWSIsImZpbGUiOiJzY29wZS1tYW5hZ2VyLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLypcbiAgQ29weXJpZ2h0IChDKSAyMDE1IFl1c3VrZSBTdXp1a2kgPHV0YXRhbmUudGVhQGdtYWlsLmNvbT5cblxuICBSZWRpc3RyaWJ1dGlvbiBhbmQgdXNlIGluIHNvdXJjZSBhbmQgYmluYXJ5IGZvcm1zLCB3aXRoIG9yIHdpdGhvdXRcbiAgbW9kaWZpY2F0aW9uLCBhcmUgcGVybWl0dGVkIHByb3ZpZGVkIHRoYXQgdGhlIGZvbGxvd2luZyBjb25kaXRpb25zIGFyZSBtZXQ6XG5cbiAgICAqIFJlZGlzdHJpYnV0aW9ucyBvZiBzb3VyY2UgY29kZSBtdXN0IHJldGFpbiB0aGUgYWJvdmUgY29weXJpZ2h0XG4gICAgICBub3RpY2UsIHRoaXMgbGlzdCBvZiBjb25kaXRpb25zIGFuZCB0aGUgZm9sbG93aW5nIGRpc2NsYWltZXIuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgaW4gYmluYXJ5IGZvcm0gbXVzdCByZXByb2R1Y2UgdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyIGluIHRoZVxuICAgICAgZG9jdW1lbnRhdGlvbiBhbmQvb3Igb3RoZXIgbWF0ZXJpYWxzIHByb3ZpZGVkIHdpdGggdGhlIGRpc3RyaWJ1dGlvbi5cblxuICBUSElTIFNPRlRXQVJFIElTIFBST1ZJREVEIEJZIFRIRSBDT1BZUklHSFQgSE9MREVSUyBBTkQgQ09OVFJJQlVUT1JTIFwiQVMgSVNcIlxuICBBTkQgQU5ZIEVYUFJFU1MgT1IgSU1QTElFRCBXQVJSQU5USUVTLCBJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgVEhFXG4gIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkgQU5EIEZJVE5FU1MgRk9SIEEgUEFSVElDVUxBUiBQVVJQT1NFXG4gIEFSRSBESVNDTEFJTUVELiBJTiBOTyBFVkVOVCBTSEFMTCA8Q09QWVJJR0hUIEhPTERFUj4gQkUgTElBQkxFIEZPUiBBTllcbiAgRElSRUNULCBJTkRJUkVDVCwgSU5DSURFTlRBTCwgU1BFQ0lBTCwgRVhFTVBMQVJZLCBPUiBDT05TRVFVRU5USUFMIERBTUFHRVNcbiAgKElOQ0xVRElORywgQlVUIE5PVCBMSU1JVEVEIFRPLCBQUk9DVVJFTUVOVCBPRiBTVUJTVElUVVRFIEdPT0RTIE9SIFNFUlZJQ0VTO1xuICBMT1NTIE9GIFVTRSwgREFUQSwgT1IgUFJPRklUUzsgT1IgQlVTSU5FU1MgSU5URVJSVVBUSU9OKSBIT1dFVkVSIENBVVNFRCBBTkRcbiAgT04gQU5ZIFRIRU9SWSBPRiBMSUFCSUxJVFksIFdIRVRIRVIgSU4gQ09OVFJBQ1QsIFNUUklDVCBMSUFCSUxJVFksIE9SIFRPUlRcbiAgKElOQ0xVRElORyBORUdMSUdFTkNFIE9SIE9USEVSV0lTRSkgQVJJU0lORyBJTiBBTlkgV0FZIE9VVCBPRiBUSEUgVVNFIE9GXG4gIFRISVMgU09GVFdBUkUsIEVWRU4gSUYgQURWSVNFRCBPRiBUSEUgUE9TU0lCSUxJVFkgT0YgU1VDSCBEQU1BR0UuXG4qL1xuXG5pbXBvcnQgV2Vha01hcCBmcm9tICdlczYtd2Vhay1tYXAnO1xuaW1wb3J0IFNjb3BlIGZyb20gJy4vc2NvcGUnO1xuaW1wb3J0IGFzc2VydCBmcm9tICdhc3NlcnQnO1xuXG5pbXBvcnQge1xuICAgIEdsb2JhbFNjb3BlLFxuICAgIENhdGNoU2NvcGUsXG4gICAgV2l0aFNjb3BlLFxuICAgIE1vZHVsZVNjb3BlLFxuICAgIENsYXNzU2NvcGUsXG4gICAgU3dpdGNoU2NvcGUsXG4gICAgRnVuY3Rpb25TY29wZSxcbiAgICBGb3JTY29wZSxcbiAgICBURFpTY29wZSxcbiAgICBGdW5jdGlvbkV4cHJlc3Npb25OYW1lU2NvcGUsXG4gICAgQmxvY2tTY29wZVxufSBmcm9tICcuL3Njb3BlJztcblxuLyoqXG4gKiBAY2xhc3MgU2NvcGVNYW5hZ2VyXG4gKi9cbmV4cG9ydCBkZWZhdWx0IGNsYXNzIFNjb3BlTWFuYWdlciB7XG4gICAgY29uc3RydWN0b3Iob3B0aW9ucykge1xuICAgICAgICB0aGlzLnNjb3BlcyA9IFtdO1xuICAgICAgICB0aGlzLmdsb2JhbFNjb3BlID0gbnVsbDtcbiAgICAgICAgdGhpcy5fX25vZGVUb1Njb3BlID0gbmV3IFdlYWtNYXAoKTtcbiAgICAgICAgdGhpcy5fX2N1cnJlbnRTY29wZSA9IG51bGw7XG4gICAgICAgIHRoaXMuX19vcHRpb25zID0gb3B0aW9ucztcbiAgICB9XG5cbiAgICBfX3VzZURpcmVjdGl2ZSgpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuX19vcHRpb25zLmRpcmVjdGl2ZTtcbiAgICB9XG5cbiAgICBfX2lzT3B0aW1pc3RpYygpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuX19vcHRpb25zLm9wdGltaXN0aWM7XG4gICAgfVxuXG4gICAgX19pZ25vcmVFdmFsKCkge1xuICAgICAgICByZXR1cm4gdGhpcy5fX29wdGlvbnMuaWdub3JlRXZhbDtcbiAgICB9XG5cbiAgICBfX2lzTm9kZWpzU2NvcGUoKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fb3B0aW9ucy5ub2RlanNTY29wZTtcbiAgICB9XG5cbiAgICBpc01vZHVsZSgpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuX19vcHRpb25zLnNvdXJjZVR5cGUgPT09ICdtb2R1bGUnO1xuICAgIH1cblxuICAgIC8vIFJldHVybnMgYXBwcm9wbGlhdGUgc2NvcGUgZm9yIHRoaXMgbm9kZS5cbiAgICBfX2dldChub2RlKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbm9kZVRvU2NvcGUuZ2V0KG5vZGUpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIGFjcXVpcmUgc2NvcGUgZnJvbSBub2RlLlxuICAgICAqIEBtZXRob2QgU2NvcGVNYW5hZ2VyI2FjcXVpcmVcbiAgICAgKiBAcGFyYW0ge0VzcHJpbWEuTm9kZX0gbm9kZSAtIG5vZGUgZm9yIHRoZSBhY3F1aXJlZCBzY29wZS5cbiAgICAgKiBAcGFyYW0ge2Jvb2xlYW49fSBpbm5lciAtIGxvb2sgdXAgdGhlIG1vc3QgaW5uZXIgc2NvcGUsIGRlZmF1bHQgdmFsdWUgaXMgZmFsc2UuXG4gICAgICogQHJldHVybiB7U2NvcGU/fVxuICAgICAqL1xuICAgIGFjcXVpcmUobm9kZSwgaW5uZXIpIHtcbiAgICAgICAgdmFyIHNjb3Blcywgc2NvcGUsIGksIGl6O1xuXG4gICAgICAgIGZ1bmN0aW9uIHByZWRpY2F0ZShzY29wZSkge1xuICAgICAgICAgICAgaWYgKHNjb3BlLnR5cGUgPT09ICdmdW5jdGlvbicgJiYgc2NvcGUuZnVuY3Rpb25FeHByZXNzaW9uU2NvcGUpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAoc2NvcGUudHlwZSA9PT0gJ1REWicpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgICAgfVxuXG4gICAgICAgIHNjb3BlcyA9IHRoaXMuX19nZXQobm9kZSk7XG4gICAgICAgIGlmICghc2NvcGVzIHx8IHNjb3Blcy5sZW5ndGggPT09IDApIHtcbiAgICAgICAgICAgIHJldHVybiBudWxsO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gSGV1cmlzdGljIHNlbGVjdGlvbiBmcm9tIGFsbCBzY29wZXMuXG4gICAgICAgIC8vIElmIHlvdSB3b3VsZCBsaWtlIHRvIGdldCBhbGwgc2NvcGVzLCBwbGVhc2UgdXNlIFNjb3BlTWFuYWdlciNhY3F1aXJlQWxsLlxuICAgICAgICBpZiAoc2NvcGVzLmxlbmd0aCA9PT0gMSkge1xuICAgICAgICAgICAgcmV0dXJuIHNjb3Blc1swXTtcbiAgICAgICAgfVxuXG4gICAgICAgIGlmIChpbm5lcikge1xuICAgICAgICAgICAgZm9yIChpID0gc2NvcGVzLmxlbmd0aCAtIDE7IGkgPj0gMDsgLS1pKSB7XG4gICAgICAgICAgICAgICAgc2NvcGUgPSBzY29wZXNbaV07XG4gICAgICAgICAgICAgICAgaWYgKHByZWRpY2F0ZShzY29wZSkpIHtcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHNjb3BlO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIGZvciAoaSA9IDAsIGl6ID0gc2NvcGVzLmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgICAgICBzY29wZSA9IHNjb3Blc1tpXTtcbiAgICAgICAgICAgICAgICBpZiAocHJlZGljYXRlKHNjb3BlKSkge1xuICAgICAgICAgICAgICAgICAgICByZXR1cm4gc2NvcGU7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICB9XG5cbiAgICAgICAgcmV0dXJuIG51bGw7XG4gICAgfVxuXG4gICAgLyoqXG4gICAgICogYWNxdWlyZSBhbGwgc2NvcGVzIGZyb20gbm9kZS5cbiAgICAgKiBAbWV0aG9kIFNjb3BlTWFuYWdlciNhY3F1aXJlQWxsXG4gICAgICogQHBhcmFtIHtFc3ByaW1hLk5vZGV9IG5vZGUgLSBub2RlIGZvciB0aGUgYWNxdWlyZWQgc2NvcGUuXG4gICAgICogQHJldHVybiB7U2NvcGVbXT99XG4gICAgICovXG4gICAgYWNxdWlyZUFsbChub2RlKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fZ2V0KG5vZGUpO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIHJlbGVhc2UgdGhlIG5vZGUuXG4gICAgICogQG1ldGhvZCBTY29wZU1hbmFnZXIjcmVsZWFzZVxuICAgICAqIEBwYXJhbSB7RXNwcmltYS5Ob2RlfSBub2RlIC0gcmVsZWFzaW5nIG5vZGUuXG4gICAgICogQHBhcmFtIHtib29sZWFuPX0gaW5uZXIgLSBsb29rIHVwIHRoZSBtb3N0IGlubmVyIHNjb3BlLCBkZWZhdWx0IHZhbHVlIGlzIGZhbHNlLlxuICAgICAqIEByZXR1cm4ge1Njb3BlP30gdXBwZXIgc2NvcGUgZm9yIHRoZSBub2RlLlxuICAgICAqL1xuICAgIHJlbGVhc2Uobm9kZSwgaW5uZXIpIHtcbiAgICAgICAgdmFyIHNjb3Blcywgc2NvcGU7XG4gICAgICAgIHNjb3BlcyA9IHRoaXMuX19nZXQobm9kZSk7XG4gICAgICAgIGlmIChzY29wZXMgJiYgc2NvcGVzLmxlbmd0aCkge1xuICAgICAgICAgICAgc2NvcGUgPSBzY29wZXNbMF0udXBwZXI7XG4gICAgICAgICAgICBpZiAoIXNjb3BlKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICByZXR1cm4gdGhpcy5hY3F1aXJlKHNjb3BlLmJsb2NrLCBpbm5lcik7XG4gICAgICAgIH1cbiAgICAgICAgcmV0dXJuIG51bGw7XG4gICAgfVxuXG4gICAgYXR0YWNoKCkgeyB9XG5cbiAgICBkZXRhY2goKSB7IH1cblxuICAgIF9fbmVzdFNjb3BlKHNjb3BlKSB7XG4gICAgICAgIGlmIChzY29wZSBpbnN0YW5jZW9mIEdsb2JhbFNjb3BlKSB7XG4gICAgICAgICAgICBhc3NlcnQodGhpcy5fX2N1cnJlbnRTY29wZSA9PT0gbnVsbCk7XG4gICAgICAgICAgICB0aGlzLmdsb2JhbFNjb3BlID0gc2NvcGU7XG4gICAgICAgIH1cbiAgICAgICAgdGhpcy5fX2N1cnJlbnRTY29wZSA9IHNjb3BlO1xuICAgICAgICByZXR1cm4gc2NvcGU7XG4gICAgfVxuXG4gICAgX19uZXN0R2xvYmFsU2NvcGUobm9kZSkge1xuICAgICAgICByZXR1cm4gdGhpcy5fX25lc3RTY29wZShuZXcgR2xvYmFsU2NvcGUodGhpcywgbm9kZSkpO1xuICAgIH1cblxuICAgIF9fbmVzdEJsb2NrU2NvcGUobm9kZSwgaXNNZXRob2REZWZpbml0aW9uKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbmVzdFNjb3BlKG5ldyBCbG9ja1Njb3BlKHRoaXMsIHRoaXMuX19jdXJyZW50U2NvcGUsIG5vZGUpKTtcbiAgICB9XG5cbiAgICBfX25lc3RGdW5jdGlvblNjb3BlKG5vZGUsIGlzTWV0aG9kRGVmaW5pdGlvbikge1xuICAgICAgICByZXR1cm4gdGhpcy5fX25lc3RTY29wZShuZXcgRnVuY3Rpb25TY29wZSh0aGlzLCB0aGlzLl9fY3VycmVudFNjb3BlLCBub2RlLCBpc01ldGhvZERlZmluaXRpb24pKTtcbiAgICB9XG5cbiAgICBfX25lc3RGb3JTY29wZShub2RlKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbmVzdFNjb3BlKG5ldyBGb3JTY29wZSh0aGlzLCB0aGlzLl9fY3VycmVudFNjb3BlLCBub2RlKSk7XG4gICAgfVxuXG4gICAgX19uZXN0Q2F0Y2hTY29wZShub2RlKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbmVzdFNjb3BlKG5ldyBDYXRjaFNjb3BlKHRoaXMsIHRoaXMuX19jdXJyZW50U2NvcGUsIG5vZGUpKTtcbiAgICB9XG5cbiAgICBfX25lc3RXaXRoU2NvcGUobm9kZSkge1xuICAgICAgICByZXR1cm4gdGhpcy5fX25lc3RTY29wZShuZXcgV2l0aFNjb3BlKHRoaXMsIHRoaXMuX19jdXJyZW50U2NvcGUsIG5vZGUpKTtcbiAgICB9XG5cbiAgICBfX25lc3RDbGFzc1Njb3BlKG5vZGUpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuX19uZXN0U2NvcGUobmV3IENsYXNzU2NvcGUodGhpcywgdGhpcy5fX2N1cnJlbnRTY29wZSwgbm9kZSkpO1xuICAgIH1cblxuICAgIF9fbmVzdFN3aXRjaFNjb3BlKG5vZGUpIHtcbiAgICAgICAgcmV0dXJuIHRoaXMuX19uZXN0U2NvcGUobmV3IFN3aXRjaFNjb3BlKHRoaXMsIHRoaXMuX19jdXJyZW50U2NvcGUsIG5vZGUpKTtcbiAgICB9XG5cbiAgICBfX25lc3RNb2R1bGVTY29wZShub2RlKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbmVzdFNjb3BlKG5ldyBNb2R1bGVTY29wZSh0aGlzLCB0aGlzLl9fY3VycmVudFNjb3BlLCBub2RlKSk7XG4gICAgfVxuXG4gICAgX19uZXN0VERaU2NvcGUobm9kZSkge1xuICAgICAgICByZXR1cm4gdGhpcy5fX25lc3RTY29wZShuZXcgVERaU2NvcGUodGhpcywgdGhpcy5fX2N1cnJlbnRTY29wZSwgbm9kZSkpO1xuICAgIH1cblxuICAgIF9fbmVzdEZ1bmN0aW9uRXhwcmVzc2lvbk5hbWVTY29wZShub2RlKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbmVzdFNjb3BlKG5ldyBGdW5jdGlvbkV4cHJlc3Npb25OYW1lU2NvcGUodGhpcywgdGhpcy5fX2N1cnJlbnRTY29wZSwgbm9kZSkpO1xuICAgIH1cblxuICAgIF9faXNFUzYoKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fb3B0aW9ucy5lY21hVmVyc2lvbiA+PSA2O1xuICAgIH1cbn1cblxuLyogdmltOiBzZXQgc3c9NCB0cz00IGV0IHR3PTgwIDogKi9cbiJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ== \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/lib/scope.js b/tools/eslint/node_modules/escope/lib/scope.js new file mode 100644 index 00000000000000..362e275474c097 --- /dev/null +++ b/tools/eslint/node_modules/escope/lib/scope.js @@ -0,0 +1,699 @@ +"use strict"; + +var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; + +var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; + +var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; + +var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +var Syntax = require("estraverse").Syntax; + +var Map = _interopRequire(require("es6-map")); + +var Reference = _interopRequire(require("./reference")); + +var Variable = _interopRequire(require("./variable")); + +var Definition = _interopRequire(require("./definition")); + +var assert = _interopRequire(require("assert")); + +function isStrictScope(scope, block, isMethodDefinition, useDirective) { + var body, i, iz, stmt, expr; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + // ArrowFunctionExpression's scope is always strict scope. + if (block.type === Syntax.ArrowFunctionExpression) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === "Program") { + body = block; + } else { + body = block.body; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search 'use strict' directive. + if (useDirective) { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== "DirectiveStatement") { + break; + } + if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { + return true; + } + } + } else { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + expr = stmt.expression; + if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { + break; + } + if (expr.raw != null) { + if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { + return true; + } + } else { + if (expr.value === "use strict") { + return true; + } + } + } + } + return false; +} + +function registerScope(scopeManager, scope) { + var scopes; + + scopeManager.scopes.push(scope); + + scopes = scopeManager.__nodeToScope.get(scope.block); + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} + +/** + * @class Scope + */ + +var Scope = (function () { + function Scope(scopeManager, type, upperScope, block, isMethodDefinition) { + _classCallCheck(this, Scope); + + /** + * One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. + * @member {String} Scope#type + */ + this.type = type; + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its prarent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; + /** + * A reference to the scope-defining syntax node. + * @member {esprima.Node} Scope#block + */ + this.block = block; + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = this.type === "global" || this.type === "function" || this.type === "module" ? this : upperScope.variableScope; + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + registerScope(scopeManager, this); + } + + _createClass(Scope, { + __shouldStaticallyClose: { + value: function __shouldStaticallyClose(scopeManager) { + return !this.dynamic || scopeManager.__isOptimistic(); + } + }, + __staticClose: { + value: function __staticClose(scopeManager) { + // static resolve + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + var ref = this.__left[i]; + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + } + }, + __dynamicClose: { + value: function __dynamicClose(scopeManager) { + // This path is for "global" and "function with eval" environment. + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + // notify all names are through to global + var ref = this.__left[i]; + var current = this; + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + } + }, + __close: { + value: function __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + this.__staticClose(); + } else { + this.__dynamicClose(); + } + + this.__left = null; + return this.upper; + } + }, + __resolve: { + value: function __resolve(ref) { + var variable, name; + name = ref.identifier.name; + if (this.set.has(name)) { + variable = this.set.get(name); + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + return true; + } + return false; + } + }, + __delegateToUpperScope: { + value: function __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + }, + __defineGeneric: { + value: function __defineGeneric(name, set, variables, node, def) { + var variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + } + if (node) { + variable.identifiers.push(node); + } + } + }, + __define: { + value: function __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric(node.name, this.set, this.variables, node, def); + } + } + }, + __referencing: { + value: function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial) { + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; + } + + // Specially handle like `this`. + if (node.name === "super") { + return; + } + + var ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial); + this.references.push(ref); + this.__left.push(ref); + } + }, + __detectEval: { + value: function __detectEval() { + var current; + current = this; + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + }, + __detectThis: { + value: function __detectThis() { + this.thisFound = true; + } + }, + __isClosed: { + value: function __isClosed() { + return this.__left === null; + } + }, + resolve: { + + /** + * returns resolved {Reference} + * @method Scope#resolve + * @param {Esprima.Identifier} ident - identifier to be resolved. + * @return {Reference} + */ + + value: function resolve(ident) { + var ref, i, iz; + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + }, + isStatic: { + + /** + * returns this scope is static + * @method Scope#isStatic + * @return {boolean} + */ + + value: function isStatic() { + return !this.dynamic; + } + }, + isArgumentsMaterialized: { + + /** + * returns this scope has materialized arguments + * @method Scope#isArgumentsMaterialized + * @return {boolean} + */ + + value: function isArgumentsMaterialized() { + return true; + } + }, + isThisMaterialized: { + + /** + * returns this scope has materialized `this` reference + * @method Scope#isThisMaterialized + * @return {boolean} + */ + + value: function isThisMaterialized() { + return true; + } + }, + isUsedName: { + value: function isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (var i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } + } + }); + + return Scope; +})(); + +exports["default"] = Scope; + +var GlobalScope = exports.GlobalScope = (function (_Scope) { + function GlobalScope(scopeManager, block) { + _classCallCheck(this, GlobalScope); + + _get(Object.getPrototypeOf(GlobalScope.prototype), "constructor", this).call(this, scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + _inherits(GlobalScope, _Scope); + + _createClass(GlobalScope, { + __close: { + value: function __close(scopeManager) { + var implicit = []; + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + var ref = this.__left[i]; + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (var i = 0, iz = implicit.length; i < iz; ++i) { + var info = implicit[i]; + this.__defineImplicit(info.pattern, new Definition(Variable.ImplicitGlobalVariable, info.pattern, info.node, null, null, null)); + } + + this.implicit.left = this.__left; + + return _get(Object.getPrototypeOf(GlobalScope.prototype), "__close", this).call(this, scopeManager); + } + }, + __defineImplicit: { + value: function __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, def); + } + } + } + }); + + return GlobalScope; +})(Scope); + +var ModuleScope = exports.ModuleScope = (function (_Scope2) { + function ModuleScope(scopeManager, upperScope, block) { + _classCallCheck(this, ModuleScope); + + _get(Object.getPrototypeOf(ModuleScope.prototype), "constructor", this).call(this, scopeManager, "module", upperScope, block, false); + } + + _inherits(ModuleScope, _Scope2); + + return ModuleScope; +})(Scope); + +var FunctionExpressionNameScope = exports.FunctionExpressionNameScope = (function (_Scope3) { + function FunctionExpressionNameScope(scopeManager, upperScope, block) { + _classCallCheck(this, FunctionExpressionNameScope); + + _get(Object.getPrototypeOf(FunctionExpressionNameScope.prototype), "constructor", this).call(this, scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, new Definition(Variable.FunctionName, block.id, block, null, null, null)); + this.functionExpressionScope = true; + } + + _inherits(FunctionExpressionNameScope, _Scope3); + + return FunctionExpressionNameScope; +})(Scope); + +var CatchScope = exports.CatchScope = (function (_Scope4) { + function CatchScope(scopeManager, upperScope, block) { + _classCallCheck(this, CatchScope); + + _get(Object.getPrototypeOf(CatchScope.prototype), "constructor", this).call(this, scopeManager, "catch", upperScope, block, false); + } + + _inherits(CatchScope, _Scope4); + + return CatchScope; +})(Scope); + +var WithScope = exports.WithScope = (function (_Scope5) { + function WithScope(scopeManager, upperScope, block) { + _classCallCheck(this, WithScope); + + _get(Object.getPrototypeOf(WithScope.prototype), "constructor", this).call(this, scopeManager, "with", upperScope, block, false); + } + + _inherits(WithScope, _Scope5); + + _createClass(WithScope, { + __close: { + value: function __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return _get(Object.getPrototypeOf(WithScope.prototype), "__close", this).call(this, scopeManager); + } + + for (var i = 0, iz = this.__left.length; i < iz; ++i) { + var ref = this.__left[i]; + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } + } + }); + + return WithScope; +})(Scope); + +var TDZScope = exports.TDZScope = (function (_Scope6) { + function TDZScope(scopeManager, upperScope, block) { + _classCallCheck(this, TDZScope); + + _get(Object.getPrototypeOf(TDZScope.prototype), "constructor", this).call(this, scopeManager, "TDZ", upperScope, block, false); + } + + _inherits(TDZScope, _Scope6); + + return TDZScope; +})(Scope); + +var BlockScope = exports.BlockScope = (function (_Scope7) { + function BlockScope(scopeManager, upperScope, block) { + _classCallCheck(this, BlockScope); + + _get(Object.getPrototypeOf(BlockScope.prototype), "constructor", this).call(this, scopeManager, "block", upperScope, block, false); + } + + _inherits(BlockScope, _Scope7); + + return BlockScope; +})(Scope); + +var SwitchScope = exports.SwitchScope = (function (_Scope8) { + function SwitchScope(scopeManager, upperScope, block) { + _classCallCheck(this, SwitchScope); + + _get(Object.getPrototypeOf(SwitchScope.prototype), "constructor", this).call(this, scopeManager, "switch", upperScope, block, false); + } + + _inherits(SwitchScope, _Scope8); + + return SwitchScope; +})(Scope); + +var FunctionScope = exports.FunctionScope = (function (_Scope9) { + function FunctionScope(scopeManager, upperScope, block, isMethodDefinition) { + _classCallCheck(this, FunctionScope); + + _get(Object.getPrototypeOf(FunctionScope.prototype), "constructor", this).call(this, scopeManager, "function", upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + _inherits(FunctionScope, _Scope9); + + _createClass(FunctionScope, { + isArgumentsMaterialized: { + value: function isArgumentsMaterialized() { + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + var variable = this.set.get("arguments"); + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } + }, + isThisMaterialized: { + value: function isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + }, + __defineArguments: { + value: function __defineArguments() { + this.__defineGeneric("arguments", this.set, this.variables, null, null); + this.taints.set("arguments", true); + } + } + }); + + return FunctionScope; +})(Scope); + +var ForScope = exports.ForScope = (function (_Scope10) { + function ForScope(scopeManager, upperScope, block) { + _classCallCheck(this, ForScope); + + _get(Object.getPrototypeOf(ForScope.prototype), "constructor", this).call(this, scopeManager, "for", upperScope, block, false); + } + + _inherits(ForScope, _Scope10); + + return ForScope; +})(Scope); + +var ClassScope = exports.ClassScope = (function (_Scope11) { + function ClassScope(scopeManager, upperScope, block) { + _classCallCheck(this, ClassScope); + + _get(Object.getPrototypeOf(ClassScope.prototype), "constructor", this).call(this, scopeManager, "class", upperScope, block, false); + } + + _inherits(ClassScope, _Scope11); + + return ClassScope; +})(Scope); + +/* vim: set sw=4 ts=4 et tw=80 : */ +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNjb3BlLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztJQXdCUyxNQUFNLFdBQVEsWUFBWSxFQUExQixNQUFNOztJQUNSLEdBQUcsMkJBQU0sU0FBUzs7SUFFbEIsU0FBUywyQkFBTSxhQUFhOztJQUM1QixRQUFRLDJCQUFNLFlBQVk7O0lBQzFCLFVBQVUsMkJBQU0sY0FBYzs7SUFDOUIsTUFBTSwyQkFBTSxRQUFROztBQUUzQixTQUFTLGFBQWEsQ0FBQyxLQUFLLEVBQUUsS0FBSyxFQUFFLGtCQUFrQixFQUFFLFlBQVksRUFBRTtBQUNuRSxRQUFJLElBQUksRUFBRSxDQUFDLEVBQUUsRUFBRSxFQUFFLElBQUksRUFBRSxJQUFJLENBQUM7OztBQUc1QixRQUFJLEtBQUssQ0FBQyxLQUFLLElBQUksS0FBSyxDQUFDLEtBQUssQ0FBQyxRQUFRLEVBQUU7QUFDckMsZUFBTyxJQUFJLENBQUM7S0FDZjs7O0FBR0QsUUFBSSxLQUFLLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyx1QkFBdUIsRUFBRTtBQUMvQyxlQUFPLElBQUksQ0FBQztLQUNmOztBQUVELFFBQUksa0JBQWtCLEVBQUU7QUFDcEIsZUFBTyxJQUFJLENBQUM7S0FDZjs7QUFFRCxRQUFJLEtBQUssQ0FBQyxJQUFJLEtBQUssT0FBTyxJQUFJLEtBQUssQ0FBQyxJQUFJLEtBQUssUUFBUSxFQUFFO0FBQ25ELGVBQU8sSUFBSSxDQUFDO0tBQ2Y7O0FBRUQsUUFBSSxLQUFLLENBQUMsSUFBSSxLQUFLLE9BQU8sSUFBSSxLQUFLLENBQUMsSUFBSSxLQUFLLFFBQVEsRUFBRTtBQUNuRCxlQUFPLEtBQUssQ0FBQztLQUNoQjs7QUFFRCxRQUFJLEtBQUssQ0FBQyxJQUFJLEtBQUssVUFBVSxFQUFFO0FBQzNCLFlBQUksS0FBSyxDQUFDLElBQUksS0FBSyxTQUFTLEVBQUU7QUFDMUIsZ0JBQUksR0FBRyxLQUFLLENBQUM7U0FDaEIsTUFBTTtBQUNILGdCQUFJLEdBQUcsS0FBSyxDQUFDLElBQUksQ0FBQztTQUNyQjtLQUNKLE1BQU0sSUFBSSxLQUFLLENBQUMsSUFBSSxLQUFLLFFBQVEsRUFBRTtBQUNoQyxZQUFJLEdBQUcsS0FBSyxDQUFDO0tBQ2hCLE1BQU07QUFDSCxlQUFPLEtBQUssQ0FBQztLQUNoQjs7O0FBR0QsUUFBSSxZQUFZLEVBQUU7QUFDZCxhQUFLLENBQUMsR0FBRyxDQUFDLEVBQUUsRUFBRSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUU7QUFDNUMsZ0JBQUksR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ3BCLGdCQUFJLElBQUksQ0FBQyxJQUFJLEtBQUssb0JBQW9CLEVBQUU7QUFDcEMsc0JBQU07YUFDVDtBQUNELGdCQUFJLElBQUksQ0FBQyxHQUFHLEtBQUssZ0JBQWMsSUFBSSxJQUFJLENBQUMsR0FBRyxLQUFLLGNBQWdCLEVBQUU7QUFDOUQsdUJBQU8sSUFBSSxDQUFDO2FBQ2Y7U0FDSjtLQUNKLE1BQU07QUFDSCxhQUFLLENBQUMsR0FBRyxDQUFDLEVBQUUsRUFBRSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUU7QUFDNUMsZ0JBQUksR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ3BCLGdCQUFJLElBQUksQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLG1CQUFtQixFQUFFO0FBQzFDLHNCQUFNO2FBQ1Q7QUFDRCxnQkFBSSxHQUFHLElBQUksQ0FBQyxVQUFVLENBQUM7QUFDdkIsZ0JBQUksSUFBSSxDQUFDLElBQUksS0FBSyxNQUFNLENBQUMsT0FBTyxJQUFJLE9BQU8sSUFBSSxDQUFDLEtBQUssS0FBSyxRQUFRLEVBQUU7QUFDaEUsc0JBQU07YUFDVDtBQUNELGdCQUFJLElBQUksQ0FBQyxHQUFHLElBQUksSUFBSSxFQUFFO0FBQ2xCLG9CQUFJLElBQUksQ0FBQyxHQUFHLEtBQUssZ0JBQWMsSUFBSSxJQUFJLENBQUMsR0FBRyxLQUFLLGNBQWdCLEVBQUU7QUFDOUQsMkJBQU8sSUFBSSxDQUFDO2lCQUNmO2FBQ0osTUFBTTtBQUNILG9CQUFJLElBQUksQ0FBQyxLQUFLLEtBQUssWUFBWSxFQUFFO0FBQzdCLDJCQUFPLElBQUksQ0FBQztpQkFDZjthQUNKO1NBQ0o7S0FDSjtBQUNELFdBQU8sS0FBSyxDQUFDO0NBQ2hCOztBQUVELFNBQVMsYUFBYSxDQUFDLFlBQVksRUFBRSxLQUFLLEVBQUU7QUFDeEMsUUFBSSxNQUFNLENBQUM7O0FBRVgsZ0JBQVksQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDOztBQUVoQyxVQUFNLEdBQUcsWUFBWSxDQUFDLGFBQWEsQ0FBQyxHQUFHLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxDQUFDO0FBQ3JELFFBQUksTUFBTSxFQUFFO0FBQ1IsY0FBTSxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsQ0FBQztLQUN0QixNQUFNO0FBQ0gsb0JBQVksQ0FBQyxhQUFhLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxLQUFLLEVBQUUsQ0FBRSxLQUFLLENBQUUsQ0FBQyxDQUFDO0tBQzFEO0NBQ0o7Ozs7OztJQUtvQixLQUFLO0FBQ1gsYUFETSxLQUFLLENBQ1YsWUFBWSxFQUFFLElBQUksRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFLGtCQUFrQixFQUFFOzhCQUR0RCxLQUFLOzs7Ozs7QUFNbEIsWUFBSSxDQUFDLElBQUksR0FBRyxJQUFJLENBQUM7Ozs7OztBQU1qQixZQUFJLENBQUMsR0FBRyxHQUFHLElBQUksR0FBRyxFQUFFLENBQUM7Ozs7O0FBS3JCLFlBQUksQ0FBQyxNQUFNLEdBQUcsSUFBSSxHQUFHLEVBQUUsQ0FBQzs7Ozs7Ozs7Ozs7QUFXeEIsWUFBSSxDQUFDLE9BQU8sR0FBRyxJQUFJLENBQUMsSUFBSSxLQUFLLFFBQVEsSUFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQzs7Ozs7QUFLOUQsWUFBSSxDQUFDLEtBQUssR0FBRyxLQUFLLENBQUM7Ozs7O0FBS25CLFlBQUksQ0FBQyxPQUFPLEdBQUcsRUFBRSxDQUFDOzs7Ozs7O0FBT2xCLFlBQUksQ0FBQyxTQUFTLEdBQUcsRUFBRSxDQUFDOzs7Ozs7Ozs7O0FBVXBCLFlBQUksQ0FBQyxVQUFVLEdBQUcsRUFBRSxDQUFDOzs7Ozs7OztBQVFyQixZQUFJLENBQUMsYUFBYSxHQUNkLEFBQUMsSUFBSSxDQUFDLElBQUksS0FBSyxRQUFRLElBQUksSUFBSSxDQUFDLElBQUksS0FBSyxVQUFVLElBQUksSUFBSSxDQUFDLElBQUksS0FBSyxRQUFRLEdBQUksSUFBSSxHQUFHLFVBQVUsQ0FBQyxhQUFhLENBQUM7Ozs7O0FBS3JILFlBQUksQ0FBQyx1QkFBdUIsR0FBRyxLQUFLLENBQUM7Ozs7O0FBS3JDLFlBQUksQ0FBQyxxQkFBcUIsR0FBRyxLQUFLLENBQUM7Ozs7QUFJbkMsWUFBSSxDQUFDLFNBQVMsR0FBRyxLQUFLLENBQUM7O0FBRXZCLFlBQUksQ0FBQyxNQUFNLEdBQUcsRUFBRSxDQUFDOzs7Ozs7QUFNakIsWUFBSSxDQUFDLEtBQUssR0FBRyxVQUFVLENBQUM7Ozs7O0FBS3hCLFlBQUksQ0FBQyxRQUFRLEdBQUcsYUFBYSxDQUFDLElBQUksRUFBRSxLQUFLLEVBQUUsa0JBQWtCLEVBQUUsWUFBWSxDQUFDLGNBQWMsRUFBRSxDQUFDLENBQUM7Ozs7OztBQU05RixZQUFJLENBQUMsV0FBVyxHQUFHLEVBQUUsQ0FBQztBQUN0QixZQUFJLElBQUksQ0FBQyxLQUFLLEVBQUU7QUFDWixnQkFBSSxDQUFDLEtBQUssQ0FBQyxXQUFXLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO1NBQ3JDOztBQUVELHFCQUFhLENBQUMsWUFBWSxFQUFFLElBQUksQ0FBQyxDQUFDO0tBQ3JDOztpQkF2R2dCLEtBQUs7QUF5R3RCLCtCQUF1QjttQkFBQSxpQ0FBQyxZQUFZLEVBQUU7QUFDbEMsdUJBQVEsQ0FBQyxJQUFJLENBQUMsT0FBTyxJQUFJLFlBQVksQ0FBQyxjQUFjLEVBQUUsQ0FBRTthQUMzRDs7QUFFRCxxQkFBYTttQkFBQSx1QkFBQyxZQUFZLEVBQUU7O0FBRXhCLHFCQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxFQUFFLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTtBQUNsRCx3QkFBSSxHQUFHLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUN6Qix3QkFBSSxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsR0FBRyxDQUFDLEVBQUU7QUFDdEIsNEJBQUksQ0FBQyxzQkFBc0IsQ0FBQyxHQUFHLENBQUMsQ0FBQztxQkFDcEM7aUJBQ0o7YUFDSjs7QUFFRCxzQkFBYzttQkFBQSx3QkFBQyxZQUFZLEVBQUU7O0FBRXpCLHFCQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxFQUFFLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTs7QUFFbEQsd0JBQUksR0FBRyxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDekIsd0JBQUksT0FBTyxHQUFHLElBQUksQ0FBQztBQUNuQix1QkFBRztBQUNDLCtCQUFPLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQztBQUMxQiwrQkFBTyxHQUFHLE9BQU8sQ0FBQyxLQUFLLENBQUM7cUJBQzNCLFFBQVEsT0FBTyxFQUFFO2lCQUNyQjthQUNKOztBQUVELGVBQU87bUJBQUEsaUJBQUMsWUFBWSxFQUFFO0FBQ2xCLG9CQUFJLElBQUksQ0FBQyx1QkFBdUIsQ0FBQyxZQUFZLENBQUMsRUFBRTtBQUM1Qyx3QkFBSSxDQUFDLGFBQWEsRUFBRSxDQUFDO2lCQUN4QixNQUFNO0FBQ0gsd0JBQUksQ0FBQyxjQUFjLEVBQUUsQ0FBQztpQkFDekI7O0FBRUQsb0JBQUksQ0FBQyxNQUFNLEdBQUcsSUFBSSxDQUFDO0FBQ25CLHVCQUFPLElBQUksQ0FBQyxLQUFLLENBQUM7YUFDckI7O0FBRUQsaUJBQVM7bUJBQUEsbUJBQUMsR0FBRyxFQUFFO0FBQ1gsb0JBQUksUUFBUSxFQUFFLElBQUksQ0FBQztBQUNuQixvQkFBSSxHQUFHLEdBQUcsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDO0FBQzNCLG9CQUFJLElBQUksQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxFQUFFO0FBQ3BCLDRCQUFRLEdBQUcsSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDOUIsNEJBQVEsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDO0FBQzlCLDRCQUFRLENBQUMsS0FBSyxHQUFHLFFBQVEsQ0FBQyxLQUFLLElBQUksR0FBRyxDQUFDLElBQUksQ0FBQyxhQUFhLEtBQUssSUFBSSxDQUFDLGFBQWEsQ0FBQztBQUNqRix3QkFBSSxHQUFHLENBQUMsT0FBTyxFQUFFO0FBQ2IsZ0NBQVEsQ0FBQyxPQUFPLEdBQUcsSUFBSSxDQUFDO0FBQ3hCLDRCQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxRQUFRLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxDQUFDO3FCQUN4QztBQUNELHVCQUFHLENBQUMsUUFBUSxHQUFHLFFBQVEsQ0FBQztBQUN4QiwyQkFBTyxJQUFJLENBQUM7aUJBQ2Y7QUFDRCx1QkFBTyxLQUFLLENBQUM7YUFDaEI7O0FBRUQsOEJBQXNCO21CQUFBLGdDQUFDLEdBQUcsRUFBRTtBQUN4QixvQkFBSSxJQUFJLENBQUMsS0FBSyxFQUFFO0FBQ1osd0JBQUksQ0FBQyxLQUFLLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQztpQkFDL0I7QUFDRCxvQkFBSSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUM7YUFDMUI7O0FBRUQsdUJBQWU7bUJBQUEseUJBQUMsSUFBSSxFQUFFLEdBQUcsRUFBRSxTQUFTLEVBQUUsSUFBSSxFQUFFLEdBQUcsRUFBRTtBQUM3QyxvQkFBSSxRQUFRLENBQUM7O0FBRWIsd0JBQVEsR0FBRyxHQUFHLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQ3pCLG9CQUFJLENBQUMsUUFBUSxFQUFFO0FBQ1gsNEJBQVEsR0FBRyxJQUFJLFFBQVEsQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLENBQUM7QUFDcEMsdUJBQUcsQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLFFBQVEsQ0FBQyxDQUFDO0FBQ3hCLDZCQUFTLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDO2lCQUM1Qjs7QUFFRCxvQkFBSSxHQUFHLEVBQUU7QUFDTCw0QkFBUSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUM7aUJBQzNCO0FBQ0Qsb0JBQUksSUFBSSxFQUFFO0FBQ04sNEJBQVEsQ0FBQyxXQUFXLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO2lCQUNuQzthQUNKOztBQUVELGdCQUFRO21CQUFBLGtCQUFDLElBQUksRUFBRSxHQUFHLEVBQUU7QUFDaEIsb0JBQUksSUFBSSxJQUFJLElBQUksQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLFVBQVUsRUFBRTtBQUN6Qyx3QkFBSSxDQUFDLGVBQWUsQ0FDWixJQUFJLENBQUMsSUFBSSxFQUNULElBQUksQ0FBQyxHQUFHLEVBQ1IsSUFBSSxDQUFDLFNBQVMsRUFDZCxJQUFJLEVBQ0osR0FBRyxDQUFDLENBQUM7aUJBQ2hCO2FBQ0o7O0FBRUQscUJBQWE7bUJBQUEsdUJBQUMsSUFBSSxFQUFFLE1BQU0sRUFBRSxTQUFTLEVBQUUsbUJBQW1CLEVBQUUsT0FBTyxFQUFFOztBQUVqRSxvQkFBSSxDQUFDLElBQUksSUFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxVQUFVLEVBQUU7QUFDMUMsMkJBQU87aUJBQ1Y7OztBQUdELG9CQUFJLElBQUksQ0FBQyxJQUFJLEtBQUssT0FBTyxFQUFFO0FBQ3ZCLDJCQUFPO2lCQUNWOztBQUVELG9CQUFJLEdBQUcsR0FBRyxJQUFJLFNBQVMsQ0FBQyxJQUFJLEVBQUUsSUFBSSxFQUFFLE1BQU0sSUFBSSxTQUFTLENBQUMsSUFBSSxFQUFFLFNBQVMsRUFBRSxtQkFBbUIsRUFBRSxDQUFDLENBQUMsT0FBTyxDQUFDLENBQUM7QUFDekcsb0JBQUksQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDO0FBQzFCLG9CQUFJLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQzthQUN6Qjs7QUFFRCxvQkFBWTttQkFBQSx3QkFBRztBQUNYLG9CQUFJLE9BQU8sQ0FBQztBQUNaLHVCQUFPLEdBQUcsSUFBSSxDQUFDO0FBQ2Ysb0JBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLENBQUM7QUFDbEMsbUJBQUc7QUFDQywyQkFBTyxDQUFDLE9BQU8sR0FBRyxJQUFJLENBQUM7QUFDdkIsMkJBQU8sR0FBRyxPQUFPLENBQUMsS0FBSyxDQUFDO2lCQUMzQixRQUFRLE9BQU8sRUFBRTthQUNyQjs7QUFFRCxvQkFBWTttQkFBQSx3QkFBRztBQUNYLG9CQUFJLENBQUMsU0FBUyxHQUFHLElBQUksQ0FBQzthQUN6Qjs7QUFFRCxrQkFBVTttQkFBQSxzQkFBRztBQUNULHVCQUFPLElBQUksQ0FBQyxNQUFNLEtBQUssSUFBSSxDQUFDO2FBQy9COztBQVFELGVBQU87Ozs7Ozs7OzttQkFBQSxpQkFBQyxLQUFLLEVBQUU7QUFDWCxvQkFBSSxHQUFHLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQztBQUNmLHNCQUFNLENBQUMsSUFBSSxDQUFDLFVBQVUsRUFBRSxFQUFFLHlCQUF5QixDQUFDLENBQUM7QUFDckQsc0JBQU0sQ0FBQyxLQUFLLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxVQUFVLEVBQUUsOEJBQThCLENBQUMsQ0FBQztBQUN6RSxxQkFBSyxDQUFDLEdBQUcsQ0FBQyxFQUFFLEVBQUUsR0FBRyxJQUFJLENBQUMsVUFBVSxDQUFDLE1BQU0sRUFBRSxDQUFDLEdBQUcsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFO0FBQ2xELHVCQUFHLEdBQUcsSUFBSSxDQUFDLFVBQVUsQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUN6Qix3QkFBSSxHQUFHLENBQUMsVUFBVSxLQUFLLEtBQUssRUFBRTtBQUMxQiwrQkFBTyxHQUFHLENBQUM7cUJBQ2Q7aUJBQ0o7QUFDRCx1QkFBTyxJQUFJLENBQUM7YUFDZjs7QUFPRCxnQkFBUTs7Ozs7Ozs7bUJBQUEsb0JBQUc7QUFDUCx1QkFBTyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUM7YUFDeEI7O0FBT0QsK0JBQXVCOzs7Ozs7OzttQkFBQSxtQ0FBRztBQUN0Qix1QkFBTyxJQUFJLENBQUM7YUFDZjs7QUFPRCwwQkFBa0I7Ozs7Ozs7O21CQUFBLDhCQUFHO0FBQ2pCLHVCQUFPLElBQUksQ0FBQzthQUNmOztBQUVELGtCQUFVO21CQUFBLG9CQUFDLElBQUksRUFBRTtBQUNiLG9CQUFJLElBQUksQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxFQUFFO0FBQ3BCLDJCQUFPLElBQUksQ0FBQztpQkFDZjtBQUNELHFCQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxFQUFFLEdBQUcsSUFBSSxDQUFDLE9BQU8sQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTtBQUNuRCx3QkFBSSxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLFVBQVUsQ0FBQyxJQUFJLEtBQUssSUFBSSxFQUFFO0FBQzFDLCtCQUFPLElBQUksQ0FBQztxQkFDZjtpQkFDSjtBQUNELHVCQUFPLEtBQUssQ0FBQzthQUNoQjs7OztXQTlSZ0IsS0FBSzs7O3FCQUFMLEtBQUs7O0lBaVNiLFdBQVcsV0FBWCxXQUFXO0FBQ1QsYUFERixXQUFXLENBQ1IsWUFBWSxFQUFFLEtBQUssRUFBRTs4QkFEeEIsV0FBVzs7QUFFaEIsbUNBRkssV0FBVyw2Q0FFVixZQUFZLEVBQUUsUUFBUSxFQUFFLElBQUksRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFFO0FBQ2xELFlBQUksQ0FBQyxRQUFRLEdBQUc7QUFDWixlQUFHLEVBQUUsSUFBSSxHQUFHLEVBQUU7QUFDZCxxQkFBUyxFQUFFLEVBQUU7Ozs7OztBQU1iLGdCQUFJLEVBQUUsRUFBRTtTQUNYLENBQUM7S0FDTDs7Y0FiUSxXQUFXOztpQkFBWCxXQUFXO0FBZXBCLGVBQU87bUJBQUEsaUJBQUMsWUFBWSxFQUFFO0FBQ2xCLG9CQUFJLFFBQVEsR0FBRyxFQUFFLENBQUM7QUFDbEIscUJBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLEVBQUUsR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLE1BQU0sRUFBRSxDQUFDLEdBQUcsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFO0FBQ2xELHdCQUFJLEdBQUcsR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ3pCLHdCQUFJLEdBQUcsQ0FBQyxxQkFBcUIsSUFBSSxDQUFDLElBQUksQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLEVBQUU7QUFDakUsZ0NBQVEsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLHFCQUFxQixDQUFDLENBQUM7cUJBQzVDO2lCQUNKOzs7QUFHRCxxQkFBSyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsRUFBRSxHQUFHLFFBQVEsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxHQUFHLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRTtBQUMvQyx3QkFBSSxJQUFJLEdBQUcsUUFBUSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQ3ZCLHdCQUFJLENBQUMsZ0JBQWdCLENBQUMsSUFBSSxDQUFDLE9BQU8sRUFDMUIsSUFBSSxVQUFVLENBQ1YsUUFBUSxDQUFDLHNCQUFzQixFQUMvQixJQUFJLENBQUMsT0FBTyxFQUNaLElBQUksQ0FBQyxJQUFJLEVBQ1QsSUFBSSxFQUNKLElBQUksRUFDSixJQUFJLENBQ1AsQ0FBQyxDQUFDO2lCQUVkOztBQUVELG9CQUFJLENBQUMsUUFBUSxDQUFDLElBQUksR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDOztBQUVqQyxrREF6Q0ssV0FBVyx5Q0F5Q0ssWUFBWSxFQUFFO2FBQ3RDOztBQUVELHdCQUFnQjttQkFBQSwwQkFBQyxJQUFJLEVBQUUsR0FBRyxFQUFFO0FBQ3hCLG9CQUFJLElBQUksSUFBSSxJQUFJLENBQUMsSUFBSSxLQUFLLE1BQU0sQ0FBQyxVQUFVLEVBQUU7QUFDekMsd0JBQUksQ0FBQyxlQUFlLENBQ1osSUFBSSxDQUFDLElBQUksRUFDVCxJQUFJLENBQUMsUUFBUSxDQUFDLEdBQUcsRUFDakIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQ3ZCLElBQUksRUFDSixHQUFHLENBQUMsQ0FBQztpQkFDaEI7YUFDSjs7OztXQXJEUSxXQUFXO0dBQVMsS0FBSzs7SUF3RHpCLFdBQVcsV0FBWCxXQUFXO0FBQ1QsYUFERixXQUFXLENBQ1IsWUFBWSxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUU7OEJBRHBDLFdBQVc7O0FBRWhCLG1DQUZLLFdBQVcsNkNBRVYsWUFBWSxFQUFFLFFBQVEsRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFLEtBQUssRUFBRTtLQUMzRDs7Y0FIUSxXQUFXOztXQUFYLFdBQVc7R0FBUyxLQUFLOztJQU16QiwyQkFBMkIsV0FBM0IsMkJBQTJCO0FBQ3pCLGFBREYsMkJBQTJCLENBQ3hCLFlBQVksRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFOzhCQURwQywyQkFBMkI7O0FBRWhDLG1DQUZLLDJCQUEyQiw2Q0FFMUIsWUFBWSxFQUFFLDBCQUEwQixFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFFO0FBQzFFLFlBQUksQ0FBQyxRQUFRLENBQUMsS0FBSyxDQUFDLEVBQUUsRUFDZCxJQUFJLFVBQVUsQ0FDVixRQUFRLENBQUMsWUFBWSxFQUNyQixLQUFLLENBQUMsRUFBRSxFQUNSLEtBQUssRUFDTCxJQUFJLEVBQ0osSUFBSSxFQUNKLElBQUksQ0FDUCxDQUFDLENBQUM7QUFDWCxZQUFJLENBQUMsdUJBQXVCLEdBQUcsSUFBSSxDQUFDO0tBQ3ZDOztjQWJRLDJCQUEyQjs7V0FBM0IsMkJBQTJCO0dBQVMsS0FBSzs7SUFnQnpDLFVBQVUsV0FBVixVQUFVO0FBQ1IsYUFERixVQUFVLENBQ1AsWUFBWSxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUU7OEJBRHBDLFVBQVU7O0FBRWYsbUNBRkssVUFBVSw2Q0FFVCxZQUFZLEVBQUUsT0FBTyxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFFO0tBQzFEOztjQUhRLFVBQVU7O1dBQVYsVUFBVTtHQUFTLEtBQUs7O0lBTXhCLFNBQVMsV0FBVCxTQUFTO0FBQ1AsYUFERixTQUFTLENBQ04sWUFBWSxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUU7OEJBRHBDLFNBQVM7O0FBRWQsbUNBRkssU0FBUyw2Q0FFUixZQUFZLEVBQUUsTUFBTSxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFFO0tBQ3pEOztjQUhRLFNBQVM7O2lCQUFULFNBQVM7QUFLbEIsZUFBTzttQkFBQSxpQkFBQyxZQUFZLEVBQUU7QUFDbEIsb0JBQUksSUFBSSxDQUFDLHVCQUF1QixDQUFDLFlBQVksQ0FBQyxFQUFFO0FBQzVDLHNEQVBDLFNBQVMseUNBT1csWUFBWSxFQUFFO2lCQUN0Qzs7QUFFRCxxQkFBSyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsRUFBRSxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsTUFBTSxFQUFFLENBQUMsR0FBRyxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUU7QUFDbEQsd0JBQUksR0FBRyxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7QUFDekIsdUJBQUcsQ0FBQyxPQUFPLEdBQUcsSUFBSSxDQUFDO0FBQ25CLHdCQUFJLENBQUMsc0JBQXNCLENBQUMsR0FBRyxDQUFDLENBQUM7aUJBQ3BDO0FBQ0Qsb0JBQUksQ0FBQyxNQUFNLEdBQUcsSUFBSSxDQUFDOztBQUVuQix1QkFBTyxJQUFJLENBQUMsS0FBSyxDQUFDO2FBQ3JCOzs7O1dBbEJRLFNBQVM7R0FBUyxLQUFLOztJQXFCdkIsUUFBUSxXQUFSLFFBQVE7QUFDTixhQURGLFFBQVEsQ0FDTCxZQUFZLEVBQUUsVUFBVSxFQUFFLEtBQUssRUFBRTs4QkFEcEMsUUFBUTs7QUFFYixtQ0FGSyxRQUFRLDZDQUVQLFlBQVksRUFBRSxLQUFLLEVBQUUsVUFBVSxFQUFFLEtBQUssRUFBRSxLQUFLLEVBQUU7S0FDeEQ7O2NBSFEsUUFBUTs7V0FBUixRQUFRO0dBQVMsS0FBSzs7SUFNdEIsVUFBVSxXQUFWLFVBQVU7QUFDUixhQURGLFVBQVUsQ0FDUCxZQUFZLEVBQUUsVUFBVSxFQUFFLEtBQUssRUFBRTs4QkFEcEMsVUFBVTs7QUFFZixtQ0FGSyxVQUFVLDZDQUVULFlBQVksRUFBRSxPQUFPLEVBQUUsVUFBVSxFQUFFLEtBQUssRUFBRSxLQUFLLEVBQUU7S0FDMUQ7O2NBSFEsVUFBVTs7V0FBVixVQUFVO0dBQVMsS0FBSzs7SUFNeEIsV0FBVyxXQUFYLFdBQVc7QUFDVCxhQURGLFdBQVcsQ0FDUixZQUFZLEVBQUUsVUFBVSxFQUFFLEtBQUssRUFBRTs4QkFEcEMsV0FBVzs7QUFFaEIsbUNBRkssV0FBVyw2Q0FFVixZQUFZLEVBQUUsUUFBUSxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUUsS0FBSyxFQUFFO0tBQzNEOztjQUhRLFdBQVc7O1dBQVgsV0FBVztHQUFTLEtBQUs7O0lBTXpCLGFBQWEsV0FBYixhQUFhO0FBQ1gsYUFERixhQUFhLENBQ1YsWUFBWSxFQUFFLFVBQVUsRUFBRSxLQUFLLEVBQUUsa0JBQWtCLEVBQUU7OEJBRHhELGFBQWE7O0FBRWxCLG1DQUZLLGFBQWEsNkNBRVosWUFBWSxFQUFFLFVBQVUsRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFLGtCQUFrQixFQUFFOzs7O0FBSXZFLFlBQUksSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLHVCQUF1QixFQUFFO0FBQ3BELGdCQUFJLENBQUMsaUJBQWlCLEVBQUUsQ0FBQztTQUM1QjtLQUNKOztjQVRRLGFBQWE7O2lCQUFiLGFBQWE7QUFXdEIsK0JBQXVCO21CQUFBLG1DQUFHOzs7Ozs7Ozs7QUFTdEIsb0JBQUksSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLEtBQUssTUFBTSxDQUFDLHVCQUF1QixFQUFFO0FBQ3BELDJCQUFPLEtBQUssQ0FBQztpQkFDaEI7O0FBRUQsb0JBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxFQUFFLEVBQUU7QUFDbEIsMkJBQU8sSUFBSSxDQUFDO2lCQUNmOztBQUVELG9CQUFJLFFBQVEsR0FBRyxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxXQUFXLENBQUMsQ0FBQztBQUN6QyxzQkFBTSxDQUFDLFFBQVEsRUFBRSxpQ0FBaUMsQ0FBQyxDQUFDO0FBQ3BELHVCQUFPLFFBQVEsQ0FBQyxPQUFPLElBQUksUUFBUSxDQUFDLFVBQVUsQ0FBQyxNQUFNLEtBQU0sQ0FBQyxDQUFDO2FBQ2hFOztBQUVELDBCQUFrQjttQkFBQSw4QkFBRztBQUNqQixvQkFBSSxDQUFDLElBQUksQ0FBQyxRQUFRLEVBQUUsRUFBRTtBQUNsQiwyQkFBTyxJQUFJLENBQUM7aUJBQ2Y7QUFDRCx1QkFBTyxJQUFJLENBQUMsU0FBUyxDQUFDO2FBQ3pCOztBQUVELHlCQUFpQjttQkFBQSw2QkFBRztBQUNoQixvQkFBSSxDQUFDLGVBQWUsQ0FDWixXQUFXLEVBQ1gsSUFBSSxDQUFDLEdBQUcsRUFDUixJQUFJLENBQUMsU0FBUyxFQUNkLElBQUksRUFDSixJQUFJLENBQUMsQ0FBQztBQUNkLG9CQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxXQUFXLEVBQUUsSUFBSSxDQUFDLENBQUM7YUFDdEM7Ozs7V0FoRFEsYUFBYTtHQUFTLEtBQUs7O0lBbUQzQixRQUFRLFdBQVIsUUFBUTtBQUNOLGFBREYsUUFBUSxDQUNMLFlBQVksRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFOzhCQURwQyxRQUFROztBQUViLG1DQUZLLFFBQVEsNkNBRVAsWUFBWSxFQUFFLEtBQUssRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFLEtBQUssRUFBRTtLQUN4RDs7Y0FIUSxRQUFROztXQUFSLFFBQVE7R0FBUyxLQUFLOztJQU10QixVQUFVLFdBQVYsVUFBVTtBQUNSLGFBREYsVUFBVSxDQUNQLFlBQVksRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFOzhCQURwQyxVQUFVOztBQUVmLG1DQUZLLFVBQVUsNkNBRVQsWUFBWSxFQUFFLE9BQU8sRUFBRSxVQUFVLEVBQUUsS0FBSyxFQUFFLEtBQUssRUFBRTtLQUMxRDs7Y0FIUSxVQUFVOztXQUFWLFVBQVU7R0FBUyxLQUFLIiwiZmlsZSI6InNjb3BlLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLypcbiAgQ29weXJpZ2h0IChDKSAyMDE1IFl1c3VrZSBTdXp1a2kgPHV0YXRhbmUudGVhQGdtYWlsLmNvbT5cblxuICBSZWRpc3RyaWJ1dGlvbiBhbmQgdXNlIGluIHNvdXJjZSBhbmQgYmluYXJ5IGZvcm1zLCB3aXRoIG9yIHdpdGhvdXRcbiAgbW9kaWZpY2F0aW9uLCBhcmUgcGVybWl0dGVkIHByb3ZpZGVkIHRoYXQgdGhlIGZvbGxvd2luZyBjb25kaXRpb25zIGFyZSBtZXQ6XG5cbiAgICAqIFJlZGlzdHJpYnV0aW9ucyBvZiBzb3VyY2UgY29kZSBtdXN0IHJldGFpbiB0aGUgYWJvdmUgY29weXJpZ2h0XG4gICAgICBub3RpY2UsIHRoaXMgbGlzdCBvZiBjb25kaXRpb25zIGFuZCB0aGUgZm9sbG93aW5nIGRpc2NsYWltZXIuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgaW4gYmluYXJ5IGZvcm0gbXVzdCByZXByb2R1Y2UgdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyIGluIHRoZVxuICAgICAgZG9jdW1lbnRhdGlvbiBhbmQvb3Igb3RoZXIgbWF0ZXJpYWxzIHByb3ZpZGVkIHdpdGggdGhlIGRpc3RyaWJ1dGlvbi5cblxuICBUSElTIFNPRlRXQVJFIElTIFBST1ZJREVEIEJZIFRIRSBDT1BZUklHSFQgSE9MREVSUyBBTkQgQ09OVFJJQlVUT1JTIFwiQVMgSVNcIlxuICBBTkQgQU5ZIEVYUFJFU1MgT1IgSU1QTElFRCBXQVJSQU5USUVTLCBJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgVEhFXG4gIElNUExJRUQgV0FSUkFOVElFUyBPRiBNRVJDSEFOVEFCSUxJVFkgQU5EIEZJVE5FU1MgRk9SIEEgUEFSVElDVUxBUiBQVVJQT1NFXG4gIEFSRSBESVNDTEFJTUVELiBJTiBOTyBFVkVOVCBTSEFMTCA8Q09QWVJJR0hUIEhPTERFUj4gQkUgTElBQkxFIEZPUiBBTllcbiAgRElSRUNULCBJTkRJUkVDVCwgSU5DSURFTlRBTCwgU1BFQ0lBTCwgRVhFTVBMQVJZLCBPUiBDT05TRVFVRU5USUFMIERBTUFHRVNcbiAgKElOQ0xVRElORywgQlVUIE5PVCBMSU1JVEVEIFRPLCBQUk9DVVJFTUVOVCBPRiBTVUJTVElUVVRFIEdPT0RTIE9SIFNFUlZJQ0VTO1xuICBMT1NTIE9GIFVTRSwgREFUQSwgT1IgUFJPRklUUzsgT1IgQlVTSU5FU1MgSU5URVJSVVBUSU9OKSBIT1dFVkVSIENBVVNFRCBBTkRcbiAgT04gQU5ZIFRIRU9SWSBPRiBMSUFCSUxJVFksIFdIRVRIRVIgSU4gQ09OVFJBQ1QsIFNUUklDVCBMSUFCSUxJVFksIE9SIFRPUlRcbiAgKElOQ0xVRElORyBORUdMSUdFTkNFIE9SIE9USEVSV0lTRSkgQVJJU0lORyBJTiBBTlkgV0FZIE9VVCBPRiBUSEUgVVNFIE9GXG4gIFRISVMgU09GVFdBUkUsIEVWRU4gSUYgQURWSVNFRCBPRiBUSEUgUE9TU0lCSUxJVFkgT0YgU1VDSCBEQU1BR0UuXG4qL1xuXG5pbXBvcnQgeyBTeW50YXggfSBmcm9tICdlc3RyYXZlcnNlJztcbmltcG9ydCBNYXAgZnJvbSAnZXM2LW1hcCc7XG5cbmltcG9ydCBSZWZlcmVuY2UgZnJvbSAnLi9yZWZlcmVuY2UnO1xuaW1wb3J0IFZhcmlhYmxlIGZyb20gJy4vdmFyaWFibGUnO1xuaW1wb3J0IERlZmluaXRpb24gZnJvbSAnLi9kZWZpbml0aW9uJztcbmltcG9ydCBhc3NlcnQgZnJvbSAnYXNzZXJ0JztcblxuZnVuY3Rpb24gaXNTdHJpY3RTY29wZShzY29wZSwgYmxvY2ssIGlzTWV0aG9kRGVmaW5pdGlvbiwgdXNlRGlyZWN0aXZlKSB7XG4gICAgdmFyIGJvZHksIGksIGl6LCBzdG10LCBleHByO1xuXG4gICAgLy8gV2hlbiB1cHBlciBzY29wZSBpcyBleGlzdHMgYW5kIHN0cmljdCwgaW5uZXIgc2NvcGUgaXMgYWxzbyBzdHJpY3QuXG4gICAgaWYgKHNjb3BlLnVwcGVyICYmIHNjb3BlLnVwcGVyLmlzU3RyaWN0KSB7XG4gICAgICAgIHJldHVybiB0cnVlO1xuICAgIH1cblxuICAgIC8vIEFycm93RnVuY3Rpb25FeHByZXNzaW9uJ3Mgc2NvcGUgaXMgYWx3YXlzIHN0cmljdCBzY29wZS5cbiAgICBpZiAoYmxvY2sudHlwZSA9PT0gU3ludGF4LkFycm93RnVuY3Rpb25FeHByZXNzaW9uKSB7XG4gICAgICAgIHJldHVybiB0cnVlO1xuICAgIH1cblxuICAgIGlmIChpc01ldGhvZERlZmluaXRpb24pIHtcbiAgICAgICAgcmV0dXJuIHRydWU7XG4gICAgfVxuXG4gICAgaWYgKHNjb3BlLnR5cGUgPT09ICdjbGFzcycgfHwgc2NvcGUudHlwZSA9PT0gJ21vZHVsZScpIHtcbiAgICAgICAgcmV0dXJuIHRydWU7XG4gICAgfVxuXG4gICAgaWYgKHNjb3BlLnR5cGUgPT09ICdibG9jaycgfHwgc2NvcGUudHlwZSA9PT0gJ3N3aXRjaCcpIHtcbiAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cblxuICAgIGlmIChzY29wZS50eXBlID09PSAnZnVuY3Rpb24nKSB7XG4gICAgICAgIGlmIChibG9jay50eXBlID09PSAnUHJvZ3JhbScpIHtcbiAgICAgICAgICAgIGJvZHkgPSBibG9jaztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIGJvZHkgPSBibG9jay5ib2R5O1xuICAgICAgICB9XG4gICAgfSBlbHNlIGlmIChzY29wZS50eXBlID09PSAnZ2xvYmFsJykge1xuICAgICAgICBib2R5ID0gYmxvY2s7XG4gICAgfSBlbHNlIHtcbiAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cblxuICAgIC8vIFNlYXJjaCAndXNlIHN0cmljdCcgZGlyZWN0aXZlLlxuICAgIGlmICh1c2VEaXJlY3RpdmUpIHtcbiAgICAgICAgZm9yIChpID0gMCwgaXogPSBib2R5LmJvZHkubGVuZ3RoOyBpIDwgaXo7ICsraSkge1xuICAgICAgICAgICAgc3RtdCA9IGJvZHkuYm9keVtpXTtcbiAgICAgICAgICAgIGlmIChzdG10LnR5cGUgIT09ICdEaXJlY3RpdmVTdGF0ZW1lbnQnKSB7XG4gICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAoc3RtdC5yYXcgPT09ICdcInVzZSBzdHJpY3RcIicgfHwgc3RtdC5yYXcgPT09ICdcXCd1c2Ugc3RyaWN0XFwnJykge1xuICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgICAgZm9yIChpID0gMCwgaXogPSBib2R5LmJvZHkubGVuZ3RoOyBpIDwgaXo7ICsraSkge1xuICAgICAgICAgICAgc3RtdCA9IGJvZHkuYm9keVtpXTtcbiAgICAgICAgICAgIGlmIChzdG10LnR5cGUgIT09IFN5bnRheC5FeHByZXNzaW9uU3RhdGVtZW50KSB7XG4gICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBleHByID0gc3RtdC5leHByZXNzaW9uO1xuICAgICAgICAgICAgaWYgKGV4cHIudHlwZSAhPT0gU3ludGF4LkxpdGVyYWwgfHwgdHlwZW9mIGV4cHIudmFsdWUgIT09ICdzdHJpbmcnKSB7XG4gICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAoZXhwci5yYXcgIT0gbnVsbCkge1xuICAgICAgICAgICAgICAgIGlmIChleHByLnJhdyA9PT0gJ1widXNlIHN0cmljdFwiJyB8fCBleHByLnJhdyA9PT0gJ1xcJ3VzZSBzdHJpY3RcXCcnKSB7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgaWYgKGV4cHIudmFsdWUgPT09ICd1c2Ugc3RyaWN0Jykge1xuICAgICAgICAgICAgICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICB9XG4gICAgcmV0dXJuIGZhbHNlO1xufVxuXG5mdW5jdGlvbiByZWdpc3RlclNjb3BlKHNjb3BlTWFuYWdlciwgc2NvcGUpIHtcbiAgICB2YXIgc2NvcGVzO1xuXG4gICAgc2NvcGVNYW5hZ2VyLnNjb3Blcy5wdXNoKHNjb3BlKTtcblxuICAgIHNjb3BlcyA9IHNjb3BlTWFuYWdlci5fX25vZGVUb1Njb3BlLmdldChzY29wZS5ibG9jayk7XG4gICAgaWYgKHNjb3Blcykge1xuICAgICAgICBzY29wZXMucHVzaChzY29wZSk7XG4gICAgfSBlbHNlIHtcbiAgICAgICAgc2NvcGVNYW5hZ2VyLl9fbm9kZVRvU2NvcGUuc2V0KHNjb3BlLmJsb2NrLCBbIHNjb3BlIF0pO1xuICAgIH1cbn1cblxuLyoqXG4gKiBAY2xhc3MgU2NvcGVcbiAqL1xuZXhwb3J0IGRlZmF1bHQgY2xhc3MgU2NvcGUge1xuICAgIGNvbnN0cnVjdG9yKHNjb3BlTWFuYWdlciwgdHlwZSwgdXBwZXJTY29wZSwgYmxvY2ssIGlzTWV0aG9kRGVmaW5pdGlvbikge1xuICAgICAgICAvKipcbiAgICAgICAgICogT25lIG9mICdURFonLCAnbW9kdWxlJywgJ2Jsb2NrJywgJ3N3aXRjaCcsICdmdW5jdGlvbicsICdjYXRjaCcsICd3aXRoJywgJ2Z1bmN0aW9uJywgJ2NsYXNzJywgJ2dsb2JhbCcuXG4gICAgICAgICAqIEBtZW1iZXIge1N0cmluZ30gU2NvcGUjdHlwZVxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy50eXBlID0gdHlwZTtcbiAgICAgICAgIC8qKlxuICAgICAgICAgKiBUaGUgc2NvcGVkIHtAbGluayBWYXJpYWJsZX1zIG9mIHRoaXMgc2NvcGUsIGFzIDxjb2RlPnsgVmFyaWFibGUubmFtZVxuICAgICAgICAgKiA6IFZhcmlhYmxlIH08L2NvZGU+LlxuICAgICAgICAgKiBAbWVtYmVyIHtNYXB9IFNjb3BlI3NldFxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5zZXQgPSBuZXcgTWFwKCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBUaGUgdGFpbnRlZCB2YXJpYWJsZXMgb2YgdGhpcyBzY29wZSwgYXMgPGNvZGU+eyBWYXJpYWJsZS5uYW1lIDpcbiAgICAgICAgICogYm9vbGVhbiB9PC9jb2RlPi5cbiAgICAgICAgICogQG1lbWJlciB7TWFwfSBTY29wZSN0YWludHMgKi9cbiAgICAgICAgdGhpcy50YWludHMgPSBuZXcgTWFwKCk7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBHZW5lcmFsbHksIHRocm91Z2ggdGhlIGxleGljYWwgc2NvcGluZyBvZiBKUyB5b3UgY2FuIGFsd2F5cyBrbm93XG4gICAgICAgICAqIHdoaWNoIHZhcmlhYmxlIGFuIGlkZW50aWZpZXIgaW4gdGhlIHNvdXJjZSBjb2RlIHJlZmVycyB0by4gVGhlcmUgYXJlXG4gICAgICAgICAqIGEgZmV3IGV4Y2VwdGlvbnMgdG8gdGhpcyBydWxlLiBXaXRoICdnbG9iYWwnIGFuZCAnd2l0aCcgc2NvcGVzIHlvdVxuICAgICAgICAgKiBjYW4gb25seSBkZWNpZGUgYXQgcnVudGltZSB3aGljaCB2YXJpYWJsZSBhIHJlZmVyZW5jZSByZWZlcnMgdG8uXG4gICAgICAgICAqIE1vcmVvdmVyLCBpZiAnZXZhbCgpJyBpcyB1c2VkIGluIGEgc2NvcGUsIGl0IG1pZ2h0IGludHJvZHVjZSBuZXdcbiAgICAgICAgICogYmluZGluZ3MgaW4gdGhpcyBvciBpdHMgcHJhcmVudCBzY29wZXMuXG4gICAgICAgICAqIEFsbCB0aG9zZSBzY29wZXMgYXJlIGNvbnNpZGVyZWQgJ2R5bmFtaWMnLlxuICAgICAgICAgKiBAbWVtYmVyIHtib29sZWFufSBTY29wZSNkeW5hbWljXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmR5bmFtaWMgPSB0aGlzLnR5cGUgPT09ICdnbG9iYWwnIHx8IHRoaXMudHlwZSA9PT0gJ3dpdGgnO1xuICAgICAgICAvKipcbiAgICAgICAgICogQSByZWZlcmVuY2UgdG8gdGhlIHNjb3BlLWRlZmluaW5nIHN5bnRheCBub2RlLlxuICAgICAgICAgKiBAbWVtYmVyIHtlc3ByaW1hLk5vZGV9IFNjb3BlI2Jsb2NrXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmJsb2NrID0gYmxvY2s7XG4gICAgICAgICAvKipcbiAgICAgICAgICogVGhlIHtAbGluayBSZWZlcmVuY2V8cmVmZXJlbmNlc30gdGhhdCBhcmUgbm90IHJlc29sdmVkIHdpdGggdGhpcyBzY29wZS5cbiAgICAgICAgICogQG1lbWJlciB7UmVmZXJlbmNlW119IFNjb3BlI3Rocm91Z2hcbiAgICAgICAgICovXG4gICAgICAgIHRoaXMudGhyb3VnaCA9IFtdO1xuICAgICAgICAgLyoqXG4gICAgICAgICAqIFRoZSBzY29wZWQge0BsaW5rIFZhcmlhYmxlfXMgb2YgdGhpcyBzY29wZS4gSW4gdGhlIGNhc2Ugb2YgYVxuICAgICAgICAgKiAnZnVuY3Rpb24nIHNjb3BlIHRoaXMgaW5jbHVkZXMgdGhlIGF1dG9tYXRpYyBhcmd1bWVudCA8ZW0+YXJndW1lbnRzPC9lbT4gYXNcbiAgICAgICAgICogaXRzIGZpcnN0IGVsZW1lbnQsIGFzIHdlbGwgYXMgYWxsIGZ1cnRoZXIgZm9ybWFsIGFyZ3VtZW50cy5cbiAgICAgICAgICogQG1lbWJlciB7VmFyaWFibGVbXX0gU2NvcGUjdmFyaWFibGVzXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnZhcmlhYmxlcyA9IFtdO1xuICAgICAgICAgLyoqXG4gICAgICAgICAqIEFueSB2YXJpYWJsZSB7QGxpbmsgUmVmZXJlbmNlfHJlZmVyZW5jZX0gZm91bmQgaW4gdGhpcyBzY29wZS4gVGhpc1xuICAgICAgICAgKiBpbmNsdWRlcyBvY2N1cnJlbmNlcyBvZiBsb2NhbCB2YXJpYWJsZXMgYXMgd2VsbCBhcyB2YXJpYWJsZXMgZnJvbVxuICAgICAgICAgKiBwYXJlbnQgc2NvcGVzIChpbmNsdWRpbmcgdGhlIGdsb2JhbCBzY29wZSkuIEZvciBsb2NhbCB2YXJpYWJsZXNcbiAgICAgICAgICogdGhpcyBhbHNvIGluY2x1ZGVzIGRlZmluaW5nIG9jY3VycmVuY2VzIChsaWtlIGluIGEgJ3Zhcicgc3RhdGVtZW50KS5cbiAgICAgICAgICogSW4gYSAnZnVuY3Rpb24nIHNjb3BlIHRoaXMgZG9lcyBub3QgaW5jbHVkZSB0aGUgb2NjdXJyZW5jZXMgb2YgdGhlXG4gICAgICAgICAqIGZvcm1hbCBwYXJhbWV0ZXIgaW4gdGhlIHBhcmFtZXRlciBsaXN0LlxuICAgICAgICAgKiBAbWVtYmVyIHtSZWZlcmVuY2VbXX0gU2NvcGUjcmVmZXJlbmNlc1xuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5yZWZlcmVuY2VzID0gW107XG5cbiAgICAgICAgIC8qKlxuICAgICAgICAgKiBGb3IgJ2dsb2JhbCcgYW5kICdmdW5jdGlvbicgc2NvcGVzLCB0aGlzIGlzIGEgc2VsZi1yZWZlcmVuY2UuIEZvclxuICAgICAgICAgKiBvdGhlciBzY29wZSB0eXBlcyB0aGlzIGlzIHRoZSA8ZW0+dmFyaWFibGVTY29wZTwvZW0+IHZhbHVlIG9mIHRoZVxuICAgICAgICAgKiBwYXJlbnQgc2NvcGUuXG4gICAgICAgICAqIEBtZW1iZXIge1Njb3BlfSBTY29wZSN2YXJpYWJsZVNjb3BlXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnZhcmlhYmxlU2NvcGUgPVxuICAgICAgICAgICAgKHRoaXMudHlwZSA9PT0gJ2dsb2JhbCcgfHwgdGhpcy50eXBlID09PSAnZnVuY3Rpb24nIHx8IHRoaXMudHlwZSA9PT0gJ21vZHVsZScpID8gdGhpcyA6IHVwcGVyU2NvcGUudmFyaWFibGVTY29wZTtcbiAgICAgICAgIC8qKlxuICAgICAgICAgKiBXaGV0aGVyIHRoaXMgc2NvcGUgaXMgY3JlYXRlZCBieSBhIEZ1bmN0aW9uRXhwcmVzc2lvbi5cbiAgICAgICAgICogQG1lbWJlciB7Ym9vbGVhbn0gU2NvcGUjZnVuY3Rpb25FeHByZXNzaW9uU2NvcGVcbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuZnVuY3Rpb25FeHByZXNzaW9uU2NvcGUgPSBmYWxzZTtcbiAgICAgICAgIC8qKlxuICAgICAgICAgKiBXaGV0aGVyIHRoaXMgaXMgYSBzY29wZSB0aGF0IGNvbnRhaW5zIGFuICdldmFsKCknIGludm9jYXRpb24uXG4gICAgICAgICAqIEBtZW1iZXIge2Jvb2xlYW59IFNjb3BlI2RpcmVjdENhbGxUb0V2YWxTY29wZVxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5kaXJlY3RDYWxsVG9FdmFsU2NvcGUgPSBmYWxzZTtcbiAgICAgICAgIC8qKlxuICAgICAgICAgKiBAbWVtYmVyIHtib29sZWFufSBTY29wZSN0aGlzRm91bmRcbiAgICAgICAgICovXG4gICAgICAgIHRoaXMudGhpc0ZvdW5kID0gZmFsc2U7XG5cbiAgICAgICAgdGhpcy5fX2xlZnQgPSBbXTtcblxuICAgICAgICAgLyoqXG4gICAgICAgICAqIFJlZmVyZW5jZSB0byB0aGUgcGFyZW50IHtAbGluayBTY29wZXxzY29wZX0uXG4gICAgICAgICAqIEBtZW1iZXIge1Njb3BlfSBTY29wZSN1cHBlclxuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy51cHBlciA9IHVwcGVyU2NvcGU7XG4gICAgICAgICAvKipcbiAgICAgICAgICogV2hldGhlciAndXNlIHN0cmljdCcgaXMgaW4gZWZmZWN0IGluIHRoaXMgc2NvcGUuXG4gICAgICAgICAqIEBtZW1iZXIge2Jvb2xlYW59IFNjb3BlI2lzU3RyaWN0XG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmlzU3RyaWN0ID0gaXNTdHJpY3RTY29wZSh0aGlzLCBibG9jaywgaXNNZXRob2REZWZpbml0aW9uLCBzY29wZU1hbmFnZXIuX191c2VEaXJlY3RpdmUoKSk7XG5cbiAgICAgICAgIC8qKlxuICAgICAgICAgKiBMaXN0IG9mIG5lc3RlZCB7QGxpbmsgU2NvcGV9cy5cbiAgICAgICAgICogQG1lbWJlciB7U2NvcGVbXX0gU2NvcGUjY2hpbGRTY29wZXNcbiAgICAgICAgICovXG4gICAgICAgIHRoaXMuY2hpbGRTY29wZXMgPSBbXTtcbiAgICAgICAgaWYgKHRoaXMudXBwZXIpIHtcbiAgICAgICAgICAgIHRoaXMudXBwZXIuY2hpbGRTY29wZXMucHVzaCh0aGlzKTtcbiAgICAgICAgfVxuXG4gICAgICAgIHJlZ2lzdGVyU2NvcGUoc2NvcGVNYW5hZ2VyLCB0aGlzKTtcbiAgICB9XG5cbiAgICBfX3Nob3VsZFN0YXRpY2FsbHlDbG9zZShzY29wZU1hbmFnZXIpIHtcbiAgICAgICAgcmV0dXJuICghdGhpcy5keW5hbWljIHx8IHNjb3BlTWFuYWdlci5fX2lzT3B0aW1pc3RpYygpKTtcbiAgICB9XG5cbiAgICBfX3N0YXRpY0Nsb3NlKHNjb3BlTWFuYWdlcikge1xuICAgICAgICAvLyBzdGF0aWMgcmVzb2x2ZVxuICAgICAgICBmb3IgKGxldCBpID0gMCwgaXogPSB0aGlzLl9fbGVmdC5sZW5ndGg7IGkgPCBpejsgKytpKSB7XG4gICAgICAgICAgICBsZXQgcmVmID0gdGhpcy5fX2xlZnRbaV07XG4gICAgICAgICAgICBpZiAoIXRoaXMuX19yZXNvbHZlKHJlZikpIHtcbiAgICAgICAgICAgICAgICB0aGlzLl9fZGVsZWdhdGVUb1VwcGVyU2NvcGUocmVmKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cblxuICAgIF9fZHluYW1pY0Nsb3NlKHNjb3BlTWFuYWdlcikge1xuICAgICAgICAvLyBUaGlzIHBhdGggaXMgZm9yIFwiZ2xvYmFsXCIgYW5kIFwiZnVuY3Rpb24gd2l0aCBldmFsXCIgZW52aXJvbm1lbnQuXG4gICAgICAgIGZvciAobGV0IGkgPSAwLCBpeiA9IHRoaXMuX19sZWZ0Lmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgIC8vIG5vdGlmeSBhbGwgbmFtZXMgYXJlIHRocm91Z2ggdG8gZ2xvYmFsXG4gICAgICAgICAgICBsZXQgcmVmID0gdGhpcy5fX2xlZnRbaV07XG4gICAgICAgICAgICBsZXQgY3VycmVudCA9IHRoaXM7XG4gICAgICAgICAgICBkbyB7XG4gICAgICAgICAgICAgICAgY3VycmVudC50aHJvdWdoLnB1c2gocmVmKTtcbiAgICAgICAgICAgICAgICBjdXJyZW50ID0gY3VycmVudC51cHBlcjtcbiAgICAgICAgICAgIH0gd2hpbGUgKGN1cnJlbnQpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgX19jbG9zZShzY29wZU1hbmFnZXIpIHtcbiAgICAgICAgaWYgKHRoaXMuX19zaG91bGRTdGF0aWNhbGx5Q2xvc2Uoc2NvcGVNYW5hZ2VyKSkge1xuICAgICAgICAgICAgdGhpcy5fX3N0YXRpY0Nsb3NlKCk7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICB0aGlzLl9fZHluYW1pY0Nsb3NlKCk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLl9fbGVmdCA9IG51bGw7XG4gICAgICAgIHJldHVybiB0aGlzLnVwcGVyO1xuICAgIH1cblxuICAgIF9fcmVzb2x2ZShyZWYpIHtcbiAgICAgICAgdmFyIHZhcmlhYmxlLCBuYW1lO1xuICAgICAgICBuYW1lID0gcmVmLmlkZW50aWZpZXIubmFtZTtcbiAgICAgICAgaWYgKHRoaXMuc2V0LmhhcyhuYW1lKSkge1xuICAgICAgICAgICAgdmFyaWFibGUgPSB0aGlzLnNldC5nZXQobmFtZSk7XG4gICAgICAgICAgICB2YXJpYWJsZS5yZWZlcmVuY2VzLnB1c2gocmVmKTtcbiAgICAgICAgICAgIHZhcmlhYmxlLnN0YWNrID0gdmFyaWFibGUuc3RhY2sgJiYgcmVmLmZyb20udmFyaWFibGVTY29wZSA9PT0gdGhpcy52YXJpYWJsZVNjb3BlO1xuICAgICAgICAgICAgaWYgKHJlZi50YWludGVkKSB7XG4gICAgICAgICAgICAgICAgdmFyaWFibGUudGFpbnRlZCA9IHRydWU7XG4gICAgICAgICAgICAgICAgdGhpcy50YWludHMuc2V0KHZhcmlhYmxlLm5hbWUsIHRydWUpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgcmVmLnJlc29sdmVkID0gdmFyaWFibGU7XG4gICAgICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgfVxuXG4gICAgX19kZWxlZ2F0ZVRvVXBwZXJTY29wZShyZWYpIHtcbiAgICAgICAgaWYgKHRoaXMudXBwZXIpIHtcbiAgICAgICAgICAgIHRoaXMudXBwZXIuX19sZWZ0LnB1c2gocmVmKTtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLnRocm91Z2gucHVzaChyZWYpO1xuICAgIH1cblxuICAgIF9fZGVmaW5lR2VuZXJpYyhuYW1lLCBzZXQsIHZhcmlhYmxlcywgbm9kZSwgZGVmKSB7XG4gICAgICAgIHZhciB2YXJpYWJsZTtcblxuICAgICAgICB2YXJpYWJsZSA9IHNldC5nZXQobmFtZSk7XG4gICAgICAgIGlmICghdmFyaWFibGUpIHtcbiAgICAgICAgICAgIHZhcmlhYmxlID0gbmV3IFZhcmlhYmxlKG5hbWUsIHRoaXMpO1xuICAgICAgICAgICAgc2V0LnNldChuYW1lLCB2YXJpYWJsZSk7XG4gICAgICAgICAgICB2YXJpYWJsZXMucHVzaCh2YXJpYWJsZSk7XG4gICAgICAgIH1cblxuICAgICAgICBpZiAoZGVmKSB7XG4gICAgICAgICAgICB2YXJpYWJsZS5kZWZzLnB1c2goZGVmKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAobm9kZSkge1xuICAgICAgICAgICAgdmFyaWFibGUuaWRlbnRpZmllcnMucHVzaChub2RlKTtcbiAgICAgICAgfVxuICAgIH1cblxuICAgIF9fZGVmaW5lKG5vZGUsIGRlZikge1xuICAgICAgICBpZiAobm9kZSAmJiBub2RlLnR5cGUgPT09IFN5bnRheC5JZGVudGlmaWVyKSB7XG4gICAgICAgICAgICB0aGlzLl9fZGVmaW5lR2VuZXJpYyhcbiAgICAgICAgICAgICAgICAgICAgbm9kZS5uYW1lLFxuICAgICAgICAgICAgICAgICAgICB0aGlzLnNldCxcbiAgICAgICAgICAgICAgICAgICAgdGhpcy52YXJpYWJsZXMsXG4gICAgICAgICAgICAgICAgICAgIG5vZGUsXG4gICAgICAgICAgICAgICAgICAgIGRlZik7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICBfX3JlZmVyZW5jaW5nKG5vZGUsIGFzc2lnbiwgd3JpdGVFeHByLCBtYXliZUltcGxpY2l0R2xvYmFsLCBwYXJ0aWFsKSB7XG4gICAgICAgIC8vIGJlY2F1c2UgQXJyYXkgZWxlbWVudCBtYXkgYmUgbnVsbFxuICAgICAgICBpZiAoIW5vZGUgfHwgbm9kZS50eXBlICE9PSBTeW50YXguSWRlbnRpZmllcikge1xuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG5cbiAgICAgICAgLy8gU3BlY2lhbGx5IGhhbmRsZSBsaWtlIGB0aGlzYC5cbiAgICAgICAgaWYgKG5vZGUubmFtZSA9PT0gJ3N1cGVyJykge1xuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG5cbiAgICAgICAgbGV0IHJlZiA9IG5ldyBSZWZlcmVuY2Uobm9kZSwgdGhpcywgYXNzaWduIHx8IFJlZmVyZW5jZS5SRUFELCB3cml0ZUV4cHIsIG1heWJlSW1wbGljaXRHbG9iYWwsICEhcGFydGlhbCk7XG4gICAgICAgIHRoaXMucmVmZXJlbmNlcy5wdXNoKHJlZik7XG4gICAgICAgIHRoaXMuX19sZWZ0LnB1c2gocmVmKTtcbiAgICB9XG5cbiAgICBfX2RldGVjdEV2YWwoKSB7XG4gICAgICAgIHZhciBjdXJyZW50O1xuICAgICAgICBjdXJyZW50ID0gdGhpcztcbiAgICAgICAgdGhpcy5kaXJlY3RDYWxsVG9FdmFsU2NvcGUgPSB0cnVlO1xuICAgICAgICBkbyB7XG4gICAgICAgICAgICBjdXJyZW50LmR5bmFtaWMgPSB0cnVlO1xuICAgICAgICAgICAgY3VycmVudCA9IGN1cnJlbnQudXBwZXI7XG4gICAgICAgIH0gd2hpbGUgKGN1cnJlbnQpO1xuICAgIH1cblxuICAgIF9fZGV0ZWN0VGhpcygpIHtcbiAgICAgICAgdGhpcy50aGlzRm91bmQgPSB0cnVlO1xuICAgIH1cblxuICAgIF9faXNDbG9zZWQoKSB7XG4gICAgICAgIHJldHVybiB0aGlzLl9fbGVmdCA9PT0gbnVsbDtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiByZXR1cm5zIHJlc29sdmVkIHtSZWZlcmVuY2V9XG4gICAgICogQG1ldGhvZCBTY29wZSNyZXNvbHZlXG4gICAgICogQHBhcmFtIHtFc3ByaW1hLklkZW50aWZpZXJ9IGlkZW50IC0gaWRlbnRpZmllciB0byBiZSByZXNvbHZlZC5cbiAgICAgKiBAcmV0dXJuIHtSZWZlcmVuY2V9XG4gICAgICovXG4gICAgcmVzb2x2ZShpZGVudCkge1xuICAgICAgICB2YXIgcmVmLCBpLCBpejtcbiAgICAgICAgYXNzZXJ0KHRoaXMuX19pc0Nsb3NlZCgpLCAnU2NvcGUgc2hvdWxkIGJlIGNsb3NlZC4nKTtcbiAgICAgICAgYXNzZXJ0KGlkZW50LnR5cGUgPT09IFN5bnRheC5JZGVudGlmaWVyLCAnVGFyZ2V0IHNob3VsZCBiZSBpZGVudGlmaWVyLicpO1xuICAgICAgICBmb3IgKGkgPSAwLCBpeiA9IHRoaXMucmVmZXJlbmNlcy5sZW5ndGg7IGkgPCBpejsgKytpKSB7XG4gICAgICAgICAgICByZWYgPSB0aGlzLnJlZmVyZW5jZXNbaV07XG4gICAgICAgICAgICBpZiAocmVmLmlkZW50aWZpZXIgPT09IGlkZW50KSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIHJlZjtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiByZXR1cm5zIHRoaXMgc2NvcGUgaXMgc3RhdGljXG4gICAgICogQG1ldGhvZCBTY29wZSNpc1N0YXRpY1xuICAgICAqIEByZXR1cm4ge2Jvb2xlYW59XG4gICAgICovXG4gICAgaXNTdGF0aWMoKSB7XG4gICAgICAgIHJldHVybiAhdGhpcy5keW5hbWljO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIHJldHVybnMgdGhpcyBzY29wZSBoYXMgbWF0ZXJpYWxpemVkIGFyZ3VtZW50c1xuICAgICAqIEBtZXRob2QgU2NvcGUjaXNBcmd1bWVudHNNYXRlcmlhbGl6ZWRcbiAgICAgKiBAcmV0dXJuIHtib29sZWFufVxuICAgICAqL1xuICAgIGlzQXJndW1lbnRzTWF0ZXJpYWxpemVkKCkge1xuICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICB9XG5cbiAgICAvKipcbiAgICAgKiByZXR1cm5zIHRoaXMgc2NvcGUgaGFzIG1hdGVyaWFsaXplZCBgdGhpc2AgcmVmZXJlbmNlXG4gICAgICogQG1ldGhvZCBTY29wZSNpc1RoaXNNYXRlcmlhbGl6ZWRcbiAgICAgKiBAcmV0dXJuIHtib29sZWFufVxuICAgICAqL1xuICAgIGlzVGhpc01hdGVyaWFsaXplZCgpIHtcbiAgICAgICAgcmV0dXJuIHRydWU7XG4gICAgfVxuXG4gICAgaXNVc2VkTmFtZShuYW1lKSB7XG4gICAgICAgIGlmICh0aGlzLnNldC5oYXMobmFtZSkpIHtcbiAgICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICB9XG4gICAgICAgIGZvciAodmFyIGkgPSAwLCBpeiA9IHRoaXMudGhyb3VnaC5sZW5ndGg7IGkgPCBpejsgKytpKSB7XG4gICAgICAgICAgICBpZiAodGhpcy50aHJvdWdoW2ldLmlkZW50aWZpZXIubmFtZSA9PT0gbmFtZSkge1xuICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIHJldHVybiBmYWxzZTtcbiAgICB9XG59XG5cbmV4cG9ydCBjbGFzcyBHbG9iYWxTY29wZSBleHRlbmRzIFNjb3BlIHtcbiAgICBjb25zdHJ1Y3RvcihzY29wZU1hbmFnZXIsIGJsb2NrKSB7XG4gICAgICAgIHN1cGVyKHNjb3BlTWFuYWdlciwgJ2dsb2JhbCcsIG51bGwsIGJsb2NrLCBmYWxzZSk7XG4gICAgICAgIHRoaXMuaW1wbGljaXQgPSB7XG4gICAgICAgICAgICBzZXQ6IG5ldyBNYXAoKSxcbiAgICAgICAgICAgIHZhcmlhYmxlczogW10sXG4gICAgICAgICAgICAvKipcbiAgICAgICAgICAgICogTGlzdCBvZiB7QGxpbmsgUmVmZXJlbmNlfXMgdGhhdCBhcmUgbGVmdCB0byBiZSByZXNvbHZlZCAoaS5lLiB3aGljaFxuICAgICAgICAgICAgKiBuZWVkIHRvIGJlIGxpbmtlZCB0byB0aGUgdmFyaWFibGUgdGhleSByZWZlciB0bykuXG4gICAgICAgICAgICAqIEBtZW1iZXIge1JlZmVyZW5jZVtdfSBTY29wZSNpbXBsaWNpdCNsZWZ0XG4gICAgICAgICAgICAqL1xuICAgICAgICAgICAgbGVmdDogW11cbiAgICAgICAgfTtcbiAgICB9XG5cbiAgICBfX2Nsb3NlKHNjb3BlTWFuYWdlcikge1xuICAgICAgICBsZXQgaW1wbGljaXQgPSBbXTtcbiAgICAgICAgZm9yIChsZXQgaSA9IDAsIGl6ID0gdGhpcy5fX2xlZnQubGVuZ3RoOyBpIDwgaXo7ICsraSkge1xuICAgICAgICAgICAgbGV0IHJlZiA9IHRoaXMuX19sZWZ0W2ldO1xuICAgICAgICAgICAgaWYgKHJlZi5fX21heWJlSW1wbGljaXRHbG9iYWwgJiYgIXRoaXMuc2V0LmhhcyhyZWYuaWRlbnRpZmllci5uYW1lKSkge1xuICAgICAgICAgICAgICAgIGltcGxpY2l0LnB1c2gocmVmLl9fbWF5YmVJbXBsaWNpdEdsb2JhbCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cblxuICAgICAgICAvLyBjcmVhdGUgYW4gaW1wbGljaXQgZ2xvYmFsIHZhcmlhYmxlIGZyb20gYXNzaWdubWVudCBleHByZXNzaW9uXG4gICAgICAgIGZvciAobGV0IGkgPSAwLCBpeiA9IGltcGxpY2l0Lmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgIGxldCBpbmZvID0gaW1wbGljaXRbaV07XG4gICAgICAgICAgICB0aGlzLl9fZGVmaW5lSW1wbGljaXQoaW5mby5wYXR0ZXJuLFxuICAgICAgICAgICAgICAgICAgICBuZXcgRGVmaW5pdGlvbihcbiAgICAgICAgICAgICAgICAgICAgICAgIFZhcmlhYmxlLkltcGxpY2l0R2xvYmFsVmFyaWFibGUsXG4gICAgICAgICAgICAgICAgICAgICAgICBpbmZvLnBhdHRlcm4sXG4gICAgICAgICAgICAgICAgICAgICAgICBpbmZvLm5vZGUsXG4gICAgICAgICAgICAgICAgICAgICAgICBudWxsLFxuICAgICAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgICAgIG51bGxcbiAgICAgICAgICAgICAgICAgICAgKSk7XG5cbiAgICAgICAgfVxuXG4gICAgICAgIHRoaXMuaW1wbGljaXQubGVmdCA9IHRoaXMuX19sZWZ0O1xuXG4gICAgICAgIHJldHVybiBzdXBlci5fX2Nsb3NlKHNjb3BlTWFuYWdlcik7XG4gICAgfVxuXG4gICAgX19kZWZpbmVJbXBsaWNpdChub2RlLCBkZWYpIHtcbiAgICAgICAgaWYgKG5vZGUgJiYgbm9kZS50eXBlID09PSBTeW50YXguSWRlbnRpZmllcikge1xuICAgICAgICAgICAgdGhpcy5fX2RlZmluZUdlbmVyaWMoXG4gICAgICAgICAgICAgICAgICAgIG5vZGUubmFtZSxcbiAgICAgICAgICAgICAgICAgICAgdGhpcy5pbXBsaWNpdC5zZXQsXG4gICAgICAgICAgICAgICAgICAgIHRoaXMuaW1wbGljaXQudmFyaWFibGVzLFxuICAgICAgICAgICAgICAgICAgICBub2RlLFxuICAgICAgICAgICAgICAgICAgICBkZWYpO1xuICAgICAgICB9XG4gICAgfVxufVxuXG5leHBvcnQgY2xhc3MgTW9kdWxlU2NvcGUgZXh0ZW5kcyBTY29wZSB7XG4gICAgY29uc3RydWN0b3Ioc2NvcGVNYW5hZ2VyLCB1cHBlclNjb3BlLCBibG9jaykge1xuICAgICAgICBzdXBlcihzY29wZU1hbmFnZXIsICdtb2R1bGUnLCB1cHBlclNjb3BlLCBibG9jaywgZmFsc2UpO1xuICAgIH1cbn1cblxuZXhwb3J0IGNsYXNzIEZ1bmN0aW9uRXhwcmVzc2lvbk5hbWVTY29wZSBleHRlbmRzIFNjb3BlIHtcbiAgICBjb25zdHJ1Y3RvcihzY29wZU1hbmFnZXIsIHVwcGVyU2NvcGUsIGJsb2NrKSB7XG4gICAgICAgIHN1cGVyKHNjb3BlTWFuYWdlciwgJ2Z1bmN0aW9uLWV4cHJlc3Npb24tbmFtZScsIHVwcGVyU2NvcGUsIGJsb2NrLCBmYWxzZSk7XG4gICAgICAgIHRoaXMuX19kZWZpbmUoYmxvY2suaWQsXG4gICAgICAgICAgICAgICAgbmV3IERlZmluaXRpb24oXG4gICAgICAgICAgICAgICAgICAgIFZhcmlhYmxlLkZ1bmN0aW9uTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgYmxvY2suaWQsXG4gICAgICAgICAgICAgICAgICAgIGJsb2NrLFxuICAgICAgICAgICAgICAgICAgICBudWxsLFxuICAgICAgICAgICAgICAgICAgICBudWxsLFxuICAgICAgICAgICAgICAgICAgICBudWxsXG4gICAgICAgICAgICAgICAgKSk7XG4gICAgICAgIHRoaXMuZnVuY3Rpb25FeHByZXNzaW9uU2NvcGUgPSB0cnVlO1xuICAgIH1cbn1cblxuZXhwb3J0IGNsYXNzIENhdGNoU2NvcGUgZXh0ZW5kcyBTY29wZSB7XG4gICAgY29uc3RydWN0b3Ioc2NvcGVNYW5hZ2VyLCB1cHBlclNjb3BlLCBibG9jaykge1xuICAgICAgICBzdXBlcihzY29wZU1hbmFnZXIsICdjYXRjaCcsIHVwcGVyU2NvcGUsIGJsb2NrLCBmYWxzZSk7XG4gICAgfVxufVxuXG5leHBvcnQgY2xhc3MgV2l0aFNjb3BlIGV4dGVuZHMgU2NvcGUge1xuICAgIGNvbnN0cnVjdG9yKHNjb3BlTWFuYWdlciwgdXBwZXJTY29wZSwgYmxvY2spIHtcbiAgICAgICAgc3VwZXIoc2NvcGVNYW5hZ2VyLCAnd2l0aCcsIHVwcGVyU2NvcGUsIGJsb2NrLCBmYWxzZSk7XG4gICAgfVxuXG4gICAgX19jbG9zZShzY29wZU1hbmFnZXIpIHtcbiAgICAgICAgaWYgKHRoaXMuX19zaG91bGRTdGF0aWNhbGx5Q2xvc2Uoc2NvcGVNYW5hZ2VyKSkge1xuICAgICAgICAgICAgcmV0dXJuIHN1cGVyLl9fY2xvc2Uoc2NvcGVNYW5hZ2VyKTtcbiAgICAgICAgfVxuXG4gICAgICAgIGZvciAobGV0IGkgPSAwLCBpeiA9IHRoaXMuX19sZWZ0Lmxlbmd0aDsgaSA8IGl6OyArK2kpIHtcbiAgICAgICAgICAgIGxldCByZWYgPSB0aGlzLl9fbGVmdFtpXTtcbiAgICAgICAgICAgIHJlZi50YWludGVkID0gdHJ1ZTtcbiAgICAgICAgICAgIHRoaXMuX19kZWxlZ2F0ZVRvVXBwZXJTY29wZShyZWYpO1xuICAgICAgICB9XG4gICAgICAgIHRoaXMuX19sZWZ0ID0gbnVsbDtcblxuICAgICAgICByZXR1cm4gdGhpcy51cHBlcjtcbiAgICB9XG59XG5cbmV4cG9ydCBjbGFzcyBURFpTY29wZSBleHRlbmRzIFNjb3BlIHtcbiAgICBjb25zdHJ1Y3RvcihzY29wZU1hbmFnZXIsIHVwcGVyU2NvcGUsIGJsb2NrKSB7XG4gICAgICAgIHN1cGVyKHNjb3BlTWFuYWdlciwgJ1REWicsIHVwcGVyU2NvcGUsIGJsb2NrLCBmYWxzZSk7XG4gICAgfVxufVxuXG5leHBvcnQgY2xhc3MgQmxvY2tTY29wZSBleHRlbmRzIFNjb3BlIHtcbiAgICBjb25zdHJ1Y3RvcihzY29wZU1hbmFnZXIsIHVwcGVyU2NvcGUsIGJsb2NrKSB7XG4gICAgICAgIHN1cGVyKHNjb3BlTWFuYWdlciwgJ2Jsb2NrJywgdXBwZXJTY29wZSwgYmxvY2ssIGZhbHNlKTtcbiAgICB9XG59XG5cbmV4cG9ydCBjbGFzcyBTd2l0Y2hTY29wZSBleHRlbmRzIFNjb3BlIHtcbiAgICBjb25zdHJ1Y3RvcihzY29wZU1hbmFnZXIsIHVwcGVyU2NvcGUsIGJsb2NrKSB7XG4gICAgICAgIHN1cGVyKHNjb3BlTWFuYWdlciwgJ3N3aXRjaCcsIHVwcGVyU2NvcGUsIGJsb2NrLCBmYWxzZSk7XG4gICAgfVxufVxuXG5leHBvcnQgY2xhc3MgRnVuY3Rpb25TY29wZSBleHRlbmRzIFNjb3BlIHtcbiAgICBjb25zdHJ1Y3RvcihzY29wZU1hbmFnZXIsIHVwcGVyU2NvcGUsIGJsb2NrLCBpc01ldGhvZERlZmluaXRpb24pIHtcbiAgICAgICAgc3VwZXIoc2NvcGVNYW5hZ2VyLCAnZnVuY3Rpb24nLCB1cHBlclNjb3BlLCBibG9jaywgaXNNZXRob2REZWZpbml0aW9uKTtcblxuICAgICAgICAvLyBzZWN0aW9uIDkuMi4xMywgRnVuY3Rpb25EZWNsYXJhdGlvbkluc3RhbnRpYXRpb24uXG4gICAgICAgIC8vIE5PVEUgQXJyb3cgZnVuY3Rpb25zIG5ldmVyIGhhdmUgYW4gYXJndW1lbnRzIG9iamVjdHMuXG4gICAgICAgIGlmICh0aGlzLmJsb2NrLnR5cGUgIT09IFN5bnRheC5BcnJvd0Z1bmN0aW9uRXhwcmVzc2lvbikge1xuICAgICAgICAgICAgdGhpcy5fX2RlZmluZUFyZ3VtZW50cygpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgaXNBcmd1bWVudHNNYXRlcmlhbGl6ZWQoKSB7XG4gICAgICAgIC8vIFRPRE8oQ29uc3RlbGxhdGlvbilcbiAgICAgICAgLy8gV2UgY2FuIG1vcmUgYWdncmVzc2l2ZSBvbiB0aGlzIGNvbmRpdGlvbiBsaWtlIHRoaXMuXG4gICAgICAgIC8vXG4gICAgICAgIC8vIGZ1bmN0aW9uIHQoKSB7XG4gICAgICAgIC8vICAgICAvLyBhcmd1bWVudHMgb2YgdCBpcyBhbHdheXMgaGlkZGVuLlxuICAgICAgICAvLyAgICAgZnVuY3Rpb24gYXJndW1lbnRzKCkge1xuICAgICAgICAvLyAgICAgfVxuICAgICAgICAvLyB9XG4gICAgICAgIGlmICh0aGlzLmJsb2NrLnR5cGUgPT09IFN5bnRheC5BcnJvd0Z1bmN0aW9uRXhwcmVzc2lvbikge1xuICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICB9XG5cbiAgICAgICAgaWYgKCF0aGlzLmlzU3RhdGljKCkpIHtcbiAgICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICB9XG5cbiAgICAgICAgbGV0IHZhcmlhYmxlID0gdGhpcy5zZXQuZ2V0KCdhcmd1bWVudHMnKTtcbiAgICAgICAgYXNzZXJ0KHZhcmlhYmxlLCAnQWx3YXlzIGhhdmUgYXJndW1lbnRzIHZhcmlhYmxlLicpO1xuICAgICAgICByZXR1cm4gdmFyaWFibGUudGFpbnRlZCB8fCB2YXJpYWJsZS5yZWZlcmVuY2VzLmxlbmd0aCAgIT09IDA7XG4gICAgfVxuXG4gICAgaXNUaGlzTWF0ZXJpYWxpemVkKCkge1xuICAgICAgICBpZiAoIXRoaXMuaXNTdGF0aWMoKSkge1xuICAgICAgICAgICAgcmV0dXJuIHRydWU7XG4gICAgICAgIH1cbiAgICAgICAgcmV0dXJuIHRoaXMudGhpc0ZvdW5kO1xuICAgIH1cblxuICAgIF9fZGVmaW5lQXJndW1lbnRzKCkge1xuICAgICAgICB0aGlzLl9fZGVmaW5lR2VuZXJpYyhcbiAgICAgICAgICAgICAgICAnYXJndW1lbnRzJyxcbiAgICAgICAgICAgICAgICB0aGlzLnNldCxcbiAgICAgICAgICAgICAgICB0aGlzLnZhcmlhYmxlcyxcbiAgICAgICAgICAgICAgICBudWxsLFxuICAgICAgICAgICAgICAgIG51bGwpO1xuICAgICAgICB0aGlzLnRhaW50cy5zZXQoJ2FyZ3VtZW50cycsIHRydWUpO1xuICAgIH1cbn1cblxuZXhwb3J0IGNsYXNzIEZvclNjb3BlIGV4dGVuZHMgU2NvcGUge1xuICAgIGNvbnN0cnVjdG9yKHNjb3BlTWFuYWdlciwgdXBwZXJTY29wZSwgYmxvY2spIHtcbiAgICAgICAgc3VwZXIoc2NvcGVNYW5hZ2VyLCAnZm9yJywgdXBwZXJTY29wZSwgYmxvY2ssIGZhbHNlKTtcbiAgICB9XG59XG5cbmV4cG9ydCBjbGFzcyBDbGFzc1Njb3BlIGV4dGVuZHMgU2NvcGUge1xuICAgIGNvbnN0cnVjdG9yKHNjb3BlTWFuYWdlciwgdXBwZXJTY29wZSwgYmxvY2spIHtcbiAgICAgICAgc3VwZXIoc2NvcGVNYW5hZ2VyLCAnY2xhc3MnLCB1cHBlclNjb3BlLCBibG9jaywgZmFsc2UpO1xuICAgIH1cbn1cblxuLyogdmltOiBzZXQgc3c9NCB0cz00IGV0IHR3PTgwIDogKi9cbiJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ== \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/lib/variable.js b/tools/eslint/node_modules/escope/lib/variable.js new file mode 100644 index 00000000000000..6630f0a646b56c --- /dev/null +++ b/tools/eslint/node_modules/escope/lib/variable.js @@ -0,0 +1,89 @@ +"use strict"; + +var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; + +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ + +var Variable = function Variable(name, scope) { + _classCallCheck(this, Variable); + + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {esprima.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; +}; + +module.exports = Variable; + +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.TDZ = "TDZ"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + +/* vim: set sw=4 ts=4 et tw=80 : */ +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInZhcmlhYmxlLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7SUE2QnFCLFFBQVEsR0FDZCxTQURNLFFBQVEsQ0FDYixJQUFJLEVBQUUsS0FBSyxFQUFFO3dCQURSLFFBQVE7Ozs7OztBQU1yQixNQUFJLENBQUMsSUFBSSxHQUFHLElBQUksQ0FBQzs7Ozs7O0FBTWpCLE1BQUksQ0FBQyxXQUFXLEdBQUcsRUFBRSxDQUFDOzs7Ozs7O0FBT3RCLE1BQUksQ0FBQyxVQUFVLEdBQUcsRUFBRSxDQUFDOzs7Ozs7O0FBT3JCLE1BQUksQ0FBQyxJQUFJLEdBQUcsRUFBRSxDQUFDOztBQUVmLE1BQUksQ0FBQyxPQUFPLEdBQUcsS0FBSyxDQUFDOzs7OztBQUtyQixNQUFJLENBQUMsS0FBSyxHQUFHLElBQUksQ0FBQzs7Ozs7QUFLbEIsTUFBSSxDQUFDLEtBQUssR0FBRyxLQUFLLENBQUM7Q0FDdEI7O2lCQXZDZ0IsUUFBUTs7QUEwQzdCLFFBQVEsQ0FBQyxXQUFXLEdBQUcsYUFBYSxDQUFDO0FBQ3JDLFFBQVEsQ0FBQyxTQUFTLEdBQUcsV0FBVyxDQUFDO0FBQ2pDLFFBQVEsQ0FBQyxZQUFZLEdBQUcsY0FBYyxDQUFDO0FBQ3ZDLFFBQVEsQ0FBQyxTQUFTLEdBQUcsV0FBVyxDQUFDO0FBQ2pDLFFBQVEsQ0FBQyxRQUFRLEdBQUcsVUFBVSxDQUFDO0FBQy9CLFFBQVEsQ0FBQyxhQUFhLEdBQUcsZUFBZSxDQUFDO0FBQ3pDLFFBQVEsQ0FBQyxHQUFHLEdBQUcsS0FBSyxDQUFDO0FBQ3JCLFFBQVEsQ0FBQyxzQkFBc0IsR0FBRyx3QkFBd0IsQ0FBQyIsImZpbGUiOiJ2YXJpYWJsZS5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qXG4gIENvcHlyaWdodCAoQykgMjAxNSBZdXN1a2UgU3V6dWtpIDx1dGF0YW5lLnRlYUBnbWFpbC5jb20+XG5cbiAgUmVkaXN0cmlidXRpb24gYW5kIHVzZSBpbiBzb3VyY2UgYW5kIGJpbmFyeSBmb3Jtcywgd2l0aCBvciB3aXRob3V0XG4gIG1vZGlmaWNhdGlvbiwgYXJlIHBlcm1pdHRlZCBwcm92aWRlZCB0aGF0IHRoZSBmb2xsb3dpbmcgY29uZGl0aW9ucyBhcmUgbWV0OlxuXG4gICAgKiBSZWRpc3RyaWJ1dGlvbnMgb2Ygc291cmNlIGNvZGUgbXVzdCByZXRhaW4gdGhlIGFib3ZlIGNvcHlyaWdodFxuICAgICAgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZyBkaXNjbGFpbWVyLlxuICAgICogUmVkaXN0cmlidXRpb25zIGluIGJpbmFyeSBmb3JtIG11c3QgcmVwcm9kdWNlIHRoZSBhYm92ZSBjb3B5cmlnaHRcbiAgICAgIG5vdGljZSwgdGhpcyBsaXN0IG9mIGNvbmRpdGlvbnMgYW5kIHRoZSBmb2xsb3dpbmcgZGlzY2xhaW1lciBpbiB0aGVcbiAgICAgIGRvY3VtZW50YXRpb24gYW5kL29yIG90aGVyIG1hdGVyaWFscyBwcm92aWRlZCB3aXRoIHRoZSBkaXN0cmlidXRpb24uXG5cbiAgVEhJUyBTT0ZUV0FSRSBJUyBQUk9WSURFRCBCWSBUSEUgQ09QWVJJR0hUIEhPTERFUlMgQU5EIENPTlRSSUJVVE9SUyBcIkFTIElTXCJcbiAgQU5EIEFOWSBFWFBSRVNTIE9SIElNUExJRUQgV0FSUkFOVElFUywgSU5DTFVESU5HLCBCVVQgTk9UIExJTUlURUQgVE8sIFRIRVxuICBJTVBMSUVEIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZIEFORCBGSVRORVNTIEZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRVxuICBBUkUgRElTQ0xBSU1FRC4gSU4gTk8gRVZFTlQgU0hBTEwgPENPUFlSSUdIVCBIT0xERVI+IEJFIExJQUJMRSBGT1IgQU5ZXG4gIERJUkVDVCwgSU5ESVJFQ1QsIElOQ0lERU5UQUwsIFNQRUNJQUwsIEVYRU1QTEFSWSwgT1IgQ09OU0VRVUVOVElBTCBEQU1BR0VTXG4gIChJTkNMVURJTkcsIEJVVCBOT1QgTElNSVRFRCBUTywgUFJPQ1VSRU1FTlQgT0YgU1VCU1RJVFVURSBHT09EUyBPUiBTRVJWSUNFUztcbiAgTE9TUyBPRiBVU0UsIERBVEEsIE9SIFBST0ZJVFM7IE9SIEJVU0lORVNTIElOVEVSUlVQVElPTikgSE9XRVZFUiBDQVVTRUQgQU5EXG4gIE9OIEFOWSBUSEVPUlkgT0YgTElBQklMSVRZLCBXSEVUSEVSIElOIENPTlRSQUNULCBTVFJJQ1QgTElBQklMSVRZLCBPUiBUT1JUXG4gIChJTkNMVURJTkcgTkVHTElHRU5DRSBPUiBPVEhFUldJU0UpIEFSSVNJTkcgSU4gQU5ZIFdBWSBPVVQgT0YgVEhFIFVTRSBPRlxuICBUSElTIFNPRlRXQVJFLCBFVkVOIElGIEFEVklTRUQgT0YgVEhFIFBPU1NJQklMSVRZIE9GIFNVQ0ggREFNQUdFLlxuKi9cblxuLyoqXG4gKiBBIFZhcmlhYmxlIHJlcHJlc2VudHMgYSBsb2NhbGx5IHNjb3BlZCBpZGVudGlmaWVyLiBUaGVzZSBpbmNsdWRlIGFyZ3VtZW50cyB0b1xuICogZnVuY3Rpb25zLlxuICogQGNsYXNzIFZhcmlhYmxlXG4gKi9cbmV4cG9ydCBkZWZhdWx0IGNsYXNzIFZhcmlhYmxlIHtcbiAgICBjb25zdHJ1Y3RvcihuYW1lLCBzY29wZSkge1xuICAgICAgICAvKipcbiAgICAgICAgICogVGhlIHZhcmlhYmxlIG5hbWUsIGFzIGdpdmVuIGluIHRoZSBzb3VyY2UgY29kZS5cbiAgICAgICAgICogQG1lbWJlciB7U3RyaW5nfSBWYXJpYWJsZSNuYW1lXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLm5hbWUgPSBuYW1lO1xuICAgICAgICAvKipcbiAgICAgICAgICogTGlzdCBvZiBkZWZpbmluZyBvY2N1cnJlbmNlcyBvZiB0aGlzIHZhcmlhYmxlIChsaWtlIGluICd2YXIgLi4uJ1xuICAgICAgICAgKiBzdGF0ZW1lbnRzIG9yIGFzIHBhcmFtZXRlciksIGFzIEFTVCBub2Rlcy5cbiAgICAgICAgICogQG1lbWJlciB7ZXNwcmltYS5JZGVudGlmaWVyW119IFZhcmlhYmxlI2lkZW50aWZpZXJzXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmlkZW50aWZpZXJzID0gW107XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBMaXN0IG9mIHtAbGluayBSZWZlcmVuY2V8cmVmZXJlbmNlc30gb2YgdGhpcyB2YXJpYWJsZSAoZXhjbHVkaW5nIHBhcmFtZXRlciBlbnRyaWVzKVxuICAgICAgICAgKiBpbiBpdHMgZGVmaW5pbmcgc2NvcGUgYW5kIGFsbCBuZXN0ZWQgc2NvcGVzLiBGb3IgZGVmaW5pbmdcbiAgICAgICAgICogb2NjdXJyZW5jZXMgb25seSBzZWUge0BsaW5rIFZhcmlhYmxlI2RlZnN9LlxuICAgICAgICAgKiBAbWVtYmVyIHtSZWZlcmVuY2VbXX0gVmFyaWFibGUjcmVmZXJlbmNlc1xuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5yZWZlcmVuY2VzID0gW107XG5cbiAgICAgICAgLyoqXG4gICAgICAgICAqIExpc3Qgb2YgZGVmaW5pbmcgb2NjdXJyZW5jZXMgb2YgdGhpcyB2YXJpYWJsZSAobGlrZSBpbiAndmFyIC4uLidcbiAgICAgICAgICogc3RhdGVtZW50cyBvciBhcyBwYXJhbWV0ZXIpLCBhcyBjdXN0b20gb2JqZWN0cy5cbiAgICAgICAgICogQG1lbWJlciB7RGVmaW5pdGlvbltdfSBWYXJpYWJsZSNkZWZzXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLmRlZnMgPSBbXTtcblxuICAgICAgICB0aGlzLnRhaW50ZWQgPSBmYWxzZTtcbiAgICAgICAgLyoqXG4gICAgICAgICAqIFdoZXRoZXIgdGhpcyBpcyBhIHN0YWNrIHZhcmlhYmxlLlxuICAgICAgICAgKiBAbWVtYmVyIHtib29sZWFufSBWYXJpYWJsZSNzdGFja1xuICAgICAgICAgKi9cbiAgICAgICAgdGhpcy5zdGFjayA9IHRydWU7XG4gICAgICAgIC8qKlxuICAgICAgICAgKiBSZWZlcmVuY2UgdG8gdGhlIGVuY2xvc2luZyBTY29wZS5cbiAgICAgICAgICogQG1lbWJlciB7U2NvcGV9IFZhcmlhYmxlI3Njb3BlXG4gICAgICAgICAqL1xuICAgICAgICB0aGlzLnNjb3BlID0gc2NvcGU7XG4gICAgfVxufVxuXG5WYXJpYWJsZS5DYXRjaENsYXVzZSA9ICdDYXRjaENsYXVzZSc7XG5WYXJpYWJsZS5QYXJhbWV0ZXIgPSAnUGFyYW1ldGVyJztcblZhcmlhYmxlLkZ1bmN0aW9uTmFtZSA9ICdGdW5jdGlvbk5hbWUnO1xuVmFyaWFibGUuQ2xhc3NOYW1lID0gJ0NsYXNzTmFtZSc7XG5WYXJpYWJsZS5WYXJpYWJsZSA9ICdWYXJpYWJsZSc7XG5WYXJpYWJsZS5JbXBvcnRCaW5kaW5nID0gJ0ltcG9ydEJpbmRpbmcnO1xuVmFyaWFibGUuVERaID0gJ1REWic7XG5WYXJpYWJsZS5JbXBsaWNpdEdsb2JhbFZhcmlhYmxlID0gJ0ltcGxpY2l0R2xvYmFsVmFyaWFibGUnO1xuXG4vKiB2aW06IHNldCBzdz00IHRzPTQgZXQgdHc9ODAgOiAqL1xuIl0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9 \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/.lint new file mode 100644 index 00000000000000..e8cb4c7581685f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/.lint @@ -0,0 +1,11 @@ +@root + +module + +indent 2 +maxlen 80 +tabs + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/.travis.yml new file mode 100644 index 00000000000000..9181d7823d86b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-map@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/CHANGES new file mode 100644 index 00000000000000..a17e221ab39e40 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/CHANGES @@ -0,0 +1,16 @@ +v0.1.1 -- 2014.10.07 +* Fix isImplemented so native Maps are detected properly +* Configure lint scripts + +v0.1.0 -- 2014.04.29 +* Assure strictly npm hosted dependencies +* Update to use latest versions of dependencies + +v0.0.1 -- 2014.04.25 +* Provide @@toStringTag symbol, and use other ES 6 symbols +* Fix iterators handling +* Fix isImplemented so it doesn't crash +* Update up to changes in dependencies + +v0.0.0 -- 2013.11.10 +- Initial (dev) version diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/LICENCE b/tools/eslint/node_modules/escope/node_modules/es6-map/LICENCE new file mode 100644 index 00000000000000..aaf35282f41f57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/LICENCE @@ -0,0 +1,19 @@ +Copyright (C) 2013 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/README.md new file mode 100644 index 00000000000000..1ea3a953c5093a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/README.md @@ -0,0 +1,75 @@ +# es6-map +## Map collection as specified in ECMAScript6 + +### Usage + +If you want to make sure your environment implements `Map`, do: + +```javascript +require('es6-map/implement'); +``` + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't, but without implementing `Map` on global scope, do: + +```javascript +var Map = require('es6-map'); +``` + +If you strictly want to use polyfill even if native `Map` exists, do: + +```javascript +var Map = require('es6-map/polyfill'); +``` + +### Installation + + $ npm install es6-map + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-map-objects). Still if you want quick look, follow examples: + +```javascript +var Map = require('es6-map'); + +var x = {}, y = {}, map = new Map([['raz', 'one'], ['dwa', 'two'], [x, y]]); + +map.size; // 3 +map.get('raz'); // 'one' +map.get(x); // y +map.has('raz'); // true +map.has(x); // true +map.has('foo'); // false +map.set('trzy', 'three'); // map +map.size // 4 +map.get('trzy'); // 'three' +map.has('trzy'); // true +map.has('dwa'); // true +map.delete('dwa'); // true +map.size; // 3 + +map.forEach(function (value, key) { + // { 'raz', 'one' }, { x, y }, { 'trzy', 'three' } iterated +}); + +// FF nightly only: +for (value of map) { + // ['raz', 'one'], [x, y], ['trzy', 'three'] iterated +} + +var iterator = map.values(); + +iterator.next(); // { done: false, value: 'one' } +iterator.next(); // { done: false, value: y } +iterator.next(); // { done: false, value: 'three' } +iterator.next(); // { done: true, value: undefined } + +map.clear(); // undefined +map.size; // 0 +``` + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-map.png)](https://travis-ci.org/medikoo/es6-map) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/implement.js new file mode 100644 index 00000000000000..ff3ebaccb7ae97 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'Map', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/index.js new file mode 100644 index 00000000000000..3e27caacb75c75 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Map : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/is-implemented.js new file mode 100644 index 00000000000000..cb872fa45938a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/is-implemented.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = function () { + var map, iterator, result; + if (typeof Map !== 'function') return false; + try { + // WebKit doesn't support arguments and crashes + map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); + } catch (e) { + return false; + } + if (map.size !== 3) return false; + if (typeof map.clear !== 'function') return false; + if (typeof map.delete !== 'function') return false; + if (typeof map.entries !== 'function') return false; + if (typeof map.forEach !== 'function') return false; + if (typeof map.get !== 'function') return false; + if (typeof map.has !== 'function') return false; + if (typeof map.keys !== 'function') return false; + if (typeof map.set !== 'function') return false; + if (typeof map.values !== 'function') return false; + + iterator = map.entries(); + result = iterator.next(); + if (result.done !== false) return false; + if (!result.value) return false; + if (result.value[0] !== 'raz') return false; + if (result.value[1] !== 'one') return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/is-map.js b/tools/eslint/node_modules/escope/node_modules/es6-map/is-map.js new file mode 100644 index 00000000000000..f45526a43ba1db --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/is-map.js @@ -0,0 +1,12 @@ +'use strict'; + +var toStringTagSymbol = require('es6-symbol').toStringTag + + , toString = Object.prototype.toString + , id = '[object Map]' + , Global = (typeof Map === 'undefined') ? null : Map; + +module.exports = function (x) { + return (x && ((Global && (x instanceof Global)) || + (toString.call(x) === id) || (x[toStringTagSymbol] === 'Map'))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/is-native-implemented.js new file mode 100644 index 00000000000000..208c6613cff844 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/is-native-implemented.js @@ -0,0 +1,9 @@ +// Exports true if environment provides native `Map` implementation, +// whatever that is. + +'use strict'; + +module.exports = (function () { + if (typeof Map === 'undefined') return false; + return (Object.prototype.toString.call(Map.prototype) === '[object Map]'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/lib/iterator-kinds.js b/tools/eslint/node_modules/escope/node_modules/es6-map/lib/iterator-kinds.js new file mode 100644 index 00000000000000..5367b38d943d1a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/lib/iterator-kinds.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('es5-ext/object/primitive-set')('key', + 'value', 'key+value'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/lib/iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/lib/iterator.js new file mode 100644 index 00000000000000..60f1e8c9e3ca90 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/lib/iterator.js @@ -0,0 +1,38 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('es6-iterator') + , toStringTagSymbol = require('es6-symbol').toStringTag + , kinds = require('./iterator-kinds') + + , defineProperties = Object.defineProperties + , unBind = Iterator.prototype._unBind + , MapIterator; + +MapIterator = module.exports = function (map, kind) { + if (!(this instanceof MapIterator)) return new MapIterator(map, kind); + Iterator.call(this, map.__mapKeysData__, map); + if (!kind || !kinds[kind]) kind = 'key+value'; + defineProperties(this, { + __kind__: d('', kind), + __values__: d('w', map.__mapValuesData__) + }); +}; +if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); + +MapIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(MapIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__values__[i]; + if (this.__kind__ === 'key') return this.__list__[i]; + return [this.__list__[i], this.__values__[i]]; + }), + _unBind: d(function () { + this.__values__ = null; + unBind.call(this); + }), + toString: d(function () { return '[object Map Iterator]'; }) +}); +Object.defineProperty(MapIterator.prototype, toStringTagSymbol, + d('c', 'Map Iterator')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/lib/primitive-iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/lib/primitive-iterator.js new file mode 100644 index 00000000000000..b9eada37c14455 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/lib/primitive-iterator.js @@ -0,0 +1,57 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , assign = require('es5-ext/object/assign') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , toStringTagSymbol = require('es6-symbol').toStringTag + , d = require('d') + , autoBind = require('d/auto-bind') + , Iterator = require('es6-iterator') + , kinds = require('./iterator-kinds') + + , defineProperties = Object.defineProperties, keys = Object.keys + , unBind = Iterator.prototype._unBind + , PrimitiveMapIterator; + +PrimitiveMapIterator = module.exports = function (map, kind) { + if (!(this instanceof PrimitiveMapIterator)) { + return new PrimitiveMapIterator(map, kind); + } + Iterator.call(this, keys(map.__mapKeysData__), map); + if (!kind || !kinds[kind]) kind = 'key+value'; + defineProperties(this, { + __kind__: d('', kind), + __keysData__: d('w', map.__mapKeysData__), + __valuesData__: d('w', map.__mapValuesData__) + }); +}; +if (setPrototypeOf) setPrototypeOf(PrimitiveMapIterator, Iterator); + +PrimitiveMapIterator.prototype = Object.create(Iterator.prototype, assign({ + constructor: d(PrimitiveMapIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__valuesData__[this.__list__[i]]; + if (this.__kind__ === 'key') return this.__keysData__[this.__list__[i]]; + return [this.__keysData__[this.__list__[i]], + this.__valuesData__[this.__list__[i]]]; + }), + _unBind: d(function () { + this.__keysData__ = null; + this.__valuesData__ = null; + unBind.call(this); + }), + toString: d(function () { return '[object Map Iterator]'; }) +}, autoBind({ + _onAdd: d(function (key) { this.__list__.push(key); }), + _onDelete: d(function (key) { + var index = this.__list__.lastIndexOf(key); + if (index < this.__nextIndex__) return; + this.__list__.splice(index, 1); + }), + _onClear: d(function () { + clear.call(this.__list__); + this.__nextIndex__ = 0; + }) +}))); +Object.defineProperty(PrimitiveMapIterator.prototype, toStringTagSymbol, + d('c', 'Map Iterator')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.lint new file mode 100644 index 00000000000000..858b75353b331c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.lint @@ -0,0 +1,12 @@ +@root + +es5 +module + +tabs +indent 2 +maxlen 80 + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.travis.yml new file mode 100644 index 00000000000000..50008b23e6bcb9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+d@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/CHANGES new file mode 100644 index 00000000000000..45233f747eca72 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/CHANGES @@ -0,0 +1,7 @@ +v0.1.1 -- 2014.04.24 +- Add `autoBind` and `lazy` utilities +- Allow to pass other options to be merged onto created descriptor. + Useful when used with other custom utilties + +v0.1.0 -- 2013.06.20 +Initial (derived from es5-ext project) diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/LICENCE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/LICENCE new file mode 100644 index 00000000000000..aaf35282f41f57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/LICENCE @@ -0,0 +1,19 @@ +Copyright (C) 2013 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/README.md new file mode 100644 index 00000000000000..872d493ed86b6b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/README.md @@ -0,0 +1,108 @@ +# D - Property descriptor factory + +_Originally derived from [es5-ext](https://github.com/medikoo/es5-ext) package._ + +Defining properties with descriptors is very verbose: + +```javascript +var Account = function () {}; +Object.defineProperties(Account.prototype, { + deposit: { value: function () { + /* ... */ + }, configurable: true, enumerable: false, writable: true }, + whithdraw: { value: function () { + /* ... */ + }, configurable: true, enumerable: false, writable: true }, + balance: { get: function () { + /* ... */ + }, configurable: true, enumerable: false } +}); +``` + +D cuts that to: + +```javascript +var d = require('d'); + +var Account = function () {}; +Object.defineProperties(Account.prototype, { + deposit: d(function () { + /* ... */ + }), + whithdraw: d(function () { + /* ... */ + }), + balance: d.gs(function () { + /* ... */ + }) +}); +``` + +By default, created descriptor follow characteristics of native ES5 properties, and defines values as: + +```javascript +{ configurable: true, enumerable: false, writable: true } +``` + +You can overwrite it by preceding _value_ argument with instruction: +```javascript +d('c', value); // { configurable: true, enumerable: false, writable: false } +d('ce', value); // { configurable: true, enumerable: true, writable: false } +d('e', value); // { configurable: false, enumerable: true, writable: false } + +// Same way for get/set: +d.gs('e', value); // { configurable: false, enumerable: true } +``` + +### Other utilities + +#### autoBind(obj, props) _(d/auto-bind)_ + +Define methods which will be automatically bound to its instances + +```javascript +var d = require('d'); +var autoBind = require('d/auto-bind'); + +var Foo = function () { this._count = 0; }; +autoBind(Foo.prototype, { + increment: d(function () { ++this._count; }); +}); + +var foo = new Foo(); + +// Increment foo counter on each domEl click +domEl.addEventListener('click', foo.increment, false); +``` + +#### lazy(obj, props) _(d/lazy)_ + +Define lazy properties, which will be resolved on first access + +```javascript +var d = require('d'); +var lazy = require('d/lazy'); + +var Foo = function () {}; +lazy(Foo.prototype, { + items: d(function () { return []; }) +}); + +var foo = new Foo(); +foo.items.push(1, 2); // foo.items array created +``` + +## Installation +### NPM + +In your project path: + + $ npm install d + +### Browser + +You can easily bundle _D_ for browser with [modules-webmake](https://github.com/medikoo/modules-webmake) + +## Tests [![Build Status](https://travis-ci.org/medikoo/d.png)](https://travis-ci.org/medikoo/d) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/auto-bind.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/auto-bind.js new file mode 100644 index 00000000000000..1b00dba3cc3ddf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/auto-bind.js @@ -0,0 +1,31 @@ +'use strict'; + +var copy = require('es5-ext/object/copy') + , map = require('es5-ext/object/map') + , callable = require('es5-ext/object/valid-callable') + , validValue = require('es5-ext/object/valid-value') + + , bind = Function.prototype.bind, defineProperty = Object.defineProperty + , hasOwnProperty = Object.prototype.hasOwnProperty + , define; + +define = function (name, desc, bindTo) { + var value = validValue(desc) && callable(desc.value), dgs; + dgs = copy(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function () { + if (hasOwnProperty.call(this, name)) return value; + desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); + defineProperty(this, name, desc); + return this[name]; + }; + return dgs; +}; + +module.exports = function (props/*, bindTo*/) { + var bindTo = arguments[1]; + return map(props, function (desc, name) { + return define(name, desc, bindTo); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/index.js new file mode 100644 index 00000000000000..076ae465f60c4b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var assign = require('es5-ext/object/assign') + , normalizeOpts = require('es5-ext/object/normalize-options') + , isCallable = require('es5-ext/object/is-callable') + , contains = require('es5-ext/string/#/contains') + + , d; + +d = module.exports = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + w = contains.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!isCallable(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!isCallable(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/lazy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/lazy.js new file mode 100644 index 00000000000000..61e466535f3dab --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/lazy.js @@ -0,0 +1,111 @@ +'use strict'; + +var map = require('es5-ext/object/map') + , isCallable = require('es5-ext/object/is-callable') + , validValue = require('es5-ext/object/valid-value') + , contains = require('es5-ext/string/#/contains') + + , call = Function.prototype.call + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getPrototypeOf = Object.getPrototypeOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , cacheDesc = { configurable: false, enumerable: false, writable: false, + value: null } + , define; + +define = function (name, options) { + var value, dgs, cacheName, desc, writable = false, resolvable + , flat; + options = Object(validValue(options)); + cacheName = options.cacheName; + flat = options.flat; + if (cacheName == null) cacheName = name; + delete options.cacheName; + value = options.value; + resolvable = isCallable(value); + delete options.value; + dgs = { configurable: Boolean(options.configurable), + enumerable: Boolean(options.enumerable) }; + if (name !== cacheName) { + dgs.get = function () { + if (hasOwnProperty.call(this, cacheName)) return this[cacheName]; + cacheDesc.value = resolvable ? call.call(value, this, options) : value; + cacheDesc.writable = writable; + defineProperty(this, cacheName, cacheDesc); + cacheDesc.value = null; + if (desc) defineProperty(this, name, desc); + return this[cacheName]; + }; + } else if (!flat) { + dgs.get = function self() { + var ownDesc; + if (hasOwnProperty.call(this, name)) { + ownDesc = getOwnPropertyDescriptor(this, name); + // It happens in Safari, that getter is still called after property + // was defined with a value, following workarounds that + if (ownDesc.hasOwnProperty('value')) return ownDesc.value; + if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) { + return ownDesc.get.call(this); + } + return value; + } + desc.value = resolvable ? call.call(value, this, options) : value; + defineProperty(this, name, desc); + desc.value = null; + return this[name]; + }; + } else { + dgs.get = function self() { + var base = this, ownDesc; + if (hasOwnProperty.call(this, name)) { + // It happens in Safari, that getter is still called after property + // was defined with a value, following workarounds that + ownDesc = getOwnPropertyDescriptor(this, name); + if (ownDesc.hasOwnProperty('value')) return ownDesc.value; + if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) { + return ownDesc.get.call(this); + } + } + while (!hasOwnProperty.call(base, name)) base = getPrototypeOf(base); + desc.value = resolvable ? call.call(value, base, options) : value; + defineProperty(base, name, desc); + desc.value = null; + return base[name]; + }; + } + dgs.set = function (value) { + dgs.get.call(this); + this[cacheName] = value; + }; + if (options.desc) { + desc = { + configurable: contains.call(options.desc, 'c'), + enumerable: contains.call(options.desc, 'e') + }; + if (cacheName === name) { + desc.writable = contains.call(options.desc, 'w'); + desc.value = null; + } else { + writable = contains.call(options.desc, 'w'); + desc.get = dgs.get; + desc.set = dgs.set; + } + delete options.desc; + } else if (cacheName === name) { + desc = { + configurable: Boolean(options.configurable), + enumerable: Boolean(options.enumerable), + writable: Boolean(options.writable), + value: null + }; + } + delete options.configurable; + delete options.enumerable; + delete options.writable; + return dgs; +}; + +module.exports = function (props) { + return map(props, function (desc, name) { return define(name, desc); }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/package.json new file mode 100644 index 00000000000000..03d81db13be8d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/package.json @@ -0,0 +1,59 @@ +{ + "name": "d", + "version": "0.1.1", + "description": "Property descriptor factory", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "scripts": { + "test": "node node_modules/tad/bin/tad" + }, + "repository": { + "type": "git", + "url": "git://github.com/medikoo/d.git" + }, + "keywords": [ + "descriptor", + "es", + "ecmascript", + "ecma", + "property", + "descriptors", + "meta", + "properties" + ], + "dependencies": { + "es5-ext": "~0.10.2" + }, + "devDependencies": { + "tad": "~0.1.21" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/medikoo/d/issues" + }, + "homepage": "https://github.com/medikoo/d", + "_id": "d@0.1.1", + "dist": { + "shasum": "da184c535d18d8ee7ba2aa229b914009fae11309", + "tarball": "http://registry.npmjs.org/d/-/d-0.1.1.tgz" + }, + "_from": "d@>=0.1.1 <0.2.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "directories": {}, + "_shasum": "da184c535d18d8ee7ba2aa229b914009fae11309", + "_resolved": "https://registry.npmjs.org/d/-/d-0.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/auto-bind.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/auto-bind.js new file mode 100644 index 00000000000000..89edfb88bbec53 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/auto-bind.js @@ -0,0 +1,12 @@ +'use strict'; + +var d = require('../'); + +module.exports = function (t, a) { + var o = Object.defineProperties({}, t({ + bar: d(function () { return this === o; }), + bar2: d(function () { return this; }) + })); + + a.deep([(o.bar)(), (o.bar2)()], [true, o]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/index.js new file mode 100644 index 00000000000000..3db0af10acd3ca --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/index.js @@ -0,0 +1,182 @@ +'use strict'; + +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +module.exports = function (t, a) { + var o, c, cg, cs, ce, ceg, ces, cew, cw, e, eg, es, ew, v, vg, vs, w, df, dfg + , dfs; + + o = Object.create(Object.prototype, { + c: t('c', c = {}), + cgs: t.gs('c', cg = function () {}, cs = function () {}), + ce: t('ce', ce = {}), + cegs: t.gs('ce', ceg = function () {}, ces = function () {}), + cew: t('cew', cew = {}), + cw: t('cw', cw = {}), + e: t('e', e = {}), + egs: t.gs('e', eg = function () {}, es = function () {}), + ew: t('ew', ew = {}), + v: t('', v = {}), + vgs: t.gs('', vg = function () {}, vs = function () {}), + w: t('w', w = {}), + + df: t(df = {}), + dfgs: t.gs(dfg = function () {}, dfs = function () {}) + }); + + return { + c: function (a) { + var d = getOwnPropertyDescriptor(o, 'c'); + a(d.value, c, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'cgs'); + a(d.value, undefined, "GS Value"); + a(d.get, cg, "GS Get"); + a(d.set, cs, "GS Set"); + a(d.configurable, true, "GS Configurable"); + a(d.enumerable, false, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + ce: function (a) { + var d = getOwnPropertyDescriptor(o, 'ce'); + a(d.value, ce, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'cegs'); + a(d.value, undefined, "GS Value"); + a(d.get, ceg, "GS Get"); + a(d.set, ces, "GS Set"); + a(d.configurable, true, "GS Configurable"); + a(d.enumerable, true, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + cew: function (a) { + var d = getOwnPropertyDescriptor(o, 'cew'); + a(d.value, cew, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, true, "Writable"); + }, + cw: function (a) { + var d = getOwnPropertyDescriptor(o, 'cw'); + a(d.value, cw, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, true, "Writable"); + }, + e: function (a) { + var d = getOwnPropertyDescriptor(o, 'e'); + a(d.value, e, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'egs'); + a(d.value, undefined, "GS Value"); + a(d.get, eg, "GS Get"); + a(d.set, es, "GS Set"); + a(d.configurable, false, "GS Configurable"); + a(d.enumerable, true, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + ew: function (a) { + var d = getOwnPropertyDescriptor(o, 'ew'); + a(d.value, ew, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, true, "Writable"); + }, + v: function (a) { + var d = getOwnPropertyDescriptor(o, 'v'); + a(d.value, v, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'vgs'); + a(d.value, undefined, "GS Value"); + a(d.get, vg, "GS Get"); + a(d.set, vs, "GS Set"); + a(d.configurable, false, "GS Configurable"); + a(d.enumerable, false, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + w: function (a) { + var d = getOwnPropertyDescriptor(o, 'w'); + a(d.value, w, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, true, "Writable"); + }, + d: function (a) { + var d = getOwnPropertyDescriptor(o, 'df'); + a(d.value, df, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, true, "Writable"); + + d = getOwnPropertyDescriptor(o, 'dfgs'); + a(d.value, undefined, "GS Value"); + a(d.get, dfg, "GS Get"); + a(d.set, dfs, "GS Set"); + a(d.configurable, true, "GS Configurable"); + a(d.enumerable, false, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + Options: { + v: function (a) { + var x = {}, d = t(x, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, writable: true, + value: x, foo: true }, "No descriptor"); + d = t('c', 'foo', { marko: 'elo' }); + a.deep(d, { configurable: true, enumerable: false, writable: false, + value: 'foo', marko: 'elo' }, "Descriptor"); + }, + gs: function (a) { + var gFn = function () {}, sFn = function () {}, d; + d = t.gs(gFn, sFn, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, get: gFn, set: sFn, + foo: true }, "No descriptor"); + d = t.gs(null, sFn, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, get: undefined, + set: sFn, foo: true }, "No descriptor: Just set"); + d = t.gs(gFn, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, get: gFn, + set: undefined, foo: true }, "No descriptor: Just get"); + + d = t.gs('e', gFn, sFn, { bar: true }); + a.deep(d, { configurable: false, enumerable: true, get: gFn, set: sFn, + bar: true }, "Descriptor"); + d = t.gs('e', null, sFn, { bar: true }); + a.deep(d, { configurable: false, enumerable: true, get: undefined, + set: sFn, bar: true }, "Descriptor: Just set"); + d = t.gs('e', gFn, { bar: true }); + a.deep(d, { configurable: false, enumerable: true, get: gFn, + set: undefined, bar: true }, "Descriptor: Just get"); + } + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/lazy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/lazy.js new file mode 100644 index 00000000000000..8266deb240fda3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/d/test/lazy.js @@ -0,0 +1,77 @@ +'use strict'; + +var d = require('../') + + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +module.exports = function (t, a) { + var Foo = function () {}, i = 1, o, o2, desc; + Object.defineProperties(Foo.prototype, t({ + bar: d(function () { return ++i; }), + bar2: d(function () { return this.bar + 23; }), + bar3: d(function () { return this.bar2 + 34; }, { desc: 'ew' }), + bar4: d(function () { return this.bar3 + 12; }, { cacheName: '_bar4_' }), + bar5: d(function () { return this.bar4 + 3; }, + { cacheName: '_bar5_', desc: 'e' }) + })); + + desc = getOwnPropertyDescriptor(Foo.prototype, 'bar'); + a(desc.configurable, true, "Configurable: default"); + a(desc.enumerable, false, "Enumerable: default"); + + o = new Foo(); + a.deep([o.bar, o.bar2, o.bar3, o.bar4, o.bar5], [2, 25, 59, 71, 74], + "Values"); + + a.deep(getOwnPropertyDescriptor(o, 'bar3'), { configurable: false, + enumerable: true, writable: true, value: 59 }, "Desc"); + a(o.hasOwnProperty('bar4'), false, "Cache not exposed"); + desc = getOwnPropertyDescriptor(o, 'bar5'); + a.deep(desc, { configurable: false, + enumerable: true, get: desc.get, set: desc.set }, "Cache & Desc: desc"); + + o2 = Object.create(o); + o2.bar = 30; + o2.bar3 = 100; + + a.deep([o2.bar, o2.bar2, o2.bar3, o2.bar4, o2.bar5], [30, 25, 100, 112, 115], + "Extension Values"); + + Foo = function () {}; + Object.defineProperties(Foo.prototype, t({ + test: d('w', function () { return 'raz'; }), + test2: d('', function () { return 'raz'; }, { desc: 'w' }), + test3: d('', function () { return 'raz'; }, + { cacheName: '__test3__', desc: 'w' }), + test4: d('w', 'bar') + })); + + o = new Foo(); + o.test = 'marko'; + a.deep(getOwnPropertyDescriptor(o, 'test'), + { configurable: false, enumerable: false, writable: true, value: 'marko' }, + "Set before get"); + o.test2 = 'marko2'; + a.deep(getOwnPropertyDescriptor(o, 'test2'), + { configurable: false, enumerable: false, writable: true, value: 'marko2' }, + "Set before get: Custom desc"); + o.test3 = 'marko3'; + a.deep(getOwnPropertyDescriptor(o, '__test3__'), + { configurable: false, enumerable: false, writable: true, value: 'marko3' }, + "Set before get: Custom cache name"); + a(o.test4, 'bar', "Resolve by value"); + + a.h1("Flat"); + Object.defineProperties(Foo.prototype, t({ + flat: d(function () { return 'foo'; }, { flat: true }), + flat2: d(function () { return 'bar'; }, { flat: true }) + })); + + a.h2("Instance"); + a(o.flat, 'foo', "Value"); + a(o.hasOwnProperty('flat'), false, "Instance"); + a(Foo.prototype.flat, 'foo', "Prototype"); + + a.h2("Direct"); + a(Foo.prototype.flat2, 'bar'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.lint new file mode 100644 index 00000000000000..d1da610376a524 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.lint @@ -0,0 +1,38 @@ +@root + +module + +indent 2 +maxlen 100 +tabs + +ass +continue +forin +nomen +plusplus +vars + +./global.js +./function/_define-length.js +./function/#/copy.js +./object/unserialize.js +./test/function/valid-function.js +evil + +./math/_pack-ieee754.js +./math/_unpack-ieee754.js +./math/clz32/shim.js +./math/imul/shim.js +./number/to-uint32.js +./string/#/at.js +bitwise + +./math/fround/shim.js +predef+ Float32Array + +./object/first-key.js +forin + +./test/reg-exp/#/index.js +predef+ __dirname diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.lintignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.lintignore new file mode 100644 index 00000000000000..ed703ed7662c89 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.lintignore @@ -0,0 +1,8 @@ +/string/#/normalize/_data.js +/test/boolean/is-boolean.js +/test/date/is-date.js +/test/number/is-number.js +/test/object/is-copy.js +/test/object/is-object.js +/test/reg-exp/is-reg-exp.js +/test/string/is-string.js diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.npmignore new file mode 100644 index 00000000000000..eb09b500d63ec8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/.lintcache +/npm-debug.log diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.travis.yml new file mode 100644 index 00000000000000..a183dbcec61795 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/.travis.yml @@ -0,0 +1,15 @@ +sudo: false # http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +language: node_js +node_js: + - 0.10 + - 0.12 + - iojs + +before_install: + - mkdir node_modules; ln -s ../ node_modules/es5-ext + +notifications: + email: + - medikoo+es5-ext@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/CHANGES new file mode 100644 index 00000000000000..5d0ace5bfe2f8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/CHANGES @@ -0,0 +1,611 @@ +v0.10.7 -- 2015.04.22 +* New utlitities. They're convention differs from v0.10, as they were supposed to land in v1. + Still they're non breaking and start the conventions to be used in v1 + * Object.validateArrayLike + * Object.validateArrayLikeObject + * Object.validateStringifiable + * Object.validateStringifiableValue + * Universal utilities for array-like/iterable objects + * Iterable.is + * Iterable.validate + * Iterable.validateObject + * Iterable.forEach +* Fix camelToHyphen resolution, it must be absolutely reversable by hyphenToCamel +* Fix calculations of large numbers in Math.tanh +* Fix algorithm of Math.sinh +* Fix indexes to not use real symbols +* Fix length of String.fromCodePoint +* Fix tests of Array#copyWithin +* Update Travis CI configuration + +v0.10.6 -- 2015.02.02 +* Fix handling of infinite values in Math.trunc +* Fix handling of getters in Object.normalizeOptions + +v0.10.5 -- 2015.01.20 +* Add Function#toStringTokens +* Add Object.serialize and Object.unserialize +* Add String.randomUniq +* Fix Strin#camelToHyphen issue with tokens that end with digit +* Optimise Number.isInteger logic +* Improve documentation +* Configure lint scripts +* Fix spelling of LICENSE + +v0.10.4 -- 2014.04.30 +* Assure maximum spec compliance of Array.of and Array.from (thanks @mathiasbynens) +* Improve documentations + +v0.10.3 -- 2014.04.29 +Provide accurate iterators handling: +* Array.from improvements: + * Assure right unicode symbols resolution when processing strings in Array.from + * Rely on ES6 symbol shim and use native @@iterator Symbol if provided by environment +* Add methods: + * Array.prototype.entries + * Array.prototype.keys + * Array.prototype.values + * Array.prototype[@@iterator] + * String.prototype[@@iterator] + +Improve documentation + +v0.10.2 -- 2014.04.24 +- Simplify and deprecate `isCallable`. It seems in ES5 based engines there are + no callable objects which are `typeof obj !== 'function'` +- Update Array.from map callback signature (up to latest resolution of TC39) +- Improve documentation + +v0.10.1 -- 2014.04.14 +Bump version for npm +(Workaround for accidental premature publish & unpublish of v0.10.0 a while ago) + +v0.10.0 -- 2014.04.13 +Major update: +- All methods and function specified for ECMAScript 6 are now introduced as + shims accompanied with functions through which (optionally) they can be + implementend on native objects +- Filename convention was changed to shorter and strictly lower case names. e.g. + `lib/String/prototype/starts-with` became `string/#/starts-with` +- Generated functions are guaranteed to have expected length +- Objects with null prototype (created via `Object.create(null)`) are widely + supported (older version have crashed due to implied `obj.hasOwnProperty` and + related invocations) +- Support array subclasses +- When handling lists do not limit its length to Uint32 range +- Use newly introduced `Object.eq` for strict equality in place of `Object.is` +- Iteration of Object have been improved so properties that were hidden or + removed after iteration started are not iterated. + +Additions: +- `Array.isPlainArray` +- `Array.validArray` +- `Array.prototype.concat` (as updated with ES6) +- `Array.prototype.copyWithin` (as introduced with ES6) +- `Array.prototype.fill` (as introduced with ES6) +- `Array.prototype.filter` (as updated with ES6) +- `Array.prototype.findIndex` (as introduced with ES6) +- `Array.prototype.map` (as updated with ES6) +- `Array.prototype.separate` +- `Array.prototype.slice` (as updated with ES6) +- `Array.prototype.splice` (as updated with ES6) +- `Function.prototype.copy` +- `Math.acosh` (as introduced with ES6) +- `Math.atanh` (as introduced with ES6) +- `Math.cbrt` (as introduced with ES6) +- `Math.clz32` (as introduced with ES6) +- `Math.cosh` (as introduced with ES6) +- `Math.expm1` (as introduced with ES6) +- `Math.fround` (as introduced with ES6) +- `Math.hypot` (as introduced with ES6) +- `Math.imul` (as introduced with ES6) +- `Math.log2` (as introduced with ES6) +- `Math.log10` (as introduced with ES6) +- `Math.log1p` (as introduced with ES6) +- `Math.sinh` (as introduced with ES6) +- `Math.tanh` (as introduced with ES6) +- `Math.trunc` (as introduced with ES6) +- `Number.EPSILON` (as introduced with ES6) +- `Number.MIN_SAFE_INTEGER` (as introduced with ES6) +- `Number.MAX_SAFE_INTEGER` (as introduced with ES6) +- `Number.isFinite` (as introduced with ES6) +- `Number.isInteger` (as introduced with ES6) +- `Number.isSafeInteger` (as introduced with ES6) +- `Object.create` (with fix for V8 issue which disallows prototype turn of + objects derived from null +- `Object.eq` - Less restrictive version of `Object.is` based on SameValueZero + algorithm +- `Object.firstKey` +- `Object.keys` (as updated with ES6) +- `Object.mixinPrototypes` +- `Object.primitiveSet` +- `Object.setPrototypeOf` (as introduced with ES6) +- `Object.validObject` +- `RegExp.escape` +- `RegExp.prototype.match` (as introduced with ES6) +- `RegExp.prototype.replace` (as introduced with ES6) +- `RegExp.prototype.search` (as introduced with ES6) +- `RegExp.prototype.split` (as introduced with ES6) +- `RegExp.prototype.sticky` (as introduced with ES6) +- `RegExp.prototype.unicode` (as introduced with ES6) +- `String.fromCodePoint` (as introduced with ES6) +- `String.raw` (as introduced with ES6) +- `String.prototype.at` +- `String.prototype.codePointAt` (as introduced with ES6) +- `String.prototype.normalize` (as introduced with ES6) +- `String.prototype.plainReplaceAll` + +Removals: +- `reserved` set +- `Array.prototype.commonLeft` +- `Function.insert` +- `Function.remove` +- `Function.prototype.silent` +- `Function.prototype.wrap` +- `Object.descriptor` Move to external `d` project. + See: https://github.com/medikoo/d +- `Object.diff` +- `Object.extendDeep` +- `Object.reduce` +- `Object.values` +- `String.prototype.trimCommonLeft` + +Renames: +- `Function.i` into `Function.identity` +- `Function.k` into `Function.constant` +- `Number.toInt` into `Number.toInteger` +- `Number.toUint` into `Number.toPosInteger` +- `Object.extend` into `Object.assign` (as introduced in ES 6) +- `Object.extendProperties` into `Object.mixin`, with improved internal + handling, so it matches temporarily specified `Object.mixin` for ECMAScript 6 +- `Object.isList` into `Object.isArrayLike` +- `Object.mapToArray` into `Object.toArray` (with fixed function length) +- `Object.toPlainObject` into `Object.normalizeOptions` (as this is the real + use case where we use this function) +- `Function.prototype.chain` into `Function.prototype.compose` +- `Function.prototype.match` into `Function.prototype.spread` +- `String.prototype.format` into `String.formatMethod` + +Improvements & Fixes: +- Remove workaround for primitive values handling in object iterators +- `Array.from`: Update so it follows ES 6 spec +- `Array.prototype.compact`: filters just null and undefined values + (not all falsies) +- `Array.prototype.eIndexOf` and `Array.prototype.eLastIndexOf`: fix position + handling, improve internals +- `Array.prototype.find`: return undefined not null, in case of not found + (follow ES 6) +- `Array.prototype.remove` fix function length +- `Error.custom`: simplify, Custom class case is addressed by outer + `error-create` project -> https://github.com/medikoo/error-create +- `Error.isError` true only for Error instances (remove detection of host + Exception objects) +- `Number.prototype.pad`: Normalize negative pad +- `Object.clear`: Handle errors same way as in `Object.assign` +- `Object.compact`: filters just null and undefined values (not all falsies) +- `Object.compare`: Take into account NaN values +- `Object.copy`: Split into `Object.copy` and `Object.copyDeep` +- `Object.isCopy`: Separate into `Object.isCopy` and `Object.isCopyDeep`, where + `isCopyDeep` handles nested plain objects and plain arrays only +- `String.prototype.endsWith`: Adjust up to ES6 specification +- `String.prototype.repeat`: Adjust up to ES6 specification and improve algorithm +- `String.prototype.simpleReplace`: Rename into `String.prototype.plainReplace` +- `String.prototype.startsWith`: Adjust up to ES6 specification +- Update lint rules, and adjust code to that +- Update Travis CI configuration +- Remove Makefile (it's cross-env utility) + +v0.9.2 -- 2013.03.11 +Added: +* Array.prototype.isCopy +* Array.prototype.isUniq +* Error.CustomError +* Function.validFunction +* Object.extendDeep +* Object.descriptor.binder +* Object.safeTraverse +* RegExp.validRegExp +* String.prototype.capitalize +* String.prototype.simpleReplace + +Fixed: +* Fix Array.prototype.diff for sparse arrays +* Accept primitive objects as input values in Object iteration methods and + Object.clear, Object.count, Object.diff, Object.extend, + Object.getPropertyNames, Object.values +* Pass expected arguments to callbacks of Object.filter, Object.mapKeys, + Object.mapToArray, Object.map +* Improve callable callback support in Object.mapToArray + +v0.9.1 -- 2012.09.17 +* Object.reduce - reduce for hash-like collections +* Accapt any callable object as callback in Object.filter, mapKeys and map +* Convention cleanup + +v0.9.0 -- 2012.09.13 +We're getting to real solid API + +Removed: +* Function#memoize - it's grown up to be external package, to be soon published + as 'memoizee' +* String.guid - it doesn't fit es5-ext (extensions) concept, will be provided as + external package +# Function.arguments - obsolete +# Function.context - obsolete +# Function#flip - not readable when used, so it was never used +# Object.clone - obsolete and confusing + +Added: +* String#camelToHyphen - String format convertion + +Renamed: +* String#dashToCamelCase -> String#hyphenToCamel + +Fixes: +* Object.isObject - Quote names in literals that match reserved keywords + (older implementations crashed on that) +* String#repeat - Do not accept negative values (coerce them to 1) + +Improvements: +* Array#remove - Accepts many arguments, we can now remove many values at once +* Object iterators (forEach, map, some) - Compare function invoked with scope + object bound to this +* Function#curry - Algorithm cleanup +* Object.isCopy - Support for all types, not just plain objects +* Object.isPlainObject - Support for cross-frame objects +* Do not memoize any of the functions, it shouldn't be decided internally +* Remove Object.freeze calls in reserved, it's not up to convention +* Improved documentation +* Better linting (hard-core approach using both JSLint mod and JSHint) +* Optional arguments are now documented in funtions signature + +v0.8.2 -- 2012.06.22 +Fix errors in Array's intersection and exclusion methods, related to improper +usage of contains method + +v0.8.1 -- 2012.06.13 +Reorganized internal logic of Function.prototype.memoize. So it's more safe now +and clears cache properly. Additionally preventCache option was provided. + +v0.8.0 -- 2012.05.28 +Again, major overhaul. Probably last experimental stuff was trashed, all API +looks more like standard extensions now. + +Changes: +* Turn all Object.prototype extensions into functions and move them to Object +namespace. We learned that extending Object.prototype is bad idea in any case. +* Rename Function.prototype.curry into Function.prototype.partial. This function + is really doing partial application while currying is slightly different + concept. +* Convert Function.prototype.ncurry to new implementation of + Function.prototype.curry, it now serves real curry concept additionaly it + covers use cases for aritize and hold, which were removed. +* Rename Array's peek to last, and provide support for sparse arrays in it +* Rename Date's monthDaysCount into daysInMonth +* Simplify object iterators, now order of iteration can be configured with just + compareFn argument (no extra byKeys option) +* Rename Object.isDuplicate to Object.isCopy +* Rename Object.isEqual to Object.is which is compatible with future 'is' + keyword +* Function.memoize is now Function.prototype.memoize. Additionally clear cache + functionality is added, and access to original arguments object. +* Rename validation functions: assertNotNull to validValue, assertCallable to + validCallable. validValue was moved to Object namespace. On success they now + return validated value instead of true, it supports better composition. + Additionally created Date.validDate and Error.validError +* All documentation is now held in README.md not in code files. +* Move guid to String namespace. All guids now start with numbers. +* Array.generate: fill argument is now optional +* Object.toArray is now Array.from (as new ES6 specification draft suggests) +* All methods that rely on indexOf or lastIndexOf, now rely on egal (Object.is) + versions of them (eIndexOf, eLastIndexOf) +* Turn all get* functions that returned methods into actuall methods (get* + functionality can still be achieved with help of Function.prototype.partial). + So: Date.getFormat is now Date.prototype.format, + Number.getPad is now Number.prototype.pad, + String.getFormat is now String.prototype.format, + String.getIndent is now String.prototype.indent, + String.getPad is now String.prototype.pad +* Refactored Object.descriptor, it is now just two functions, main one and + main.gs, main is for describing values, and gs for describing getters and + setters. Configuration is passed with first argument as string e.g. 'ce' for + configurable and enumerable. If no configuration string is provided then by + default it returns configurable and writable but not enumerable for value or + configurable but not enumerable for getter/setter +* Function.prototype.silent now returns prepared function (it was + expected to be fixed for 0.7) +* Reserved keywords map (reserved) is now array not hash. +* Object.merge is now Object.extend (while former Object.extend was completely + removed) - 'extend' implies that we change object, not creating new one (as + 'merge' may imply). Similarily Object.mergeProperties was renamed to + Object.extendProperties +* Position argument support in Array.prototype.contains and + String.prototype.contains (so it follows ES6 specification draft) +* endPosition argument support in String.prototype.endsWith and fromPosition + argument support in String.prototype.startsWith (so it follows ES6 + specification draft) +* Better and cleaner String.prototype.indent implementation. No default value + for indent string argument, optional nest value (defaults to 1), remove + nostart argument +* Correct length values for most methods (so they reflect length of similar + methods in standard) +* Length argument is now optional in number and string pad methods. +* Improve arguments validation in general, so it adheres to standard conventions +* Fixed format of package.json + +Removed methods and functions: +* Object.prototype.slice - Object is not ordered collection, so slice doesn't + make sense. +* Function's rcurry, rncurry, s - too cumbersome for JS, not many use cases for + that +* Function.prototype.aritize and Function.prototype.hold - same functionality + can be achieved with new Function.prototype.curry +* Function.prototype.log - provided more generic Function.prototype.wrap for + same use case +* getNextIdGenerator - no use case for that (String.guid should be used if + needed) +* Object.toObject - Can be now acheived with Object(validValue(x)) +* Array.prototype.someValue - no real use case (personally used once and + case was already controversial) +* Date.prototype.duration - moved to external package +* Number.getAutoincrement - No real use case +* Object.prototype.extend, Object.prototype.override, + Object.prototype.plainCreate, Object.prototype.plainExtend - It was probably + too complex, same should be achieved just with Object.create, + Object.descriptor and by saving references to super methods in local scope. +* Object.getCompareBy - Functions should be created individually for each use + case +* Object.get, Object.getSet, Object.set, Object.unset - Not many use cases and + same can be easily achieved with simple inline function +* String.getPrefixWith - Not real use case for something that can be easily + achieved with '+' operator +* Object.isPrimitive - It's just negation of Object.isObject +* Number.prototype.isLess, Number.prototype.isLessOrEqual - they shouldn't be in + Number namespace and should rather be addressed with simple inline functions. +* Number.prototype.subtract - Should rather be addressed with simple inline + function + +New methods and functions: +* Array.prototype.lastIndex - Returns last declared index in array +* String.prototype.last - last for strings +* Function.prototype.wrap - Wrap function with other, it allows to specify + before and after behavior transform return value or prevent original function + from being called. +* Math.sign - Returns sign of a number (already in ES6 specification draft) +* Number.toInt - Converts value to integer (already in ES6 specification draft) +* Number.isNaN - Returns true if value is NaN (already in ES6 specification + draft) +* Number.toUint - Converts value to unsigned integer +* Number.toUint32 - Converts value to 32bit unsigned integer +* Array.prototype.eIndexOf, eLastIndexOf - Egal version (that uses Object.is) of + standard methods (all methods that were using native indexOf or lastIndexOf + now uses eIndexOf and elastIndexOf respectively) +* Array.of - as it's specified for ES6 + +Fixes: +* Fixed binarySearch so it always returns valid list index +* Object.isList - it failed on lists that are callable (e.g. NodeList in Nitro + engine) +* Object.map now supports third argument for callback + +v0.7.1 -- 2012.01.05 +New methods: +* Array.prototype.firstIndex - returns first valid index of array (for + sparse arrays it may not be '0' + +Improvements: +* Array.prototype.first - now returns value for index returned by firstIndex +* Object.prototype.mapToArray - can be called without callback, then array of + key-value pairs is returned + +Fixes +* Array.prototype.forEachRight, object's length read through UInt32 conversion + +v0.7.0 -- 2011.12.27 +Major update. +Stepped back from experimental ideas and introduced more standard approach +taking example from how ES5 methods and functions are designed. One exceptions +is that, we don’t refrain from declaring methods for Object.prototype - it’s up +to developer whether how he decides to use it in his context (as function or as +method). + +In general: +* Removed any method 'functionalization' and functionalize method itself. + es5-ext declares plain methods, which can be configured to work as functions + with call.bind(method) - see documentation. +* Removed separation of Object methods for ES5 (with descriptors) and + ES3 (plain) - we're following ES5 idea on that, some methods are intended just + for enumerable properties and some are for all properties, all are declared + for Object.prototype +* Removed separation of Array generic (collected in List folder) and not generic + methods (collected in Array folder). Now all methods are generic and are in + Array/prototype folder. This separation also meant, that methods in Array are + usually destructive. We don’t do that separation now, there’s generally no use + case for destructive iterators, we should be fine with one version of each + method, (same as ES5 is fine with e.g. one, non destructive 'filter' method) +* Folder structure resembles tree of native ES5 Objects +* All methods are written with ES5 conventions in mind, it means that most + methods are generic and can be run on any object. In more detail: + ** Array.prototype and Object.prototype methods can be run on any object (any + not null or undefined value), + ** Date.prototype methods should be called only on Date instances. + ** Function.prototype methods can be called on any callable objects (not + necessarily functions) + ** Number.prototype & String.prototype methods can be called on any value, in + case of Number it it’ll be degraded to number, in case of string it’ll be + degraded to string. +* Travis CI support (only for Node v0.6 branch, as v0.4 has buggy V8 version) + +Improvements for existing functions and methods: +* Function.memoize (was Function.cache) is now fully generic, can operate on any + type of arguments and it’s NaN safe (all NaN objects are considered equal) +* Method properties passed to Object.prototype.extend or + Object.prototype.override can aside of _super optionally take prototype object + via _proto argument +* Object iterators: forEach, mapToArray and every can now iterate in specified + order +* pluck, invoke and other functions that return reusable functions or methods + have now their results memoized. + +New methods: +* Global: assertNotNull, getNextIdGenerator, guid, isEqual, isPrimitive, + toObject +* Array: generate +* Array.prototype: binarySearch, clear, contains, diff, exclusion, find, first, + forEachRight, group, indexesOf, intersection, remove, someRight, someValue +* Boolean: isBoolean +* Date: isDate +* Function: arguments, context, insert, isArguments, remove +* Function.prototype: not, silent +* Number: getAutoincrement, isNumber +* Number.prototype: isLessOrEqual, isLess, subtract +* Object: assertCallable, descriptor (functions for clean descriptors), + getCompareBy, isCallable, isObject +* Object.prototype: clone (real clone), compact, count, diff, empty, + getPropertyNames, get, keyOf, mapKeys, override, plainCreate, plainExtend, + slice, some, unset +* RegExp: isRegExp +* String: getPrefixWith, isString +* String.prototype: caseInsensitiveCompare, contains, isNumeric + +Renamed methods: +* Date.clone -> Date.prototype.copy +* Date.format -> Date.getFormat +* Date/day/floor -> Date.prototype.floorDay +* Date/month/floor -> Date.prototype.floorMonth +* Date/month/year -> Date.prototype.floorYear +* Function.cache -> Function.memoize +* Function.getApplyArg -> Function.prototype.match +* Function.sequence -> Function.prototype.chain +* List.findSameStartLength -> Array.prototype.commonLeft +* Number.pad -> Number.getPad +* Object/plain/clone -> Object.prototype.copy +* Object/plain/elevate -> Object.prototype.flatten +* Object/plain/same -> Object.prototype.isDuplicate +* Object/plain/setValue -> Object.getSet +* String.format -> String.getFormat +* String.indent -> String.getIndent +* String.pad -> String.getPad +* String.trimLeftStr -> String.prototype.trimCommonLeft +* Object.merge -> Object.prototype.mergeProperties +* Object/plain/pluck -> Object.prototype.get +* Array.clone is now Array.prototype.copy and can be used also on any array-like + objects +* List.isList -> Object.isList +* List.toArray -> Object.prototype.toArray +* String/convert/dashToCamelCase -> String.prototype.dashToCamelCase + +Removed methods: +* Array.compact - removed destructive version (that operated on same array), we + have now non destructive version as Array.prototype.compact. +* Function.applyBind -> use apply.bind directly +* Function.bindBind -> use bind.bind directly +* Function.callBind -> use call.bind directly +* Fuction.clone -> no valid use case +* Function.dscope -> controversial approach, shouldn’t be considered seriously +* Function.functionalize -> It was experimental but standards are standards +* List/sort/length -> It can be easy obtained by Object.getCompareBy(‘length’) +* List.concat -> Concat’s for array-like’s makes no sense, just convert to array + first +* List.every -> Use Array.prototype.every directly +* List.filter -> Use Array.prototype.filter directly +* List.forEach -> User Array.prototype.forEach directly +* List.isListObject -> No valid use case, do: isList(list) && (typeof list === + 'object’) +* List.map -> Use Array.prototype.map directly +* List.reduce -> Use Array.prototype.reduce directly +* List.shiftSame -> Use Array.prototype.commonLeft and do slice +* List.slice -> Use Array.prototype.slice directly +* List.some -> Use Array.prototype.some directly +* Object.bindMethods -> it was version that considered descriptors, we have now + Object.prototype.bindMethods which operates only on enumerable properties +* Object.every -> version that considered all properties, we have now + Object.prototype.every which iterates only enumerables +* Object.invoke -> no use case +* Object.mergeDeep -> no use case +* Object.pluck -> no use case +* Object.same -> it considered descriptors, now there’s only Object.isDuplicate + which compares only enumerable properties +* Object.sameType -> no use case +* Object.toDescriptor and Object.toDescriptors -> replaced by much nicer + Object.descriptor functions +* Object/plain/link -> no use case (it was used internally only by + Object/plain/merge) +* Object/plain/setTrue -> now easily configurable by more universal + Object.getSet(true) +* String.trimRightStr -> Eventually String.prototype.trimCommonRight will be + added + +v0.6.3 -- 2011.12.12 +* Cleared npm warning for misnamed property in package.json + +v0.6.2 -- 2011.08.12 +* Calling String.indent without scope (global scope then) now treated as calling + it with null scope, it allows more direct invocations when using default nest + string: indent().call(str, nest) + +v0.6.1 -- 2011.08.08 +* Added TAD test suite to devDependencies, configured test commands. + Tests can be run with 'make test' or 'npm test' + +v0.6.0 -- 2011.08.07 +New methods: +* Array: clone, compact (in place) +* Date: format, duration, clone, monthDaysCount, day.floor, month.floor, + year.floor +* Function: getApplyArg, , ncurry, rncurry, hold, cache, log +* List: findSameStartLength, shiftSame, peek, isListObject +* Number: pad +* Object: sameType, toString, mapToArray, mergeDeep, toDescriptor, + toDescriptors, invoke +* String: startsWith, endsWith, indent, trimLeftStr, trimRightStr, pad, format + +Fixed: +* Object.extend does now prototypal extend as exptected +* Object.merge now tries to overwrite only configurable properties +* Function.flip + +Improved: +* Faster List.toArray +* Better global retrieval +* Functionalized all Function methods +* Renamed bindApply and bindCall to applyBind and callBind +* Removed Function.inherit (as it's unintuitive curry clone) +* Straightforward logic in Function.k +* Fixed naming of some tests files (letter case issue) +* Renamed Function.saturate into Function.lock +* String.dashToCamelCase digits support +* Strings now considered as List objects +* Improved List.compact +* Concise logic for List.concat +* Test wit TAD in clean ES5 context + +v0.5.1 -- 2011.07.11 +* Function's bindBind, bindCall and bindApply now more versatile + +v0.5.0 -- 2011.07.07 +* Removed Object.is and List.apply +* Renamed Object.plain.is to Object.plain.isPlainObject (keep naming convention + consistent) +* Improved documentation + +v0.4.0 -- 2011.07.05 +* Take most functions on Object to Object.plain to keep them away from object + descriptors +* Object functions with ES5 standard in mind (object descriptors) + +v0.3.0 -- 2011.06.24 +* New functions +* Consistent file naming (dash instead of camelCase) + +v0.2.1 -- 2011.05.28 +* Renamed Functions.K and Function.S to to lowercase versions (use consistent + naming) + +v0.2.0 -- 2011.05.28 +* Renamed Array folder to List (as its generic functions for array-like objects) +* Added Makefile +* Added various functions + +v0.1.0 -- 2011.05.24 +* Initial version diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/LICENSE new file mode 100644 index 00000000000000..de39071f1b8bbf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/README.md new file mode 100644 index 00000000000000..11d8a343d57f1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/README.md @@ -0,0 +1,993 @@ +# es5-ext +## ECMAScript 5 extensions +### (with respect to ECMAScript 6 standard) + +Shims for upcoming ES6 standard and other goodies implemented strictly with ECMAScript conventions in mind. + +It's designed to be used in compliant ECMAScript 5 or ECMAScript 6 environments. Older environments are not supported, although most of the features should work with correct ECMAScript 5 shim on board. + +When used in ECMAScript 6 environment, native implementation (if valid) takes precedence over shims. + +### Installation + + $ npm install es5-ext + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +### Usage + +#### ECMAScript 6 features + +You can force ES6 features to be implemented in your environment, e.g. following will assign `from` function to `Array` (only if it's not implemented already). + +```javascript +require('es5-ext/array/from/implement'); +Array.from('foo'); // ['f', 'o', 'o'] +``` + +You can also access shims directly, without fixing native objects. Following will return native `Array.from` if it's available and fallback to shim if it's not. + +```javascript +var aFrom = require('es5-ext/array/from'); +aFrom('foo'); // ['f', 'o', 'o'] +``` + +If you want to use shim unconditionally (even if native implementation exists) do: + +```javascript +var aFrom = require('es5-ext/array/from/shim'); +aFrom('foo'); // ['f', 'o', 'o'] +``` + +##### List of ES6 shims + +It's about properties introduced with ES6 and those that have been updated in new spec. + +- `Array.from` -> `require('es5-ext/array/from')` +- `Array.of` -> `require('es5-ext/array/of')` +- `Array.prototype.concat` -> `require('es5-ext/array/#/concat')` +- `Array.prototype.copyWithin` -> `require('es5-ext/array/#/copy-within')` +- `Array.prototype.entries` -> `require('es5-ext/array/#/entries')` +- `Array.prototype.fill` -> `require('es5-ext/array/#/fill')` +- `Array.prototype.filter` -> `require('es5-ext/array/#/filter')` +- `Array.prototype.find` -> `require('es5-ext/array/#/find')` +- `Array.prototype.findIndex` -> `require('es5-ext/array/#/find-index')` +- `Array.prototype.keys` -> `require('es5-ext/array/#/keys')` +- `Array.prototype.map` -> `require('es5-ext/array/#/map')` +- `Array.prototype.slice` -> `require('es5-ext/array/#/slice')` +- `Array.prototype.splice` -> `require('es5-ext/array/#/splice')` +- `Array.prototype.values` -> `require('es5-ext/array/#/values')` +- `Array.prototype[@@iterator]` -> `require('es5-ext/array/#/@@iterator')` +- `Math.acosh` -> `require('es5-ext/math/acosh')` +- `Math.asinh` -> `require('es5-ext/math/asinh')` +- `Math.atanh` -> `require('es5-ext/math/atanh')` +- `Math.cbrt` -> `require('es5-ext/math/cbrt')` +- `Math.clz32` -> `require('es5-ext/math/clz32')` +- `Math.cosh` -> `require('es5-ext/math/cosh')` +- `Math.exmp1` -> `require('es5-ext/math/expm1')` +- `Math.fround` -> `require('es5-ext/math/fround')` +- `Math.hypot` -> `require('es5-ext/math/hypot')` +- `Math.imul` -> `require('es5-ext/math/imul')` +- `Math.log1p` -> `require('es5-ext/math/log1p')` +- `Math.log2` -> `require('es5-ext/math/log2')` +- `Math.log10` -> `require('es5-ext/math/log10')` +- `Math.sign` -> `require('es5-ext/math/sign')` +- `Math.signh` -> `require('es5-ext/math/signh')` +- `Math.tanh` -> `require('es5-ext/math/tanh')` +- `Math.trunc` -> `require('es5-ext/math/trunc')` +- `Number.EPSILON` -> `require('es5-ext/number/epsilon')` +- `Number.MAX_SAFE_INTEGER` -> `require('es5-ext/number/max-safe-integer')` +- `Number.MIN_SAFE_INTEGER` -> `require('es5-ext/number/min-safe-integer')` +- `Number.isFinite` -> `require('es5-ext/number/is-finite')` +- `Number.isInteger` -> `require('es5-ext/number/is-integer')` +- `Number.isNaN` -> `require('es5-ext/number/is-nan')` +- `Number.isSafeInteger` -> `require('es5-ext/number/is-safe-integer')` +- `Object.assign` -> `require('es5-ext/object/assign')` +- `Object.keys` -> `require('es5-ext/object/keys')` +- `Object.setPrototypeOf` -> `require('es5-ext/object/set-prototype-of')` +- `RegExp.prototype.match` -> `require('es5-ext/reg-exp/#/match')` +- `RegExp.prototype.replace` -> `require('es5-ext/reg-exp/#/replace')` +- `RegExp.prototype.search` -> `require('es5-ext/reg-exp/#/search')` +- `RegExp.prototype.split` -> `require('es5-ext/reg-exp/#/split')` +- `RegExp.prototype.sticky` -> Implement with `require('es5-ext/reg-exp/#/sticky/implement')`, use as function with `require('es5-ext/reg-exp/#/is-sticky')` +- `RegExp.prototype.unicode` -> Implement with `require('es5-ext/reg-exp/#/unicode/implement')`, use as function with `require('es5-ext/reg-exp/#/is-unicode')` +- `String.fromCodePoint` -> `require('es5-ext/string/from-code-point')` +- `String.raw` -> `require('es5-ext/string/raw')` +- `String.prototype.codePointAt` -> `require('es5-ext/string/#/code-point-at')` +- `String.prototype.contains` -> `require('es5-ext/string/#/contains')` +- `String.prototype.endsWith` -> `require('es5-ext/string/#/ends-with')` +- `String.prototype.normalize` -> `require('es5-ext/string/#/normalize')` +- `String.prototype.repeat` -> `require('es5-ext/string/#/repeat')` +- `String.prototype.startsWith` -> `require('es5-ext/string/#/starts-with')` +- `String.prototype[@@iterator]` -> `require('es5-ext/string/#/@@iterator')` + +#### Non ECMAScript standard features + +__es5-ext__ provides also other utils, and implements them as if they were proposed for a standard. It mostly offers methods (not functions) which can directly be assigned to native prototypes: + +```javascript +Object.defineProperty(Function.prototype, 'partial', { value: require('es5-ext/function/#/partial'), + configurable: true, enumerable: false, writable: true }); +Object.defineProperty(Array.prototype, 'flatten', { value: require('es5-ext/array/#/flatten'), + configurable: true, enumerable: false, writable: true }); +Object.defineProperty(String.prototype, 'capitalize', { value: require('es5-ext/string/#/capitalize'), + configurable: true, enumerable: false, writable: true }); +``` + +See [es5-extend](https://github.com/wookieb/es5-extend#es5-extend), a great utility that automatically will extend natives for you. + +__Important:__ Remember to __not__ extend natives in scope of generic reusable packages (e.g. ones you intend to publish to npm). Extending natives is fine __only__ if you're the _owner_ of the global scope, so e.g. in final project you lead development of. + +When you're in situation when native extensions are not good idea, then you should use methods indirectly: + + +```javascript +var flatten = require('es5-ext/array/#/flatten'); + +flatten.call([1, [2, [3, 4]]]); // [1, 2, 3, 4] +``` + +for better convenience you can turn methods into functions: + + +```javascript +var call = Function.prototype.call +var flatten = call.bind(require('es5-ext/array/#/flatten')); + +flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4] +``` + +You can configure custom toolkit (like [underscorejs](http://underscorejs.org/)), and use it throughout your application + +```javascript +var util = {}; +util.partial = call.bind(require('es5-ext/function/#/partial')); +util.flatten = call.bind(require('es5-ext/array/#/flatten')); +util.startsWith = call.bind(require('es5-ext/string/#/starts-with')); + +util.flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4] +``` + +As with native ones most methods are generic and can be run on any type of object. + +## API + +### Global extensions + +#### global _(es5-ext/global)_ + +Object that represents global scope + +### Array Constructor extensions + +#### from(arrayLike[, mapFn[, thisArg]]) _(es5-ext/array/from)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from). +Returns array representation of _iterable_ or _arrayLike_. If _arrayLike_ is an instance of array, its copy is returned. + +#### generate([length[, …fill]]) _(es5-ext/array/generate)_ + +Generate an array of pre-given _length_ built of repeated arguments. + +#### isPlainArray(x) _(es5-ext/array/is-plain-array)_ + +Returns true if object is plain array (not instance of one of the Array's extensions). + +#### of([…items]) _(es5-ext/array/of)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.of). +Create an array from given arguments. + +#### toArray(obj) _(es5-ext/array/to-array)_ + +Returns array representation of `obj`. If `obj` is already an array, `obj` is returned back. + +#### validArray(obj) _(es5-ext/array/valid-array)_ + +Returns `obj` if it's an array, otherwise throws `TypeError` + +### Array Prototype extensions + +#### arr.binarySearch(compareFn) _(es5-ext/array/#/binary-search)_ + +In __sorted__ list search for index of item for which _compareFn_ returns value closest to _0_. +It's variant of binary search algorithm + +#### arr.clear() _(es5-ext/array/#/clear)_ + +Clears the array + +#### arr.compact() _(es5-ext/array/#/compact)_ + +Returns a copy of the context with all non-values (`null` or `undefined`) removed. + +#### arr.concat() _(es5-ext/array/#/concat)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.concat). +ES6's version of `concat`. Supports `isConcatSpreadable` symbol, and returns array of same type as the context. + +#### arr.contains(searchElement[, position]) _(es5-ext/array/#/contains)_ + +Whether list contains the given value. + +#### arr.copyWithin(target, start[, end]) _(es5-ext/array/#/copy-within)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.copywithin). + +#### arr.diff(other) _(es5-ext/array/#/diff)_ + +Returns the array of elements that are present in context list but not present in other list. + +#### arr.eIndexOf(searchElement[, fromIndex]) _(es5-ext/array/#/e-index-of)_ + +_egal_ version of `indexOf` method. [_SameValueZero_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) logic is used for comparision + +#### arr.eLastIndexOf(searchElement[, fromIndex]) _(es5-ext/array/#/e-last-index-of)_ + +_egal_ version of `lastIndexOf` method. [_SameValueZero_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) logic is used for comparision + +#### arr.entries() _(es5-ext/array/#/entries)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.entries). +Returns iterator object, which traverses the array. Each value is represented with an array, where first value is an index and second is corresponding to index value. + +#### arr.exclusion([…lists]]) _(es5-ext/array/#/exclusion)_ + +Returns the array of elements that are found only in one of the lists (either context list or list provided in arguments). + +#### arr.fill(value[, start, end]) _(es5-ext/array/#/fill)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.fill). + +#### arr.filter(callback[, thisArg]) _(es5-ext/array/#/filter)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.filter). +ES6's version of `filter`, returns array of same type as the context. + +#### arr.find(predicate[, thisArg]) _(es5-ext/array/#/find)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.find). +Return first element for which given function returns true + +#### arr.findIndex(predicate[, thisArg]) _(es5-ext/array/#/find-index)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.findindex). +Return first index for which given function returns true + +#### arr.first() _(es5-ext/array/#/first)_ + +Returns value for first defined index + +#### arr.firstIndex() _(es5-ext/array/#/first-index)_ + +Returns first declared index of the array + +#### arr.flatten() _(es5-ext/array/#/flatten)_ + +Returns flattened version of the array + +#### arr.forEachRight(cb[, thisArg]) _(es5-ext/array/#/for-each-right)_ + +`forEach` starting from last element + +#### arr.group(cb[, thisArg]) _(es5-ext/array/#/group)_ + +Group list elements by value returned by _cb_ function + +#### arr.indexesOf(searchElement[, fromIndex]) _(es5-ext/array/#/indexes-of)_ + +Returns array of all indexes of given value + +#### arr.intersection([…lists]) _(es5-ext/array/#/intersection)_ + +Computes the array of values that are the intersection of all lists (context list and lists given in arguments) + +#### arr.isCopy(other) _(es5-ext/array/#/is-copy)_ + +Returns true if both context and _other_ lists have same content + +#### arr.isUniq() _(es5-ext/array/#/is-uniq)_ + +Returns true if all values in array are unique + +#### arr.keys() _(es5-ext/array/#/keys)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.keys). +Returns iterator object, which traverses all array indexes. + +#### arr.last() _(es5-ext/array/#/last)_ + +Returns value of last defined index + +#### arr.lastIndex() _(es5-ext/array/#/last)_ + +Returns last defined index of the array + +#### arr.map(callback[, thisArg]) _(es5-ext/array/#/map)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.map). +ES6's version of `map`, returns array of same type as the context. + +#### arr.remove(value[, …valuen]) _(es5-ext/array/#/remove)_ + +Remove values from the array + +#### arr.separate(sep) _(es5-ext/array/#/separate)_ + +Returns array with items separated with `sep` value + +#### arr.slice(callback[, thisArg]) _(es5-ext/array/#/slice)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.slice). +ES6's version of `slice`, returns array of same type as the context. + +#### arr.someRight(cb[, thisArg]) _(es5-ext/array/#/someRight)_ + +`some` starting from last element + +#### arr.splice(callback[, thisArg]) _(es5-ext/array/#/splice)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.splice). +ES6's version of `splice`, returns array of same type as the context. + +#### arr.uniq() _(es5-ext/array/#/uniq)_ + +Returns duplicate-free version of the array + +#### arr.values() _(es5-ext/array/#/values)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.values). +Returns iterator object which traverses all array values. + +#### arr[@@iterator] _(es5-ext/array/#/@@iterator)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype-@@iterator). +Returns iterator object which traverses all array values. + +### Boolean Constructor extensions + +#### isBoolean(x) _(es5-ext/boolean/is-boolean)_ + +Whether value is boolean + +### Date Constructor extensions + +#### isDate(x) _(es5-ext/date/is-date)_ + +Whether value is date instance + +#### validDate(x) _(es5-ext/date/valid-date)_ + +If given object is not date throw TypeError in other case return it. + +### Date Prototype extensions + +#### date.copy(date) _(es5-ext/date/#/copy)_ + +Returns a copy of the date object + +#### date.daysInMonth() _(es5-ext/date/#/days-in-month)_ + +Returns number of days of date's month + +#### date.floorDay() _(es5-ext/date/#/floor-day)_ + +Sets the date time to 00:00:00.000 + +#### date.floorMonth() _(es5-ext/date/#/floor-month)_ + +Sets date day to 1 and date time to 00:00:00.000 + +#### date.floorYear() _(es5-ext/date/#/floor-year)_ + +Sets date month to 0, day to 1 and date time to 00:00:00.000 + +#### date.format(pattern) _(es5-ext/date/#/format)_ + +Formats date up to given string. Supported patterns: + +* `%Y` - Year with century, 1999, 2003 +* `%y` - Year without century, 99, 03 +* `%m` - Month, 01..12 +* `%d` - Day of the month 01..31 +* `%H` - Hour (24-hour clock), 00..23 +* `%M` - Minute, 00..59 +* `%S` - Second, 00..59 +* `%L` - Milliseconds, 000..999 + +### Error Constructor extensions + +#### custom(message/*, code, ext*/) _(es5-ext/error/custom)_ + +Creates custom error object, optinally extended with `code` and other extension properties (provided with `ext` object) + +#### isError(x) _(es5-ext/error/is-error)_ + +Whether value is an error (instance of `Error`). + +#### validError(x) _(es5-ext/error/valid-error)_ + +If given object is not error throw TypeError in other case return it. + +### Error Prototype extensions + +#### err.throw() _(es5-ext/error/#/throw)_ + +Throws error + +### Function Constructor extensions + +Some of the functions were inspired by [Functional JavaScript](http://osteele.com/sources/javascript/functional/) project by Olivier Steele + +#### constant(x) _(es5-ext/function/constant)_ + +Returns a constant function that returns pregiven argument + +_k(x)(y) =def x_ + +#### identity(x) _(es5-ext/function/identity)_ + +Identity function. Returns first argument + +_i(x) =def x_ + +#### invoke(name[, …args]) _(es5-ext/function/invoke)_ + +Returns a function that takes an object as an argument, and applies object's +_name_ method to arguments. +_name_ can be name of the method or method itself. + +_invoke(name, …args)(object, …args2) =def object\[name\]\(…args, …args2\)_ + +#### isArguments(x) _(es5-ext/function/is-arguments)_ + +Whether value is arguments object + +#### isFunction(arg) _(es5-ext/function/is-function)_ + +Wether value is instance of function + +#### noop() _(es5-ext/function/noop)_ + +No operation function + +#### pluck(name) _(es5-ext/function/pluck)_ + +Returns a function that takes an object, and returns the value of its _name_ +property + +_pluck(name)(obj) =def obj[name]_ + +#### validFunction(arg) _(es5-ext/function/valid-function)_ + +If given object is not function throw TypeError in other case return it. + +### Function Prototype extensions + +Some of the methods were inspired by [Functional JavaScript](http://osteele.com/sources/javascript/functional/) project by Olivier Steele + +#### fn.compose([…fns]) _(es5-ext/function/#/compose)_ + +Applies the functions in reverse argument-list order. + +_f1.compose(f2, f3, f4)(…args) =def f1(f2(f3(f4(…arg))))_ + +#### fn.copy() _(es5-ext/function/#/copy)_ + +Produces copy of given function + +#### fn.curry([n]) _(es5-ext/function/#/curry)_ + +Invoking the function returned by this function only _n_ arguments are passed to the underlying function. If the underlying function is not saturated, the result is a function that passes all its arguments to the underlying function. +If _n_ is not provided then it defaults to context function length + +_f.curry(4)(arg1, arg2)(arg3)(arg4) =def f(arg1, args2, arg3, arg4)_ + +#### fn.lock([…args]) _(es5-ext/function/#/lock)_ + +Returns a function that applies the underlying function to _args_, and ignores its own arguments. + +_f.lock(…args)(…args2) =def f(…args)_ + +_Named after it's counterpart in Google Closure_ + +#### fn.not() _(es5-ext/function/#/not)_ + +Returns a function that returns boolean negation of value returned by underlying function. + +_f.not()(…args) =def !f(…args)_ + +#### fn.partial([…args]) _(es5-ext/function/#/partial)_ + +Returns a function that when called will behave like context function called with initially passed arguments. If more arguments are suplilied, they are appended to initial args. + +_f.partial(…args1)(…args2) =def f(…args1, …args2)_ + +#### fn.spread() _(es5-ext/function/#/spread)_ + +Returns a function that applies underlying function with first list argument + +_f.match()(args) =def f.apply(null, args)_ + +#### fn.toStringTokens() _(es5-ext/function/#/to-string-tokens)_ + +Serializes function into two (arguments and body) string tokens. Result is plain object with `args` and `body` properties. + +### Math extensions + +#### acosh(x) _(es5-ext/math/acosh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.acosh). + +#### asinh(x) _(es5-ext/math/asinh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.asinh). + +#### atanh(x) _(es5-ext/math/atanh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.atanh). + +#### cbrt(x) _(es5-ext/math/cbrt)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.cbrt). + +#### clz32(x) _(es5-ext/math/clz32)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.clz32). + +#### cosh(x) _(es5-ext/math/cosh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.cosh). + +#### expm1(x) _(es5-ext/math/expm1)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.expm1). + +#### fround(x) _(es5-ext/math/fround)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.fround). + +#### hypot([…values]) _(es5-ext/math/hypot)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.hypot). + +#### imul(x, y) _(es5-ext/math/imul)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.imul). + +#### log1p(x) _(es5-ext/math/log1p)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.log1p). + +#### log2(x) _(es5-ext/math/log2)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.log2). + +#### log10(x) _(es5-ext/math/log10)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.log10). + +#### sign(x) _(es5-ext/math/sign)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.sign). + +#### sinh(x) _(es5-ext/math/sinh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.sinh). + +#### tanh(x) _(es5-ext/math/tanh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.tanh). + +#### trunc(x) _(es5-ext/math/trunc)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.trunc). + +### Number Constructor extensions + +#### EPSILON _(es5-ext/number/epsilon)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.epsilon). + +The difference between 1 and the smallest value greater than 1 that is representable as a Number value, which is approximately 2.2204460492503130808472633361816 x 10-16. + +#### isFinite(x) _(es5-ext/number/is-finite)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite). +Whether value is finite. Differs from global isNaN that it doesn't do type coercion. + +#### isInteger(x) _(es5-ext/number/is-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isinteger). +Whether value is integer. + +#### isNaN(x) _(es5-ext/number/is-nan)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isnan). +Whether value is NaN. Differs from global isNaN that it doesn't do type coercion. + +#### isNumber(x) _(es5-ext/number/is-number)_ + +Whether given value is number + +#### isSafeInteger(x) _(es5-ext/number/is-safe-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.issafeinteger). + +#### MAX_SAFE_INTEGER _(es5-ext/number/max-safe-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.maxsafeinteger). +The value of Number.MAX_SAFE_INTEGER is 9007199254740991. + +#### MIN_SAFE_INTEGER _(es5-ext/number/min-safe-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.minsafeinteger). +The value of Number.MIN_SAFE_INTEGER is -9007199254740991 (253-1). + +#### toInteger(x) _(es5-ext/number/to-integer)_ + +Converts value to integer + +#### toPosInteger(x) _(es5-ext/number/to-pos-integer)_ + +Converts value to positive integer. If provided value is less than 0, then 0 is returned + +#### toUint32(x) _(es5-ext/number/to-uint32)_ + +Converts value to unsigned 32 bit integer. This type is used for array lengths. +See: http://www.2ality.com/2012/02/js-integers.html + +### Number Prototype extensions + +#### num.pad(length[, precision]) _(es5-ext/number/#/pad)_ + +Pad given number with zeros. Returns string + +### Object Constructor extensions + +#### assign(target, source[, …sourcen]) _(es5-ext/object/assign)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). +Extend _target_ by enumerable own properties of other objects. If properties are already set on target object, they will be overwritten. + +#### clear(obj) _(es5-ext/object/clear)_ + +Remove all enumerable own properties of the object + +#### compact(obj) _(es5-ext/object/compact)_ + +Returns copy of the object with all enumerable properties that have no falsy values + +#### compare(obj1, obj2) _(es5-ext/object/compare)_ + +Universal cross-type compare function. To be used for e.g. array sort. + +#### copy(obj) _(es5-ext/object/copy)_ + +Returns copy of the object with all enumerable properties. + +#### copyDeep(obj) _(es5-ext/object/copy-deep)_ + +Returns deep copy of the object with all enumerable properties. + +#### count(obj) _(es5-ext/object/count)_ + +Counts number of enumerable own properties on object + +#### create(obj[, properties]) _(es5-ext/object/create)_ + +`Object.create` alternative that provides workaround for [V8 issue](http://code.google.com/p/v8/issues/detail?id=2804). + +When `null` is provided as a prototype, it's substituted with specially prepared object that derives from Object.prototype but has all Object.prototype properties shadowed with undefined. + +It's quirky solution that allows us to have plain objects with no truthy properties but with turnable prototype. + +Use only for objects that you plan to switch prototypes of and be aware of limitations of this workaround. + +#### eq(x, y) _(es5-ext/object/eq)_ + +Whether two values are equal, using [_SameValueZero_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) algorithm. + +#### every(obj, cb[, thisArg[, compareFn]]) _(es5-ext/object/every)_ + +Analogous to Array.prototype.every. Returns true if every key-value pair in this object satisfies the provided testing function. +Optionally _compareFn_ can be provided which assures that keys are tested in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### filter(obj, cb[, thisArg]) _(es5-ext/object/filter)_ + +Analogous to Array.prototype.filter. Returns new object with properites for which _cb_ function returned truthy value. + +#### firstKey(obj) _(es5-ext/object/first-key)_ + +Returns first enumerable key of the object, as keys are unordered by specification, it can be any key of an object. + +#### flatten(obj) _(es5-ext/object/flatten)_ + +Returns new object, with flatten properties of input object + +_flatten({ a: { b: 1 }, c: { d: 1 } }) =def { b: 1, d: 1 }_ + +#### forEach(obj, cb[, thisArg[, compareFn]]) _(es5-ext/object/for-each)_ + +Analogous to Array.prototype.forEach. Calls a function for each key-value pair found in object +Optionally _compareFn_ can be provided which assures that properties are iterated in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### getPropertyNames() _(es5-ext/object/get-property-names)_ + +Get all (not just own) property names of the object + +#### is(x, y) _(es5-ext/object/is)_ + +Whether two values are equal, using [_SameValue_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) algorithm. + +#### isArrayLike(x) _(es5-ext/object/is-array-like)_ + +Whether object is array-like object + +#### isCopy(x, y) _(es5-ext/object/is-copy)_ + +Two values are considered a copy of same value when all of their own enumerable properties have same values. + +#### isCopyDeep(x, y) _(es5-ext/object/is-copy-deep)_ + +Deep comparision of objects + +#### isEmpty(obj) _(es5-ext/object/is-empty)_ + +True if object doesn't have any own enumerable property + +#### isObject(arg) _(es5-ext/object/is-object)_ + +Whether value is not primitive + +#### isPlainObject(arg) _(es5-ext/object/is-plain-object)_ + +Whether object is plain object, its protototype should be Object.prototype and it cannot be host object. + +#### keyOf(obj, searchValue) _(es5-ext/object/key-of)_ + +Search object for value + +#### keys(obj) _(es5-ext/object/keys)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys). +ES6's version of `keys`, doesn't throw on primitive input + +#### map(obj, cb[, thisArg]) _(es5-ext/object/map)_ + +Analogous to Array.prototype.map. Creates a new object with properties which values are results of calling a provided function on every key-value pair in this object. + +#### mapKeys(obj, cb[, thisArg]) _(es5-ext/object/map-keys)_ + +Create new object with same values, but remapped keys + +#### mixin(target, source) _(es5-ext/object/mixin)_ + +Extend _target_ by all own properties of other objects. Properties found in both objects will be overwritten (unless they're not configurable and cannot be overwritten). +_It was for a moment part of ECMAScript 6 draft._ + +#### mixinPrototypes(target, …source]) _(es5-ext/object/mixin-prototypes)_ + +Extends _target_, with all source and source's prototype properties. +Useful as an alternative for `setPrototypeOf` in environments in which it cannot be shimmed (no `__proto__` support). + +#### normalizeOptions(options) _(es5-ext/object/normalize-options)_ + +Normalizes options object into flat plain object. + +Useful for functions in which we either need to keep options object for future reference or need to modify it for internal use. + +- It never returns input `options` object back (always a copy is created) +- `options` can be undefined in such case empty plain object is returned. +- Copies all enumerable properties found down prototype chain. + +#### primitiveSet([…names]) _(es5-ext/object/primitive-set)_ + +Creates `null` prototype based plain object, and sets on it all property names provided in arguments to true. + +#### safeTraverse(obj[, …names]) _(es5-ext/object/safe-traverse)_ + +Safe navigation of object properties. See http://wiki.ecmascript.org/doku.php?id=strawman:existential_operator + +#### serialize(value) _(es5-ext/object/serialize)_ + +Serialize value into string. Differs from [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that it serializes also dates, functions and regular expresssions. + +#### setPrototypeOf(object, proto) _(es5-ext/object/set-prototype-of)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.setprototypeof). +If native version is not provided, it depends on existence of `__proto__` functionality, if it's missing, `null` instead of function is exposed. + +#### some(obj, cb[, thisArg[, compareFn]]) _(es5-ext/object/some)_ + +Analogous to Array.prototype.some Returns true if any key-value pair satisfies the provided +testing function. +Optionally _compareFn_ can be provided which assures that keys are tested in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### toArray(obj[, cb[, thisArg[, compareFn]]]) _(es5-ext/object/to-array)_ + +Creates an array of results of calling a provided function on every key-value pair in this object. +Optionally _compareFn_ can be provided which assures that results are added in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### unserialize(str) _(es5-ext/object/unserialize)_ + +Userializes value previously serialized with [serialize](#serializevalue-es5-extobjectserialize) + +#### validCallable(x) _(es5-ext/object/valid-callable)_ + +If given object is not callable throw TypeError in other case return it. + +#### validObject(x) _(es5-ext/object/valid-object)_ + +Throws error if given value is not an object, otherwise it is returned. + +#### validValue(x) _(es5-ext/object/valid-value)_ + +Throws error if given value is `null` or `undefined`, otherwise returns value. + +### RegExp Constructor extensions + +#### escape(str) _(es5-ext/reg-exp/escape)_ + +Escapes string to be used in regular expression + +#### isRegExp(x) _(es5-ext/reg-exp/is-reg-exp)_ + +Whether object is regular expression + +#### validRegExp(x) _(es5-ext/reg-exp/valid-reg-exp)_ + +If object is regular expression it is returned, otherwise TypeError is thrown. + +### RegExp Prototype extensions + +#### re.isSticky(x) _(es5-ext/reg-exp/#/is-sticky)_ + +Whether regular expression has `sticky` flag. + +It's to be used as counterpart to [regExp.sticky](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-get-regexp.prototype.sticky) if it's not implemented. + +#### re.isUnicode(x) _(es5-ext/reg-exp/#/is-unicode)_ + +Whether regular expression has `unicode` flag. + +It's to be used as counterpart to [regExp.unicode](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-get-regexp.prototype.unicode) if it's not implemented. + +#### re.match(string) _(es5-ext/reg-exp/#/match)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.match). + +#### re.replace(string, replaceValue) _(es5-ext/reg-exp/#/replace)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.replace). + +#### re.search(string) _(es5-ext/reg-exp/#/search)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.search). + +#### re.split(string) _(es5-ext/reg-exp/#/search)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.split). + +#### re.sticky _(es5-ext/reg-exp/#/sticky/implement)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.sticky). +It's a getter, so only `implement` and `is-implemented` modules are provided. + +#### re.unicode _(es5-ext/reg-exp/#/unicode/implement)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.unicode). +It's a getter, so only `implement` and `is-implemented` modules are provided. + +### String Constructor extensions + +#### formatMethod(fMap) _(es5-ext/string/format-method)_ + +Creates format method. It's used e.g. to create `Date.prototype.format` method + +#### fromCodePoint([…codePoints]) _(es5-ext/string/from-code-point)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.fromcodepoint) + +#### isString(x) _(es5-ext/string/is-string)_ + +Whether object is string + +#### randomUniq() _(es5-ext/string/random-uniq)_ + +Returns randomly generated id, with guarantee of local uniqueness (no same id will be returned twice) + +#### raw(callSite[, …substitutions]) _(es5-ext/string/raw)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.raw) + +### String Prototype extensions + +#### str.at(pos) _(es5-ext/string/#/at)_ + +_Proposed for ECMAScript 6/7 standard, but not (yet) in a draft_ + +Returns a string at given position in Unicode-safe manner. +Based on [implementation by Mathias Bynens](https://github.com/mathiasbynens/String.prototype.at). + +#### str.camelToHyphen() _(es5-ext/string/#/camel-to-hyphen)_ + +Convert camelCase string to hyphen separated, e.g. one-two-three -> oneTwoThree. +Useful when converting names from js property convention into filename convention. + +#### str.capitalize() _(es5-ext/string/#/capitalize)_ + +Capitalize first character of a string + +#### str.caseInsensitiveCompare(str) _(es5-ext/string/#/case-insensitive-compare)_ + +Case insensitive compare + +#### str.codePointAt(pos) _(es5-ext/string/#/code-point-at)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.codepointat) + +Based on [implementation by Mathias Bynens](https://github.com/mathiasbynens/String.prototype.codePointAt). + +#### str.contains(searchString[, position]) _(es5-ext/string/#/contains)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.contains) + +Whether string contains given string. + +#### str.endsWith(searchString[, endPosition]) _(es5-ext/string/#/ends-with)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.endswith). +Whether strings ends with given string + +#### str.hyphenToCamel() _(es5-ext/string/#/hyphen-to-camel)_ + +Convert hyphen separated string to camelCase, e.g. one-two-three -> oneTwoThree. +Useful when converting names from filename convention to js property name convention. + +#### str.indent(str[, count]) _(es5-ext/string/#/indent)_ + +Indents each line with provided _str_ (if _count_ given then _str_ is repeated _count_ times). + +#### str.last() _(es5-ext/string/#/last)_ + +Return last character + +#### str.normalize([form]) _(es5-ext/string/#/normalize)_ + +[_Introduced with ECMAScript 6_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize). +Returns the Unicode Normalization Form of a given string. +Based on Matsuza's version. Code used for integrated shim can be found at [github.com/walling/unorm](https://github.com/walling/unorm/blob/master/lib/unorm.js) + +#### str.pad(fill[, length]) _(es5-ext/string/#/pad)_ + +Pad string with _fill_. +If _length_ si given than _fill_ is reapated _length_ times. +If _length_ is negative then pad is applied from right. + +#### str.repeat(n) _(es5-ext/string/#/repeat)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.repeat). +Repeat given string _n_ times + +#### str.plainReplace(search, replace) _(es5-ext/string/#/plain-replace)_ + +Simple `replace` version. Doesn't support regular expressions. Replaces just first occurrence of search string. Doesn't support insert patterns, therefore it is safe to replace text with text obtained programmatically (there's no need for additional _$_ characters escape in such case). + +#### str.plainReplaceAll(search, replace) _(es5-ext/string/#/plain-replace-all)_ + +Simple `replace` version. Doesn't support regular expressions. Replaces all occurrences of search string. Doesn't support insert patterns, therefore it is safe to replace text with text obtained programmatically (there's no need for additional _$_ characters escape in such case). + +#### str.startsWith(searchString[, position]) _(es5-ext/string/#/starts-with)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.startswith). +Whether strings starts with given string + +#### str[@@iterator] _(es5-ext/string/#/@@iterator)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator). +Returns iterator object which traverses all string characters (with respect to unicode symbols) + +### Tests [![Build Status](https://travis-ci.org/medikoo/es5-ext.png)](https://travis-ci.org/medikoo/es5-ext) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/implement.js new file mode 100644 index 00000000000000..0f714a1d2795e3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, require('es6-symbol').iterator, { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/index.js new file mode 100644 index 00000000000000..a69462650e7302 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.prototype[require('es6-symbol').iterator] : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..72eb1f8a27ff30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/is-implemented.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function () { + var arr = ['foo', 1], iterator, result; + if (typeof arr[iteratorSymbol] !== 'function') return false; + iterator = arr[iteratorSymbol](); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== 'foo') return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/shim.js new file mode 100644 index 00000000000000..ff295df9961e9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/@@iterator/shim.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('../values/shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/_compare-by-length.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/_compare-by-length.js new file mode 100644 index 00000000000000..d8343ce306d3ca --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/_compare-by-length.js @@ -0,0 +1,9 @@ +// Used internally to sort array of lists by length + +'use strict'; + +var toPosInt = require('../../number/to-pos-integer'); + +module.exports = function (a, b) { + return toPosInt(a.length) - toPosInt(b.length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/binary-search.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/binary-search.js new file mode 100644 index 00000000000000..8eb45675149256 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/binary-search.js @@ -0,0 +1,28 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , floor = Math.floor; + +module.exports = function (compareFn) { + var length, low, high, middle; + + value(this); + callable(compareFn); + + length = toPosInt(this.length); + low = 0; + high = length - 1; + + while (low <= high) { + middle = floor((low + high) / 2); + if (compareFn(this[middle]) < 0) high = middle - 1; + else low = middle + 1; + } + + if (high < 0) return 0; + if (high >= length) return length - 1; + return high; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/clear.js new file mode 100644 index 00000000000000..3587bdf972d458 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/clear.js @@ -0,0 +1,12 @@ +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear + +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + value(this).length = 0; + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/compact.js new file mode 100644 index 00000000000000..d529d5a2beab8f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/compact.js @@ -0,0 +1,9 @@ +// Inspired by: http://documentcloud.github.com/underscore/#compact + +'use strict'; + +var filter = Array.prototype.filter; + +module.exports = function () { + return filter.call(this, function (val) { return val != null; }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/implement.js new file mode 100644 index 00000000000000..80c67cb4faf764 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'concat', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/index.js new file mode 100644 index 00000000000000..db205ea54a41ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.concat : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/is-implemented.js new file mode 100644 index 00000000000000..cab8bc9e323bbd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).concat('foo') instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/shim.js new file mode 100644 index 00000000000000..8b28e4ae03b70f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/concat/shim.js @@ -0,0 +1,39 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + , toPosInt = require('../../../number/to-pos-integer') + , isObject = require('../../../object/is-object') + + , isArray = Array.isArray, concat = Array.prototype.concat + , forEach = Array.prototype.forEach + + , isSpreadable; + +isSpreadable = function (value) { + if (!value) return false; + if (!isObject(value)) return false; + if (value['@@isConcatSpreadable'] !== undefined) { + return Boolean(value['@@isConcatSpreadable']); + } + return isArray(value); +}; + +module.exports = function (item/*, …items*/) { + var result; + if (!this || !isArray(this) || isPlainArray(this)) { + return concat.apply(this, arguments); + } + result = new this.constructor(this.length); + forEach.call(this, function (val, i) { result[i] = val; }); + forEach.call(arguments, function (arg) { + var base; + if (isSpreadable(arg)) { + base = result.length; + result.length += toPosInt(arg.length); + forEach.call(arg, function (val, i) { result[base + i] = val; }); + return; + } + result.push(arg); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/contains.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/contains.js new file mode 100644 index 00000000000000..4a2f9f6731c8c6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/contains.js @@ -0,0 +1,7 @@ +'use strict'; + +var indexOf = require('./e-index-of'); + +module.exports = function (searchElement/*, position*/) { + return indexOf.call(this, searchElement, arguments[1]) > -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/implement.js new file mode 100644 index 00000000000000..eedbad77eebe09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'copyWithin', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/index.js new file mode 100644 index 00000000000000..bb89d0b87934d1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.copyWithin : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/is-implemented.js new file mode 100644 index 00000000000000..8f17e06d816d14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5]; + if (typeof arr.copyWithin !== 'function') return false; + return String(arr.copyWithin(1, 3)) === '1,4,5,4,5'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/shim.js new file mode 100644 index 00000000000000..c0bfb8b0609f4e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/copy-within/shim.js @@ -0,0 +1,39 @@ +// Taken from: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var toInteger = require('../../../number/to-integer') + , toPosInt = require('../../../number/to-pos-integer') + , validValue = require('../../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty + , max = Math.max, min = Math.min; + +module.exports = function (target, start/*, end*/) { + var o = validValue(this), end = arguments[2], l = toPosInt(o.length) + , to, from, fin, count, direction; + + target = toInteger(target); + start = toInteger(start); + end = (end === undefined) ? l : toInteger(end); + + to = target < 0 ? max(l + target, 0) : min(target, l); + from = start < 0 ? max(l + start, 0) : min(start, l); + fin = end < 0 ? max(l + end, 0) : min(end, l); + count = min(fin - from, l - to); + direction = 1; + + if ((from < to) && (to < (from + count))) { + direction = -1; + from += count - 1; + to += count - 1; + } + while (count > 0) { + if (hasOwnProperty.call(o, from)) o[to] = o[from]; + else delete o[from]; + from += direction; + to += direction; + count -= 1; + } + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/diff.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/diff.js new file mode 100644 index 00000000000000..a1f95419d4ed65 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/diff.js @@ -0,0 +1,13 @@ +'use strict'; + +var value = require('../../object/valid-value') + , contains = require('./contains') + + , filter = Array.prototype.filter; + +module.exports = function (other) { + (value(this) && value(other)); + return filter.call(this, function (item) { + return !contains.call(other, item); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/e-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/e-index-of.js new file mode 100644 index 00000000000000..80864d0666168a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/e-index-of.js @@ -0,0 +1,29 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , indexOf = Array.prototype.indexOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs, floor = Math.floor; + +module.exports = function (searchElement/*, fromIndex*/) { + var i, l, fromIndex, val; + if (searchElement === searchElement) { //jslint: ignore + return indexOf.apply(this, arguments); + } + + l = toPosInt(value(this).length); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = 0; + else if (fromIndex >= 0) fromIndex = floor(fromIndex); + else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + + for (i = fromIndex; i < l; ++i) { + if (hasOwnProperty.call(this, i)) { + val = this[i]; + if (val !== val) return i; //jslint: ignore + } + } + return -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/e-last-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/e-last-index-of.js new file mode 100644 index 00000000000000..4fc536bd68082d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/e-last-index-of.js @@ -0,0 +1,29 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , lastIndexOf = Array.prototype.lastIndexOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs, floor = Math.floor; + +module.exports = function (searchElement/*, fromIndex*/) { + var i, fromIndex, val; + if (searchElement === searchElement) { //jslint: ignore + return lastIndexOf.apply(this, arguments); + } + + value(this); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = (toPosInt(this.length) - 1); + else if (fromIndex >= 0) fromIndex = floor(fromIndex); + else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + + for (i = fromIndex; i >= 0; --i) { + if (hasOwnProperty.call(this, i)) { + val = this[i]; + if (val !== val) return i; //jslint: ignore + } + } + return -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/implement.js new file mode 100644 index 00000000000000..490de60e207ab4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'entries', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/index.js new file mode 100644 index 00000000000000..292792cf159da8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.entries : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/is-implemented.js new file mode 100644 index 00000000000000..e186c17237bd39 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/is-implemented.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 'foo'], iterator, result; + if (typeof arr.entries !== 'function') return false; + iterator = arr.entries(); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result || !result.value) return false; + if (result.value[0] !== 0) return false; + if (result.value[1] !== 1) return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/shim.js new file mode 100644 index 00000000000000..c052b53f01d89f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/entries/shim.js @@ -0,0 +1,4 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array'); +module.exports = function () { return new ArrayIterator(this, 'key+value'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/exclusion.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/exclusion.js new file mode 100644 index 00000000000000..f08adc81c9631e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/exclusion.js @@ -0,0 +1,27 @@ +'use strict'; + +var value = require('../../object/valid-value') + , aFrom = require('../from') + , toArray = require('../to-array') + , contains = require('./contains') + , byLength = require('./_compare-by-length') + + , filter = Array.prototype.filter, push = Array.prototype.push; + +module.exports = function (/*…lists*/) { + var lists, seen, result; + if (!arguments.length) return aFrom(this); + push.apply(lists = [this], arguments); + lists.forEach(value); + seen = []; + result = []; + lists.sort(byLength).forEach(function (list) { + result = result.filter(function (item) { + return !contains.call(list, item); + }).concat(filter.call(list, function (x) { + return !contains.call(seen, x); + })); + push.apply(seen, toArray(list)); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/implement.js new file mode 100644 index 00000000000000..22511919c516fe --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'fill', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/index.js new file mode 100644 index 00000000000000..36c1f66668b29d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.fill : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/is-implemented.js new file mode 100644 index 00000000000000..b8e546888af2b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5, 6]; + if (typeof arr.fill !== 'function') return false; + return String(arr.fill(-1, -3)) === '1,2,3,-1,-1,-1'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/shim.js new file mode 100644 index 00000000000000..45823be51fc193 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/fill/shim.js @@ -0,0 +1,21 @@ +// Taken from: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var toInteger = require('../../../number/to-integer') + , toPosInt = require('../../../number/to-pos-integer') + , validValue = require('../../../object/valid-value') + + , max = Math.max, min = Math.min; + +module.exports = function (value/*, start, end*/) { + var o = validValue(this), start = arguments[1], end = arguments[2] + , l = toPosInt(o.length), relativeStart, i; + + start = (start === undefined) ? 0 : toInteger(start); + end = (end === undefined) ? l : toInteger(end); + + relativeStart = start < 0 ? max(l + start, 0) : min(start, l); + for (i = relativeStart; i < l && i < end; ++i) o[i] = value; + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/implement.js new file mode 100644 index 00000000000000..090c5f109aee35 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'filter', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/index.js new file mode 100644 index 00000000000000..bcf0268dc2dcb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.filter : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/is-implemented.js new file mode 100644 index 00000000000000..5577273501531e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe') + + , pass = function () { return true; }; + +module.exports = function () { + return (new SubArray()).filter(pass) instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/shim.js new file mode 100644 index 00000000000000..b0116defce5021 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/filter/shim.js @@ -0,0 +1,22 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + , callable = require('../../../object/valid-callable') + + , isArray = Array.isArray, filter = Array.prototype.filter + , forEach = Array.prototype.forEach, call = Function.prototype.call; + +module.exports = function (callbackFn/*, thisArg*/) { + var result, thisArg, i; + if (!this || !isArray(this) || isPlainArray(this)) { + return filter.apply(this, arguments); + } + callable(callbackFn); + thisArg = arguments[1]; + result = new this.constructor(); + i = 0; + forEach.call(this, function (val, j, self) { + if (call.call(callbackFn, thisArg, val, j, self)) result[i++] = val; + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/implement.js new file mode 100644 index 00000000000000..556cb846002b0e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'findIndex', + { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/index.js new file mode 100644 index 00000000000000..03a987e22347bf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.findIndex : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/is-implemented.js new file mode 100644 index 00000000000000..dbd3c814b4650f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var fn = function (x) { return x > 3; }; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5, 6]; + if (typeof arr.findIndex !== 'function') return false; + return arr.findIndex(fn) === 3; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/shim.js new file mode 100644 index 00000000000000..957939f2ba224a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find-index/shim.js @@ -0,0 +1,20 @@ +'use strict'; + +var callable = require('../../../object/valid-callable') + , value = require('../../../object/valid-value') + + , some = Array.prototype.some, apply = Function.prototype.apply; + +module.exports = function (predicate/*, thisArg*/) { + var k, self; + self = Object(value(this)); + callable(predicate); + + return some.call(self, function (value, index) { + if (apply.call(predicate, this, arguments)) { + k = index; + return true; + } + return false; + }, arguments[1]) ? k : -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/implement.js new file mode 100644 index 00000000000000..0f37104ac8dbbf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'find', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/index.js new file mode 100644 index 00000000000000..96819d09f02198 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.find : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/is-implemented.js new file mode 100644 index 00000000000000..cc7ec774df0fa4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var fn = function (x) { return x > 3; }; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5, 6]; + if (typeof arr.find !== 'function') return false; + return arr.find(fn) === 4; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/shim.js new file mode 100644 index 00000000000000..c7ee9069a9a308 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/find/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var findIndex = require('../find-index/shim'); + +module.exports = function (predicate/*, thisArg*/) { + var index = findIndex.apply(this, arguments); + return (index === -1) ? undefined : this[index]; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/first-index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/first-index.js new file mode 100644 index 00000000000000..7a9e4c34736ca3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/first-index.js @@ -0,0 +1,16 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function () { + var i, l; + if (!(l = toPosInt(value(this).length))) return null; + i = 0; + while (!hasOwnProperty.call(this, i)) { + if (++i === l) return null; + } + return i; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/first.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/first.js new file mode 100644 index 00000000000000..11df571754857f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/first.js @@ -0,0 +1,9 @@ +'use strict'; + +var firstIndex = require('./first-index'); + +module.exports = function () { + var i; + if ((i = firstIndex.call(this)) !== null) return this[i]; + return undefined; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/flatten.js new file mode 100644 index 00000000000000..c95407d317fd3b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/flatten.js @@ -0,0 +1,12 @@ +'use strict'; + +var isArray = Array.isArray, forEach = Array.prototype.forEach + , push = Array.prototype.push; + +module.exports = function flatten() { + var r = []; + forEach.call(this, function (x) { + push.apply(r, isArray(x) ? flatten.call(x) : [x]); + }); + return r; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/for-each-right.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/for-each-right.js new file mode 100644 index 00000000000000..2f0ffaea84cb38 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/for-each-right.js @@ -0,0 +1,20 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty + , call = Function.prototype.call; + +module.exports = function (cb/*, thisArg*/) { + var i, self, thisArg; + + self = Object(value(this)); + callable(cb); + thisArg = arguments[1]; + + for (i = toPosInt(self.length); i >= 0; --i) { + if (hasOwnProperty.call(self, i)) call.call(cb, thisArg, self[i], i, self); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/group.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/group.js new file mode 100644 index 00000000000000..fbb178c35c1730 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/group.js @@ -0,0 +1,23 @@ +// Inspired by Underscore's groupBy: +// http://documentcloud.github.com/underscore/#groupBy + +'use strict'; + +var callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , forEach = Array.prototype.forEach, apply = Function.prototype.apply; + +module.exports = function (cb/*, thisArg*/) { + var r; + + (value(this) && callable(cb)); + + r = {}; + forEach.call(this, function (v) { + var key = apply.call(cb, this, arguments); + if (!r.hasOwnProperty(key)) r[key] = []; + r[key].push(v); + }, arguments[1]); + return r; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/index.js new file mode 100644 index 00000000000000..97ef65cfd42cf1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/index.js @@ -0,0 +1,40 @@ +'use strict'; + +module.exports = { + '@@iterator': require('./@@iterator'), + binarySearch: require('./binary-search'), + clear: require('./clear'), + compact: require('./compact'), + concat: require('./concat'), + contains: require('./contains'), + copyWithin: require('./copy-within'), + diff: require('./diff'), + eIndexOf: require('./e-index-of'), + eLastIndexOf: require('./e-last-index-of'), + entries: require('./entries'), + exclusion: require('./exclusion'), + fill: require('./fill'), + filter: require('./filter'), + find: require('./find'), + findIndex: require('./find-index'), + first: require('./first'), + firstIndex: require('./first-index'), + flatten: require('./flatten'), + forEachRight: require('./for-each-right'), + keys: require('./keys'), + group: require('./group'), + indexesOf: require('./indexes-of'), + intersection: require('./intersection'), + isCopy: require('./is-copy'), + isUniq: require('./is-uniq'), + last: require('./last'), + lastIndex: require('./last-index'), + map: require('./map'), + remove: require('./remove'), + separate: require('./separate'), + slice: require('./slice'), + someRight: require('./some-right'), + splice: require('./splice'), + uniq: require('./uniq'), + values: require('./values') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/indexes-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/indexes-of.js new file mode 100644 index 00000000000000..6b89157a35b805 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/indexes-of.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexOf = require('./e-index-of'); + +module.exports = function (value/*, fromIndex*/) { + var r = [], i, fromIndex = arguments[1]; + while ((i = indexOf.call(this, value, fromIndex)) !== -1) { + r.push(i); + fromIndex = i + 1; + } + return r; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/intersection.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/intersection.js new file mode 100644 index 00000000000000..fadcb525308964 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/intersection.js @@ -0,0 +1,19 @@ +'use strict'; + +var value = require('../../object/valid-value') + , contains = require('./contains') + , byLength = require('./_compare-by-length') + + , filter = Array.prototype.filter, push = Array.prototype.push + , slice = Array.prototype.slice; + +module.exports = function (/*…list*/) { + var lists; + if (!arguments.length) slice.call(this); + push.apply(lists = [this], arguments); + lists.forEach(value); + lists.sort(byLength); + return lists.reduce(function (a, b) { + return filter.call(a, function (x) { return contains.call(b, x); }); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/is-copy.js new file mode 100644 index 00000000000000..ac7c79bc4521ce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/is-copy.js @@ -0,0 +1,21 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , eq = require('../../object/eq') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function (other) { + var i, l; + (value(this) && value(other)); + l = toPosInt(this.length); + if (l !== toPosInt(other.length)) return false; + for (i = 0; i < l; ++i) { + if (hasOwnProperty.call(this, i) !== hasOwnProperty.call(other, i)) { + return false; + } + if (!eq(this[i], other[i])) return false; + } + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/is-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/is-uniq.js new file mode 100644 index 00000000000000..b14f461d941ee5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/is-uniq.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexOf = require('./e-index-of') + + , every = Array.prototype.every + , isFirst; + +isFirst = function (value, index) { + return indexOf.call(this, value) === index; +}; + +module.exports = function () { return every.call(this, isFirst, this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/implement.js new file mode 100644 index 00000000000000..e18e61701fa028 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'keys', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/index.js new file mode 100644 index 00000000000000..2f89cffe101d61 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.keys : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/is-implemented.js new file mode 100644 index 00000000000000..06bd87bf296c15 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 'foo'], iterator, result; + if (typeof arr.keys !== 'function') return false; + iterator = arr.keys(); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== 0) return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/shim.js new file mode 100644 index 00000000000000..83773f6ec955d2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/keys/shim.js @@ -0,0 +1,4 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array'); +module.exports = function () { return new ArrayIterator(this, 'key'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/last-index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/last-index.js new file mode 100644 index 00000000000000..a191d6e153d6ae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/last-index.js @@ -0,0 +1,16 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function () { + var i, l; + if (!(l = toPosInt(value(this).length))) return null; + i = l - 1; + while (!hasOwnProperty.call(this, i)) { + if (--i === -1) return null; + } + return i; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/last.js new file mode 100644 index 00000000000000..bf9d2f29249d09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/last.js @@ -0,0 +1,9 @@ +'use strict'; + +var lastIndex = require('./last-index'); + +module.exports = function () { + var i; + if ((i = lastIndex.call(this)) !== null) return this[i]; + return undefined; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/implement.js new file mode 100644 index 00000000000000..3aabb87440e099 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'map', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/index.js new file mode 100644 index 00000000000000..66f66607df4f14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.map : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/is-implemented.js new file mode 100644 index 00000000000000..c328b473302cea --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var identity = require('../../../function/identity') + , SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).map(identity) instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/shim.js new file mode 100644 index 00000000000000..2ee731347b1aee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/map/shim.js @@ -0,0 +1,21 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + , callable = require('../../../object/valid-callable') + + , isArray = Array.isArray, map = Array.prototype.map + , forEach = Array.prototype.forEach, call = Function.prototype.call; + +module.exports = function (callbackFn/*, thisArg*/) { + var result, thisArg; + if (!this || !isArray(this) || isPlainArray(this)) { + return map.apply(this, arguments); + } + callable(callbackFn); + thisArg = arguments[1]; + result = new this.constructor(this.length); + forEach.call(this, function (val, i, self) { + result[i] = call.call(callbackFn, thisArg, val, i, self); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/remove.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/remove.js new file mode 100644 index 00000000000000..dcf843313d5fcb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/remove.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexOf = require('./e-index-of') + + , forEach = Array.prototype.forEach, splice = Array.prototype.splice; + +module.exports = function (item/*, …item*/) { + forEach.call(arguments, function (item) { + var index = indexOf.call(this, item); + if (index !== -1) splice.call(this, index, 1); + }, this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/separate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/separate.js new file mode 100644 index 00000000000000..dc974b832e07d2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/separate.js @@ -0,0 +1,10 @@ +'use strict'; + +var forEach = Array.prototype.forEach; + +module.exports = function (sep) { + var result = []; + forEach.call(this, function (val, i) { result.push(val, sep); }); + result.pop(); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/implement.js new file mode 100644 index 00000000000000..cd488a063956e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'slice', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/index.js new file mode 100644 index 00000000000000..72200ca9e381b6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.prototype.slice : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/is-implemented.js new file mode 100644 index 00000000000000..ec1985e70ee034 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).slice() instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/shim.js new file mode 100644 index 00000000000000..2761a1aad8340d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/slice/shim.js @@ -0,0 +1,35 @@ +'use strict'; + +var toInteger = require('../../../number/to-integer') + , toPosInt = require('../../../number/to-pos-integer') + , isPlainArray = require('../../is-plain-array') + + , isArray = Array.isArray, slice = Array.prototype.slice + , hasOwnProperty = Object.prototype.hasOwnProperty, max = Math.max; + +module.exports = function (start, end) { + var length, result, i; + if (!this || !isArray(this) || isPlainArray(this)) { + return slice.apply(this, arguments); + } + length = toPosInt(this.length); + start = toInteger(start); + if (start < 0) start = max(length + start, 0); + else if (start > length) start = length; + if (end === undefined) { + end = length; + } else { + end = toInteger(end); + if (end < 0) end = max(length + end, 0); + else if (end > length) end = length; + } + if (start > end) start = end; + result = new this.constructor(end - start); + i = 0; + while (start !== end) { + if (hasOwnProperty.call(this, start)) result[i] = this[start]; + ++i; + ++start; + } + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/some-right.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/some-right.js new file mode 100644 index 00000000000000..de7460d62234cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/some-right.js @@ -0,0 +1,22 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty + , call = Function.prototype.call; + +module.exports = function (cb/*, thisArg*/) { + var i, self, thisArg; + self = Object(value(this)); + callable(cb); + thisArg = arguments[1]; + + for (i = self.length; i >= 0; --i) { + if (hasOwnProperty.call(self, i) && + call.call(cb, thisArg, self[i], i, self)) { + return true; + } + } + return false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/implement.js new file mode 100644 index 00000000000000..aab1f8eff677b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'splice', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/index.js new file mode 100644 index 00000000000000..e8ecf3cf856171 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.prototype.splice : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/is-implemented.js new file mode 100644 index 00000000000000..ffddaa81ef83dd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).splice(0) instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/shim.js new file mode 100644 index 00000000000000..a8505a2ce2a201 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/splice/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + + , isArray = Array.isArray, splice = Array.prototype.splice + , forEach = Array.prototype.forEach; + +module.exports = function (start, deleteCount/*, …items*/) { + var arr = splice.apply(this, arguments), result; + if (!this || !isArray(this) || isPlainArray(this)) return arr; + result = new this.constructor(arr.length); + forEach.call(arr, function (val, i) { result[i] = val; }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/uniq.js new file mode 100644 index 00000000000000..db0146555733a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/uniq.js @@ -0,0 +1,13 @@ +'use strict'; + +var indexOf = require('./e-index-of') + + , filter = Array.prototype.filter + + , isFirst; + +isFirst = function (value, index) { + return indexOf.call(this, value) === index; +}; + +module.exports = function () { return filter.call(this, isFirst, this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/implement.js new file mode 100644 index 00000000000000..237281fd3beed0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'values', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/index.js new file mode 100644 index 00000000000000..c0832c30ea4566 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Array.prototype.values : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/is-implemented.js new file mode 100644 index 00000000000000..cc0c6294e2af14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function () { + var arr = ['foo', 1], iterator, result; + if (typeof arr.values !== 'function') return false; + iterator = arr.values(); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== 'foo') return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/shim.js new file mode 100644 index 00000000000000..f6555fd858e99a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/#/values/shim.js @@ -0,0 +1,4 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array'); +module.exports = function () { return new ArrayIterator(this, 'value'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_is-extensible.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_is-extensible.js new file mode 100644 index 00000000000000..612320647b39f6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_is-extensible.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = (function () { + var SubArray = require('./_sub-array-dummy'), arr; + + if (!SubArray) return false; + arr = new SubArray(); + if (!Array.isArray(arr)) return false; + if (!(arr instanceof SubArray)) return false; + + arr[34] = 'foo'; + return (arr.length === 35); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_sub-array-dummy-safe.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_sub-array-dummy-safe.js new file mode 100644 index 00000000000000..5baf8a8d1127a4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_sub-array-dummy-safe.js @@ -0,0 +1,23 @@ +'use strict'; + +var setPrototypeOf = require('../object/set-prototype-of') + , isExtensible = require('./_is-extensible'); + +module.exports = (function () { + var SubArray; + + if (isExtensible) return require('./_sub-array-dummy'); + + if (!setPrototypeOf) return null; + SubArray = function () { + var arr = Array.apply(this, arguments); + setPrototypeOf(arr, SubArray.prototype); + return arr; + }; + setPrototypeOf(SubArray, Array); + SubArray.prototype = Object.create(Array.prototype, { + constructor: { value: SubArray, enumerable: false, writable: true, + configurable: true } + }); + return SubArray; +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_sub-array-dummy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_sub-array-dummy.js new file mode 100644 index 00000000000000..a926d1a32ddd7e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/_sub-array-dummy.js @@ -0,0 +1,16 @@ +'use strict'; + +var setPrototypeOf = require('../object/set-prototype-of'); + +module.exports = (function () { + var SubArray; + + if (!setPrototypeOf) return null; + SubArray = function () { Array.apply(this, arguments); }; + setPrototypeOf(SubArray, Array); + SubArray.prototype = Object.create(Array.prototype, { + constructor: { value: SubArray, enumerable: false, writable: true, + configurable: true } + }); + return SubArray; +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/implement.js new file mode 100644 index 00000000000000..f3411b13770743 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array, 'from', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/index.js new file mode 100644 index 00000000000000..3b99cda8ec3db6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.from + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/is-implemented.js new file mode 100644 index 00000000000000..63ff2a572a353b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function () { + var from = Array.from, arr, result; + if (typeof from !== 'function') return false; + arr = ['raz', 'dwa']; + result = from(arr); + return Boolean(result && (result !== arr) && (result[1] === 'dwa')); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/shim.js new file mode 100644 index 00000000000000..a90ba2f9730c54 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/from/shim.js @@ -0,0 +1,106 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , isArguments = require('../../function/is-arguments') + , isFunction = require('../../function/is-function') + , toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , validValue = require('../../object/valid-value') + , isString = require('../../string/is-string') + + , isArray = Array.isArray, call = Function.prototype.call + , desc = { configurable: true, enumerable: true, writable: true, value: null } + , defineProperty = Object.defineProperty; + +module.exports = function (arrayLike/*, mapFn, thisArg*/) { + var mapFn = arguments[1], thisArg = arguments[2], Constructor, i, j, arr, l, code, iterator + , result, getIterator, value; + + arrayLike = Object(validValue(arrayLike)); + + if (mapFn != null) callable(mapFn); + if (!this || (this === Array) || !isFunction(this)) { + // Result: Plain array + if (!mapFn) { + if (isArguments(arrayLike)) { + // Source: Arguments + l = arrayLike.length; + if (l !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (isArray(arrayLike)) { + // Source: Array + arr = new Array(l = arrayLike.length); + for (i = 0; i < l; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + // Result: Non plain array + Constructor = this; + } + + if (!isArray(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { + // Source: Iterator + iterator = callable(getIterator).call(arrayLike); + if (Constructor) arr = new Constructor(); + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (!Constructor) { + arr[i] = value; + } else { + desc.value = value; + defineProperty(arr, i, desc); + } + result = iterator.next(); + ++i; + } + l = i; + } else if (isString(arrayLike)) { + // Source: String + l = arrayLike.length; + if (Constructor) arr = new Constructor(); + for (i = 0, j = 0; i < l; ++i) { + value = arrayLike[i]; + if ((i + 1) < l) { + code = value.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) value += arrayLike[++i]; + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (!Constructor) { + arr[j] = value; + } else { + desc.value = value; + defineProperty(arr, j, desc); + } + ++j; + } + l = j; + } + } + if (l === undefined) { + // Source: array or array-like + l = toPosInt(arrayLike.length); + if (Constructor) arr = new Constructor(l); + for (i = 0; i < l; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (!Constructor) { + arr[i] = value; + } else { + desc.value = value; + defineProperty(arr, i, desc); + } + } + } + if (Constructor) { + desc.value = null; + arr.length = l; + } + return arr; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/generate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/generate.js new file mode 100644 index 00000000000000..5e066750b1d5ba --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/generate.js @@ -0,0 +1,20 @@ +'use strict'; + +var toPosInt = require('../number/to-pos-integer') + , value = require('../object/valid-value') + + , slice = Array.prototype.slice; + +module.exports = function (length/*, …fill*/) { + var arr, l; + length = toPosInt(value(length)); + if (length === 0) return []; + + arr = (arguments.length < 2) ? [undefined] : + slice.call(arguments, 1, 1 + length); + + while ((l = arr.length) < length) { + arr = arr.concat(arr.slice(0, length - l)); + } + return arr; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/index.js new file mode 100644 index 00000000000000..7a6867894b56dd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/index.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + from: require('./from'), + generate: require('./generate'), + isPlainArray: require('./is-plain-array'), + of: require('./of'), + toArray: require('./to-array'), + validArray: require('./valid-array') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/is-plain-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/is-plain-array.js new file mode 100644 index 00000000000000..6b37e4069738b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/is-plain-array.js @@ -0,0 +1,11 @@ +'use strict'; + +var isArray = Array.isArray, getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (obj) { + var proto; + if (!obj || !isArray(obj)) return false; + proto = getPrototypeOf(obj); + if (!isArray(proto)) return false; + return !isArray(getPrototypeOf(proto)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/implement.js new file mode 100644 index 00000000000000..bf2a5a54a740e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array, 'of', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/index.js new file mode 100644 index 00000000000000..07ee54dbcd4283 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.of + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/is-implemented.js new file mode 100644 index 00000000000000..4390a10863326b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + var of = Array.of, result; + if (typeof of !== 'function') return false; + result = of('foo', 'bar'); + return Boolean(result && (result[1] === 'bar')); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/shim.js new file mode 100644 index 00000000000000..de72bc92291154 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/of/shim.js @@ -0,0 +1,19 @@ +'use strict'; + +var isFunction = require('../../function/is-function') + + , slice = Array.prototype.slice, defineProperty = Object.defineProperty + , desc = { configurable: true, enumerable: true, writable: true, value: null }; + +module.exports = function (/*…items*/) { + var result, i, l; + if (!this || (this === Array) || !isFunction(this)) return slice.call(arguments); + result = new this(l = arguments.length); + for (i = 0; i < l; ++i) { + desc.value = arguments[i]; + defineProperty(result, i, desc); + } + desc.value = null; + result.length = l; + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/to-array.js new file mode 100644 index 00000000000000..ce908dd912959b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/to-array.js @@ -0,0 +1,9 @@ +'use strict'; + +var from = require('./from') + + , isArray = Array.isArray; + +module.exports = function (arrayLike) { + return isArray(arrayLike) ? arrayLike : from(arrayLike); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/valid-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/valid-array.js new file mode 100644 index 00000000000000..d86a8f5f242b27 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/array/valid-array.js @@ -0,0 +1,8 @@ +'use strict'; + +var isArray = Array.isArray; + +module.exports = function (value) { + if (isArray(value)) return value; + throw new TypeError(value + " is not an array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/boolean/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/boolean/index.js new file mode 100644 index 00000000000000..c193b948eb9d01 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/boolean/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + isBoolean: require('./is-boolean') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/boolean/is-boolean.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/boolean/is-boolean.js new file mode 100644 index 00000000000000..5d1a802e11211c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/boolean/is-boolean.js @@ -0,0 +1,10 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(true); + +module.exports = function (x) { + return (typeof x === 'boolean') || ((typeof x === 'object') && + ((x instanceof Boolean) || (toString.call(x) === id))); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/copy.js new file mode 100644 index 00000000000000..69e2eb09fcbcf1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/copy.js @@ -0,0 +1,5 @@ +'use strict'; + +var getTime = Date.prototype.getTime; + +module.exports = function () { return new Date(getTime.call(this)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/days-in-month.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/days-in-month.js new file mode 100644 index 00000000000000..e780efe3c7f99e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/days-in-month.js @@ -0,0 +1,17 @@ +'use strict'; + +var getMonth = Date.prototype.getMonth; + +module.exports = function () { + switch (getMonth.call(this)) { + case 1: + return this.getFullYear() % 4 ? 28 : 29; + case 3: + case 5: + case 8: + case 10: + return 30; + default: + return 31; + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-day.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-day.js new file mode 100644 index 00000000000000..0c9eb8b62788cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-day.js @@ -0,0 +1,8 @@ +'use strict'; + +var setHours = Date.prototype.setHours; + +module.exports = function () { + setHours.call(this, 0, 0, 0, 0); + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-month.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-month.js new file mode 100644 index 00000000000000..7328c250b36506 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-month.js @@ -0,0 +1,8 @@ +'use strict'; + +var floorDay = require('./floor-day'); + +module.exports = function () { + floorDay.call(this).setDate(1); + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-year.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-year.js new file mode 100644 index 00000000000000..9c5085389fbf67 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/floor-year.js @@ -0,0 +1,8 @@ +'use strict'; + +var floorMonth = require('./floor-month'); + +module.exports = function () { + floorMonth.call(this).setMonth(0); + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/format.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/format.js new file mode 100644 index 00000000000000..15bd95f7eddf21 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/format.js @@ -0,0 +1,21 @@ +'use strict'; + +var pad = require('../../number/#/pad') + , date = require('../valid-date') + + , format; + +format = require('../../string/format-method')({ + Y: function () { return String(this.getFullYear()); }, + y: function () { return String(this.getFullYear()).slice(-2); }, + m: function () { return pad.call(this.getMonth() + 1, 2); }, + d: function () { return pad.call(this.getDate(), 2); }, + H: function () { return pad.call(this.getHours(), 2); }, + M: function () { return pad.call(this.getMinutes(), 2); }, + S: function () { return pad.call(this.getSeconds(), 2); }, + L: function () { return pad.call(this.getMilliseconds(), 3); } +}); + +module.exports = function (pattern) { + return format.call(date(this), pattern); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/index.js new file mode 100644 index 00000000000000..f71b2950029e59 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/#/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + copy: require('./copy'), + daysInMonth: require('./days-in-month'), + floorDay: require('./floor-day'), + floorMonth: require('./floor-month'), + floorYear: require('./floor-year'), + format: require('./format') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/index.js new file mode 100644 index 00000000000000..eac33fbe6dddce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/index.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + isDate: require('./is-date'), + validDate: require('./valid-date') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/is-date.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/is-date.js new file mode 100644 index 00000000000000..6ba236ecbc0783 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/is-date.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(new Date()); + +module.exports = function (x) { + return (x && ((x instanceof Date) || (toString.call(x) === id))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/valid-date.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/valid-date.js new file mode 100644 index 00000000000000..7d1a9b60d4748a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/date/valid-date.js @@ -0,0 +1,8 @@ +'use strict'; + +var isDate = require('./is-date'); + +module.exports = function (x) { + if (!isDate(x)) throw new TypeError(x + " is not a Date object"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/#/index.js new file mode 100644 index 00000000000000..b984aa91fef8b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/#/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + throw: require('./throw') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/#/throw.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/#/throw.js new file mode 100644 index 00000000000000..7e15ebd1cf028b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/#/throw.js @@ -0,0 +1,5 @@ +'use strict'; + +var error = require('../valid-error'); + +module.exports = function () { throw error(this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/custom.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/custom.js new file mode 100644 index 00000000000000..bbc2dc20b462b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/custom.js @@ -0,0 +1,20 @@ +'use strict'; + +var assign = require('../object/assign') + + , captureStackTrace = Error.captureStackTrace; + +exports = module.exports = function (message/*, code, ext*/) { + var err = new Error(), code = arguments[1], ext = arguments[2]; + if (ext == null) { + if (code && (typeof code === 'object')) { + ext = code; + code = null; + } + } + if (ext != null) assign(err, ext); + err.message = String(message); + if (code != null) err.code = String(code); + if (captureStackTrace) captureStackTrace(err, exports); + return err; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/index.js new file mode 100644 index 00000000000000..62984b52de0871 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + custom: require('./custom'), + isError: require('./is-error'), + validError: require('./valid-error') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/is-error.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/is-error.js new file mode 100644 index 00000000000000..422705faf71d2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/is-error.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(new Error()); + +module.exports = function (x) { + return (x && ((x instanceof Error) || (toString.call(x)) === id)) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/valid-error.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/valid-error.js new file mode 100644 index 00000000000000..0bef768a776d09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/error/valid-error.js @@ -0,0 +1,8 @@ +'use strict'; + +var isError = require('./is-error'); + +module.exports = function (x) { + if (!isError(x)) throw new TypeError(x + " is not an Error object"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/compose.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/compose.js new file mode 100644 index 00000000000000..1da5e01162dcf5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/compose.js @@ -0,0 +1,20 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , aFrom = require('../../array/from') + + , apply = Function.prototype.apply, call = Function.prototype.call + , callFn = function (arg, fn) { return call.call(fn, this, arg); }; + +module.exports = function (fn/*, …fnn*/) { + var fns, first; + if (!fn) callable(fn); + fns = [this].concat(aFrom(arguments)); + fns.forEach(callable); + fns = fns.reverse(); + first = fns[0]; + fns = fns.slice(1); + return function (arg) { + return fns.reduce(callFn, apply.call(first, this, arguments)); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/copy.js new file mode 100644 index 00000000000000..e1467f7671946c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/copy.js @@ -0,0 +1,15 @@ +'use strict'; + +var mixin = require('../../object/mixin') + , validFunction = require('../valid-function') + + , re = /^\s*function\s*([\0-'\)-\uffff]+)*\s*\(([\0-\(\*-\uffff]*)\)\s*\{/; + +module.exports = function () { + var match = String(validFunction(this)).match(re), fn; + + fn = new Function('fn', 'return function ' + match[1].trim() + '(' + + match[2] + ') { return fn.apply(this, arguments); };')(this); + try { mixin(fn, this); } catch (ignore) {} + return fn; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/curry.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/curry.js new file mode 100644 index 00000000000000..943d6faf860772 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/curry.js @@ -0,0 +1,24 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , defineLength = require('../_define-length') + + , slice = Array.prototype.slice, apply = Function.prototype.apply + , curry; + +curry = function self(fn, length, preArgs) { + return defineLength(function () { + var args = preArgs ? + preArgs.concat(slice.call(arguments, 0, length - preArgs.length)) : + slice.call(arguments, 0, length); + return (args.length === length) ? apply.call(fn, this, args) : + self(fn, length, args); + }, preArgs ? (length - preArgs.length) : length); +}; + +module.exports = function (/*length*/) { + var length = arguments[0]; + return curry(callable(this), + isNaN(length) ? toPosInt(this.length) : toPosInt(length)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/index.js new file mode 100644 index 00000000000000..8d0da007fa182b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/index.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + compose: require('./compose'), + copy: require('./copy'), + curry: require('./curry'), + lock: require('./lock'), + not: require('./not'), + partial: require('./partial'), + spread: require('./spread'), + toStringTokens: require('./to-string-tokens') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/lock.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/lock.js new file mode 100644 index 00000000000000..91e1a65cd91887 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/lock.js @@ -0,0 +1,12 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + + , apply = Function.prototype.apply; + +module.exports = function (/*…args*/) { + var fn = callable(this) + , args = arguments; + + return function () { return apply.call(fn, this, args); }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/not.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/not.js new file mode 100644 index 00000000000000..c6dbe97fb6ecd9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/not.js @@ -0,0 +1,14 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , defineLength = require('../_define-length') + + , apply = Function.prototype.apply; + +module.exports = function () { + var fn = callable(this); + + return defineLength(function () { + return !apply.call(fn, this, arguments); + }, fn.length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/partial.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/partial.js new file mode 100644 index 00000000000000..bf31a3575a56df --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/partial.js @@ -0,0 +1,16 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , aFrom = require('../../array/from') + , defineLength = require('../_define-length') + + , apply = Function.prototype.apply; + +module.exports = function (/*…args*/) { + var fn = callable(this) + , args = aFrom(arguments); + + return defineLength(function () { + return apply.call(fn, this, args.concat(aFrom(arguments))); + }, fn.length - args.length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/spread.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/spread.js new file mode 100644 index 00000000000000..d7c93b7e07ee15 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/spread.js @@ -0,0 +1,10 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + + , apply = Function.prototype.apply; + +module.exports = function () { + var fn = callable(this); + return function (args) { return apply.call(fn, this, args); }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/to-string-tokens.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/to-string-tokens.js new file mode 100644 index 00000000000000..67afeae82def7e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/#/to-string-tokens.js @@ -0,0 +1,11 @@ +'use strict'; + +var validFunction = require('../valid-function') + + , re = new RegExp('^\\s*function[\\0-\'\\)-\\uffff]*' + + '\\(([\\0-\\(\\*-\\uffff]*)\\)\\s*\\{([\\0-\\uffff]*)\\}\\s*$'); + +module.exports = function () { + var data = String(validFunction(this)).match(re); + return { args: data[1], body: data[2] }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/_define-length.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/_define-length.js new file mode 100644 index 00000000000000..496ea62c52b612 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/_define-length.js @@ -0,0 +1,44 @@ +'use strict'; + +var toPosInt = require('../number/to-pos-integer') + + , test = function (a, b) {}, desc, defineProperty + , generate, mixin; + +try { + Object.defineProperty(test, 'length', { configurable: true, writable: false, + enumerable: false, value: 1 }); +} catch (ignore) {} + +if (test.length === 1) { + // ES6 + desc = { configurable: true, writable: false, enumerable: false }; + defineProperty = Object.defineProperty; + module.exports = function (fn, length) { + length = toPosInt(length); + if (fn.length === length) return fn; + desc.value = length; + return defineProperty(fn, 'length', desc); + }; +} else { + mixin = require('../object/mixin'); + generate = (function () { + var cache = []; + return function (l) { + var args, i = 0; + if (cache[l]) return cache[l]; + args = []; + while (l--) args.push('a' + (++i).toString(36)); + return new Function('fn', 'return function (' + args.join(', ') + + ') { return fn.apply(this, arguments); };'); + }; + }()); + module.exports = function (src, length) { + var target; + length = toPosInt(length); + if (src.length === length) return src; + target = generate(length)(src); + try { mixin(target, src); } catch (ignore) {} + return target; + }; +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/constant.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/constant.js new file mode 100644 index 00000000000000..10f1e203e2d023 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/constant.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x) { + return function () { return x; }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/identity.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/identity.js new file mode 100644 index 00000000000000..a9289f0b21dfac --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/identity.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (x) { return x; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/index.js new file mode 100644 index 00000000000000..cfad3f3ec25bf8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/index.js @@ -0,0 +1,15 @@ +// Export all modules. + +'use strict'; + +module.exports = { + '#': require('./#'), + constant: require('./constant'), + identity: require('./identity'), + invoke: require('./invoke'), + isArguments: require('./is-arguments'), + isFunction: require('./is-function'), + noop: require('./noop'), + pluck: require('./pluck'), + validFunction: require('./valid-function') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/invoke.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/invoke.js new file mode 100644 index 00000000000000..9195afddd8c1e8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/invoke.js @@ -0,0 +1,15 @@ +'use strict'; + +var isCallable = require('../object/is-callable') + , value = require('../object/valid-value') + + , slice = Array.prototype.slice, apply = Function.prototype.apply; + +module.exports = function (name/*, …args*/) { + var args = slice.call(arguments, 1), isFn = isCallable(name); + return function (obj) { + value(obj); + return apply.call(isFn ? name : obj[name], obj, + args.concat(slice.call(arguments, 1))); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/is-arguments.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/is-arguments.js new file mode 100644 index 00000000000000..9a29855f87dc6a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/is-arguments.js @@ -0,0 +1,7 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call((function () { return arguments; }())); + +module.exports = function (x) { return (toString.call(x) === id); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/is-function.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/is-function.js new file mode 100644 index 00000000000000..ab4399ce25e98b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/is-function.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(require('./noop')); + +module.exports = function (f) { + return (typeof f === "function") && (toString.call(f) === id); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/noop.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/noop.js new file mode 100644 index 00000000000000..aa43baedf1d5d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/noop.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function () {}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/pluck.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/pluck.js new file mode 100644 index 00000000000000..7f70a30cbd95ee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/pluck.js @@ -0,0 +1,7 @@ +'use strict'; + +var value = require('../object/valid-value'); + +module.exports = function (name) { + return function (o) { return value(o)[name]; }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/valid-function.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/valid-function.js new file mode 100644 index 00000000000000..05fdee2c3debda --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/function/valid-function.js @@ -0,0 +1,8 @@ +'use strict'; + +var isFunction = require('./is-function'); + +module.exports = function (x) { + if (!isFunction(x)) throw new TypeError(x + " is not a function"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/global.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/global.js new file mode 100644 index 00000000000000..872a40e814be44 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/global.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = new Function("return this")(); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/index.js new file mode 100644 index 00000000000000..db9a7600b47115 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/index.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + global: require('./global'), + + array: require('./array'), + boolean: require('./boolean'), + date: require('./date'), + error: require('./error'), + function: require('./function'), + iterable: require('./iterable'), + math: require('./math'), + number: require('./number'), + object: require('./object'), + regExp: require('./reg-exp'), + string: require('./string') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/for-each.js new file mode 100644 index 00000000000000..f1e20425b329a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/for-each.js @@ -0,0 +1,12 @@ +'use strict'; + +var forOf = require('es6-iterator/for-of') + , isIterable = require('es6-iterator/is-iterable') + , iterable = require('./validate') + + , forEach = Array.prototype.forEach; + +module.exports = function (target, cb/*, thisArg*/) { + if (isIterable(iterable(target))) forOf(target, cb, arguments[2]); + else forEach.call(target, cb, arguments[2]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/index.js new file mode 100644 index 00000000000000..a3e16a5e892c6c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + forEach: require('./for-each'), + is: require('./is'), + validate: require('./validate'), + validateObject: require('./validate-object') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/is.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/is.js new file mode 100644 index 00000000000000..bb8bf287276bee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/is.js @@ -0,0 +1,10 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , isArrayLike = require('../object/is-array-like'); + +module.exports = function (x) { + if (x == null) return false; + if (typeof x[iteratorSymbol] === 'function') return true; + return isArrayLike(x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/validate-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/validate-object.js new file mode 100644 index 00000000000000..988a6adb6249e7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/validate-object.js @@ -0,0 +1,9 @@ +'use strict'; + +var isObject = require('../object/is-object') + , is = require('./is'); + +module.exports = function (x) { + if (is(x) && isObject(x)) return x; + throw new TypeError(x + " is not an iterable or array-like object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/validate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/validate.js new file mode 100644 index 00000000000000..1be6d7fcd96e44 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/iterable/validate.js @@ -0,0 +1,8 @@ +'use strict'; + +var is = require('./is'); + +module.exports = function (x) { + if (is(x)) return x; + throw new TypeError(x + " is not an iterable or array-like"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/_pack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/_pack-ieee754.js new file mode 100644 index 00000000000000..eecda5654dad51 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/_pack-ieee754.js @@ -0,0 +1,82 @@ +// Credit: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min + , pow = Math.pow, LN2 = Math.LN2 + , roundToEven; + +roundToEven = function (n) { + var w = floor(n), f = n - w; + if (f < 0.5) return w; + if (f > 0.5) return w + 1; + return w % 2 ? w + 1 : w; +}; + +module.exports = function (v, ebits, fbits) { + var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes; + + // Compute sign, exponent, fraction + if (isNaN(v)) { + // NaN + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping + e = (1 << ebits) - 1; + f = pow(2, fbits - 1); + s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; + f = 0; + s = (v < 0) ? 1 : 0; + } else if (v === 0) { + e = 0; + f = 0; + s = (1 / v === -Infinity) ? 1 : 0; + } else { + s = v < 0; + v = abs(v); + + if (v >= pow(2, 1 - bias)) { + e = min(floor(log(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + // Overflow + e = (1 << ebits) - 1; + f = 0; + } else { + // Normal + e = e + bias; + f = f - pow(2, fbits); + } + } else { + // Subnormal + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } + + // Pack sign, exponent, fraction + bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + + // Bits to bytes + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/_unpack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/_unpack-ieee754.js new file mode 100644 index 00000000000000..c9f26f2bb6f12e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/_unpack-ieee754.js @@ -0,0 +1,33 @@ +// Credit: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var pow = Math.pow; + +module.exports = function (bytes, ebits, fbits) { + // Bytes to bits + var bits = [], i, j, b, str, + bias, s, e, f; + + for (i = bytes.length; i; i -= 1) { + b = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b % 2 ? 1 : 0); + b = b >> 1; + } + } + bits.reverse(); + str = bits.join(''); + + // Unpack sign, exponent, fraction + bias = (1 << (ebits - 1)) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) return f !== 0 ? NaN : s * Infinity; + if (e > 0) return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + if (f !== 0) return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + return s < 0 ? -0 : 0; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/implement.js new file mode 100644 index 00000000000000..f48ad11de722a1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'acosh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/index.js new file mode 100644 index 00000000000000..00ddea69dd7a46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.acosh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/is-implemented.js new file mode 100644 index 00000000000000..363f0d8bcdd61b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var acosh = Math.acosh; + if (typeof acosh !== 'function') return false; + return acosh(2) === 1.3169578969248166; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/shim.js new file mode 100644 index 00000000000000..89a24b5d767e18 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/acosh/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var log = Math.log, sqrt = Math.sqrt; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < 1) return NaN; + if (x === 1) return 0; + if (x === Infinity) return x; + return log(x + sqrt(x * x - 1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/implement.js new file mode 100644 index 00000000000000..21f64d50491960 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'asinh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/index.js new file mode 100644 index 00000000000000..d415144eea7373 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.asinh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/is-implemented.js new file mode 100644 index 00000000000000..6c205f418cae9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var asinh = Math.asinh; + if (typeof asinh !== 'function') return false; + return asinh(2) === 1.4436354751788103; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/shim.js new file mode 100644 index 00000000000000..42fbf1457f7604 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/asinh/shim.js @@ -0,0 +1,15 @@ +'use strict'; + +var log = Math.log, sqrt = Math.sqrt; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + if (x < 0) { + x = -x; + return -log(x + sqrt(x * x + 1)); + } + return log(x + sqrt(x * x + 1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/implement.js new file mode 100644 index 00000000000000..1a4851343b3196 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'atanh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/index.js new file mode 100644 index 00000000000000..785b3deba5eb11 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.atanh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/is-implemented.js new file mode 100644 index 00000000000000..dbaf18ece2d2b0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var atanh = Math.atanh; + if (typeof atanh !== 'function') return false; + return atanh(0.5) === 0.5493061443340549; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/shim.js new file mode 100644 index 00000000000000..531e2891fe2f67 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/atanh/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var log = Math.log; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < -1) return NaN; + if (x > 1) return NaN; + if (x === -1) return -Infinity; + if (x === 1) return Infinity; + if (x === 0) return x; + return 0.5 * log((1 + x) / (1 - x)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/implement.js new file mode 100644 index 00000000000000..3a12dde487eba3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'cbrt', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/index.js new file mode 100644 index 00000000000000..89f966dfe4ed1a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.cbrt + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/is-implemented.js new file mode 100644 index 00000000000000..69809f3cf4956d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var cbrt = Math.cbrt; + if (typeof cbrt !== 'function') return false; + return cbrt(2) === 1.2599210498948732; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/shim.js new file mode 100644 index 00000000000000..bca196026c730a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cbrt/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var pow = Math.pow; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + if (x < 0) return -pow(-x, 1 / 3); + return pow(x, 1 / 3); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/implement.js new file mode 100644 index 00000000000000..339df33ea71822 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'clz32', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/index.js new file mode 100644 index 00000000000000..1687b337e3bdf9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.clz32 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/is-implemented.js new file mode 100644 index 00000000000000..ccc8f71337bf29 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var clz32 = Math.clz32; + if (typeof clz32 !== 'function') return false; + return clz32(1000) === 22; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/shim.js new file mode 100644 index 00000000000000..2a582da3bf0b31 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/clz32/shim.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (value) { + value = value >>> 0; + return value ? 32 - value.toString(2).length : 32; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/implement.js new file mode 100644 index 00000000000000..f90d83056c8b62 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'cosh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/index.js new file mode 100644 index 00000000000000..000636ab774ae5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.cosh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/is-implemented.js new file mode 100644 index 00000000000000..c796bcbf314f05 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var cosh = Math.cosh; + if (typeof cosh !== 'function') return false; + return cosh(1) === 1.5430806348152437; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/shim.js new file mode 100644 index 00000000000000..f9062bd976c693 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/cosh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +var exp = Math.exp; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return 1; + if (!isFinite(x)) return Infinity; + return (exp(x) + exp(-x)) / 2; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/implement.js new file mode 100644 index 00000000000000..fc20c8cfa068c4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'expm1', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/index.js new file mode 100644 index 00000000000000..4c1bc77a222f78 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.expm1 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/is-implemented.js new file mode 100644 index 00000000000000..3b106d5d535858 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var expm1 = Math.expm1; + if (typeof expm1 !== 'function') return false; + return expm1(1).toFixed(15) === '1.718281828459045'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/shim.js new file mode 100644 index 00000000000000..9c8c2360857e59 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/expm1/shim.js @@ -0,0 +1,16 @@ +// Thanks: https://github.com/monolithed/ECMAScript-6 + +'use strict'; + +var exp = Math.exp; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (x === Infinity) return Infinity; + if (x === -Infinity) return -1; + + if ((x > -1.0e-6) && (x < 1.0e-6)) return x + x * x / 2; + return exp(x) - 1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/implement.js new file mode 100644 index 00000000000000..c55b26c464bce5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'fround', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/index.js new file mode 100644 index 00000000000000..a077ed0ba33aa7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.fround + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/is-implemented.js new file mode 100644 index 00000000000000..ffbf094e6b3447 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var fround = Math.fround; + if (typeof fround !== 'function') return false; + return fround(1.337) === 1.3370000123977661; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/shim.js new file mode 100644 index 00000000000000..f2c86e46a41c7a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/fround/shim.js @@ -0,0 +1,33 @@ +// Credit: https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js + +'use strict'; + +var toFloat32; + +if (typeof Float32Array !== 'undefined') { + toFloat32 = (function () { + var float32Array = new Float32Array(1); + return function (x) { + float32Array[0] = x; + return float32Array[0]; + }; + }()); +} else { + toFloat32 = (function () { + var pack = require('../_pack-ieee754') + , unpack = require('../_unpack-ieee754'); + + return function (x) { + return unpack(pack(x, 8, 23), 8, 23); + }; + }()); +} + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + + return toFloat32(x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/implement.js new file mode 100644 index 00000000000000..b27fda7a0961b9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'hypot', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/index.js new file mode 100644 index 00000000000000..334bc584cf7778 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.hypot + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/is-implemented.js new file mode 100644 index 00000000000000..e75c5d36be34c8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var hypot = Math.hypot; + if (typeof hypot !== 'function') return false; + return hypot(3, 4) === 5; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/shim.js new file mode 100644 index 00000000000000..3d0988bc13dd4e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/hypot/shim.js @@ -0,0 +1,34 @@ +// Thanks for hints: https://github.com/paulmillr/es6-shim + +'use strict'; + +var some = Array.prototype.some, abs = Math.abs, sqrt = Math.sqrt + + , compare = function (a, b) { return b - a; } + , divide = function (x) { return x / this; } + , add = function (sum, number) { return sum + number * number; }; + +module.exports = function (val1, val2/*, …valn*/) { + var result, numbers; + if (!arguments.length) return 0; + some.call(arguments, function (val) { + if (isNaN(val)) { + result = NaN; + return; + } + if (!isFinite(val)) { + result = Infinity; + return true; + } + if (result !== undefined) return; + val = Number(val); + if (val === 0) return; + if (!numbers) numbers = [abs(val)]; + else numbers.push(abs(val)); + }); + if (result !== undefined) return result; + if (!numbers) return 0; + + numbers.sort(compare); + return numbers[0] * sqrt(numbers.map(divide, numbers[0]).reduce(add, 0)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/implement.js new file mode 100644 index 00000000000000..ed207bd271f7f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'imul', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/index.js new file mode 100644 index 00000000000000..41e5d5f010383f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.imul + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/is-implemented.js new file mode 100644 index 00000000000000..d8495dea2a8ec9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var imul = Math.imul; + if (typeof imul !== 'function') return false; + return imul(-1, 8) === -8; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/shim.js new file mode 100644 index 00000000000000..8fd8a8d7a79111 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/imul/shim.js @@ -0,0 +1,13 @@ +// Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference +// /Global_Objects/Math/imul + +'use strict'; + +module.exports = function (x, y) { + var xh = (x >>> 16) & 0xffff, xl = x & 0xffff + , yh = (y >>> 16) & 0xffff, yl = y & 0xffff; + + // the shift by 0 fixes the sign on the high part + // the final |0 converts the unsigned value into a signed value + return ((xl * yl) + (((xh * yl + xl * yh) << 16) >>> 0) | 0); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/index.js new file mode 100644 index 00000000000000..d112d0bfe0d04d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/index.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = { + acosh: require('./acosh'), + asinh: require('./asinh'), + atanh: require('./atanh'), + cbrt: require('./cbrt'), + clz32: require('./clz32'), + cosh: require('./cosh'), + expm1: require('./expm1'), + fround: require('./fround'), + hypot: require('./hypot'), + imul: require('./imul'), + log10: require('./log10'), + log2: require('./log2'), + log1p: require('./log1p'), + sign: require('./sign'), + sinh: require('./sinh'), + tanh: require('./tanh'), + trunc: require('./trunc') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/implement.js new file mode 100644 index 00000000000000..dd96edd80e0f20 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'log10', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/index.js new file mode 100644 index 00000000000000..a9eee513130691 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.log10 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/is-implemented.js new file mode 100644 index 00000000000000..c7f40ee7753bef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var log10 = Math.log10; + if (typeof log10 !== 'function') return false; + return log10(2) === 0.3010299956639812; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/shim.js new file mode 100644 index 00000000000000..fc77287f6176ff --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log10/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var log = Math.log, LOG10E = Math.LOG10E; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < 0) return NaN; + if (x === 0) return -Infinity; + if (x === 1) return 0; + if (x === Infinity) return Infinity; + + return log(x) * LOG10E; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/implement.js new file mode 100644 index 00000000000000..f62f91f6877d5b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'log1p', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/index.js new file mode 100644 index 00000000000000..107b114713cb57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.log1p + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/is-implemented.js new file mode 100644 index 00000000000000..61e90974c5f5e0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var log1p = Math.log1p; + if (typeof log1p !== 'function') return false; + return log1p(1) === 0.6931471805599453; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/shim.js new file mode 100644 index 00000000000000..10acebca4ab9af --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log1p/shim.js @@ -0,0 +1,17 @@ +// Thanks: https://github.com/monolithed/ECMAScript-6/blob/master/ES6.js + +'use strict'; + +var log = Math.log; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < -1) return NaN; + if (x === -1) return -Infinity; + if (x === 0) return x; + if (x === Infinity) return Infinity; + + if (x > -1.0e-8 && x < 1.0e-8) return (x - x * x / 2); + return log(1 + x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/implement.js new file mode 100644 index 00000000000000..8483f0950aa965 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'log2', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/index.js new file mode 100644 index 00000000000000..87e9050abe0895 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.log2 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/is-implemented.js new file mode 100644 index 00000000000000..802322faf38e32 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var log2 = Math.log2; + if (typeof log2 !== 'function') return false; + return log2(3).toFixed(15) === '1.584962500721156'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/shim.js new file mode 100644 index 00000000000000..cd80994a72b7d5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/log2/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var log = Math.log, LOG2E = Math.LOG2E; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < 0) return NaN; + if (x === 0) return -Infinity; + if (x === 1) return 0; + if (x === Infinity) return Infinity; + + return log(x) * LOG2E; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/implement.js new file mode 100644 index 00000000000000..b0db2f413fa598 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'sign', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/index.js new file mode 100644 index 00000000000000..b2326333432fcb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sign + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/is-implemented.js new file mode 100644 index 00000000000000..6d0de475aba61e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var sign = Math.sign; + if (typeof sign !== 'function') return false; + return ((sign(10) === 1) && (sign(-20) === -1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/shim.js new file mode 100644 index 00000000000000..4df9c95aa5d64f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sign/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return (value > 0) ? 1 : -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/implement.js new file mode 100644 index 00000000000000..f259a631b5718a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'sinh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/index.js new file mode 100644 index 00000000000000..e5bea572f838d6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sinh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/is-implemented.js new file mode 100644 index 00000000000000..888ec67a9c8cd8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var sinh = Math.sinh; + if (typeof sinh !== 'function') return false; + return ((sinh(1) === 1.1752011936438014) && (sinh(Number.MIN_VALUE) === 5e-324)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/shim.js new file mode 100644 index 00000000000000..5b725bed656d95 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/sinh/shim.js @@ -0,0 +1,17 @@ +// Parts of implementation taken from es6-shim project +// See: https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js + +'use strict'; + +var expm1 = require('../expm1') + + , abs = Math.abs, exp = Math.exp, e = Math.E; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + if (abs(x) < 1) return (expm1(x) - expm1(-x)) / 2; + return (exp(x - 1) - exp(-x - 1)) * e / 2; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/implement.js new file mode 100644 index 00000000000000..5199a029c88b7e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'tanh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/index.js new file mode 100644 index 00000000000000..6099c408a82be9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.tanh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/is-implemented.js new file mode 100644 index 00000000000000..a7d22237136416 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var tanh = Math.tanh; + if (typeof tanh !== 'function') return false; + return ((tanh(1) === 0.7615941559557649) && (tanh(Number.MAX_VALUE) === 1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/shim.js new file mode 100644 index 00000000000000..f6e948f2c53797 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/tanh/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +var exp = Math.exp; + +module.exports = function (x) { + var a, b; + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (x === Infinity) return 1; + if (x === -Infinity) return -1; + a = exp(x); + if (a === Infinity) return 1; + b = exp(-x); + if (b === Infinity) return -1; + return (a - b) / (a + b); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/implement.js new file mode 100644 index 00000000000000..3ee80ab2a0a0b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'trunc', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/index.js new file mode 100644 index 00000000000000..0b0f9b2ac93882 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.trunc + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/is-implemented.js new file mode 100644 index 00000000000000..3e8cde1f0053dd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var trunc = Math.trunc; + if (typeof trunc !== 'function') return false; + return (trunc(13.67) === 13) && (trunc(-13.67) === -13); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/shim.js new file mode 100644 index 00000000000000..02e2c2ad3bfcf4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/math/trunc/shim.js @@ -0,0 +1,13 @@ +'use strict'; + +var floor = Math.floor; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (x === Infinity) return Infinity; + if (x === -Infinity) return -Infinity; + if (x > 0) return floor(x); + return -floor(-x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.lint new file mode 100644 index 00000000000000..1851752f99bfda --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.lint @@ -0,0 +1,13 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus +newcap +vars diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.travis.yml new file mode 100644 index 00000000000000..afd3509a26b27d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-symbol@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/CHANGES new file mode 100644 index 00000000000000..df8c27efc38de2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/CHANGES @@ -0,0 +1,34 @@ +v2.0.1 -- 2015.01.28 +* Fix Symbol.prototype[Symbol.isPrimitive] implementation +* Improve validation within Symbol.prototype.toString and + Symbol.prototype.valueOf + +v2.0.0 -- 2015.01.28 +* Update up to changes in specification: + * Implement `for` and `keyFor` + * Remove `Symbol.create` and `Symbol.isRegExp` + * Add `Symbol.match`, `Symbol.replace`, `Symbol.search`, `Symbol.species` and + `Symbol.split` +* Rename `validSymbol` to `validateSymbol` +* Improve documentation +* Remove dead test modules + +v1.0.0 -- 2015.01.26 +* Fix enumerability for symbol properties set normally (e.g. obj[symbol] = value) +* Introduce initialization via hidden constructor +* Fix isSymbol handling of polyfill values when native Symbol is present +* Fix spelling of LICENSE +* Configure lint scripts + +v0.1.1 -- 2014.10.07 +* Fix isImplemented, so it returns true in case of polyfill +* Improve documentations + +v0.1.0 -- 2014.04.28 +* Assure strictly npm dependencies +* Update to use latest versions of dependencies +* Fix implementation detection so it doesn't crash on `String(symbol)` +* throw on `new Symbol()` (as decided by TC39) + +v0.0.0 -- 2013.11.15 +* Initial (dev) version \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/LICENSE new file mode 100644 index 00000000000000..04724a3ab1b70b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/README.md new file mode 100644 index 00000000000000..95d6780ba78cb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/README.md @@ -0,0 +1,71 @@ +# es6-symbol +## ECMAScript 6 Symbol polyfill + +For more information about symbols see following links +- [Symbols in ECMAScript 6 by Axel Rauschmayer](http://www.2ality.com/2014/12/es6-symbols.html) +- [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) +- [Specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-constructor) + +### Limitations + +Underneath it uses real string property names which can easily be retrieved, however accidental collision with other property names is unlikely. + +### Usage + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't (but without implementing `Symbol` on global scope), do: + +```javascript +var Symbol = require('es6-symbol'); +``` + +If you want to make sure your environment implements `Symbol`, do: + +```javascript +require('es6-symbol/implement'); +``` + +If you strictly want to use polyfill even if native `Symbol` exists (hard to find a good reason for that), do: + +```javascript +var Symbol = require('es6-symbol/polyfill'); +``` + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-objects). Still if you want quick look, follow examples: + +```javascript +var Symbol = require('es6-symbol'); + +var symbol = Symbol('My custom symbol'); +var x = {}; + +x[symbol] = 'foo'; +console.log(x[symbol]); 'foo' + +// Detect iterable: +var iterator, result; +if (possiblyIterable[Symbol.iterator]) { + iterator = possiblyIterable[Symbol.iterator](); + result = iterator.next(); + while(!result.done) { + console.log(result.value); + result = iterator.next(); + } +} +``` + +### Installation +#### NPM + +In your project path: + + $ npm install es6-symbol + +##### Browser + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-symbol.png)](https://travis-ci.org/medikoo/es6-symbol) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/implement.js new file mode 100644 index 00000000000000..153edacdbedf9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'Symbol', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/index.js new file mode 100644 index 00000000000000..609f1faf551164 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-implemented.js new file mode 100644 index 00000000000000..53759f32124b1c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-implemented.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + if (typeof Symbol.iterator === 'symbol') return true; + + // Return 'true' for polyfills + if (typeof Symbol.isConcatSpreadable !== 'object') return false; + if (typeof Symbol.iterator !== 'object') return false; + if (typeof Symbol.toPrimitive !== 'object') return false; + if (typeof Symbol.toStringTag !== 'object') return false; + if (typeof Symbol.unscopables !== 'object') return false; + + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-native-implemented.js new file mode 100644 index 00000000000000..a8cb8b8681ee69 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-native-implemented.js @@ -0,0 +1,8 @@ +// Exports true if environment provides native `Symbol` implementation + +'use strict'; + +module.exports = (function () { + if (typeof Symbol !== 'function') return false; + return (typeof Symbol.iterator === 'symbol'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-symbol.js new file mode 100644 index 00000000000000..beeba2cb4fa23f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/is-symbol.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x) { + return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/package.json new file mode 100644 index 00000000000000..0efffeaec90658 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/package.json @@ -0,0 +1,63 @@ +{ + "name": "es6-symbol", + "version": "2.0.1", + "description": "ECMAScript6 Symbol polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "symbol", + "private", + "property", + "es6", + "ecmascript", + "harmony" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-symbol.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.5" + }, + "devDependencies": { + "tad": "~0.2.1", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "51f6938d7830269fefa38f02eb912f5472b3ccd7", + "bugs": { + "url": "https://github.com/medikoo/es6-symbol/issues" + }, + "homepage": "https://github.com/medikoo/es6-symbol", + "_id": "es6-symbol@2.0.1", + "_shasum": "761b5c67cfd4f1d18afb234f691d678682cb3bf3", + "_from": "es6-symbol@>=2.0.1 <2.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "761b5c67cfd4f1d18afb234f691d678682cb3bf3", + "tarball": "http://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/polyfill.js new file mode 100644 index 00000000000000..735eb676b23c9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/polyfill.js @@ -0,0 +1,77 @@ +'use strict'; + +var d = require('d') + , validateSymbol = require('./validate-symbol') + + , create = Object.create, defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty, objPrototype = Object.prototype + , Symbol, HiddenSymbol, globalSymbols = create(null); + +var generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0, name; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + defineProperty(objPrototype, name, d.gs(null, function (value) { + defineProperty(this, name, d(value)); + })); + return name; + }; +}()); + +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); + return Symbol(description); +}; +module.exports = Symbol = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); + symbol = create(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: d('', description), + __name__: d('', generateName(description)) + }); +}; +defineProperties(Symbol, { + for: d(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = Symbol(String(key))); + }), + keyFor: d(function (s) { + var key; + validateSymbol(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + hasInstance: d('', Symbol('hasInstance')), + isConcatSpreadable: d('', Symbol('isConcatSpreadable')), + iterator: d('', Symbol('iterator')), + match: d('', Symbol('match')), + replace: d('', Symbol('replace')), + search: d('', Symbol('search')), + species: d('', Symbol('species')), + split: d('', Symbol('split')), + toPrimitive: d('', Symbol('toPrimitive')), + toStringTag: d('', Symbol('toStringTag')), + unscopables: d('', Symbol('unscopables')) +}); +defineProperties(HiddenSymbol.prototype, { + constructor: d(Symbol), + toString: d('', function () { return this.__name__; }) +}); + +defineProperties(Symbol.prototype, { + toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), + valueOf: d(function () { return validateSymbol(this); }) +}); +defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', + function () { return validateSymbol(this); })); +defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); + +defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, + d('c', Symbol.prototype[Symbol.toPrimitive])); +defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, + d('c', Symbol.prototype[Symbol.toStringTag])); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/implement.js new file mode 100644 index 00000000000000..eb35c3018835c7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof Symbol, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/index.js new file mode 100644 index 00000000000000..62b3296df6fc5e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var d = require('d') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-implemented.js new file mode 100644 index 00000000000000..bb0d64536ebbae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +var global = require('es5-ext/global') + , polyfill = require('../polyfill'); + +module.exports = function (t, a) { + var cache; + a(typeof t(), 'boolean'); + cache = global.Symbol; + global.Symbol = polyfill; + a(t(), true); + if (cache === undefined) delete global.Symbol; + else global.Symbol = cache; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-symbol.js new file mode 100644 index 00000000000000..ac24b9abbff4e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/is-symbol.js @@ -0,0 +1,16 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof Symbol !== 'undefined') { + a(t(Symbol()), true, "Native"); + } + a(t(SymbolPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/polyfill.js new file mode 100644 index 00000000000000..83fb5e9253677b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/polyfill.js @@ -0,0 +1,27 @@ +'use strict'; + +var d = require('d') + , isSymbol = require('../is-symbol') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); + a(x instanceof T, false); + + a(isSymbol(symbol), true, "Symbol"); + a(isSymbol(T.iterator), true, "iterator"); + a(isSymbol(T.toStringTag), true, "toStringTag"); + + x = {}; + x[symbol] = 'foo'; + a.deep(Object.getOwnPropertyDescriptor(x, symbol), { configurable: true, enumerable: false, + value: 'foo', writable: true }); + symbol = T.for('marko'); + a(isSymbol(symbol), true); + a(T.for('marko'), symbol); + a(T.keyFor(symbol), 'marko'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/validate-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/validate-symbol.js new file mode 100644 index 00000000000000..2c8f84c8239b6e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/test/validate-symbol.js @@ -0,0 +1,19 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + var symbol; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof Symbol !== 'undefined') { + symbol = Symbol(); + a(t(symbol), symbol, "Native"); + } + symbol = SymbolPoly(); + a(t(symbol), symbol, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/validate-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/validate-symbol.js new file mode 100644 index 00000000000000..42750043d4271c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/node_modules/es6-symbol/validate-symbol.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSymbol = require('./is-symbol'); + +module.exports = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/#/index.js new file mode 100644 index 00000000000000..324811704b80a0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/#/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + pad: require('./pad') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/#/pad.js new file mode 100644 index 00000000000000..4478f6a11e0c9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/#/pad.js @@ -0,0 +1,15 @@ +'use strict'; + +var pad = require('../../string/#/pad') + , toPosInt = require('../to-pos-integer') + + , toFixed = Number.prototype.toFixed; + +module.exports = function (length/*, precision*/) { + var precision; + length = toPosInt(length); + precision = toPosInt(arguments[1]); + + return pad.call(precision ? toFixed.call(this, precision) : this, + '0', length + (precision ? (1 + precision) : 0)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/implement.js new file mode 100644 index 00000000000000..f0a670ae33824b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'EPSILON', { value: require('./'), + configurable: false, enumerable: false, writable: false }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/index.js new file mode 100644 index 00000000000000..4e4b621b7bc6f5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = 2.220446049250313e-16; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/is-implemented.js new file mode 100644 index 00000000000000..141f5d2f24a512 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/epsilon/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return (typeof Number.EPSILON === 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/index.js new file mode 100644 index 00000000000000..35daf78eea88c2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/index.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + EPSILON: require('./epsilon'), + isFinite: require('./is-finite'), + isInteger: require('./is-integer'), + isNaN: require('./is-nan'), + isNumber: require('./is-number'), + isSafeInteger: require('./is-safe-integer'), + MAX_SAFE_INTEGER: require('./max-safe-integer'), + MIN_SAFE_INTEGER: require('./min-safe-integer'), + toInteger: require('./to-integer'), + toPosInteger: require('./to-pos-integer'), + toUint32: require('./to-uint32') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/implement.js new file mode 100644 index 00000000000000..51d7cac07adb71 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isFinite', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/index.js new file mode 100644 index 00000000000000..15d5f40588134c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isFinite + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/is-implemented.js new file mode 100644 index 00000000000000..556e396bb0b0fd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var isFinite = Number.isFinite; + if (typeof isFinite !== 'function') return false; + return !isFinite('23') && isFinite(34) && !isFinite(Infinity); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/shim.js new file mode 100644 index 00000000000000..e3aee551a7053a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-finite/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (value) { + return (typeof value === 'number') && isFinite(value); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/implement.js new file mode 100644 index 00000000000000..fe53f28143ad0c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isInteger', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/index.js new file mode 100644 index 00000000000000..55e039a99d6d97 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isInteger + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/is-implemented.js new file mode 100644 index 00000000000000..a0e573be7c299d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var isInteger = Number.isInteger; + if (typeof isInteger !== 'function') return false; + return !isInteger('23') && isInteger(34) && !isInteger(32.34); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/shim.js new file mode 100644 index 00000000000000..5402939806da40 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-integer/shim.js @@ -0,0 +1,8 @@ +// Credit: http://www.2ality.com/2014/05/is-integer.html + +'use strict'; + +module.exports = function (value) { + if (typeof value !== 'number') return false; + return (value % 1 === 0); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/implement.js new file mode 100644 index 00000000000000..e1c5deea36a653 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isNaN', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/index.js new file mode 100644 index 00000000000000..3b2c4ca6bd902a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isNaN + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/is-implemented.js new file mode 100644 index 00000000000000..4cf276656365ca --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var isNaN = Number.isNaN; + if (typeof isNaN !== 'function') return false; + return !isNaN({}) && isNaN(NaN) && !isNaN(34); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/shim.js new file mode 100644 index 00000000000000..070d96cd460d3a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-nan/shim.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (value) { return (value !== value); } //jslint: ignore diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-number.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-number.js new file mode 100644 index 00000000000000..19a99e4f194c2e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-number.js @@ -0,0 +1,11 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(1); + +module.exports = function (x) { + return ((typeof x === 'number') || + ((x instanceof Number) || + ((typeof x === 'object') && (toString.call(x) === id)))); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/implement.js new file mode 100644 index 00000000000000..51cef960212134 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isSafeInteger', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/index.js new file mode 100644 index 00000000000000..49adeaaf784e23 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isSafeInteger + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..510b60e4e4bd43 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + var isSafeInteger = Number.isSafeInteger; + if (typeof isSafeInteger !== 'function') return false; + return !isSafeInteger('23') && isSafeInteger(34232322323) && + !isSafeInteger(9007199254740992); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/shim.js new file mode 100644 index 00000000000000..692acdd6ca7799 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/is-safe-integer/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +var isInteger = require('../is-integer/shim') + , maxValue = require('../max-safe-integer') + + , abs = Math.abs; + +module.exports = function (value) { + if (!isInteger(value)) return false; + return abs(value) <= maxValue; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/implement.js new file mode 100644 index 00000000000000..4e0bb5741d926d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'MAX_SAFE_INTEGER', { value: require('./'), + configurable: false, enumerable: false, writable: false }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/index.js new file mode 100644 index 00000000000000..ed5d6a5379fe15 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = Math.pow(2, 53) - 1; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..7bd08a9da4edc5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/max-safe-integer/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return (typeof Number.MAX_SAFE_INTEGER === 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/implement.js new file mode 100644 index 00000000000000..e3f110e419162f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'MIN_SAFE_INTEGER', { value: require('./'), + configurable: false, enumerable: false, writable: false }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/index.js new file mode 100644 index 00000000000000..1c6cc2744efe14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = -(Math.pow(2, 53) - 1); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..efc9875f486d4a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/min-safe-integer/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return (typeof Number.MIN_SAFE_INTEGER === 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-integer.js new file mode 100644 index 00000000000000..60e798c5fda58d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-integer.js @@ -0,0 +1,12 @@ +'use strict'; + +var sign = require('../math/sign') + + , abs = Math.abs, floor = Math.floor; + +module.exports = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if ((value === 0) || !isFinite(value)) return value; + return sign(value) * floor(abs(value)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-pos-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-pos-integer.js new file mode 100644 index 00000000000000..605a302c7106f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-pos-integer.js @@ -0,0 +1,7 @@ +'use strict'; + +var toInteger = require('./to-integer') + + , max = Math.max; + +module.exports = function (value) { return max(0, toInteger(value)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-uint32.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-uint32.js new file mode 100644 index 00000000000000..6263e85ed6de95 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/number/to-uint32.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (value) { return value >>> 0; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/_iterate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/_iterate.js new file mode 100644 index 00000000000000..bf2c55d08601d3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/_iterate.js @@ -0,0 +1,29 @@ +// Internal method, used by iteration functions. +// Calls a function for each key-value pair found in object +// Optionally takes compareFn to iterate object in specific order + +'use strict'; + +var isCallable = require('./is-callable') + , callable = require('./valid-callable') + , value = require('./valid-value') + + , call = Function.prototype.call, keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (method, defVal) { + return function (obj, cb/*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(value(obj)); + callable(cb); + + list = keys(obj); + if (compareFn) { + list.sort(isCallable(compareFn) ? compareFn.bind(obj) : undefined); + } + return list[method](function (key, index) { + if (!propertyIsEnumerable.call(obj, key)) return defVal; + return call.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/implement.js new file mode 100644 index 00000000000000..3bcc68e31e1a44 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Object, 'assign', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/index.js new file mode 100644 index 00000000000000..ab0f9f249e81a8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.assign + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/is-implemented.js new file mode 100644 index 00000000000000..579ad2ddc433b9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function () { + var assign = Object.assign, obj; + if (typeof assign !== 'function') return false; + obj = { foo: 'raz' }; + assign(obj, { bar: 'dwa' }, { trzy: 'trzy' }); + return (obj.foo + obj.bar + obj.trzy) === 'razdwatrzy'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/shim.js new file mode 100644 index 00000000000000..74da11a86a8556 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/assign/shim.js @@ -0,0 +1,22 @@ +'use strict'; + +var keys = require('../keys') + , value = require('../valid-value') + + , max = Math.max; + +module.exports = function (dest, src/*, …srcn*/) { + var error, i, l = max(arguments.length, 2), assign; + dest = Object(value(dest)); + assign = function (key) { + try { dest[key] = src[key]; } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < l; ++i) { + src = arguments[i]; + keys(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/clear.js new file mode 100644 index 00000000000000..85e463728550d0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/clear.js @@ -0,0 +1,16 @@ +'use strict'; + +var keys = require('./keys'); + +module.exports = function (obj) { + var error; + keys(obj).forEach(function (key) { + try { + delete this[key]; + } catch (e) { + if (!error) error = e; + } + }, obj); + if (error !== undefined) throw error; + return obj; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/compact.js new file mode 100644 index 00000000000000..d021da457e3914 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/compact.js @@ -0,0 +1,7 @@ +'use strict'; + +var filter = require('./filter'); + +module.exports = function (obj) { + return filter(obj, function (val) { return val != null; }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/compare.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/compare.js new file mode 100644 index 00000000000000..2ab11f1a396350 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/compare.js @@ -0,0 +1,42 @@ +'use strict'; + +var strCompare = require('../string/#/case-insensitive-compare') + , isObject = require('./is-object') + + , resolve, typeMap; + +typeMap = { + undefined: 0, + object: 1, + boolean: 2, + string: 3, + number: 4 +}; + +resolve = function (a) { + if (isObject(a)) { + if (typeof a.valueOf !== 'function') return NaN; + a = a.valueOf(); + if (isObject(a)) { + if (typeof a.toString !== 'function') return NaN; + a = a.toString(); + if (typeof a !== 'string') return NaN; + } + } + return a; +}; + +module.exports = function (a, b) { + if (a === b) return 0; // Same + + a = resolve(a); + b = resolve(b); + if (a == b) return typeMap[typeof a] - typeMap[typeof b]; //jslint: ignore + if (a == null) return -1; + if (b == null) return 1; + if ((typeof a === 'string') || (typeof b === 'string')) { + return strCompare.call(a, b); + } + if ((a !== a) && (b !== b)) return 0; //jslint: ignore + return Number(a) - Number(b); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/copy-deep.js new file mode 100644 index 00000000000000..548e3ee4b66bac --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/copy-deep.js @@ -0,0 +1,30 @@ +'use strict'; + +var isPlainObject = require('./is-plain-object') + , value = require('./valid-value') + + , keys = Object.keys + , copy; + +copy = function (source) { + var target = {}; + this[0].push(source); + this[1].push(target); + keys(source).forEach(function (key) { + var index; + if (!isPlainObject(source[key])) { + target[key] = source[key]; + return; + } + index = this[0].indexOf(source[key]); + if (index === -1) target[key] = copy.call(this, source[key]); + else target[key] = this[1][index]; + }, this); + return target; +}; + +module.exports = function (source) { + var obj = Object(value(source)); + if (obj !== source) return obj; + return copy.call([[], []], obj); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/copy.js new file mode 100644 index 00000000000000..4d7177285fe5b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/copy.js @@ -0,0 +1,10 @@ +'use strict'; + +var assign = require('./assign') + , value = require('./valid-value'); + +module.exports = function (obj) { + var copy = Object(value(obj)); + if (copy !== obj) return copy; + return assign({}, obj); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/count.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/count.js new file mode 100644 index 00000000000000..29cfbb53fb40ae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/count.js @@ -0,0 +1,5 @@ +'use strict'; + +var keys = require('./keys'); + +module.exports = function (obj) { return keys(obj).length; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/create.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/create.js new file mode 100644 index 00000000000000..f813b4661c4498 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/create.js @@ -0,0 +1,36 @@ +// Workaround for http://code.google.com/p/v8/issues/detail?id=2804 + +'use strict'; + +var create = Object.create, shim; + +if (!require('./set-prototype-of/is-implemented')()) { + shim = require('./set-prototype-of/shim'); +} + +module.exports = (function () { + var nullObject, props, desc; + if (!shim) return create; + if (shim.level !== 1) return create; + + nullObject = {}; + props = {}; + desc = { configurable: false, enumerable: false, writable: true, + value: undefined }; + Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { + if (name === '__proto__') { + props[name] = { configurable: true, enumerable: false, writable: true, + value: undefined }; + return; + } + props[name] = desc; + }); + Object.defineProperties(nullObject, props); + + Object.defineProperty(shim, 'nullPolyfill', { configurable: false, + enumerable: false, writable: false, value: nullObject }); + + return function (prototype, props) { + return create((prototype === null) ? nullObject : prototype, props); + }; +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/eq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/eq.js new file mode 100644 index 00000000000000..037937ea6e9749 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/eq.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x, y) { + return ((x === y) || ((x !== x) && (y !== y))); //jslint: ignore +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/every.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/every.js new file mode 100644 index 00000000000000..1303db20958f8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/every.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_iterate')('every', true); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/filter.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/filter.js new file mode 100644 index 00000000000000..e5edb49b1b1610 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/filter.js @@ -0,0 +1,15 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + if (call.call(cb, thisArg, value, key, obj, index)) o[key] = obj[key]; + }); + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/first-key.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/first-key.js new file mode 100644 index 00000000000000..7df10b2f7f948d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/first-key.js @@ -0,0 +1,14 @@ +'use strict'; + +var value = require('./valid-value') + + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (obj) { + var i; + value(obj); + for (i in obj) { + if (propertyIsEnumerable.call(obj, i)) return i; + } + return null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/flatten.js new file mode 100644 index 00000000000000..e8b40444a94692 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/flatten.js @@ -0,0 +1,17 @@ +'use strict'; + +var isPlainObject = require('./is-plain-object') + , forEach = require('./for-each') + + , process; + +process = function self(value, key) { + if (isPlainObject(value)) forEach(value, self, this); + else this[key] = value; +}; + +module.exports = function (obj) { + var flattened = {}; + forEach(obj, process, flattened); + return flattened; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/for-each.js new file mode 100644 index 00000000000000..6674f8a614795b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/for-each.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_iterate')('forEach'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/get-property-names.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/get-property-names.js new file mode 100644 index 00000000000000..54a01e5047a392 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/get-property-names.js @@ -0,0 +1,18 @@ +'use strict'; + +var uniq = require('../array/#/uniq') + , value = require('./valid-value') + + , push = Array.prototype.push + , getOwnPropertyNames = Object.getOwnPropertyNames + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (obj) { + var keys; + obj = Object(value(obj)); + keys = getOwnPropertyNames(obj); + while ((obj = getPrototypeOf(obj))) { + push.apply(keys, getOwnPropertyNames(obj)); + } + return uniq.call(keys); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/index.js new file mode 100644 index 00000000000000..4bdf403583ace9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/index.js @@ -0,0 +1,48 @@ +'use strict'; + +module.exports = { + assign: require('./assign'), + clear: require('./clear'), + compact: require('./compact'), + compare: require('./compare'), + copy: require('./copy'), + copyDeep: require('./copy-deep'), + count: require('./count'), + create: require('./create'), + eq: require('./eq'), + every: require('./every'), + filter: require('./filter'), + firstKey: require('./first-key'), + flatten: require('./flatten'), + forEach: require('./for-each'), + getPropertyNames: require('./get-property-names'), + is: require('./is'), + isArrayLike: require('./is-array-like'), + isCallable: require('./is-callable'), + isCopy: require('./is-copy'), + isCopyDeep: require('./is-copy-deep'), + isEmpty: require('./is-empty'), + isObject: require('./is-object'), + isPlainObject: require('./is-plain-object'), + keyOf: require('./key-of'), + keys: require('./keys'), + map: require('./map'), + mapKeys: require('./map-keys'), + normalizeOptions: require('./normalize-options'), + mixin: require('./mixin'), + mixinPrototypes: require('./mixin-prototypes'), + primitiveSet: require('./primitive-set'), + safeTraverse: require('./safe-traverse'), + serialize: require('./serialize'), + setPrototypeOf: require('./set-prototype-of'), + some: require('./some'), + toArray: require('./to-array'), + unserialize: require('./unserialize'), + validateArrayLike: require('./validate-array-like'), + validateArrayLikeObject: require('./validate-array-like-object'), + validCallable: require('./valid-callable'), + validObject: require('./valid-object'), + validateStringifiable: require('./validate-stringifiable'), + validateStringifiableValue: require('./validate-stringifiable-value'), + validValue: require('./valid-value') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-array-like.js new file mode 100644 index 00000000000000..b8beed225b05ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-array-like.js @@ -0,0 +1,14 @@ +'use strict'; + +var isFunction = require('../function/is-function') + , isObject = require('./is-object'); + +module.exports = function (x) { + return ((x != null) && (typeof x.length === 'number') && + + // Just checking ((typeof x === 'object') && (typeof x !== 'function')) + // won't work right for some cases, e.g.: + // type of instance of NodeList in Safari is a 'function' + + ((isObject(x) && !isFunction(x)) || (typeof x === "string"))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-callable.js new file mode 100644 index 00000000000000..5d5d4b316b2a1c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-callable.js @@ -0,0 +1,5 @@ +// Deprecated + +'use strict'; + +module.exports = function (obj) { return typeof obj === 'function'; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-copy-deep.js new file mode 100644 index 00000000000000..c4b2b42b100836 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-copy-deep.js @@ -0,0 +1,58 @@ +'use strict'; + +var eq = require('./eq') + , isPlainObject = require('./is-plain-object') + , value = require('./valid-value') + + , isArray = Array.isArray, keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable + + , eqArr, eqVal, eqObj; + +eqArr = function (a, b, recMap) { + var i, l = a.length; + if (l !== b.length) return false; + for (i = 0; i < l; ++i) { + if (a.hasOwnProperty(i) !== b.hasOwnProperty(i)) return false; + if (!eqVal(a[i], b[i], recMap)) return false; + } + return true; +}; + +eqObj = function (a, b, recMap) { + var k1 = keys(a), k2 = keys(b); + if (k1.length !== k2.length) return false; + return k1.every(function (key) { + if (!propertyIsEnumerable.call(b, key)) return false; + return eqVal(a[key], b[key], recMap); + }); +}; + +eqVal = function (a, b, recMap) { + var i, eqX, c1, c2; + if (eq(a, b)) return true; + if (isPlainObject(a)) { + if (!isPlainObject(b)) return false; + eqX = eqObj; + } else if (isArray(a) && isArray(b)) { + eqX = eqArr; + } else { + return false; + } + c1 = recMap[0]; + c2 = recMap[1]; + i = c1.indexOf(a); + if (i !== -1) { + if (c2[i].indexOf(b) !== -1) return true; + } else { + i = c1.push(a) - 1; + c2[i] = []; + } + c2[i].push(b); + return eqX(a, b, recMap); +}; + +module.exports = function (a, b) { + if (eq(value(a), value(b))) return true; + return eqVal(Object(a), Object(b), [[], []]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-copy.js new file mode 100644 index 00000000000000..4fe639d4efcd2d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-copy.js @@ -0,0 +1,24 @@ +'use strict'; + +var eq = require('./eq') + , value = require('./valid-value') + + , keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (a, b) { + var k1, k2; + + if (eq(value(a), value(b))) return true; + + a = Object(a); + b = Object(b); + + k1 = keys(a); + k2 = keys(b); + if (k1.length !== k2.length) return false; + return k1.every(function (key) { + if (!propertyIsEnumerable.call(b, key)) return false; + return eq(a[key], b[key]); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-empty.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-empty.js new file mode 100644 index 00000000000000..7b51a87cf57e70 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-empty.js @@ -0,0 +1,14 @@ +'use strict'; + +var value = require('./valid-value') + + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (obj) { + var i; + value(obj); + for (i in obj) { //jslint: ignore + if (propertyIsEnumerable.call(obj, i)) return false; + } + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-object.js new file mode 100644 index 00000000000000..a86facf187a86f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-object.js @@ -0,0 +1,7 @@ +'use strict'; + +var map = { function: true, object: true }; + +module.exports = function (x) { + return ((x != null) && map[typeof x]) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-plain-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-plain-object.js new file mode 100644 index 00000000000000..9a2823198e746f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is-plain-object.js @@ -0,0 +1,20 @@ +'use strict'; + +var getPrototypeOf = Object.getPrototypeOf, prototype = Object.prototype + , toString = prototype.toString + + , id = Object().toString(); + +module.exports = function (value) { + var proto, constructor; + if (!value || (typeof value !== 'object') || (toString.call(value) !== id)) { + return false; + } + proto = getPrototypeOf(value); + if (proto === null) { + constructor = value.constructor; + if (typeof constructor !== 'function') return true; + return (constructor.prototype !== value); + } + return (proto === prototype) || (getPrototypeOf(proto) === null); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is.js new file mode 100644 index 00000000000000..5778b502d924cd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/is.js @@ -0,0 +1,10 @@ +// Implementation credits go to: +// http://wiki.ecmascript.org/doku.php?id=harmony:egal + +'use strict'; + +module.exports = function (x, y) { + return (x === y) ? + ((x !== 0) || ((1 / x) === (1 / y))) : + ((x !== x) && (y !== y)); //jslint: ignore +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/key-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/key-of.js new file mode 100644 index 00000000000000..8c44c8d8027f8b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/key-of.js @@ -0,0 +1,15 @@ +'use strict'; + +var eq = require('./eq') + , some = require('./some'); + +module.exports = function (obj, searchValue) { + var r; + return some(obj, function (value, name) { + if (eq(value, searchValue)) { + r = name; + return true; + } + return false; + }) ? r : null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/implement.js new file mode 100644 index 00000000000000..c6872bd02af0b2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Object, 'keys', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/index.js new file mode 100644 index 00000000000000..5ef052233a76e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.keys + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/is-implemented.js new file mode 100644 index 00000000000000..40c32c33940c7c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + try { + Object.keys('primitive'); + return true; + } catch (e) { return false; } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/shim.js new file mode 100644 index 00000000000000..034b6b2981185a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/keys/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +var keys = Object.keys; + +module.exports = function (object) { + return keys(object == null ? object : Object(object)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/map-keys.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/map-keys.js new file mode 100644 index 00000000000000..26f0ecacb8aef3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/map-keys.js @@ -0,0 +1,15 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + o[call.call(cb, thisArg, key, value, this, index)] = value; + }, obj); + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/map.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/map.js new file mode 100644 index 00000000000000..6b39d3c94b7421 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/map.js @@ -0,0 +1,15 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + o[key] = call.call(cb, thisArg, value, key, obj, index); + }); + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/mixin-prototypes.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/mixin-prototypes.js new file mode 100644 index 00000000000000..1ef5756423cd36 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/mixin-prototypes.js @@ -0,0 +1,34 @@ +'use strict'; + +var value = require('./valid-value') + , mixin = require('./mixin') + + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getOwnPropertyNames = Object.getOwnPropertyNames + , getPrototypeOf = Object.getPrototypeOf + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function (target, source) { + var error, end, define; + target = Object(value(target)); + source = Object(value(source)); + end = getPrototypeOf(target); + if (source === end) return target; + try { + mixin(target, source); + } catch (e) { error = e; } + source = getPrototypeOf(source); + define = function (name) { + if (hasOwnProperty.call(target, name)) return; + try { + defineProperty(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { error = e; } + }; + while (source && (source !== end)) { + getOwnPropertyNames(source).forEach(define); + source = getPrototypeOf(source); + } + if (error) throw error; + return target; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/mixin.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/mixin.js new file mode 100644 index 00000000000000..80b5df5e04b9b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/mixin.js @@ -0,0 +1,19 @@ +'use strict'; + +var value = require('./valid-value') + + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getOwnPropertyNames = Object.getOwnPropertyNames; + +module.exports = function (target, source) { + var error; + target = Object(value(target)); + getOwnPropertyNames(Object(value(source))).forEach(function (name) { + try { + defineProperty(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { error = e; } + }); + if (error !== undefined) throw error; + return target; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/normalize-options.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/normalize-options.js new file mode 100644 index 00000000000000..cf8ed8d38cabd1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/normalize-options.js @@ -0,0 +1,17 @@ +'use strict'; + +var forEach = Array.prototype.forEach, create = Object.create; + +var process = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +module.exports = function (options/*, …options*/) { + var result = create(null); + forEach.call(arguments, function (options) { + if (options == null) return; + process(Object(options), result); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/primitive-set.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/primitive-set.js new file mode 100644 index 00000000000000..ada109510d4bd9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/primitive-set.js @@ -0,0 +1,9 @@ +'use strict'; + +var forEach = Array.prototype.forEach, create = Object.create; + +module.exports = function (arg/*, …args*/) { + var set = create(null); + forEach.call(arguments, function (name) { set[name] = true; }); + return set; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/safe-traverse.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/safe-traverse.js new file mode 100644 index 00000000000000..7e1b5f41edf162 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/safe-traverse.js @@ -0,0 +1,15 @@ +'use strict'; + +var value = require('./valid-value'); + +module.exports = function (obj/*, …names*/) { + var length, current = 1; + value(obj); + length = arguments.length - 1; + if (!length) return obj; + while (current < length) { + obj = obj[arguments[current++]]; + if (obj == null) return undefined; + } + return obj[arguments[current]]; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/serialize.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/serialize.js new file mode 100644 index 00000000000000..8113b6801dd395 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/serialize.js @@ -0,0 +1,36 @@ +'use strict'; + +var toArray = require('./to-array') + , isDate = require('../date/is-date') + , isRegExp = require('../reg-exp/is-reg-exp') + + , isArray = Array.isArray, stringify = JSON.stringify + , keyValueToString = function (value, key) { return stringify(key) + ':' + exports(value); }; + +var sparseMap = function (arr) { + var i, l = arr.length, result = new Array(l); + for (i = 0; i < l; ++i) { + if (!arr.hasOwnProperty(i)) continue; + result[i] = exports(arr[i]); + } + return result; +}; + +module.exports = exports = function (obj) { + if (obj == null) return String(obj); + switch (typeof obj) { + case 'string': + return stringify(obj); + case 'number': + case 'boolean': + case 'function': + return String(obj); + case 'object': + if (isArray(obj)) return '[' + sparseMap(obj) + ']'; + if (isRegExp(obj)) return String(obj); + if (isDate(obj)) return 'new Date(' + obj.valueOf() + ')'; + return '{' + toArray(obj, keyValueToString) + '}'; + default: + throw new TypeError("Serialization of " + String(obj) + "is unsupported"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/implement.js new file mode 100644 index 00000000000000..000e6bdbbebcb7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/implement.js @@ -0,0 +1,8 @@ +'use strict'; + +var shim; + +if (!require('./is-implemented')() && (shim = require('./shim'))) { + Object.defineProperty(Object, 'setPrototypeOf', + { value: shim, configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/index.js new file mode 100644 index 00000000000000..ccc40995b1e6b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.setPrototypeOf + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/is-implemented.js new file mode 100644 index 00000000000000..98d0c8436a8d46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/is-implemented.js @@ -0,0 +1,11 @@ +'use strict'; + +var create = Object.create, getPrototypeOf = Object.getPrototypeOf + , x = {}; + +module.exports = function (/*customCreate*/) { + var setPrototypeOf = Object.setPrototypeOf + , customCreate = arguments[0] || create; + if (typeof setPrototypeOf !== 'function') return false; + return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/shim.js new file mode 100644 index 00000000000000..4ec944675e5685 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/set-prototype-of/shim.js @@ -0,0 +1,73 @@ +// Big thanks to @WebReflection for sorting this out +// https://gist.github.com/WebReflection/5593554 + +'use strict'; + +var isObject = require('../is-object') + , value = require('../valid-value') + + , isPrototypeOf = Object.prototype.isPrototypeOf + , defineProperty = Object.defineProperty + , nullDesc = { configurable: true, enumerable: false, writable: true, + value: undefined } + , validate; + +validate = function (obj, prototype) { + value(obj); + if ((prototype === null) || isObject(prototype)) return obj; + throw new TypeError('Prototype must be null or an object'); +}; + +module.exports = (function (status) { + var fn, set; + if (!status) return null; + if (status.level === 2) { + if (status.set) { + set = status.set; + fn = function (obj, prototype) { + set.call(validate(obj, prototype), prototype); + return obj; + }; + } else { + fn = function (obj, prototype) { + validate(obj, prototype).__proto__ = prototype; + return obj; + }; + } + } else { + fn = function self(obj, prototype) { + var isNullBase; + validate(obj, prototype); + isNullBase = isPrototypeOf.call(self.nullPolyfill, obj); + if (isNullBase) delete self.nullPolyfill.__proto__; + if (prototype === null) prototype = self.nullPolyfill; + obj.__proto__ = prototype; + if (isNullBase) defineProperty(self.nullPolyfill, '__proto__', nullDesc); + return obj; + }; + } + return Object.defineProperty(fn, 'level', { configurable: false, + enumerable: false, writable: false, value: status.level }); +}((function () { + var x = Object.create(null), y = {}, set + , desc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'); + + if (desc) { + try { + set = desc.set; // Opera crashes at this point + set.call(x, y); + } catch (ignore) { } + if (Object.getPrototypeOf(x) === y) return { set: set, level: 2 }; + } + + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 2 }; + + x = {}; + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 1 }; + + return false; +}()))); + +require('../create'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/some.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/some.js new file mode 100644 index 00000000000000..cde5ddeecdf749 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/some.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_iterate')('some', false); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/to-array.js new file mode 100644 index 00000000000000..a954abb26fdffd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/to-array.js @@ -0,0 +1,18 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call + + , defaultCb = function (value, key) { return [key, value]; }; + +module.exports = function (obj/*, cb, thisArg, compareFn*/) { + var a = [], cb = arguments[1], thisArg = arguments[2]; + cb = (cb == null) ? defaultCb : callable(cb); + + forEach(obj, function (value, key, obj, index) { + a.push(call.call(cb, thisArg, value, key, this, index)); + }, obj, arguments[3]); + return a; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/unserialize.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/unserialize.js new file mode 100644 index 00000000000000..ce68e403ae1b6e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/unserialize.js @@ -0,0 +1,7 @@ +'use strict'; + +var value = require('./valid-value'); + +module.exports = exports = function (code) { + return (new Function('return ' + value(code)))(); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-callable.js new file mode 100644 index 00000000000000..c977527a4fd660 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-callable.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-object.js new file mode 100644 index 00000000000000..f82bd51ed106f2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-object.js @@ -0,0 +1,8 @@ +'use strict'; + +var isObject = require('./is-object'); + +module.exports = function (value) { + if (!isObject(value)) throw new TypeError(value + " is not an Object"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-value.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-value.js new file mode 100644 index 00000000000000..36c8ec31e84731 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/valid-value.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (value) { + if (value == null) throw new TypeError("Cannot use null or undefined"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-array-like-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-array-like-object.js new file mode 100644 index 00000000000000..89e12c51c5dfcf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-array-like-object.js @@ -0,0 +1,9 @@ +'use strict'; + +var isArrayLike = require('./is-array-like') + , isObject = require('./is-object'); + +module.exports = function (obj) { + if (isObject(obj) && isArrayLike(obj)) return obj; + throw new TypeError(obj + " is not array-like object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-array-like.js new file mode 100644 index 00000000000000..6a35b54a14f677 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-array-like.js @@ -0,0 +1,8 @@ +'use strict'; + +var isArrayLike = require('./is-array-like'); + +module.exports = function (obj) { + if (isArrayLike(obj)) return obj; + throw new TypeError(obj + " is not array-like value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-stringifiable-value.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-stringifiable-value.js new file mode 100644 index 00000000000000..9df3b668fb06c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-stringifiable-value.js @@ -0,0 +1,6 @@ +'use strict'; + +var value = require('./valid-value') + , stringifiable = require('./validate-stringifiable'); + +module.exports = function (x) { return stringifiable(value(x)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-stringifiable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-stringifiable.js new file mode 100644 index 00000000000000..eba7ce787cdfad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/object/validate-stringifiable.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (stringifiable) { + try { + return String(stringifiable); + } catch (e) { + throw new TypeError("Passed argument cannot be stringifed"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/package.json new file mode 100644 index 00000000000000..01d6532749e89c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/package.json @@ -0,0 +1,74 @@ +{ + "name": "es5-ext", + "version": "0.10.7", + "description": "ECMAScript 5 extensions and ES6 shims", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "ecmascript", + "ecmascript5", + "ecmascript6", + "es5", + "es6", + "extensions", + "ext", + "addons", + "extras", + "harmony", + "javascript", + "polyfill", + "shim", + "util", + "utils", + "utilities" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es5-ext.git" + }, + "dependencies": { + "es6-iterator": "~0.1.3", + "es6-symbol": "~2.0.1" + }, + "devDependencies": { + "tad": "~0.2.2", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "5b63ee02f50dfbc70dc1f62bc66b8718af443f83", + "bugs": { + "url": "https://github.com/medikoo/es5-ext/issues" + }, + "homepage": "https://github.com/medikoo/es5-ext", + "_id": "es5-ext@0.10.7", + "_shasum": "dfaea50721301042e2d89c1719d43493fa821656", + "_from": "es5-ext@>=0.10.6 <0.11.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "dfaea50721301042e2d89c1719d43493fa821656", + "tarball": "http://registry.npmjs.org/es5-ext/-/es5-ext-0.10.7.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/index.js new file mode 100644 index 00000000000000..f7e7a58ebd780a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + isSticky: require('./is-sticky'), + isUnicode: require('./is-unicode'), + match: require('./match'), + replace: require('./replace'), + search: require('./search'), + split: require('./split') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/is-sticky.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/is-sticky.js new file mode 100644 index 00000000000000..830a481f7e9213 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/is-sticky.js @@ -0,0 +1,9 @@ +'use strict'; + +var validRegExp = require('../valid-reg-exp') + + , re = /\/[a-xz]*y[a-xz]*$/; + +module.exports = function () { + return Boolean(String(validRegExp(this)).match(re)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/is-unicode.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/is-unicode.js new file mode 100644 index 00000000000000..b005f6d9194f1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/is-unicode.js @@ -0,0 +1,9 @@ +'use strict'; + +var validRegExp = require('../valid-reg-exp') + + , re = /\/[a-xz]*u[a-xz]*$/; + +module.exports = function () { + return Boolean(String(validRegExp(this)).match(re)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/implement.js new file mode 100644 index 00000000000000..921c9368e780b6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'match', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/index.js new file mode 100644 index 00000000000000..0534ac3bc352b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.match + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/is-implemented.js new file mode 100644 index 00000000000000..b7e99643148089 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /foo/; + +module.exports = function () { + if (typeof re.match !== 'function') return false; + return re.match('barfoobar') && !re.match('elo'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/shim.js new file mode 100644 index 00000000000000..4f99cf4d1c02c5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/match/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string) { + validRegExp(this); + return String(string).match(this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/implement.js new file mode 100644 index 00000000000000..ad580de890618e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'replace', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/index.js new file mode 100644 index 00000000000000..5658177d804881 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.replace + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/is-implemented.js new file mode 100644 index 00000000000000..1b42d252430bd5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /foo/; + +module.exports = function () { + if (typeof re.replace !== 'function') return false; + return re.replace('foobar', 'mar') === 'marbar'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/shim.js new file mode 100644 index 00000000000000..c3e6aebab04cf3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/replace/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string, replaceValue) { + validRegExp(this); + return String(string).replace(this, replaceValue); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/implement.js new file mode 100644 index 00000000000000..3804f4eb1c3bb5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'search', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/index.js new file mode 100644 index 00000000000000..67995d4ac7b9f3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.search + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/is-implemented.js new file mode 100644 index 00000000000000..efba889f81724d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /foo/; + +module.exports = function () { + if (typeof re.search !== 'function') return false; + return re.search('barfoo') === 3; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/shim.js new file mode 100644 index 00000000000000..6d9dcaed8ab26f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/search/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string) { + validRegExp(this); + return String(string).search(this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/implement.js new file mode 100644 index 00000000000000..50facb6834d7c1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'split', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/index.js new file mode 100644 index 00000000000000..f101f5af7503cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.split + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/is-implemented.js new file mode 100644 index 00000000000000..7244c998bf45fd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /\|/; + +module.exports = function () { + if (typeof re.split !== 'function') return false; + return re.split('bar|foo')[1] === 'foo'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/shim.js new file mode 100644 index 00000000000000..76154e7e3c0069 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/split/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string) { + validRegExp(this); + return String(string).split(this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/sticky/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/sticky/implement.js new file mode 100644 index 00000000000000..7e8af1db31641b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/sticky/implement.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSticky = require('../is-sticky'); + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'sticky', { configurable: true, + enumerable: false, get: isSticky }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/sticky/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/sticky/is-implemented.js new file mode 100644 index 00000000000000..379c4a5a8fb1b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/sticky/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return RegExp.prototype.sticky === false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/unicode/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/unicode/implement.js new file mode 100644 index 00000000000000..5a82a4d1d23386 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/unicode/implement.js @@ -0,0 +1,8 @@ +'use strict'; + +var isUnicode = require('../is-unicode'); + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'unicode', { configurable: true, + enumerable: false, get: isUnicode }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/unicode/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/unicode/is-implemented.js new file mode 100644 index 00000000000000..a8b15b3b38defb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/#/unicode/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return RegExp.prototype.unicode === false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/escape.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/escape.js new file mode 100644 index 00000000000000..a2363fcfc68a03 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/escape.js @@ -0,0 +1,9 @@ +// Thanks to Andrew Clover: +// http://stackoverflow.com/questions/3561493 +// /is-there-a-regexp-escape-function-in-javascript + +'use strict'; + +var re = /[\-\/\\\^$*+?.()|\[\]{}]/g; + +module.exports = function (str) { return String(str).replace(re, '\\$&'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/index.js new file mode 100644 index 00000000000000..75ea3135a89afe --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + escape: require('./escape'), + isRegExp: require('./is-reg-exp'), + validRegExp: require('./valid-reg-exp') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/is-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/is-reg-exp.js new file mode 100644 index 00000000000000..6eb12977c031d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/is-reg-exp.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(/a/); + +module.exports = function (x) { + return (x && (x instanceof RegExp || (toString.call(x) === id))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/valid-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/valid-reg-exp.js new file mode 100644 index 00000000000000..d3a77641da0f86 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/reg-exp/valid-reg-exp.js @@ -0,0 +1,8 @@ +'use strict'; + +var isRegExp = require('./is-reg-exp'); + +module.exports = function (x) { + if (!isRegExp(x)) throw new TypeError(x + " is not a RegExp object"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/implement.js new file mode 100644 index 00000000000000..4494d7b6af3d93 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, require('es6-symbol').iterator, + { value: require('./shim'), configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/index.js new file mode 100644 index 00000000000000..22f15e69600bc0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype[require('es6-symbol').iterator] : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..f5c462deb91064 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/is-implemented.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function () { + var str = '🙈f', iterator, result; + if (typeof str[iteratorSymbol] !== 'function') return false; + iterator = str[iteratorSymbol](); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== '🙈') return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/shim.js new file mode 100644 index 00000000000000..0be30292f6e98d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/@@iterator/shim.js @@ -0,0 +1,6 @@ +'use strict'; + +var StringIterator = require('es6-iterator/string') + , value = require('../../../object/valid-value'); + +module.exports = function () { return new StringIterator(value(this)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/at.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/at.js new file mode 100644 index 00000000000000..77bd251ac4f1ae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/at.js @@ -0,0 +1,33 @@ +// Based on: https://github.com/mathiasbynens/String.prototype.at +// Thanks @mathiasbynens ! + +'use strict'; + +var toInteger = require('../../number/to-integer') + , validValue = require('../../object/valid-value'); + +module.exports = function (pos) { + var str = String(validValue(this)), size = str.length + , cuFirst, cuSecond, nextPos, len; + pos = toInteger(pos); + + // Account for out-of-bounds indices + // The odd lower bound is because the ToInteger operation is + // going to round `n` to `0` for `-1 < n <= 0`. + if (pos <= -1 || pos >= size) return ''; + + // Second half of `ToInteger` + pos = pos | 0; + // Get the first code unit and code unit value + cuFirst = str.charCodeAt(pos); + nextPos = pos + 1; + len = 1; + if ( // check if it’s the start of a surrogate pair + (cuFirst >= 0xD800) && (cuFirst <= 0xDBFF) && // high surrogate + (size > nextPos) // there is a next code unit + ) { + cuSecond = str.charCodeAt(nextPos); + if (cuSecond >= 0xDC00 && cuSecond <= 0xDFFF) len = 2; // low surrogate + } + return str.slice(pos, pos + len); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/camel-to-hyphen.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/camel-to-hyphen.js new file mode 100644 index 00000000000000..1cb8d127796d8b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/camel-to-hyphen.js @@ -0,0 +1,10 @@ +'use strict'; + +var replace = String.prototype.replace + , re = /([A-Z])/g; + +module.exports = function () { + var str = replace.call(this, re, "-$1").toLowerCase(); + if (str[0] === '-') str = str.slice(1); + return str; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/capitalize.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/capitalize.js new file mode 100644 index 00000000000000..ed768273651c9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/capitalize.js @@ -0,0 +1,8 @@ +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + var str = String(value(this)); + return str.charAt(0).toUpperCase() + str.slice(1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/case-insensitive-compare.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/case-insensitive-compare.js new file mode 100644 index 00000000000000..599cb83469c149 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/case-insensitive-compare.js @@ -0,0 +1,7 @@ +'use strict'; + +var toLowerCase = String.prototype.toLowerCase; + +module.exports = function (other) { + return toLowerCase.call(this).localeCompare(toLowerCase.call(String(other))); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/implement.js new file mode 100644 index 00000000000000..1e7a37bd4d34ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'codePointAt', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/index.js new file mode 100644 index 00000000000000..7e91d833a867e4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.codePointAt + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/is-implemented.js new file mode 100644 index 00000000000000..b27158913a91d1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'abc\uD834\uDF06def'; + +module.exports = function () { + if (typeof str.codePointAt !== 'function') return false; + return str.codePointAt(3) === 0x1D306; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/shim.js new file mode 100644 index 00000000000000..1c9038b3cb0a79 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/code-point-at/shim.js @@ -0,0 +1,26 @@ +// Based on: https://github.com/mathiasbynens/String.prototype.codePointAt +// Thanks @mathiasbynens ! + +'use strict'; + +var toInteger = require('../../../number/to-integer') + , validValue = require('../../../object/valid-value'); + +module.exports = function (pos) { + var str = String(validValue(this)), l = str.length, first, second; + pos = toInteger(pos); + + // Account for out-of-bounds indices: + if (pos < 0 || pos >= l) return undefined; + + // Get the first code unit + first = str.charCodeAt(pos); + if ((first >= 0xD800) && (first <= 0xDBFF) && (l > pos + 1)) { + second = str.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/implement.js new file mode 100644 index 00000000000000..6b7a3c08164c4e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'contains', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/index.js new file mode 100644 index 00000000000000..abb3e3730bf103 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.contains + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/is-implemented.js new file mode 100644 index 00000000000000..6f7d4b719e218e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.contains !== 'function') return false; + return ((str.contains('dwa') === true) && (str.contains('foo') === false)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/shim.js new file mode 100644 index 00000000000000..89e39e793324b7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/contains/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +var indexOf = String.prototype.indexOf; + +module.exports = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/implement.js new file mode 100644 index 00000000000000..0b09025b0cde8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'endsWith', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/index.js new file mode 100644 index 00000000000000..d2d9484827957e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.endsWith + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/is-implemented.js new file mode 100644 index 00000000000000..f3bb00883bb978 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.endsWith !== 'function') return false; + return ((str.endsWith('trzy') === true) && (str.endsWith('raz') === false)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/shim.js new file mode 100644 index 00000000000000..26cbdb1366be10 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/ends-with/shim.js @@ -0,0 +1,16 @@ +'use strict'; + +var toInteger = require('../../../number/to-integer') + , value = require('../../../object/valid-value') + + , min = Math.min, max = Math.max; + +module.exports = function (searchString/*, endPosition*/) { + var self, start, endPos; + self = String(value(this)); + searchString = String(searchString); + endPos = arguments[1]; + start = ((endPos == null) ? self.length : + min(max(toInteger(endPos), 0), self.length)) - searchString.length; + return (start < 0) ? false : (self.indexOf(searchString, start) === start); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/hyphen-to-camel.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/hyphen-to-camel.js new file mode 100644 index 00000000000000..8928b02497f1a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/hyphen-to-camel.js @@ -0,0 +1,8 @@ +'use strict'; + +var replace = String.prototype.replace + + , re = /-([a-z0-9])/g + , toUpperCase = function (m, a) { return a.toUpperCase(); }; + +module.exports = function () { return replace.call(this, re, toUpperCase); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/indent.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/indent.js new file mode 100644 index 00000000000000..223bd82b0f1a97 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/indent.js @@ -0,0 +1,12 @@ +'use strict'; + +var repeat = require('./repeat') + + , replace = String.prototype.replace + , re = /(\r\n|[\n\r\u2028\u2029])([\u0000-\u0009\u000b-\uffff]+)/g; + +module.exports = function (indent/*, count*/) { + var count = arguments[1]; + indent = repeat.call(String(indent), (count == null) ? 1 : count); + return indent + replace.call(this, re, '$1' + indent + '$2'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/index.js new file mode 100644 index 00000000000000..d45d747cbe0954 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/index.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = { + '@@iterator': require('./@@iterator'), + at: require('./at'), + camelToHyphen: require('./camel-to-hyphen'), + capitalize: require('./capitalize'), + caseInsensitiveCompare: require('./case-insensitive-compare'), + codePointAt: require('./code-point-at'), + contains: require('./contains'), + hyphenToCamel: require('./hyphen-to-camel'), + endsWith: require('./ends-with'), + indent: require('./indent'), + last: require('./last'), + normalize: require('./normalize'), + pad: require('./pad'), + plainReplace: require('./plain-replace'), + plainReplaceAll: require('./plain-replace-all'), + repeat: require('./repeat'), + startsWith: require('./starts-with') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/last.js new file mode 100644 index 00000000000000..d5cf46ee5fb863 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/last.js @@ -0,0 +1,8 @@ +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + var self = String(value(this)), l = self.length; + return l ? self[l - 1] : null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/_data.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/_data.js new file mode 100644 index 00000000000000..e4e00a3298120f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/_data.js @@ -0,0 +1,69 @@ +'use strict'; + +module.exports = { 0:{60:[,,{824:8814}],61:[,,{824:8800}],62:[,,{824:8815}],65:[,,{768:192,769:193,770:194,771:195,772:256,774:258,775:550,776:196,777:7842,778:197,780:461,783:512,785:514,803:7840,805:7680,808:260}],66:[,,{775:7682,803:7684,817:7686}],67:[,,{769:262,770:264,775:266,780:268,807:199}],68:[,,{775:7690,780:270,803:7692,807:7696,813:7698,817:7694}],69:[,,{768:200,769:201,770:202,771:7868,772:274,774:276,775:278,776:203,777:7866,780:282,783:516,785:518,803:7864,807:552,808:280,813:7704,816:7706}],70:[,,{775:7710}],71:[,,{769:500,770:284,772:7712,774:286,775:288,780:486,807:290}],72:[,,{770:292,775:7714,776:7718,780:542,803:7716,807:7720,814:7722}],73:[,,{768:204,769:205,770:206,771:296,772:298,774:300,775:304,776:207,777:7880,780:463,783:520,785:522,803:7882,808:302,816:7724}],74:[,,{770:308}],75:[,,{769:7728,780:488,803:7730,807:310,817:7732}],76:[,,{769:313,780:317,803:7734,807:315,813:7740,817:7738}],77:[,,{769:7742,775:7744,803:7746}],78:[,,{768:504,769:323,771:209,775:7748,780:327,803:7750,807:325,813:7754,817:7752}],79:[,,{768:210,769:211,770:212,771:213,772:332,774:334,775:558,776:214,777:7886,779:336,780:465,783:524,785:526,795:416,803:7884,808:490}],80:[,,{769:7764,775:7766}],82:[,,{769:340,775:7768,780:344,783:528,785:530,803:7770,807:342,817:7774}],83:[,,{769:346,770:348,775:7776,780:352,803:7778,806:536,807:350}],84:[,,{775:7786,780:356,803:7788,806:538,807:354,813:7792,817:7790}],85:[,,{768:217,769:218,770:219,771:360,772:362,774:364,776:220,777:7910,778:366,779:368,780:467,783:532,785:534,795:431,803:7908,804:7794,808:370,813:7798,816:7796}],86:[,,{771:7804,803:7806}],87:[,,{768:7808,769:7810,770:372,775:7814,776:7812,803:7816}],88:[,,{775:7818,776:7820}],89:[,,{768:7922,769:221,770:374,771:7928,772:562,775:7822,776:376,777:7926,803:7924}],90:[,,{769:377,770:7824,775:379,780:381,803:7826,817:7828}],97:[,,{768:224,769:225,770:226,771:227,772:257,774:259,775:551,776:228,777:7843,778:229,780:462,783:513,785:515,803:7841,805:7681,808:261}],98:[,,{775:7683,803:7685,817:7687}],99:[,,{769:263,770:265,775:267,780:269,807:231}],100:[,,{775:7691,780:271,803:7693,807:7697,813:7699,817:7695}],101:[,,{768:232,769:233,770:234,771:7869,772:275,774:277,775:279,776:235,777:7867,780:283,783:517,785:519,803:7865,807:553,808:281,813:7705,816:7707}],102:[,,{775:7711}],103:[,,{769:501,770:285,772:7713,774:287,775:289,780:487,807:291}],104:[,,{770:293,775:7715,776:7719,780:543,803:7717,807:7721,814:7723,817:7830}],105:[,,{768:236,769:237,770:238,771:297,772:299,774:301,776:239,777:7881,780:464,783:521,785:523,803:7883,808:303,816:7725}],106:[,,{770:309,780:496}],107:[,,{769:7729,780:489,803:7731,807:311,817:7733}],108:[,,{769:314,780:318,803:7735,807:316,813:7741,817:7739}],109:[,,{769:7743,775:7745,803:7747}],110:[,,{768:505,769:324,771:241,775:7749,780:328,803:7751,807:326,813:7755,817:7753}],111:[,,{768:242,769:243,770:244,771:245,772:333,774:335,775:559,776:246,777:7887,779:337,780:466,783:525,785:527,795:417,803:7885,808:491}],112:[,,{769:7765,775:7767}],114:[,,{769:341,775:7769,780:345,783:529,785:531,803:7771,807:343,817:7775}],115:[,,{769:347,770:349,775:7777,780:353,803:7779,806:537,807:351}],116:[,,{775:7787,776:7831,780:357,803:7789,806:539,807:355,813:7793,817:7791}],117:[,,{768:249,769:250,770:251,771:361,772:363,774:365,776:252,777:7911,778:367,779:369,780:468,783:533,785:535,795:432,803:7909,804:7795,808:371,813:7799,816:7797}],118:[,,{771:7805,803:7807}],119:[,,{768:7809,769:7811,770:373,775:7815,776:7813,778:7832,803:7817}],120:[,,{775:7819,776:7821}],121:[,,{768:7923,769:253,770:375,771:7929,772:563,775:7823,776:255,777:7927,778:7833,803:7925}],122:[,,{769:378,770:7825,775:380,780:382,803:7827,817:7829}],160:[[32],256],168:[[32,776],256,{768:8173,769:901,834:8129}],170:[[97],256],175:[[32,772],256],178:[[50],256],179:[[51],256],180:[[32,769],256],181:[[956],256],184:[[32,807],256],185:[[49],256],186:[[111],256],188:[[49,8260,52],256],189:[[49,8260,50],256],190:[[51,8260,52],256],192:[[65,768]],193:[[65,769]],194:[[65,770],,{768:7846,769:7844,771:7850,777:7848}],195:[[65,771]],196:[[65,776],,{772:478}],197:[[65,778],,{769:506}],198:[,,{769:508,772:482}],199:[[67,807],,{769:7688}],200:[[69,768]],201:[[69,769]],202:[[69,770],,{768:7872,769:7870,771:7876,777:7874}],203:[[69,776]],204:[[73,768]],205:[[73,769]],206:[[73,770]],207:[[73,776],,{769:7726}],209:[[78,771]],210:[[79,768]],211:[[79,769]],212:[[79,770],,{768:7890,769:7888,771:7894,777:7892}],213:[[79,771],,{769:7756,772:556,776:7758}],214:[[79,776],,{772:554}],216:[,,{769:510}],217:[[85,768]],218:[[85,769]],219:[[85,770]],220:[[85,776],,{768:475,769:471,772:469,780:473}],221:[[89,769]],224:[[97,768]],225:[[97,769]],226:[[97,770],,{768:7847,769:7845,771:7851,777:7849}],227:[[97,771]],228:[[97,776],,{772:479}],229:[[97,778],,{769:507}],230:[,,{769:509,772:483}],231:[[99,807],,{769:7689}],232:[[101,768]],233:[[101,769]],234:[[101,770],,{768:7873,769:7871,771:7877,777:7875}],235:[[101,776]],236:[[105,768]],237:[[105,769]],238:[[105,770]],239:[[105,776],,{769:7727}],241:[[110,771]],242:[[111,768]],243:[[111,769]],244:[[111,770],,{768:7891,769:7889,771:7895,777:7893}],245:[[111,771],,{769:7757,772:557,776:7759}],246:[[111,776],,{772:555}],248:[,,{769:511}],249:[[117,768]],250:[[117,769]],251:[[117,770]],252:[[117,776],,{768:476,769:472,772:470,780:474}],253:[[121,769]],255:[[121,776]]}, + 256:{256:[[65,772]],257:[[97,772]],258:[[65,774],,{768:7856,769:7854,771:7860,777:7858}],259:[[97,774],,{768:7857,769:7855,771:7861,777:7859}],260:[[65,808]],261:[[97,808]],262:[[67,769]],263:[[99,769]],264:[[67,770]],265:[[99,770]],266:[[67,775]],267:[[99,775]],268:[[67,780]],269:[[99,780]],270:[[68,780]],271:[[100,780]],274:[[69,772],,{768:7700,769:7702}],275:[[101,772],,{768:7701,769:7703}],276:[[69,774]],277:[[101,774]],278:[[69,775]],279:[[101,775]],280:[[69,808]],281:[[101,808]],282:[[69,780]],283:[[101,780]],284:[[71,770]],285:[[103,770]],286:[[71,774]],287:[[103,774]],288:[[71,775]],289:[[103,775]],290:[[71,807]],291:[[103,807]],292:[[72,770]],293:[[104,770]],296:[[73,771]],297:[[105,771]],298:[[73,772]],299:[[105,772]],300:[[73,774]],301:[[105,774]],302:[[73,808]],303:[[105,808]],304:[[73,775]],306:[[73,74],256],307:[[105,106],256],308:[[74,770]],309:[[106,770]],310:[[75,807]],311:[[107,807]],313:[[76,769]],314:[[108,769]],315:[[76,807]],316:[[108,807]],317:[[76,780]],318:[[108,780]],319:[[76,183],256],320:[[108,183],256],323:[[78,769]],324:[[110,769]],325:[[78,807]],326:[[110,807]],327:[[78,780]],328:[[110,780]],329:[[700,110],256],332:[[79,772],,{768:7760,769:7762}],333:[[111,772],,{768:7761,769:7763}],334:[[79,774]],335:[[111,774]],336:[[79,779]],337:[[111,779]],340:[[82,769]],341:[[114,769]],342:[[82,807]],343:[[114,807]],344:[[82,780]],345:[[114,780]],346:[[83,769],,{775:7780}],347:[[115,769],,{775:7781}],348:[[83,770]],349:[[115,770]],350:[[83,807]],351:[[115,807]],352:[[83,780],,{775:7782}],353:[[115,780],,{775:7783}],354:[[84,807]],355:[[116,807]],356:[[84,780]],357:[[116,780]],360:[[85,771],,{769:7800}],361:[[117,771],,{769:7801}],362:[[85,772],,{776:7802}],363:[[117,772],,{776:7803}],364:[[85,774]],365:[[117,774]],366:[[85,778]],367:[[117,778]],368:[[85,779]],369:[[117,779]],370:[[85,808]],371:[[117,808]],372:[[87,770]],373:[[119,770]],374:[[89,770]],375:[[121,770]],376:[[89,776]],377:[[90,769]],378:[[122,769]],379:[[90,775]],380:[[122,775]],381:[[90,780]],382:[[122,780]],383:[[115],256,{775:7835}],416:[[79,795],,{768:7900,769:7898,771:7904,777:7902,803:7906}],417:[[111,795],,{768:7901,769:7899,771:7905,777:7903,803:7907}],431:[[85,795],,{768:7914,769:7912,771:7918,777:7916,803:7920}],432:[[117,795],,{768:7915,769:7913,771:7919,777:7917,803:7921}],439:[,,{780:494}],452:[[68,381],256],453:[[68,382],256],454:[[100,382],256],455:[[76,74],256],456:[[76,106],256],457:[[108,106],256],458:[[78,74],256],459:[[78,106],256],460:[[110,106],256],461:[[65,780]],462:[[97,780]],463:[[73,780]],464:[[105,780]],465:[[79,780]],466:[[111,780]],467:[[85,780]],468:[[117,780]],469:[[220,772]],470:[[252,772]],471:[[220,769]],472:[[252,769]],473:[[220,780]],474:[[252,780]],475:[[220,768]],476:[[252,768]],478:[[196,772]],479:[[228,772]],480:[[550,772]],481:[[551,772]],482:[[198,772]],483:[[230,772]],486:[[71,780]],487:[[103,780]],488:[[75,780]],489:[[107,780]],490:[[79,808],,{772:492}],491:[[111,808],,{772:493}],492:[[490,772]],493:[[491,772]],494:[[439,780]],495:[[658,780]],496:[[106,780]],497:[[68,90],256],498:[[68,122],256],499:[[100,122],256],500:[[71,769]],501:[[103,769]],504:[[78,768]],505:[[110,768]],506:[[197,769]],507:[[229,769]],508:[[198,769]],509:[[230,769]],510:[[216,769]],511:[[248,769]],66045:[,220]}, + 512:{512:[[65,783]],513:[[97,783]],514:[[65,785]],515:[[97,785]],516:[[69,783]],517:[[101,783]],518:[[69,785]],519:[[101,785]],520:[[73,783]],521:[[105,783]],522:[[73,785]],523:[[105,785]],524:[[79,783]],525:[[111,783]],526:[[79,785]],527:[[111,785]],528:[[82,783]],529:[[114,783]],530:[[82,785]],531:[[114,785]],532:[[85,783]],533:[[117,783]],534:[[85,785]],535:[[117,785]],536:[[83,806]],537:[[115,806]],538:[[84,806]],539:[[116,806]],542:[[72,780]],543:[[104,780]],550:[[65,775],,{772:480}],551:[[97,775],,{772:481}],552:[[69,807],,{774:7708}],553:[[101,807],,{774:7709}],554:[[214,772]],555:[[246,772]],556:[[213,772]],557:[[245,772]],558:[[79,775],,{772:560}],559:[[111,775],,{772:561}],560:[[558,772]],561:[[559,772]],562:[[89,772]],563:[[121,772]],658:[,,{780:495}],688:[[104],256],689:[[614],256],690:[[106],256],691:[[114],256],692:[[633],256],693:[[635],256],694:[[641],256],695:[[119],256],696:[[121],256],728:[[32,774],256],729:[[32,775],256],730:[[32,778],256],731:[[32,808],256],732:[[32,771],256],733:[[32,779],256],736:[[611],256],737:[[108],256],738:[[115],256],739:[[120],256],740:[[661],256]}, + 768:{768:[,230],769:[,230],770:[,230],771:[,230],772:[,230],773:[,230],774:[,230],775:[,230],776:[,230,{769:836}],777:[,230],778:[,230],779:[,230],780:[,230],781:[,230],782:[,230],783:[,230],784:[,230],785:[,230],786:[,230],787:[,230],788:[,230],789:[,232],790:[,220],791:[,220],792:[,220],793:[,220],794:[,232],795:[,216],796:[,220],797:[,220],798:[,220],799:[,220],800:[,220],801:[,202],802:[,202],803:[,220],804:[,220],805:[,220],806:[,220],807:[,202],808:[,202],809:[,220],810:[,220],811:[,220],812:[,220],813:[,220],814:[,220],815:[,220],816:[,220],817:[,220],818:[,220],819:[,220],820:[,1],821:[,1],822:[,1],823:[,1],824:[,1],825:[,220],826:[,220],827:[,220],828:[,220],829:[,230],830:[,230],831:[,230],832:[[768],230],833:[[769],230],834:[,230],835:[[787],230],836:[[776,769],230],837:[,240],838:[,230],839:[,220],840:[,220],841:[,220],842:[,230],843:[,230],844:[,230],845:[,220],846:[,220],848:[,230],849:[,230],850:[,230],851:[,220],852:[,220],853:[,220],854:[,220],855:[,230],856:[,232],857:[,220],858:[,220],859:[,230],860:[,233],861:[,234],862:[,234],863:[,233],864:[,234],865:[,234],866:[,233],867:[,230],868:[,230],869:[,230],870:[,230],871:[,230],872:[,230],873:[,230],874:[,230],875:[,230],876:[,230],877:[,230],878:[,230],879:[,230],884:[[697]],890:[[32,837],256],894:[[59]],900:[[32,769],256],901:[[168,769]],902:[[913,769]],903:[[183]],904:[[917,769]],905:[[919,769]],906:[[921,769]],908:[[927,769]],910:[[933,769]],911:[[937,769]],912:[[970,769]],913:[,,{768:8122,769:902,772:8121,774:8120,787:7944,788:7945,837:8124}],917:[,,{768:8136,769:904,787:7960,788:7961}],919:[,,{768:8138,769:905,787:7976,788:7977,837:8140}],921:[,,{768:8154,769:906,772:8153,774:8152,776:938,787:7992,788:7993}],927:[,,{768:8184,769:908,787:8008,788:8009}],929:[,,{788:8172}],933:[,,{768:8170,769:910,772:8169,774:8168,776:939,788:8025}],937:[,,{768:8186,769:911,787:8040,788:8041,837:8188}],938:[[921,776]],939:[[933,776]],940:[[945,769],,{837:8116}],941:[[949,769]],942:[[951,769],,{837:8132}],943:[[953,769]],944:[[971,769]],945:[,,{768:8048,769:940,772:8113,774:8112,787:7936,788:7937,834:8118,837:8115}],949:[,,{768:8050,769:941,787:7952,788:7953}],951:[,,{768:8052,769:942,787:7968,788:7969,834:8134,837:8131}],953:[,,{768:8054,769:943,772:8145,774:8144,776:970,787:7984,788:7985,834:8150}],959:[,,{768:8056,769:972,787:8000,788:8001}],961:[,,{787:8164,788:8165}],965:[,,{768:8058,769:973,772:8161,774:8160,776:971,787:8016,788:8017,834:8166}],969:[,,{768:8060,769:974,787:8032,788:8033,834:8182,837:8179}],970:[[953,776],,{768:8146,769:912,834:8151}],971:[[965,776],,{768:8162,769:944,834:8167}],972:[[959,769]],973:[[965,769]],974:[[969,769],,{837:8180}],976:[[946],256],977:[[952],256],978:[[933],256,{769:979,776:980}],979:[[978,769]],980:[[978,776]],981:[[966],256],982:[[960],256],1008:[[954],256],1009:[[961],256],1010:[[962],256],1012:[[920],256],1013:[[949],256],1017:[[931],256]}, + 1024:{1024:[[1045,768]],1025:[[1045,776]],1027:[[1043,769]],1030:[,,{776:1031}],1031:[[1030,776]],1036:[[1050,769]],1037:[[1048,768]],1038:[[1059,774]],1040:[,,{774:1232,776:1234}],1043:[,,{769:1027}],1045:[,,{768:1024,774:1238,776:1025}],1046:[,,{774:1217,776:1244}],1047:[,,{776:1246}],1048:[,,{768:1037,772:1250,774:1049,776:1252}],1049:[[1048,774]],1050:[,,{769:1036}],1054:[,,{776:1254}],1059:[,,{772:1262,774:1038,776:1264,779:1266}],1063:[,,{776:1268}],1067:[,,{776:1272}],1069:[,,{776:1260}],1072:[,,{774:1233,776:1235}],1075:[,,{769:1107}],1077:[,,{768:1104,774:1239,776:1105}],1078:[,,{774:1218,776:1245}],1079:[,,{776:1247}],1080:[,,{768:1117,772:1251,774:1081,776:1253}],1081:[[1080,774]],1082:[,,{769:1116}],1086:[,,{776:1255}],1091:[,,{772:1263,774:1118,776:1265,779:1267}],1095:[,,{776:1269}],1099:[,,{776:1273}],1101:[,,{776:1261}],1104:[[1077,768]],1105:[[1077,776]],1107:[[1075,769]],1110:[,,{776:1111}],1111:[[1110,776]],1116:[[1082,769]],1117:[[1080,768]],1118:[[1091,774]],1140:[,,{783:1142}],1141:[,,{783:1143}],1142:[[1140,783]],1143:[[1141,783]],1155:[,230],1156:[,230],1157:[,230],1158:[,230],1159:[,230],1217:[[1046,774]],1218:[[1078,774]],1232:[[1040,774]],1233:[[1072,774]],1234:[[1040,776]],1235:[[1072,776]],1238:[[1045,774]],1239:[[1077,774]],1240:[,,{776:1242}],1241:[,,{776:1243}],1242:[[1240,776]],1243:[[1241,776]],1244:[[1046,776]],1245:[[1078,776]],1246:[[1047,776]],1247:[[1079,776]],1250:[[1048,772]],1251:[[1080,772]],1252:[[1048,776]],1253:[[1080,776]],1254:[[1054,776]],1255:[[1086,776]],1256:[,,{776:1258}],1257:[,,{776:1259}],1258:[[1256,776]],1259:[[1257,776]],1260:[[1069,776]],1261:[[1101,776]],1262:[[1059,772]],1263:[[1091,772]],1264:[[1059,776]],1265:[[1091,776]],1266:[[1059,779]],1267:[[1091,779]],1268:[[1063,776]],1269:[[1095,776]],1272:[[1067,776]],1273:[[1099,776]]}, + 1280:{1415:[[1381,1410],256],1425:[,220],1426:[,230],1427:[,230],1428:[,230],1429:[,230],1430:[,220],1431:[,230],1432:[,230],1433:[,230],1434:[,222],1435:[,220],1436:[,230],1437:[,230],1438:[,230],1439:[,230],1440:[,230],1441:[,230],1442:[,220],1443:[,220],1444:[,220],1445:[,220],1446:[,220],1447:[,220],1448:[,230],1449:[,230],1450:[,220],1451:[,230],1452:[,230],1453:[,222],1454:[,228],1455:[,230],1456:[,10],1457:[,11],1458:[,12],1459:[,13],1460:[,14],1461:[,15],1462:[,16],1463:[,17],1464:[,18],1465:[,19],1466:[,19],1467:[,20],1468:[,21],1469:[,22],1471:[,23],1473:[,24],1474:[,25],1476:[,230],1477:[,220],1479:[,18]}, + 1536:{1552:[,230],1553:[,230],1554:[,230],1555:[,230],1556:[,230],1557:[,230],1558:[,230],1559:[,230],1560:[,30],1561:[,31],1562:[,32],1570:[[1575,1619]],1571:[[1575,1620]],1572:[[1608,1620]],1573:[[1575,1621]],1574:[[1610,1620]],1575:[,,{1619:1570,1620:1571,1621:1573}],1608:[,,{1620:1572}],1610:[,,{1620:1574}],1611:[,27],1612:[,28],1613:[,29],1614:[,30],1615:[,31],1616:[,32],1617:[,33],1618:[,34],1619:[,230],1620:[,230],1621:[,220],1622:[,220],1623:[,230],1624:[,230],1625:[,230],1626:[,230],1627:[,230],1628:[,220],1629:[,230],1630:[,230],1631:[,220],1648:[,35],1653:[[1575,1652],256],1654:[[1608,1652],256],1655:[[1735,1652],256],1656:[[1610,1652],256],1728:[[1749,1620]],1729:[,,{1620:1730}],1730:[[1729,1620]],1746:[,,{1620:1747}],1747:[[1746,1620]],1749:[,,{1620:1728}],1750:[,230],1751:[,230],1752:[,230],1753:[,230],1754:[,230],1755:[,230],1756:[,230],1759:[,230],1760:[,230],1761:[,230],1762:[,230],1763:[,220],1764:[,230],1767:[,230],1768:[,230],1770:[,220],1771:[,230],1772:[,230],1773:[,220]}, + 1792:{1809:[,36],1840:[,230],1841:[,220],1842:[,230],1843:[,230],1844:[,220],1845:[,230],1846:[,230],1847:[,220],1848:[,220],1849:[,220],1850:[,230],1851:[,220],1852:[,220],1853:[,230],1854:[,220],1855:[,230],1856:[,230],1857:[,230],1858:[,220],1859:[,230],1860:[,220],1861:[,230],1862:[,220],1863:[,230],1864:[,220],1865:[,230],1866:[,230],2027:[,230],2028:[,230],2029:[,230],2030:[,230],2031:[,230],2032:[,230],2033:[,230],2034:[,220],2035:[,230]}, + 2048:{2070:[,230],2071:[,230],2072:[,230],2073:[,230],2075:[,230],2076:[,230],2077:[,230],2078:[,230],2079:[,230],2080:[,230],2081:[,230],2082:[,230],2083:[,230],2085:[,230],2086:[,230],2087:[,230],2089:[,230],2090:[,230],2091:[,230],2092:[,230],2093:[,230],2137:[,220],2138:[,220],2139:[,220],2276:[,230],2277:[,230],2278:[,220],2279:[,230],2280:[,230],2281:[,220],2282:[,230],2283:[,230],2284:[,230],2285:[,220],2286:[,220],2287:[,220],2288:[,27],2289:[,28],2290:[,29],2291:[,230],2292:[,230],2293:[,230],2294:[,220],2295:[,230],2296:[,230],2297:[,220],2298:[,220],2299:[,230],2300:[,230],2301:[,230],2302:[,230]}, + 2304:{2344:[,,{2364:2345}],2345:[[2344,2364]],2352:[,,{2364:2353}],2353:[[2352,2364]],2355:[,,{2364:2356}],2356:[[2355,2364]],2364:[,7],2381:[,9],2385:[,230],2386:[,220],2387:[,230],2388:[,230],2392:[[2325,2364],512],2393:[[2326,2364],512],2394:[[2327,2364],512],2395:[[2332,2364],512],2396:[[2337,2364],512],2397:[[2338,2364],512],2398:[[2347,2364],512],2399:[[2351,2364],512],2492:[,7],2503:[,,{2494:2507,2519:2508}],2507:[[2503,2494]],2508:[[2503,2519]],2509:[,9],2524:[[2465,2492],512],2525:[[2466,2492],512],2527:[[2479,2492],512]}, + 2560:{2611:[[2610,2620],512],2614:[[2616,2620],512],2620:[,7],2637:[,9],2649:[[2582,2620],512],2650:[[2583,2620],512],2651:[[2588,2620],512],2654:[[2603,2620],512],2748:[,7],2765:[,9],68109:[,220],68111:[,230],68152:[,230],68153:[,1],68154:[,220],68159:[,9]}, + 2816:{2876:[,7],2887:[,,{2878:2891,2902:2888,2903:2892}],2888:[[2887,2902]],2891:[[2887,2878]],2892:[[2887,2903]],2893:[,9],2908:[[2849,2876],512],2909:[[2850,2876],512],2962:[,,{3031:2964}],2964:[[2962,3031]],3014:[,,{3006:3018,3031:3020}],3015:[,,{3006:3019}],3018:[[3014,3006]],3019:[[3015,3006]],3020:[[3014,3031]],3021:[,9]}, + 3072:{3142:[,,{3158:3144}],3144:[[3142,3158]],3149:[,9],3157:[,84],3158:[,91],3260:[,7],3263:[,,{3285:3264}],3264:[[3263,3285]],3270:[,,{3266:3274,3285:3271,3286:3272}],3271:[[3270,3285]],3272:[[3270,3286]],3274:[[3270,3266],,{3285:3275}],3275:[[3274,3285]],3277:[,9]}, + 3328:{3398:[,,{3390:3402,3415:3404}],3399:[,,{3390:3403}],3402:[[3398,3390]],3403:[[3399,3390]],3404:[[3398,3415]],3405:[,9],3530:[,9],3545:[,,{3530:3546,3535:3548,3551:3550}],3546:[[3545,3530]],3548:[[3545,3535],,{3530:3549}],3549:[[3548,3530]],3550:[[3545,3551]]}, + 3584:{3635:[[3661,3634],256],3640:[,103],3641:[,103],3642:[,9],3656:[,107],3657:[,107],3658:[,107],3659:[,107],3763:[[3789,3762],256],3768:[,118],3769:[,118],3784:[,122],3785:[,122],3786:[,122],3787:[,122],3804:[[3755,3737],256],3805:[[3755,3745],256]}, + 3840:{3852:[[3851],256],3864:[,220],3865:[,220],3893:[,220],3895:[,220],3897:[,216],3907:[[3906,4023],512],3917:[[3916,4023],512],3922:[[3921,4023],512],3927:[[3926,4023],512],3932:[[3931,4023],512],3945:[[3904,4021],512],3953:[,129],3954:[,130],3955:[[3953,3954],512],3956:[,132],3957:[[3953,3956],512],3958:[[4018,3968],512],3959:[[4018,3969],256],3960:[[4019,3968],512],3961:[[4019,3969],256],3962:[,130],3963:[,130],3964:[,130],3965:[,130],3968:[,130],3969:[[3953,3968],512],3970:[,230],3971:[,230],3972:[,9],3974:[,230],3975:[,230],3987:[[3986,4023],512],3997:[[3996,4023],512],4002:[[4001,4023],512],4007:[[4006,4023],512],4012:[[4011,4023],512],4025:[[3984,4021],512],4038:[,220]}, + 4096:{4133:[,,{4142:4134}],4134:[[4133,4142]],4151:[,7],4153:[,9],4154:[,9],4237:[,220],4348:[[4316],256],69702:[,9],69785:[,,{69818:69786}],69786:[[69785,69818]],69787:[,,{69818:69788}],69788:[[69787,69818]],69797:[,,{69818:69803}],69803:[[69797,69818]],69817:[,9],69818:[,7]}, + 4352:{69888:[,230],69889:[,230],69890:[,230],69934:[[69937,69927]],69935:[[69938,69927]],69937:[,,{69927:69934}],69938:[,,{69927:69935}],69939:[,9],69940:[,9],70080:[,9]}, + 4864:{4957:[,230],4958:[,230],4959:[,230]}, + 5632:{71350:[,9],71351:[,7]}, + 5888:{5908:[,9],5940:[,9],6098:[,9],6109:[,230]}, + 6144:{6313:[,228]}, + 6400:{6457:[,222],6458:[,230],6459:[,220]}, + 6656:{6679:[,230],6680:[,220],6752:[,9],6773:[,230],6774:[,230],6775:[,230],6776:[,230],6777:[,230],6778:[,230],6779:[,230],6780:[,230],6783:[,220]}, + 6912:{6917:[,,{6965:6918}],6918:[[6917,6965]],6919:[,,{6965:6920}],6920:[[6919,6965]],6921:[,,{6965:6922}],6922:[[6921,6965]],6923:[,,{6965:6924}],6924:[[6923,6965]],6925:[,,{6965:6926}],6926:[[6925,6965]],6929:[,,{6965:6930}],6930:[[6929,6965]],6964:[,7],6970:[,,{6965:6971}],6971:[[6970,6965]],6972:[,,{6965:6973}],6973:[[6972,6965]],6974:[,,{6965:6976}],6975:[,,{6965:6977}],6976:[[6974,6965]],6977:[[6975,6965]],6978:[,,{6965:6979}],6979:[[6978,6965]],6980:[,9],7019:[,230],7020:[,220],7021:[,230],7022:[,230],7023:[,230],7024:[,230],7025:[,230],7026:[,230],7027:[,230],7082:[,9],7083:[,9],7142:[,7],7154:[,9],7155:[,9]}, + 7168:{7223:[,7],7376:[,230],7377:[,230],7378:[,230],7380:[,1],7381:[,220],7382:[,220],7383:[,220],7384:[,220],7385:[,220],7386:[,230],7387:[,230],7388:[,220],7389:[,220],7390:[,220],7391:[,220],7392:[,230],7394:[,1],7395:[,1],7396:[,1],7397:[,1],7398:[,1],7399:[,1],7400:[,1],7405:[,220],7412:[,230]}, + 7424:{7468:[[65],256],7469:[[198],256],7470:[[66],256],7472:[[68],256],7473:[[69],256],7474:[[398],256],7475:[[71],256],7476:[[72],256],7477:[[73],256],7478:[[74],256],7479:[[75],256],7480:[[76],256],7481:[[77],256],7482:[[78],256],7484:[[79],256],7485:[[546],256],7486:[[80],256],7487:[[82],256],7488:[[84],256],7489:[[85],256],7490:[[87],256],7491:[[97],256],7492:[[592],256],7493:[[593],256],7494:[[7426],256],7495:[[98],256],7496:[[100],256],7497:[[101],256],7498:[[601],256],7499:[[603],256],7500:[[604],256],7501:[[103],256],7503:[[107],256],7504:[[109],256],7505:[[331],256],7506:[[111],256],7507:[[596],256],7508:[[7446],256],7509:[[7447],256],7510:[[112],256],7511:[[116],256],7512:[[117],256],7513:[[7453],256],7514:[[623],256],7515:[[118],256],7516:[[7461],256],7517:[[946],256],7518:[[947],256],7519:[[948],256],7520:[[966],256],7521:[[967],256],7522:[[105],256],7523:[[114],256],7524:[[117],256],7525:[[118],256],7526:[[946],256],7527:[[947],256],7528:[[961],256],7529:[[966],256],7530:[[967],256],7544:[[1085],256],7579:[[594],256],7580:[[99],256],7581:[[597],256],7582:[[240],256],7583:[[604],256],7584:[[102],256],7585:[[607],256],7586:[[609],256],7587:[[613],256],7588:[[616],256],7589:[[617],256],7590:[[618],256],7591:[[7547],256],7592:[[669],256],7593:[[621],256],7594:[[7557],256],7595:[[671],256],7596:[[625],256],7597:[[624],256],7598:[[626],256],7599:[[627],256],7600:[[628],256],7601:[[629],256],7602:[[632],256],7603:[[642],256],7604:[[643],256],7605:[[427],256],7606:[[649],256],7607:[[650],256],7608:[[7452],256],7609:[[651],256],7610:[[652],256],7611:[[122],256],7612:[[656],256],7613:[[657],256],7614:[[658],256],7615:[[952],256],7616:[,230],7617:[,230],7618:[,220],7619:[,230],7620:[,230],7621:[,230],7622:[,230],7623:[,230],7624:[,230],7625:[,230],7626:[,220],7627:[,230],7628:[,230],7629:[,234],7630:[,214],7631:[,220],7632:[,202],7633:[,230],7634:[,230],7635:[,230],7636:[,230],7637:[,230],7638:[,230],7639:[,230],7640:[,230],7641:[,230],7642:[,230],7643:[,230],7644:[,230],7645:[,230],7646:[,230],7647:[,230],7648:[,230],7649:[,230],7650:[,230],7651:[,230],7652:[,230],7653:[,230],7654:[,230],7676:[,233],7677:[,220],7678:[,230],7679:[,220]}, + 7680:{7680:[[65,805]],7681:[[97,805]],7682:[[66,775]],7683:[[98,775]],7684:[[66,803]],7685:[[98,803]],7686:[[66,817]],7687:[[98,817]],7688:[[199,769]],7689:[[231,769]],7690:[[68,775]],7691:[[100,775]],7692:[[68,803]],7693:[[100,803]],7694:[[68,817]],7695:[[100,817]],7696:[[68,807]],7697:[[100,807]],7698:[[68,813]],7699:[[100,813]],7700:[[274,768]],7701:[[275,768]],7702:[[274,769]],7703:[[275,769]],7704:[[69,813]],7705:[[101,813]],7706:[[69,816]],7707:[[101,816]],7708:[[552,774]],7709:[[553,774]],7710:[[70,775]],7711:[[102,775]],7712:[[71,772]],7713:[[103,772]],7714:[[72,775]],7715:[[104,775]],7716:[[72,803]],7717:[[104,803]],7718:[[72,776]],7719:[[104,776]],7720:[[72,807]],7721:[[104,807]],7722:[[72,814]],7723:[[104,814]],7724:[[73,816]],7725:[[105,816]],7726:[[207,769]],7727:[[239,769]],7728:[[75,769]],7729:[[107,769]],7730:[[75,803]],7731:[[107,803]],7732:[[75,817]],7733:[[107,817]],7734:[[76,803],,{772:7736}],7735:[[108,803],,{772:7737}],7736:[[7734,772]],7737:[[7735,772]],7738:[[76,817]],7739:[[108,817]],7740:[[76,813]],7741:[[108,813]],7742:[[77,769]],7743:[[109,769]],7744:[[77,775]],7745:[[109,775]],7746:[[77,803]],7747:[[109,803]],7748:[[78,775]],7749:[[110,775]],7750:[[78,803]],7751:[[110,803]],7752:[[78,817]],7753:[[110,817]],7754:[[78,813]],7755:[[110,813]],7756:[[213,769]],7757:[[245,769]],7758:[[213,776]],7759:[[245,776]],7760:[[332,768]],7761:[[333,768]],7762:[[332,769]],7763:[[333,769]],7764:[[80,769]],7765:[[112,769]],7766:[[80,775]],7767:[[112,775]],7768:[[82,775]],7769:[[114,775]],7770:[[82,803],,{772:7772}],7771:[[114,803],,{772:7773}],7772:[[7770,772]],7773:[[7771,772]],7774:[[82,817]],7775:[[114,817]],7776:[[83,775]],7777:[[115,775]],7778:[[83,803],,{775:7784}],7779:[[115,803],,{775:7785}],7780:[[346,775]],7781:[[347,775]],7782:[[352,775]],7783:[[353,775]],7784:[[7778,775]],7785:[[7779,775]],7786:[[84,775]],7787:[[116,775]],7788:[[84,803]],7789:[[116,803]],7790:[[84,817]],7791:[[116,817]],7792:[[84,813]],7793:[[116,813]],7794:[[85,804]],7795:[[117,804]],7796:[[85,816]],7797:[[117,816]],7798:[[85,813]],7799:[[117,813]],7800:[[360,769]],7801:[[361,769]],7802:[[362,776]],7803:[[363,776]],7804:[[86,771]],7805:[[118,771]],7806:[[86,803]],7807:[[118,803]],7808:[[87,768]],7809:[[119,768]],7810:[[87,769]],7811:[[119,769]],7812:[[87,776]],7813:[[119,776]],7814:[[87,775]],7815:[[119,775]],7816:[[87,803]],7817:[[119,803]],7818:[[88,775]],7819:[[120,775]],7820:[[88,776]],7821:[[120,776]],7822:[[89,775]],7823:[[121,775]],7824:[[90,770]],7825:[[122,770]],7826:[[90,803]],7827:[[122,803]],7828:[[90,817]],7829:[[122,817]],7830:[[104,817]],7831:[[116,776]],7832:[[119,778]],7833:[[121,778]],7834:[[97,702],256],7835:[[383,775]],7840:[[65,803],,{770:7852,774:7862}],7841:[[97,803],,{770:7853,774:7863}],7842:[[65,777]],7843:[[97,777]],7844:[[194,769]],7845:[[226,769]],7846:[[194,768]],7847:[[226,768]],7848:[[194,777]],7849:[[226,777]],7850:[[194,771]],7851:[[226,771]],7852:[[7840,770]],7853:[[7841,770]],7854:[[258,769]],7855:[[259,769]],7856:[[258,768]],7857:[[259,768]],7858:[[258,777]],7859:[[259,777]],7860:[[258,771]],7861:[[259,771]],7862:[[7840,774]],7863:[[7841,774]],7864:[[69,803],,{770:7878}],7865:[[101,803],,{770:7879}],7866:[[69,777]],7867:[[101,777]],7868:[[69,771]],7869:[[101,771]],7870:[[202,769]],7871:[[234,769]],7872:[[202,768]],7873:[[234,768]],7874:[[202,777]],7875:[[234,777]],7876:[[202,771]],7877:[[234,771]],7878:[[7864,770]],7879:[[7865,770]],7880:[[73,777]],7881:[[105,777]],7882:[[73,803]],7883:[[105,803]],7884:[[79,803],,{770:7896}],7885:[[111,803],,{770:7897}],7886:[[79,777]],7887:[[111,777]],7888:[[212,769]],7889:[[244,769]],7890:[[212,768]],7891:[[244,768]],7892:[[212,777]],7893:[[244,777]],7894:[[212,771]],7895:[[244,771]],7896:[[7884,770]],7897:[[7885,770]],7898:[[416,769]],7899:[[417,769]],7900:[[416,768]],7901:[[417,768]],7902:[[416,777]],7903:[[417,777]],7904:[[416,771]],7905:[[417,771]],7906:[[416,803]],7907:[[417,803]],7908:[[85,803]],7909:[[117,803]],7910:[[85,777]],7911:[[117,777]],7912:[[431,769]],7913:[[432,769]],7914:[[431,768]],7915:[[432,768]],7916:[[431,777]],7917:[[432,777]],7918:[[431,771]],7919:[[432,771]],7920:[[431,803]],7921:[[432,803]],7922:[[89,768]],7923:[[121,768]],7924:[[89,803]],7925:[[121,803]],7926:[[89,777]],7927:[[121,777]],7928:[[89,771]],7929:[[121,771]]}, + 7936:{7936:[[945,787],,{768:7938,769:7940,834:7942,837:8064}],7937:[[945,788],,{768:7939,769:7941,834:7943,837:8065}],7938:[[7936,768],,{837:8066}],7939:[[7937,768],,{837:8067}],7940:[[7936,769],,{837:8068}],7941:[[7937,769],,{837:8069}],7942:[[7936,834],,{837:8070}],7943:[[7937,834],,{837:8071}],7944:[[913,787],,{768:7946,769:7948,834:7950,837:8072}],7945:[[913,788],,{768:7947,769:7949,834:7951,837:8073}],7946:[[7944,768],,{837:8074}],7947:[[7945,768],,{837:8075}],7948:[[7944,769],,{837:8076}],7949:[[7945,769],,{837:8077}],7950:[[7944,834],,{837:8078}],7951:[[7945,834],,{837:8079}],7952:[[949,787],,{768:7954,769:7956}],7953:[[949,788],,{768:7955,769:7957}],7954:[[7952,768]],7955:[[7953,768]],7956:[[7952,769]],7957:[[7953,769]],7960:[[917,787],,{768:7962,769:7964}],7961:[[917,788],,{768:7963,769:7965}],7962:[[7960,768]],7963:[[7961,768]],7964:[[7960,769]],7965:[[7961,769]],7968:[[951,787],,{768:7970,769:7972,834:7974,837:8080}],7969:[[951,788],,{768:7971,769:7973,834:7975,837:8081}],7970:[[7968,768],,{837:8082}],7971:[[7969,768],,{837:8083}],7972:[[7968,769],,{837:8084}],7973:[[7969,769],,{837:8085}],7974:[[7968,834],,{837:8086}],7975:[[7969,834],,{837:8087}],7976:[[919,787],,{768:7978,769:7980,834:7982,837:8088}],7977:[[919,788],,{768:7979,769:7981,834:7983,837:8089}],7978:[[7976,768],,{837:8090}],7979:[[7977,768],,{837:8091}],7980:[[7976,769],,{837:8092}],7981:[[7977,769],,{837:8093}],7982:[[7976,834],,{837:8094}],7983:[[7977,834],,{837:8095}],7984:[[953,787],,{768:7986,769:7988,834:7990}],7985:[[953,788],,{768:7987,769:7989,834:7991}],7986:[[7984,768]],7987:[[7985,768]],7988:[[7984,769]],7989:[[7985,769]],7990:[[7984,834]],7991:[[7985,834]],7992:[[921,787],,{768:7994,769:7996,834:7998}],7993:[[921,788],,{768:7995,769:7997,834:7999}],7994:[[7992,768]],7995:[[7993,768]],7996:[[7992,769]],7997:[[7993,769]],7998:[[7992,834]],7999:[[7993,834]],8000:[[959,787],,{768:8002,769:8004}],8001:[[959,788],,{768:8003,769:8005}],8002:[[8000,768]],8003:[[8001,768]],8004:[[8000,769]],8005:[[8001,769]],8008:[[927,787],,{768:8010,769:8012}],8009:[[927,788],,{768:8011,769:8013}],8010:[[8008,768]],8011:[[8009,768]],8012:[[8008,769]],8013:[[8009,769]],8016:[[965,787],,{768:8018,769:8020,834:8022}],8017:[[965,788],,{768:8019,769:8021,834:8023}],8018:[[8016,768]],8019:[[8017,768]],8020:[[8016,769]],8021:[[8017,769]],8022:[[8016,834]],8023:[[8017,834]],8025:[[933,788],,{768:8027,769:8029,834:8031}],8027:[[8025,768]],8029:[[8025,769]],8031:[[8025,834]],8032:[[969,787],,{768:8034,769:8036,834:8038,837:8096}],8033:[[969,788],,{768:8035,769:8037,834:8039,837:8097}],8034:[[8032,768],,{837:8098}],8035:[[8033,768],,{837:8099}],8036:[[8032,769],,{837:8100}],8037:[[8033,769],,{837:8101}],8038:[[8032,834],,{837:8102}],8039:[[8033,834],,{837:8103}],8040:[[937,787],,{768:8042,769:8044,834:8046,837:8104}],8041:[[937,788],,{768:8043,769:8045,834:8047,837:8105}],8042:[[8040,768],,{837:8106}],8043:[[8041,768],,{837:8107}],8044:[[8040,769],,{837:8108}],8045:[[8041,769],,{837:8109}],8046:[[8040,834],,{837:8110}],8047:[[8041,834],,{837:8111}],8048:[[945,768],,{837:8114}],8049:[[940]],8050:[[949,768]],8051:[[941]],8052:[[951,768],,{837:8130}],8053:[[942]],8054:[[953,768]],8055:[[943]],8056:[[959,768]],8057:[[972]],8058:[[965,768]],8059:[[973]],8060:[[969,768],,{837:8178}],8061:[[974]],8064:[[7936,837]],8065:[[7937,837]],8066:[[7938,837]],8067:[[7939,837]],8068:[[7940,837]],8069:[[7941,837]],8070:[[7942,837]],8071:[[7943,837]],8072:[[7944,837]],8073:[[7945,837]],8074:[[7946,837]],8075:[[7947,837]],8076:[[7948,837]],8077:[[7949,837]],8078:[[7950,837]],8079:[[7951,837]],8080:[[7968,837]],8081:[[7969,837]],8082:[[7970,837]],8083:[[7971,837]],8084:[[7972,837]],8085:[[7973,837]],8086:[[7974,837]],8087:[[7975,837]],8088:[[7976,837]],8089:[[7977,837]],8090:[[7978,837]],8091:[[7979,837]],8092:[[7980,837]],8093:[[7981,837]],8094:[[7982,837]],8095:[[7983,837]],8096:[[8032,837]],8097:[[8033,837]],8098:[[8034,837]],8099:[[8035,837]],8100:[[8036,837]],8101:[[8037,837]],8102:[[8038,837]],8103:[[8039,837]],8104:[[8040,837]],8105:[[8041,837]],8106:[[8042,837]],8107:[[8043,837]],8108:[[8044,837]],8109:[[8045,837]],8110:[[8046,837]],8111:[[8047,837]],8112:[[945,774]],8113:[[945,772]],8114:[[8048,837]],8115:[[945,837]],8116:[[940,837]],8118:[[945,834],,{837:8119}],8119:[[8118,837]],8120:[[913,774]],8121:[[913,772]],8122:[[913,768]],8123:[[902]],8124:[[913,837]],8125:[[32,787],256],8126:[[953]],8127:[[32,787],256,{768:8141,769:8142,834:8143}],8128:[[32,834],256],8129:[[168,834]],8130:[[8052,837]],8131:[[951,837]],8132:[[942,837]],8134:[[951,834],,{837:8135}],8135:[[8134,837]],8136:[[917,768]],8137:[[904]],8138:[[919,768]],8139:[[905]],8140:[[919,837]],8141:[[8127,768]],8142:[[8127,769]],8143:[[8127,834]],8144:[[953,774]],8145:[[953,772]],8146:[[970,768]],8147:[[912]],8150:[[953,834]],8151:[[970,834]],8152:[[921,774]],8153:[[921,772]],8154:[[921,768]],8155:[[906]],8157:[[8190,768]],8158:[[8190,769]],8159:[[8190,834]],8160:[[965,774]],8161:[[965,772]],8162:[[971,768]],8163:[[944]],8164:[[961,787]],8165:[[961,788]],8166:[[965,834]],8167:[[971,834]],8168:[[933,774]],8169:[[933,772]],8170:[[933,768]],8171:[[910]],8172:[[929,788]],8173:[[168,768]],8174:[[901]],8175:[[96]],8178:[[8060,837]],8179:[[969,837]],8180:[[974,837]],8182:[[969,834],,{837:8183}],8183:[[8182,837]],8184:[[927,768]],8185:[[908]],8186:[[937,768]],8187:[[911]],8188:[[937,837]],8189:[[180]],8190:[[32,788],256,{768:8157,769:8158,834:8159}]}, + 8192:{8192:[[8194]],8193:[[8195]],8194:[[32],256],8195:[[32],256],8196:[[32],256],8197:[[32],256],8198:[[32],256],8199:[[32],256],8200:[[32],256],8201:[[32],256],8202:[[32],256],8209:[[8208],256],8215:[[32,819],256],8228:[[46],256],8229:[[46,46],256],8230:[[46,46,46],256],8239:[[32],256],8243:[[8242,8242],256],8244:[[8242,8242,8242],256],8246:[[8245,8245],256],8247:[[8245,8245,8245],256],8252:[[33,33],256],8254:[[32,773],256],8263:[[63,63],256],8264:[[63,33],256],8265:[[33,63],256],8279:[[8242,8242,8242,8242],256],8287:[[32],256],8304:[[48],256],8305:[[105],256],8308:[[52],256],8309:[[53],256],8310:[[54],256],8311:[[55],256],8312:[[56],256],8313:[[57],256],8314:[[43],256],8315:[[8722],256],8316:[[61],256],8317:[[40],256],8318:[[41],256],8319:[[110],256],8320:[[48],256],8321:[[49],256],8322:[[50],256],8323:[[51],256],8324:[[52],256],8325:[[53],256],8326:[[54],256],8327:[[55],256],8328:[[56],256],8329:[[57],256],8330:[[43],256],8331:[[8722],256],8332:[[61],256],8333:[[40],256],8334:[[41],256],8336:[[97],256],8337:[[101],256],8338:[[111],256],8339:[[120],256],8340:[[601],256],8341:[[104],256],8342:[[107],256],8343:[[108],256],8344:[[109],256],8345:[[110],256],8346:[[112],256],8347:[[115],256],8348:[[116],256],8360:[[82,115],256],8400:[,230],8401:[,230],8402:[,1],8403:[,1],8404:[,230],8405:[,230],8406:[,230],8407:[,230],8408:[,1],8409:[,1],8410:[,1],8411:[,230],8412:[,230],8417:[,230],8421:[,1],8422:[,1],8423:[,230],8424:[,220],8425:[,230],8426:[,1],8427:[,1],8428:[,220],8429:[,220],8430:[,220],8431:[,220],8432:[,230]}, + 8448:{8448:[[97,47,99],256],8449:[[97,47,115],256],8450:[[67],256],8451:[[176,67],256],8453:[[99,47,111],256],8454:[[99,47,117],256],8455:[[400],256],8457:[[176,70],256],8458:[[103],256],8459:[[72],256],8460:[[72],256],8461:[[72],256],8462:[[104],256],8463:[[295],256],8464:[[73],256],8465:[[73],256],8466:[[76],256],8467:[[108],256],8469:[[78],256],8470:[[78,111],256],8473:[[80],256],8474:[[81],256],8475:[[82],256],8476:[[82],256],8477:[[82],256],8480:[[83,77],256],8481:[[84,69,76],256],8482:[[84,77],256],8484:[[90],256],8486:[[937]],8488:[[90],256],8490:[[75]],8491:[[197]],8492:[[66],256],8493:[[67],256],8495:[[101],256],8496:[[69],256],8497:[[70],256],8499:[[77],256],8500:[[111],256],8501:[[1488],256],8502:[[1489],256],8503:[[1490],256],8504:[[1491],256],8505:[[105],256],8507:[[70,65,88],256],8508:[[960],256],8509:[[947],256],8510:[[915],256],8511:[[928],256],8512:[[8721],256],8517:[[68],256],8518:[[100],256],8519:[[101],256],8520:[[105],256],8521:[[106],256],8528:[[49,8260,55],256],8529:[[49,8260,57],256],8530:[[49,8260,49,48],256],8531:[[49,8260,51],256],8532:[[50,8260,51],256],8533:[[49,8260,53],256],8534:[[50,8260,53],256],8535:[[51,8260,53],256],8536:[[52,8260,53],256],8537:[[49,8260,54],256],8538:[[53,8260,54],256],8539:[[49,8260,56],256],8540:[[51,8260,56],256],8541:[[53,8260,56],256],8542:[[55,8260,56],256],8543:[[49,8260],256],8544:[[73],256],8545:[[73,73],256],8546:[[73,73,73],256],8547:[[73,86],256],8548:[[86],256],8549:[[86,73],256],8550:[[86,73,73],256],8551:[[86,73,73,73],256],8552:[[73,88],256],8553:[[88],256],8554:[[88,73],256],8555:[[88,73,73],256],8556:[[76],256],8557:[[67],256],8558:[[68],256],8559:[[77],256],8560:[[105],256],8561:[[105,105],256],8562:[[105,105,105],256],8563:[[105,118],256],8564:[[118],256],8565:[[118,105],256],8566:[[118,105,105],256],8567:[[118,105,105,105],256],8568:[[105,120],256],8569:[[120],256],8570:[[120,105],256],8571:[[120,105,105],256],8572:[[108],256],8573:[[99],256],8574:[[100],256],8575:[[109],256],8585:[[48,8260,51],256],8592:[,,{824:8602}],8594:[,,{824:8603}],8596:[,,{824:8622}],8602:[[8592,824]],8603:[[8594,824]],8622:[[8596,824]],8653:[[8656,824]],8654:[[8660,824]],8655:[[8658,824]],8656:[,,{824:8653}],8658:[,,{824:8655}],8660:[,,{824:8654}]}, + 8704:{8707:[,,{824:8708}],8708:[[8707,824]],8712:[,,{824:8713}],8713:[[8712,824]],8715:[,,{824:8716}],8716:[[8715,824]],8739:[,,{824:8740}],8740:[[8739,824]],8741:[,,{824:8742}],8742:[[8741,824]],8748:[[8747,8747],256],8749:[[8747,8747,8747],256],8751:[[8750,8750],256],8752:[[8750,8750,8750],256],8764:[,,{824:8769}],8769:[[8764,824]],8771:[,,{824:8772}],8772:[[8771,824]],8773:[,,{824:8775}],8775:[[8773,824]],8776:[,,{824:8777}],8777:[[8776,824]],8781:[,,{824:8813}],8800:[[61,824]],8801:[,,{824:8802}],8802:[[8801,824]],8804:[,,{824:8816}],8805:[,,{824:8817}],8813:[[8781,824]],8814:[[60,824]],8815:[[62,824]],8816:[[8804,824]],8817:[[8805,824]],8818:[,,{824:8820}],8819:[,,{824:8821}],8820:[[8818,824]],8821:[[8819,824]],8822:[,,{824:8824}],8823:[,,{824:8825}],8824:[[8822,824]],8825:[[8823,824]],8826:[,,{824:8832}],8827:[,,{824:8833}],8828:[,,{824:8928}],8829:[,,{824:8929}],8832:[[8826,824]],8833:[[8827,824]],8834:[,,{824:8836}],8835:[,,{824:8837}],8836:[[8834,824]],8837:[[8835,824]],8838:[,,{824:8840}],8839:[,,{824:8841}],8840:[[8838,824]],8841:[[8839,824]],8849:[,,{824:8930}],8850:[,,{824:8931}],8866:[,,{824:8876}],8872:[,,{824:8877}],8873:[,,{824:8878}],8875:[,,{824:8879}],8876:[[8866,824]],8877:[[8872,824]],8878:[[8873,824]],8879:[[8875,824]],8882:[,,{824:8938}],8883:[,,{824:8939}],8884:[,,{824:8940}],8885:[,,{824:8941}],8928:[[8828,824]],8929:[[8829,824]],8930:[[8849,824]],8931:[[8850,824]],8938:[[8882,824]],8939:[[8883,824]],8940:[[8884,824]],8941:[[8885,824]]}, + 8960:{9001:[[12296]],9002:[[12297]]}, + 9216:{9312:[[49],256],9313:[[50],256],9314:[[51],256],9315:[[52],256],9316:[[53],256],9317:[[54],256],9318:[[55],256],9319:[[56],256],9320:[[57],256],9321:[[49,48],256],9322:[[49,49],256],9323:[[49,50],256],9324:[[49,51],256],9325:[[49,52],256],9326:[[49,53],256],9327:[[49,54],256],9328:[[49,55],256],9329:[[49,56],256],9330:[[49,57],256],9331:[[50,48],256],9332:[[40,49,41],256],9333:[[40,50,41],256],9334:[[40,51,41],256],9335:[[40,52,41],256],9336:[[40,53,41],256],9337:[[40,54,41],256],9338:[[40,55,41],256],9339:[[40,56,41],256],9340:[[40,57,41],256],9341:[[40,49,48,41],256],9342:[[40,49,49,41],256],9343:[[40,49,50,41],256],9344:[[40,49,51,41],256],9345:[[40,49,52,41],256],9346:[[40,49,53,41],256],9347:[[40,49,54,41],256],9348:[[40,49,55,41],256],9349:[[40,49,56,41],256],9350:[[40,49,57,41],256],9351:[[40,50,48,41],256],9352:[[49,46],256],9353:[[50,46],256],9354:[[51,46],256],9355:[[52,46],256],9356:[[53,46],256],9357:[[54,46],256],9358:[[55,46],256],9359:[[56,46],256],9360:[[57,46],256],9361:[[49,48,46],256],9362:[[49,49,46],256],9363:[[49,50,46],256],9364:[[49,51,46],256],9365:[[49,52,46],256],9366:[[49,53,46],256],9367:[[49,54,46],256],9368:[[49,55,46],256],9369:[[49,56,46],256],9370:[[49,57,46],256],9371:[[50,48,46],256],9372:[[40,97,41],256],9373:[[40,98,41],256],9374:[[40,99,41],256],9375:[[40,100,41],256],9376:[[40,101,41],256],9377:[[40,102,41],256],9378:[[40,103,41],256],9379:[[40,104,41],256],9380:[[40,105,41],256],9381:[[40,106,41],256],9382:[[40,107,41],256],9383:[[40,108,41],256],9384:[[40,109,41],256],9385:[[40,110,41],256],9386:[[40,111,41],256],9387:[[40,112,41],256],9388:[[40,113,41],256],9389:[[40,114,41],256],9390:[[40,115,41],256],9391:[[40,116,41],256],9392:[[40,117,41],256],9393:[[40,118,41],256],9394:[[40,119,41],256],9395:[[40,120,41],256],9396:[[40,121,41],256],9397:[[40,122,41],256],9398:[[65],256],9399:[[66],256],9400:[[67],256],9401:[[68],256],9402:[[69],256],9403:[[70],256],9404:[[71],256],9405:[[72],256],9406:[[73],256],9407:[[74],256],9408:[[75],256],9409:[[76],256],9410:[[77],256],9411:[[78],256],9412:[[79],256],9413:[[80],256],9414:[[81],256],9415:[[82],256],9416:[[83],256],9417:[[84],256],9418:[[85],256],9419:[[86],256],9420:[[87],256],9421:[[88],256],9422:[[89],256],9423:[[90],256],9424:[[97],256],9425:[[98],256],9426:[[99],256],9427:[[100],256],9428:[[101],256],9429:[[102],256],9430:[[103],256],9431:[[104],256],9432:[[105],256],9433:[[106],256],9434:[[107],256],9435:[[108],256],9436:[[109],256],9437:[[110],256],9438:[[111],256],9439:[[112],256],9440:[[113],256],9441:[[114],256],9442:[[115],256],9443:[[116],256],9444:[[117],256],9445:[[118],256],9446:[[119],256],9447:[[120],256],9448:[[121],256],9449:[[122],256],9450:[[48],256]}, + 10752:{10764:[[8747,8747,8747,8747],256],10868:[[58,58,61],256],10869:[[61,61],256],10870:[[61,61,61],256],10972:[[10973,824],512]}, + 11264:{11388:[[106],256],11389:[[86],256],11503:[,230],11504:[,230],11505:[,230]}, + 11520:{11631:[[11617],256],11647:[,9],11744:[,230],11745:[,230],11746:[,230],11747:[,230],11748:[,230],11749:[,230],11750:[,230],11751:[,230],11752:[,230],11753:[,230],11754:[,230],11755:[,230],11756:[,230],11757:[,230],11758:[,230],11759:[,230],11760:[,230],11761:[,230],11762:[,230],11763:[,230],11764:[,230],11765:[,230],11766:[,230],11767:[,230],11768:[,230],11769:[,230],11770:[,230],11771:[,230],11772:[,230],11773:[,230],11774:[,230],11775:[,230]}, + 11776:{11935:[[27597],256],12019:[[40863],256]}, + 12032:{12032:[[19968],256],12033:[[20008],256],12034:[[20022],256],12035:[[20031],256],12036:[[20057],256],12037:[[20101],256],12038:[[20108],256],12039:[[20128],256],12040:[[20154],256],12041:[[20799],256],12042:[[20837],256],12043:[[20843],256],12044:[[20866],256],12045:[[20886],256],12046:[[20907],256],12047:[[20960],256],12048:[[20981],256],12049:[[20992],256],12050:[[21147],256],12051:[[21241],256],12052:[[21269],256],12053:[[21274],256],12054:[[21304],256],12055:[[21313],256],12056:[[21340],256],12057:[[21353],256],12058:[[21378],256],12059:[[21430],256],12060:[[21448],256],12061:[[21475],256],12062:[[22231],256],12063:[[22303],256],12064:[[22763],256],12065:[[22786],256],12066:[[22794],256],12067:[[22805],256],12068:[[22823],256],12069:[[22899],256],12070:[[23376],256],12071:[[23424],256],12072:[[23544],256],12073:[[23567],256],12074:[[23586],256],12075:[[23608],256],12076:[[23662],256],12077:[[23665],256],12078:[[24027],256],12079:[[24037],256],12080:[[24049],256],12081:[[24062],256],12082:[[24178],256],12083:[[24186],256],12084:[[24191],256],12085:[[24308],256],12086:[[24318],256],12087:[[24331],256],12088:[[24339],256],12089:[[24400],256],12090:[[24417],256],12091:[[24435],256],12092:[[24515],256],12093:[[25096],256],12094:[[25142],256],12095:[[25163],256],12096:[[25903],256],12097:[[25908],256],12098:[[25991],256],12099:[[26007],256],12100:[[26020],256],12101:[[26041],256],12102:[[26080],256],12103:[[26085],256],12104:[[26352],256],12105:[[26376],256],12106:[[26408],256],12107:[[27424],256],12108:[[27490],256],12109:[[27513],256],12110:[[27571],256],12111:[[27595],256],12112:[[27604],256],12113:[[27611],256],12114:[[27663],256],12115:[[27668],256],12116:[[27700],256],12117:[[28779],256],12118:[[29226],256],12119:[[29238],256],12120:[[29243],256],12121:[[29247],256],12122:[[29255],256],12123:[[29273],256],12124:[[29275],256],12125:[[29356],256],12126:[[29572],256],12127:[[29577],256],12128:[[29916],256],12129:[[29926],256],12130:[[29976],256],12131:[[29983],256],12132:[[29992],256],12133:[[30000],256],12134:[[30091],256],12135:[[30098],256],12136:[[30326],256],12137:[[30333],256],12138:[[30382],256],12139:[[30399],256],12140:[[30446],256],12141:[[30683],256],12142:[[30690],256],12143:[[30707],256],12144:[[31034],256],12145:[[31160],256],12146:[[31166],256],12147:[[31348],256],12148:[[31435],256],12149:[[31481],256],12150:[[31859],256],12151:[[31992],256],12152:[[32566],256],12153:[[32593],256],12154:[[32650],256],12155:[[32701],256],12156:[[32769],256],12157:[[32780],256],12158:[[32786],256],12159:[[32819],256],12160:[[32895],256],12161:[[32905],256],12162:[[33251],256],12163:[[33258],256],12164:[[33267],256],12165:[[33276],256],12166:[[33292],256],12167:[[33307],256],12168:[[33311],256],12169:[[33390],256],12170:[[33394],256],12171:[[33400],256],12172:[[34381],256],12173:[[34411],256],12174:[[34880],256],12175:[[34892],256],12176:[[34915],256],12177:[[35198],256],12178:[[35211],256],12179:[[35282],256],12180:[[35328],256],12181:[[35895],256],12182:[[35910],256],12183:[[35925],256],12184:[[35960],256],12185:[[35997],256],12186:[[36196],256],12187:[[36208],256],12188:[[36275],256],12189:[[36523],256],12190:[[36554],256],12191:[[36763],256],12192:[[36784],256],12193:[[36789],256],12194:[[37009],256],12195:[[37193],256],12196:[[37318],256],12197:[[37324],256],12198:[[37329],256],12199:[[38263],256],12200:[[38272],256],12201:[[38428],256],12202:[[38582],256],12203:[[38585],256],12204:[[38632],256],12205:[[38737],256],12206:[[38750],256],12207:[[38754],256],12208:[[38761],256],12209:[[38859],256],12210:[[38893],256],12211:[[38899],256],12212:[[38913],256],12213:[[39080],256],12214:[[39131],256],12215:[[39135],256],12216:[[39318],256],12217:[[39321],256],12218:[[39340],256],12219:[[39592],256],12220:[[39640],256],12221:[[39647],256],12222:[[39717],256],12223:[[39727],256],12224:[[39730],256],12225:[[39740],256],12226:[[39770],256],12227:[[40165],256],12228:[[40565],256],12229:[[40575],256],12230:[[40613],256],12231:[[40635],256],12232:[[40643],256],12233:[[40653],256],12234:[[40657],256],12235:[[40697],256],12236:[[40701],256],12237:[[40718],256],12238:[[40723],256],12239:[[40736],256],12240:[[40763],256],12241:[[40778],256],12242:[[40786],256],12243:[[40845],256],12244:[[40860],256],12245:[[40864],256]}, + 12288:{12288:[[32],256],12330:[,218],12331:[,228],12332:[,232],12333:[,222],12334:[,224],12335:[,224],12342:[[12306],256],12344:[[21313],256],12345:[[21316],256],12346:[[21317],256],12358:[,,{12441:12436}],12363:[,,{12441:12364}],12364:[[12363,12441]],12365:[,,{12441:12366}],12366:[[12365,12441]],12367:[,,{12441:12368}],12368:[[12367,12441]],12369:[,,{12441:12370}],12370:[[12369,12441]],12371:[,,{12441:12372}],12372:[[12371,12441]],12373:[,,{12441:12374}],12374:[[12373,12441]],12375:[,,{12441:12376}],12376:[[12375,12441]],12377:[,,{12441:12378}],12378:[[12377,12441]],12379:[,,{12441:12380}],12380:[[12379,12441]],12381:[,,{12441:12382}],12382:[[12381,12441]],12383:[,,{12441:12384}],12384:[[12383,12441]],12385:[,,{12441:12386}],12386:[[12385,12441]],12388:[,,{12441:12389}],12389:[[12388,12441]],12390:[,,{12441:12391}],12391:[[12390,12441]],12392:[,,{12441:12393}],12393:[[12392,12441]],12399:[,,{12441:12400,12442:12401}],12400:[[12399,12441]],12401:[[12399,12442]],12402:[,,{12441:12403,12442:12404}],12403:[[12402,12441]],12404:[[12402,12442]],12405:[,,{12441:12406,12442:12407}],12406:[[12405,12441]],12407:[[12405,12442]],12408:[,,{12441:12409,12442:12410}],12409:[[12408,12441]],12410:[[12408,12442]],12411:[,,{12441:12412,12442:12413}],12412:[[12411,12441]],12413:[[12411,12442]],12436:[[12358,12441]],12441:[,8],12442:[,8],12443:[[32,12441],256],12444:[[32,12442],256],12445:[,,{12441:12446}],12446:[[12445,12441]],12447:[[12424,12426],256],12454:[,,{12441:12532}],12459:[,,{12441:12460}],12460:[[12459,12441]],12461:[,,{12441:12462}],12462:[[12461,12441]],12463:[,,{12441:12464}],12464:[[12463,12441]],12465:[,,{12441:12466}],12466:[[12465,12441]],12467:[,,{12441:12468}],12468:[[12467,12441]],12469:[,,{12441:12470}],12470:[[12469,12441]],12471:[,,{12441:12472}],12472:[[12471,12441]],12473:[,,{12441:12474}],12474:[[12473,12441]],12475:[,,{12441:12476}],12476:[[12475,12441]],12477:[,,{12441:12478}],12478:[[12477,12441]],12479:[,,{12441:12480}],12480:[[12479,12441]],12481:[,,{12441:12482}],12482:[[12481,12441]],12484:[,,{12441:12485}],12485:[[12484,12441]],12486:[,,{12441:12487}],12487:[[12486,12441]],12488:[,,{12441:12489}],12489:[[12488,12441]],12495:[,,{12441:12496,12442:12497}],12496:[[12495,12441]],12497:[[12495,12442]],12498:[,,{12441:12499,12442:12500}],12499:[[12498,12441]],12500:[[12498,12442]],12501:[,,{12441:12502,12442:12503}],12502:[[12501,12441]],12503:[[12501,12442]],12504:[,,{12441:12505,12442:12506}],12505:[[12504,12441]],12506:[[12504,12442]],12507:[,,{12441:12508,12442:12509}],12508:[[12507,12441]],12509:[[12507,12442]],12527:[,,{12441:12535}],12528:[,,{12441:12536}],12529:[,,{12441:12537}],12530:[,,{12441:12538}],12532:[[12454,12441]],12535:[[12527,12441]],12536:[[12528,12441]],12537:[[12529,12441]],12538:[[12530,12441]],12541:[,,{12441:12542}],12542:[[12541,12441]],12543:[[12467,12488],256]}, + 12544:{12593:[[4352],256],12594:[[4353],256],12595:[[4522],256],12596:[[4354],256],12597:[[4524],256],12598:[[4525],256],12599:[[4355],256],12600:[[4356],256],12601:[[4357],256],12602:[[4528],256],12603:[[4529],256],12604:[[4530],256],12605:[[4531],256],12606:[[4532],256],12607:[[4533],256],12608:[[4378],256],12609:[[4358],256],12610:[[4359],256],12611:[[4360],256],12612:[[4385],256],12613:[[4361],256],12614:[[4362],256],12615:[[4363],256],12616:[[4364],256],12617:[[4365],256],12618:[[4366],256],12619:[[4367],256],12620:[[4368],256],12621:[[4369],256],12622:[[4370],256],12623:[[4449],256],12624:[[4450],256],12625:[[4451],256],12626:[[4452],256],12627:[[4453],256],12628:[[4454],256],12629:[[4455],256],12630:[[4456],256],12631:[[4457],256],12632:[[4458],256],12633:[[4459],256],12634:[[4460],256],12635:[[4461],256],12636:[[4462],256],12637:[[4463],256],12638:[[4464],256],12639:[[4465],256],12640:[[4466],256],12641:[[4467],256],12642:[[4468],256],12643:[[4469],256],12644:[[4448],256],12645:[[4372],256],12646:[[4373],256],12647:[[4551],256],12648:[[4552],256],12649:[[4556],256],12650:[[4558],256],12651:[[4563],256],12652:[[4567],256],12653:[[4569],256],12654:[[4380],256],12655:[[4573],256],12656:[[4575],256],12657:[[4381],256],12658:[[4382],256],12659:[[4384],256],12660:[[4386],256],12661:[[4387],256],12662:[[4391],256],12663:[[4393],256],12664:[[4395],256],12665:[[4396],256],12666:[[4397],256],12667:[[4398],256],12668:[[4399],256],12669:[[4402],256],12670:[[4406],256],12671:[[4416],256],12672:[[4423],256],12673:[[4428],256],12674:[[4593],256],12675:[[4594],256],12676:[[4439],256],12677:[[4440],256],12678:[[4441],256],12679:[[4484],256],12680:[[4485],256],12681:[[4488],256],12682:[[4497],256],12683:[[4498],256],12684:[[4500],256],12685:[[4510],256],12686:[[4513],256],12690:[[19968],256],12691:[[20108],256],12692:[[19977],256],12693:[[22235],256],12694:[[19978],256],12695:[[20013],256],12696:[[19979],256],12697:[[30002],256],12698:[[20057],256],12699:[[19993],256],12700:[[19969],256],12701:[[22825],256],12702:[[22320],256],12703:[[20154],256]}, + 12800:{12800:[[40,4352,41],256],12801:[[40,4354,41],256],12802:[[40,4355,41],256],12803:[[40,4357,41],256],12804:[[40,4358,41],256],12805:[[40,4359,41],256],12806:[[40,4361,41],256],12807:[[40,4363,41],256],12808:[[40,4364,41],256],12809:[[40,4366,41],256],12810:[[40,4367,41],256],12811:[[40,4368,41],256],12812:[[40,4369,41],256],12813:[[40,4370,41],256],12814:[[40,4352,4449,41],256],12815:[[40,4354,4449,41],256],12816:[[40,4355,4449,41],256],12817:[[40,4357,4449,41],256],12818:[[40,4358,4449,41],256],12819:[[40,4359,4449,41],256],12820:[[40,4361,4449,41],256],12821:[[40,4363,4449,41],256],12822:[[40,4364,4449,41],256],12823:[[40,4366,4449,41],256],12824:[[40,4367,4449,41],256],12825:[[40,4368,4449,41],256],12826:[[40,4369,4449,41],256],12827:[[40,4370,4449,41],256],12828:[[40,4364,4462,41],256],12829:[[40,4363,4457,4364,4453,4523,41],256],12830:[[40,4363,4457,4370,4462,41],256],12832:[[40,19968,41],256],12833:[[40,20108,41],256],12834:[[40,19977,41],256],12835:[[40,22235,41],256],12836:[[40,20116,41],256],12837:[[40,20845,41],256],12838:[[40,19971,41],256],12839:[[40,20843,41],256],12840:[[40,20061,41],256],12841:[[40,21313,41],256],12842:[[40,26376,41],256],12843:[[40,28779,41],256],12844:[[40,27700,41],256],12845:[[40,26408,41],256],12846:[[40,37329,41],256],12847:[[40,22303,41],256],12848:[[40,26085,41],256],12849:[[40,26666,41],256],12850:[[40,26377,41],256],12851:[[40,31038,41],256],12852:[[40,21517,41],256],12853:[[40,29305,41],256],12854:[[40,36001,41],256],12855:[[40,31069,41],256],12856:[[40,21172,41],256],12857:[[40,20195,41],256],12858:[[40,21628,41],256],12859:[[40,23398,41],256],12860:[[40,30435,41],256],12861:[[40,20225,41],256],12862:[[40,36039,41],256],12863:[[40,21332,41],256],12864:[[40,31085,41],256],12865:[[40,20241,41],256],12866:[[40,33258,41],256],12867:[[40,33267,41],256],12868:[[21839],256],12869:[[24188],256],12870:[[25991],256],12871:[[31631],256],12880:[[80,84,69],256],12881:[[50,49],256],12882:[[50,50],256],12883:[[50,51],256],12884:[[50,52],256],12885:[[50,53],256],12886:[[50,54],256],12887:[[50,55],256],12888:[[50,56],256],12889:[[50,57],256],12890:[[51,48],256],12891:[[51,49],256],12892:[[51,50],256],12893:[[51,51],256],12894:[[51,52],256],12895:[[51,53],256],12896:[[4352],256],12897:[[4354],256],12898:[[4355],256],12899:[[4357],256],12900:[[4358],256],12901:[[4359],256],12902:[[4361],256],12903:[[4363],256],12904:[[4364],256],12905:[[4366],256],12906:[[4367],256],12907:[[4368],256],12908:[[4369],256],12909:[[4370],256],12910:[[4352,4449],256],12911:[[4354,4449],256],12912:[[4355,4449],256],12913:[[4357,4449],256],12914:[[4358,4449],256],12915:[[4359,4449],256],12916:[[4361,4449],256],12917:[[4363,4449],256],12918:[[4364,4449],256],12919:[[4366,4449],256],12920:[[4367,4449],256],12921:[[4368,4449],256],12922:[[4369,4449],256],12923:[[4370,4449],256],12924:[[4366,4449,4535,4352,4457],256],12925:[[4364,4462,4363,4468],256],12926:[[4363,4462],256],12928:[[19968],256],12929:[[20108],256],12930:[[19977],256],12931:[[22235],256],12932:[[20116],256],12933:[[20845],256],12934:[[19971],256],12935:[[20843],256],12936:[[20061],256],12937:[[21313],256],12938:[[26376],256],12939:[[28779],256],12940:[[27700],256],12941:[[26408],256],12942:[[37329],256],12943:[[22303],256],12944:[[26085],256],12945:[[26666],256],12946:[[26377],256],12947:[[31038],256],12948:[[21517],256],12949:[[29305],256],12950:[[36001],256],12951:[[31069],256],12952:[[21172],256],12953:[[31192],256],12954:[[30007],256],12955:[[22899],256],12956:[[36969],256],12957:[[20778],256],12958:[[21360],256],12959:[[27880],256],12960:[[38917],256],12961:[[20241],256],12962:[[20889],256],12963:[[27491],256],12964:[[19978],256],12965:[[20013],256],12966:[[19979],256],12967:[[24038],256],12968:[[21491],256],12969:[[21307],256],12970:[[23447],256],12971:[[23398],256],12972:[[30435],256],12973:[[20225],256],12974:[[36039],256],12975:[[21332],256],12976:[[22812],256],12977:[[51,54],256],12978:[[51,55],256],12979:[[51,56],256],12980:[[51,57],256],12981:[[52,48],256],12982:[[52,49],256],12983:[[52,50],256],12984:[[52,51],256],12985:[[52,52],256],12986:[[52,53],256],12987:[[52,54],256],12988:[[52,55],256],12989:[[52,56],256],12990:[[52,57],256],12991:[[53,48],256],12992:[[49,26376],256],12993:[[50,26376],256],12994:[[51,26376],256],12995:[[52,26376],256],12996:[[53,26376],256],12997:[[54,26376],256],12998:[[55,26376],256],12999:[[56,26376],256],13000:[[57,26376],256],13001:[[49,48,26376],256],13002:[[49,49,26376],256],13003:[[49,50,26376],256],13004:[[72,103],256],13005:[[101,114,103],256],13006:[[101,86],256],13007:[[76,84,68],256],13008:[[12450],256],13009:[[12452],256],13010:[[12454],256],13011:[[12456],256],13012:[[12458],256],13013:[[12459],256],13014:[[12461],256],13015:[[12463],256],13016:[[12465],256],13017:[[12467],256],13018:[[12469],256],13019:[[12471],256],13020:[[12473],256],13021:[[12475],256],13022:[[12477],256],13023:[[12479],256],13024:[[12481],256],13025:[[12484],256],13026:[[12486],256],13027:[[12488],256],13028:[[12490],256],13029:[[12491],256],13030:[[12492],256],13031:[[12493],256],13032:[[12494],256],13033:[[12495],256],13034:[[12498],256],13035:[[12501],256],13036:[[12504],256],13037:[[12507],256],13038:[[12510],256],13039:[[12511],256],13040:[[12512],256],13041:[[12513],256],13042:[[12514],256],13043:[[12516],256],13044:[[12518],256],13045:[[12520],256],13046:[[12521],256],13047:[[12522],256],13048:[[12523],256],13049:[[12524],256],13050:[[12525],256],13051:[[12527],256],13052:[[12528],256],13053:[[12529],256],13054:[[12530],256]}, + 13056:{13056:[[12450,12497,12540,12488],256],13057:[[12450,12523,12501,12449],256],13058:[[12450,12531,12506,12450],256],13059:[[12450,12540,12523],256],13060:[[12452,12491,12531,12464],256],13061:[[12452,12531,12481],256],13062:[[12454,12457,12531],256],13063:[[12456,12473,12463,12540,12489],256],13064:[[12456,12540,12459,12540],256],13065:[[12458,12531,12473],256],13066:[[12458,12540,12512],256],13067:[[12459,12452,12522],256],13068:[[12459,12521,12483,12488],256],13069:[[12459,12525,12522,12540],256],13070:[[12460,12525,12531],256],13071:[[12460,12531,12510],256],13072:[[12462,12460],256],13073:[[12462,12491,12540],256],13074:[[12461,12517,12522,12540],256],13075:[[12462,12523,12480,12540],256],13076:[[12461,12525],256],13077:[[12461,12525,12464,12521,12512],256],13078:[[12461,12525,12513,12540,12488,12523],256],13079:[[12461,12525,12527,12483,12488],256],13080:[[12464,12521,12512],256],13081:[[12464,12521,12512,12488,12531],256],13082:[[12463,12523,12476,12452,12525],256],13083:[[12463,12525,12540,12493],256],13084:[[12465,12540,12473],256],13085:[[12467,12523,12490],256],13086:[[12467,12540,12509],256],13087:[[12469,12452,12463,12523],256],13088:[[12469,12531,12481,12540,12512],256],13089:[[12471,12522,12531,12464],256],13090:[[12475,12531,12481],256],13091:[[12475,12531,12488],256],13092:[[12480,12540,12473],256],13093:[[12487,12471],256],13094:[[12489,12523],256],13095:[[12488,12531],256],13096:[[12490,12494],256],13097:[[12494,12483,12488],256],13098:[[12495,12452,12484],256],13099:[[12497,12540,12475,12531,12488],256],13100:[[12497,12540,12484],256],13101:[[12496,12540,12524,12523],256],13102:[[12500,12450,12473,12488,12523],256],13103:[[12500,12463,12523],256],13104:[[12500,12467],256],13105:[[12499,12523],256],13106:[[12501,12449,12521,12483,12489],256],13107:[[12501,12451,12540,12488],256],13108:[[12502,12483,12471,12455,12523],256],13109:[[12501,12521,12531],256],13110:[[12504,12463,12479,12540,12523],256],13111:[[12506,12477],256],13112:[[12506,12491,12498],256],13113:[[12504,12523,12484],256],13114:[[12506,12531,12473],256],13115:[[12506,12540,12472],256],13116:[[12505,12540,12479],256],13117:[[12509,12452,12531,12488],256],13118:[[12508,12523,12488],256],13119:[[12507,12531],256],13120:[[12509,12531,12489],256],13121:[[12507,12540,12523],256],13122:[[12507,12540,12531],256],13123:[[12510,12452,12463,12525],256],13124:[[12510,12452,12523],256],13125:[[12510,12483,12495],256],13126:[[12510,12523,12463],256],13127:[[12510,12531,12471,12519,12531],256],13128:[[12511,12463,12525,12531],256],13129:[[12511,12522],256],13130:[[12511,12522,12496,12540,12523],256],13131:[[12513,12460],256],13132:[[12513,12460,12488,12531],256],13133:[[12513,12540,12488,12523],256],13134:[[12516,12540,12489],256],13135:[[12516,12540,12523],256],13136:[[12518,12450,12531],256],13137:[[12522,12483,12488,12523],256],13138:[[12522,12521],256],13139:[[12523,12500,12540],256],13140:[[12523,12540,12502,12523],256],13141:[[12524,12512],256],13142:[[12524,12531,12488,12466,12531],256],13143:[[12527,12483,12488],256],13144:[[48,28857],256],13145:[[49,28857],256],13146:[[50,28857],256],13147:[[51,28857],256],13148:[[52,28857],256],13149:[[53,28857],256],13150:[[54,28857],256],13151:[[55,28857],256],13152:[[56,28857],256],13153:[[57,28857],256],13154:[[49,48,28857],256],13155:[[49,49,28857],256],13156:[[49,50,28857],256],13157:[[49,51,28857],256],13158:[[49,52,28857],256],13159:[[49,53,28857],256],13160:[[49,54,28857],256],13161:[[49,55,28857],256],13162:[[49,56,28857],256],13163:[[49,57,28857],256],13164:[[50,48,28857],256],13165:[[50,49,28857],256],13166:[[50,50,28857],256],13167:[[50,51,28857],256],13168:[[50,52,28857],256],13169:[[104,80,97],256],13170:[[100,97],256],13171:[[65,85],256],13172:[[98,97,114],256],13173:[[111,86],256],13174:[[112,99],256],13175:[[100,109],256],13176:[[100,109,178],256],13177:[[100,109,179],256],13178:[[73,85],256],13179:[[24179,25104],256],13180:[[26157,21644],256],13181:[[22823,27491],256],13182:[[26126,27835],256],13183:[[26666,24335,20250,31038],256],13184:[[112,65],256],13185:[[110,65],256],13186:[[956,65],256],13187:[[109,65],256],13188:[[107,65],256],13189:[[75,66],256],13190:[[77,66],256],13191:[[71,66],256],13192:[[99,97,108],256],13193:[[107,99,97,108],256],13194:[[112,70],256],13195:[[110,70],256],13196:[[956,70],256],13197:[[956,103],256],13198:[[109,103],256],13199:[[107,103],256],13200:[[72,122],256],13201:[[107,72,122],256],13202:[[77,72,122],256],13203:[[71,72,122],256],13204:[[84,72,122],256],13205:[[956,8467],256],13206:[[109,8467],256],13207:[[100,8467],256],13208:[[107,8467],256],13209:[[102,109],256],13210:[[110,109],256],13211:[[956,109],256],13212:[[109,109],256],13213:[[99,109],256],13214:[[107,109],256],13215:[[109,109,178],256],13216:[[99,109,178],256],13217:[[109,178],256],13218:[[107,109,178],256],13219:[[109,109,179],256],13220:[[99,109,179],256],13221:[[109,179],256],13222:[[107,109,179],256],13223:[[109,8725,115],256],13224:[[109,8725,115,178],256],13225:[[80,97],256],13226:[[107,80,97],256],13227:[[77,80,97],256],13228:[[71,80,97],256],13229:[[114,97,100],256],13230:[[114,97,100,8725,115],256],13231:[[114,97,100,8725,115,178],256],13232:[[112,115],256],13233:[[110,115],256],13234:[[956,115],256],13235:[[109,115],256],13236:[[112,86],256],13237:[[110,86],256],13238:[[956,86],256],13239:[[109,86],256],13240:[[107,86],256],13241:[[77,86],256],13242:[[112,87],256],13243:[[110,87],256],13244:[[956,87],256],13245:[[109,87],256],13246:[[107,87],256],13247:[[77,87],256],13248:[[107,937],256],13249:[[77,937],256],13250:[[97,46,109,46],256],13251:[[66,113],256],13252:[[99,99],256],13253:[[99,100],256],13254:[[67,8725,107,103],256],13255:[[67,111,46],256],13256:[[100,66],256],13257:[[71,121],256],13258:[[104,97],256],13259:[[72,80],256],13260:[[105,110],256],13261:[[75,75],256],13262:[[75,77],256],13263:[[107,116],256],13264:[[108,109],256],13265:[[108,110],256],13266:[[108,111,103],256],13267:[[108,120],256],13268:[[109,98],256],13269:[[109,105,108],256],13270:[[109,111,108],256],13271:[[80,72],256],13272:[[112,46,109,46],256],13273:[[80,80,77],256],13274:[[80,82],256],13275:[[115,114],256],13276:[[83,118],256],13277:[[87,98],256],13278:[[86,8725,109],256],13279:[[65,8725,109],256],13280:[[49,26085],256],13281:[[50,26085],256],13282:[[51,26085],256],13283:[[52,26085],256],13284:[[53,26085],256],13285:[[54,26085],256],13286:[[55,26085],256],13287:[[56,26085],256],13288:[[57,26085],256],13289:[[49,48,26085],256],13290:[[49,49,26085],256],13291:[[49,50,26085],256],13292:[[49,51,26085],256],13293:[[49,52,26085],256],13294:[[49,53,26085],256],13295:[[49,54,26085],256],13296:[[49,55,26085],256],13297:[[49,56,26085],256],13298:[[49,57,26085],256],13299:[[50,48,26085],256],13300:[[50,49,26085],256],13301:[[50,50,26085],256],13302:[[50,51,26085],256],13303:[[50,52,26085],256],13304:[[50,53,26085],256],13305:[[50,54,26085],256],13306:[[50,55,26085],256],13307:[[50,56,26085],256],13308:[[50,57,26085],256],13309:[[51,48,26085],256],13310:[[51,49,26085],256],13311:[[103,97,108],256]}, + 42496:{42607:[,230],42612:[,230],42613:[,230],42614:[,230],42615:[,230],42616:[,230],42617:[,230],42618:[,230],42619:[,230],42620:[,230],42621:[,230],42655:[,230],42736:[,230],42737:[,230]}, + 42752:{42864:[[42863],256],43000:[[294],256],43001:[[339],256]}, + 43008:{43014:[,9],43204:[,9],43232:[,230],43233:[,230],43234:[,230],43235:[,230],43236:[,230],43237:[,230],43238:[,230],43239:[,230],43240:[,230],43241:[,230],43242:[,230],43243:[,230],43244:[,230],43245:[,230],43246:[,230],43247:[,230],43248:[,230],43249:[,230]}, + 43264:{43307:[,220],43308:[,220],43309:[,220],43347:[,9],43443:[,7],43456:[,9]}, + 43520:{43696:[,230],43698:[,230],43699:[,230],43700:[,220],43703:[,230],43704:[,230],43710:[,230],43711:[,230],43713:[,230],43766:[,9]}, + 43776:{44013:[,9]}, + 53504:{119134:[[119127,119141],512],119135:[[119128,119141],512],119136:[[119135,119150],512],119137:[[119135,119151],512],119138:[[119135,119152],512],119139:[[119135,119153],512],119140:[[119135,119154],512],119141:[,216],119142:[,216],119143:[,1],119144:[,1],119145:[,1],119149:[,226],119150:[,216],119151:[,216],119152:[,216],119153:[,216],119154:[,216],119163:[,220],119164:[,220],119165:[,220],119166:[,220],119167:[,220],119168:[,220],119169:[,220],119170:[,220],119173:[,230],119174:[,230],119175:[,230],119176:[,230],119177:[,230],119178:[,220],119179:[,220],119210:[,230],119211:[,230],119212:[,230],119213:[,230],119227:[[119225,119141],512],119228:[[119226,119141],512],119229:[[119227,119150],512],119230:[[119228,119150],512],119231:[[119227,119151],512],119232:[[119228,119151],512]}, + 53760:{119362:[,230],119363:[,230],119364:[,230]}, + 54272:{119808:[[65],256],119809:[[66],256],119810:[[67],256],119811:[[68],256],119812:[[69],256],119813:[[70],256],119814:[[71],256],119815:[[72],256],119816:[[73],256],119817:[[74],256],119818:[[75],256],119819:[[76],256],119820:[[77],256],119821:[[78],256],119822:[[79],256],119823:[[80],256],119824:[[81],256],119825:[[82],256],119826:[[83],256],119827:[[84],256],119828:[[85],256],119829:[[86],256],119830:[[87],256],119831:[[88],256],119832:[[89],256],119833:[[90],256],119834:[[97],256],119835:[[98],256],119836:[[99],256],119837:[[100],256],119838:[[101],256],119839:[[102],256],119840:[[103],256],119841:[[104],256],119842:[[105],256],119843:[[106],256],119844:[[107],256],119845:[[108],256],119846:[[109],256],119847:[[110],256],119848:[[111],256],119849:[[112],256],119850:[[113],256],119851:[[114],256],119852:[[115],256],119853:[[116],256],119854:[[117],256],119855:[[118],256],119856:[[119],256],119857:[[120],256],119858:[[121],256],119859:[[122],256],119860:[[65],256],119861:[[66],256],119862:[[67],256],119863:[[68],256],119864:[[69],256],119865:[[70],256],119866:[[71],256],119867:[[72],256],119868:[[73],256],119869:[[74],256],119870:[[75],256],119871:[[76],256],119872:[[77],256],119873:[[78],256],119874:[[79],256],119875:[[80],256],119876:[[81],256],119877:[[82],256],119878:[[83],256],119879:[[84],256],119880:[[85],256],119881:[[86],256],119882:[[87],256],119883:[[88],256],119884:[[89],256],119885:[[90],256],119886:[[97],256],119887:[[98],256],119888:[[99],256],119889:[[100],256],119890:[[101],256],119891:[[102],256],119892:[[103],256],119894:[[105],256],119895:[[106],256],119896:[[107],256],119897:[[108],256],119898:[[109],256],119899:[[110],256],119900:[[111],256],119901:[[112],256],119902:[[113],256],119903:[[114],256],119904:[[115],256],119905:[[116],256],119906:[[117],256],119907:[[118],256],119908:[[119],256],119909:[[120],256],119910:[[121],256],119911:[[122],256],119912:[[65],256],119913:[[66],256],119914:[[67],256],119915:[[68],256],119916:[[69],256],119917:[[70],256],119918:[[71],256],119919:[[72],256],119920:[[73],256],119921:[[74],256],119922:[[75],256],119923:[[76],256],119924:[[77],256],119925:[[78],256],119926:[[79],256],119927:[[80],256],119928:[[81],256],119929:[[82],256],119930:[[83],256],119931:[[84],256],119932:[[85],256],119933:[[86],256],119934:[[87],256],119935:[[88],256],119936:[[89],256],119937:[[90],256],119938:[[97],256],119939:[[98],256],119940:[[99],256],119941:[[100],256],119942:[[101],256],119943:[[102],256],119944:[[103],256],119945:[[104],256],119946:[[105],256],119947:[[106],256],119948:[[107],256],119949:[[108],256],119950:[[109],256],119951:[[110],256],119952:[[111],256],119953:[[112],256],119954:[[113],256],119955:[[114],256],119956:[[115],256],119957:[[116],256],119958:[[117],256],119959:[[118],256],119960:[[119],256],119961:[[120],256],119962:[[121],256],119963:[[122],256],119964:[[65],256],119966:[[67],256],119967:[[68],256],119970:[[71],256],119973:[[74],256],119974:[[75],256],119977:[[78],256],119978:[[79],256],119979:[[80],256],119980:[[81],256],119982:[[83],256],119983:[[84],256],119984:[[85],256],119985:[[86],256],119986:[[87],256],119987:[[88],256],119988:[[89],256],119989:[[90],256],119990:[[97],256],119991:[[98],256],119992:[[99],256],119993:[[100],256],119995:[[102],256],119997:[[104],256],119998:[[105],256],119999:[[106],256],120000:[[107],256],120001:[[108],256],120002:[[109],256],120003:[[110],256],120005:[[112],256],120006:[[113],256],120007:[[114],256],120008:[[115],256],120009:[[116],256],120010:[[117],256],120011:[[118],256],120012:[[119],256],120013:[[120],256],120014:[[121],256],120015:[[122],256],120016:[[65],256],120017:[[66],256],120018:[[67],256],120019:[[68],256],120020:[[69],256],120021:[[70],256],120022:[[71],256],120023:[[72],256],120024:[[73],256],120025:[[74],256],120026:[[75],256],120027:[[76],256],120028:[[77],256],120029:[[78],256],120030:[[79],256],120031:[[80],256],120032:[[81],256],120033:[[82],256],120034:[[83],256],120035:[[84],256],120036:[[85],256],120037:[[86],256],120038:[[87],256],120039:[[88],256],120040:[[89],256],120041:[[90],256],120042:[[97],256],120043:[[98],256],120044:[[99],256],120045:[[100],256],120046:[[101],256],120047:[[102],256],120048:[[103],256],120049:[[104],256],120050:[[105],256],120051:[[106],256],120052:[[107],256],120053:[[108],256],120054:[[109],256],120055:[[110],256],120056:[[111],256],120057:[[112],256],120058:[[113],256],120059:[[114],256],120060:[[115],256],120061:[[116],256],120062:[[117],256],120063:[[118],256]}, + 54528:{120064:[[119],256],120065:[[120],256],120066:[[121],256],120067:[[122],256],120068:[[65],256],120069:[[66],256],120071:[[68],256],120072:[[69],256],120073:[[70],256],120074:[[71],256],120077:[[74],256],120078:[[75],256],120079:[[76],256],120080:[[77],256],120081:[[78],256],120082:[[79],256],120083:[[80],256],120084:[[81],256],120086:[[83],256],120087:[[84],256],120088:[[85],256],120089:[[86],256],120090:[[87],256],120091:[[88],256],120092:[[89],256],120094:[[97],256],120095:[[98],256],120096:[[99],256],120097:[[100],256],120098:[[101],256],120099:[[102],256],120100:[[103],256],120101:[[104],256],120102:[[105],256],120103:[[106],256],120104:[[107],256],120105:[[108],256],120106:[[109],256],120107:[[110],256],120108:[[111],256],120109:[[112],256],120110:[[113],256],120111:[[114],256],120112:[[115],256],120113:[[116],256],120114:[[117],256],120115:[[118],256],120116:[[119],256],120117:[[120],256],120118:[[121],256],120119:[[122],256],120120:[[65],256],120121:[[66],256],120123:[[68],256],120124:[[69],256],120125:[[70],256],120126:[[71],256],120128:[[73],256],120129:[[74],256],120130:[[75],256],120131:[[76],256],120132:[[77],256],120134:[[79],256],120138:[[83],256],120139:[[84],256],120140:[[85],256],120141:[[86],256],120142:[[87],256],120143:[[88],256],120144:[[89],256],120146:[[97],256],120147:[[98],256],120148:[[99],256],120149:[[100],256],120150:[[101],256],120151:[[102],256],120152:[[103],256],120153:[[104],256],120154:[[105],256],120155:[[106],256],120156:[[107],256],120157:[[108],256],120158:[[109],256],120159:[[110],256],120160:[[111],256],120161:[[112],256],120162:[[113],256],120163:[[114],256],120164:[[115],256],120165:[[116],256],120166:[[117],256],120167:[[118],256],120168:[[119],256],120169:[[120],256],120170:[[121],256],120171:[[122],256],120172:[[65],256],120173:[[66],256],120174:[[67],256],120175:[[68],256],120176:[[69],256],120177:[[70],256],120178:[[71],256],120179:[[72],256],120180:[[73],256],120181:[[74],256],120182:[[75],256],120183:[[76],256],120184:[[77],256],120185:[[78],256],120186:[[79],256],120187:[[80],256],120188:[[81],256],120189:[[82],256],120190:[[83],256],120191:[[84],256],120192:[[85],256],120193:[[86],256],120194:[[87],256],120195:[[88],256],120196:[[89],256],120197:[[90],256],120198:[[97],256],120199:[[98],256],120200:[[99],256],120201:[[100],256],120202:[[101],256],120203:[[102],256],120204:[[103],256],120205:[[104],256],120206:[[105],256],120207:[[106],256],120208:[[107],256],120209:[[108],256],120210:[[109],256],120211:[[110],256],120212:[[111],256],120213:[[112],256],120214:[[113],256],120215:[[114],256],120216:[[115],256],120217:[[116],256],120218:[[117],256],120219:[[118],256],120220:[[119],256],120221:[[120],256],120222:[[121],256],120223:[[122],256],120224:[[65],256],120225:[[66],256],120226:[[67],256],120227:[[68],256],120228:[[69],256],120229:[[70],256],120230:[[71],256],120231:[[72],256],120232:[[73],256],120233:[[74],256],120234:[[75],256],120235:[[76],256],120236:[[77],256],120237:[[78],256],120238:[[79],256],120239:[[80],256],120240:[[81],256],120241:[[82],256],120242:[[83],256],120243:[[84],256],120244:[[85],256],120245:[[86],256],120246:[[87],256],120247:[[88],256],120248:[[89],256],120249:[[90],256],120250:[[97],256],120251:[[98],256],120252:[[99],256],120253:[[100],256],120254:[[101],256],120255:[[102],256],120256:[[103],256],120257:[[104],256],120258:[[105],256],120259:[[106],256],120260:[[107],256],120261:[[108],256],120262:[[109],256],120263:[[110],256],120264:[[111],256],120265:[[112],256],120266:[[113],256],120267:[[114],256],120268:[[115],256],120269:[[116],256],120270:[[117],256],120271:[[118],256],120272:[[119],256],120273:[[120],256],120274:[[121],256],120275:[[122],256],120276:[[65],256],120277:[[66],256],120278:[[67],256],120279:[[68],256],120280:[[69],256],120281:[[70],256],120282:[[71],256],120283:[[72],256],120284:[[73],256],120285:[[74],256],120286:[[75],256],120287:[[76],256],120288:[[77],256],120289:[[78],256],120290:[[79],256],120291:[[80],256],120292:[[81],256],120293:[[82],256],120294:[[83],256],120295:[[84],256],120296:[[85],256],120297:[[86],256],120298:[[87],256],120299:[[88],256],120300:[[89],256],120301:[[90],256],120302:[[97],256],120303:[[98],256],120304:[[99],256],120305:[[100],256],120306:[[101],256],120307:[[102],256],120308:[[103],256],120309:[[104],256],120310:[[105],256],120311:[[106],256],120312:[[107],256],120313:[[108],256],120314:[[109],256],120315:[[110],256],120316:[[111],256],120317:[[112],256],120318:[[113],256],120319:[[114],256]}, + 54784:{120320:[[115],256],120321:[[116],256],120322:[[117],256],120323:[[118],256],120324:[[119],256],120325:[[120],256],120326:[[121],256],120327:[[122],256],120328:[[65],256],120329:[[66],256],120330:[[67],256],120331:[[68],256],120332:[[69],256],120333:[[70],256],120334:[[71],256],120335:[[72],256],120336:[[73],256],120337:[[74],256],120338:[[75],256],120339:[[76],256],120340:[[77],256],120341:[[78],256],120342:[[79],256],120343:[[80],256],120344:[[81],256],120345:[[82],256],120346:[[83],256],120347:[[84],256],120348:[[85],256],120349:[[86],256],120350:[[87],256],120351:[[88],256],120352:[[89],256],120353:[[90],256],120354:[[97],256],120355:[[98],256],120356:[[99],256],120357:[[100],256],120358:[[101],256],120359:[[102],256],120360:[[103],256],120361:[[104],256],120362:[[105],256],120363:[[106],256],120364:[[107],256],120365:[[108],256],120366:[[109],256],120367:[[110],256],120368:[[111],256],120369:[[112],256],120370:[[113],256],120371:[[114],256],120372:[[115],256],120373:[[116],256],120374:[[117],256],120375:[[118],256],120376:[[119],256],120377:[[120],256],120378:[[121],256],120379:[[122],256],120380:[[65],256],120381:[[66],256],120382:[[67],256],120383:[[68],256],120384:[[69],256],120385:[[70],256],120386:[[71],256],120387:[[72],256],120388:[[73],256],120389:[[74],256],120390:[[75],256],120391:[[76],256],120392:[[77],256],120393:[[78],256],120394:[[79],256],120395:[[80],256],120396:[[81],256],120397:[[82],256],120398:[[83],256],120399:[[84],256],120400:[[85],256],120401:[[86],256],120402:[[87],256],120403:[[88],256],120404:[[89],256],120405:[[90],256],120406:[[97],256],120407:[[98],256],120408:[[99],256],120409:[[100],256],120410:[[101],256],120411:[[102],256],120412:[[103],256],120413:[[104],256],120414:[[105],256],120415:[[106],256],120416:[[107],256],120417:[[108],256],120418:[[109],256],120419:[[110],256],120420:[[111],256],120421:[[112],256],120422:[[113],256],120423:[[114],256],120424:[[115],256],120425:[[116],256],120426:[[117],256],120427:[[118],256],120428:[[119],256],120429:[[120],256],120430:[[121],256],120431:[[122],256],120432:[[65],256],120433:[[66],256],120434:[[67],256],120435:[[68],256],120436:[[69],256],120437:[[70],256],120438:[[71],256],120439:[[72],256],120440:[[73],256],120441:[[74],256],120442:[[75],256],120443:[[76],256],120444:[[77],256],120445:[[78],256],120446:[[79],256],120447:[[80],256],120448:[[81],256],120449:[[82],256],120450:[[83],256],120451:[[84],256],120452:[[85],256],120453:[[86],256],120454:[[87],256],120455:[[88],256],120456:[[89],256],120457:[[90],256],120458:[[97],256],120459:[[98],256],120460:[[99],256],120461:[[100],256],120462:[[101],256],120463:[[102],256],120464:[[103],256],120465:[[104],256],120466:[[105],256],120467:[[106],256],120468:[[107],256],120469:[[108],256],120470:[[109],256],120471:[[110],256],120472:[[111],256],120473:[[112],256],120474:[[113],256],120475:[[114],256],120476:[[115],256],120477:[[116],256],120478:[[117],256],120479:[[118],256],120480:[[119],256],120481:[[120],256],120482:[[121],256],120483:[[122],256],120484:[[305],256],120485:[[567],256],120488:[[913],256],120489:[[914],256],120490:[[915],256],120491:[[916],256],120492:[[917],256],120493:[[918],256],120494:[[919],256],120495:[[920],256],120496:[[921],256],120497:[[922],256],120498:[[923],256],120499:[[924],256],120500:[[925],256],120501:[[926],256],120502:[[927],256],120503:[[928],256],120504:[[929],256],120505:[[1012],256],120506:[[931],256],120507:[[932],256],120508:[[933],256],120509:[[934],256],120510:[[935],256],120511:[[936],256],120512:[[937],256],120513:[[8711],256],120514:[[945],256],120515:[[946],256],120516:[[947],256],120517:[[948],256],120518:[[949],256],120519:[[950],256],120520:[[951],256],120521:[[952],256],120522:[[953],256],120523:[[954],256],120524:[[955],256],120525:[[956],256],120526:[[957],256],120527:[[958],256],120528:[[959],256],120529:[[960],256],120530:[[961],256],120531:[[962],256],120532:[[963],256],120533:[[964],256],120534:[[965],256],120535:[[966],256],120536:[[967],256],120537:[[968],256],120538:[[969],256],120539:[[8706],256],120540:[[1013],256],120541:[[977],256],120542:[[1008],256],120543:[[981],256],120544:[[1009],256],120545:[[982],256],120546:[[913],256],120547:[[914],256],120548:[[915],256],120549:[[916],256],120550:[[917],256],120551:[[918],256],120552:[[919],256],120553:[[920],256],120554:[[921],256],120555:[[922],256],120556:[[923],256],120557:[[924],256],120558:[[925],256],120559:[[926],256],120560:[[927],256],120561:[[928],256],120562:[[929],256],120563:[[1012],256],120564:[[931],256],120565:[[932],256],120566:[[933],256],120567:[[934],256],120568:[[935],256],120569:[[936],256],120570:[[937],256],120571:[[8711],256],120572:[[945],256],120573:[[946],256],120574:[[947],256],120575:[[948],256]}, + 55040:{120576:[[949],256],120577:[[950],256],120578:[[951],256],120579:[[952],256],120580:[[953],256],120581:[[954],256],120582:[[955],256],120583:[[956],256],120584:[[957],256],120585:[[958],256],120586:[[959],256],120587:[[960],256],120588:[[961],256],120589:[[962],256],120590:[[963],256],120591:[[964],256],120592:[[965],256],120593:[[966],256],120594:[[967],256],120595:[[968],256],120596:[[969],256],120597:[[8706],256],120598:[[1013],256],120599:[[977],256],120600:[[1008],256],120601:[[981],256],120602:[[1009],256],120603:[[982],256],120604:[[913],256],120605:[[914],256],120606:[[915],256],120607:[[916],256],120608:[[917],256],120609:[[918],256],120610:[[919],256],120611:[[920],256],120612:[[921],256],120613:[[922],256],120614:[[923],256],120615:[[924],256],120616:[[925],256],120617:[[926],256],120618:[[927],256],120619:[[928],256],120620:[[929],256],120621:[[1012],256],120622:[[931],256],120623:[[932],256],120624:[[933],256],120625:[[934],256],120626:[[935],256],120627:[[936],256],120628:[[937],256],120629:[[8711],256],120630:[[945],256],120631:[[946],256],120632:[[947],256],120633:[[948],256],120634:[[949],256],120635:[[950],256],120636:[[951],256],120637:[[952],256],120638:[[953],256],120639:[[954],256],120640:[[955],256],120641:[[956],256],120642:[[957],256],120643:[[958],256],120644:[[959],256],120645:[[960],256],120646:[[961],256],120647:[[962],256],120648:[[963],256],120649:[[964],256],120650:[[965],256],120651:[[966],256],120652:[[967],256],120653:[[968],256],120654:[[969],256],120655:[[8706],256],120656:[[1013],256],120657:[[977],256],120658:[[1008],256],120659:[[981],256],120660:[[1009],256],120661:[[982],256],120662:[[913],256],120663:[[914],256],120664:[[915],256],120665:[[916],256],120666:[[917],256],120667:[[918],256],120668:[[919],256],120669:[[920],256],120670:[[921],256],120671:[[922],256],120672:[[923],256],120673:[[924],256],120674:[[925],256],120675:[[926],256],120676:[[927],256],120677:[[928],256],120678:[[929],256],120679:[[1012],256],120680:[[931],256],120681:[[932],256],120682:[[933],256],120683:[[934],256],120684:[[935],256],120685:[[936],256],120686:[[937],256],120687:[[8711],256],120688:[[945],256],120689:[[946],256],120690:[[947],256],120691:[[948],256],120692:[[949],256],120693:[[950],256],120694:[[951],256],120695:[[952],256],120696:[[953],256],120697:[[954],256],120698:[[955],256],120699:[[956],256],120700:[[957],256],120701:[[958],256],120702:[[959],256],120703:[[960],256],120704:[[961],256],120705:[[962],256],120706:[[963],256],120707:[[964],256],120708:[[965],256],120709:[[966],256],120710:[[967],256],120711:[[968],256],120712:[[969],256],120713:[[8706],256],120714:[[1013],256],120715:[[977],256],120716:[[1008],256],120717:[[981],256],120718:[[1009],256],120719:[[982],256],120720:[[913],256],120721:[[914],256],120722:[[915],256],120723:[[916],256],120724:[[917],256],120725:[[918],256],120726:[[919],256],120727:[[920],256],120728:[[921],256],120729:[[922],256],120730:[[923],256],120731:[[924],256],120732:[[925],256],120733:[[926],256],120734:[[927],256],120735:[[928],256],120736:[[929],256],120737:[[1012],256],120738:[[931],256],120739:[[932],256],120740:[[933],256],120741:[[934],256],120742:[[935],256],120743:[[936],256],120744:[[937],256],120745:[[8711],256],120746:[[945],256],120747:[[946],256],120748:[[947],256],120749:[[948],256],120750:[[949],256],120751:[[950],256],120752:[[951],256],120753:[[952],256],120754:[[953],256],120755:[[954],256],120756:[[955],256],120757:[[956],256],120758:[[957],256],120759:[[958],256],120760:[[959],256],120761:[[960],256],120762:[[961],256],120763:[[962],256],120764:[[963],256],120765:[[964],256],120766:[[965],256],120767:[[966],256],120768:[[967],256],120769:[[968],256],120770:[[969],256],120771:[[8706],256],120772:[[1013],256],120773:[[977],256],120774:[[1008],256],120775:[[981],256],120776:[[1009],256],120777:[[982],256],120778:[[988],256],120779:[[989],256],120782:[[48],256],120783:[[49],256],120784:[[50],256],120785:[[51],256],120786:[[52],256],120787:[[53],256],120788:[[54],256],120789:[[55],256],120790:[[56],256],120791:[[57],256],120792:[[48],256],120793:[[49],256],120794:[[50],256],120795:[[51],256],120796:[[52],256],120797:[[53],256],120798:[[54],256],120799:[[55],256],120800:[[56],256],120801:[[57],256],120802:[[48],256],120803:[[49],256],120804:[[50],256],120805:[[51],256],120806:[[52],256],120807:[[53],256],120808:[[54],256],120809:[[55],256],120810:[[56],256],120811:[[57],256],120812:[[48],256],120813:[[49],256],120814:[[50],256],120815:[[51],256],120816:[[52],256],120817:[[53],256],120818:[[54],256],120819:[[55],256],120820:[[56],256],120821:[[57],256],120822:[[48],256],120823:[[49],256],120824:[[50],256],120825:[[51],256],120826:[[52],256],120827:[[53],256],120828:[[54],256],120829:[[55],256],120830:[[56],256],120831:[[57],256]}, + 60928:{126464:[[1575],256],126465:[[1576],256],126466:[[1580],256],126467:[[1583],256],126469:[[1608],256],126470:[[1586],256],126471:[[1581],256],126472:[[1591],256],126473:[[1610],256],126474:[[1603],256],126475:[[1604],256],126476:[[1605],256],126477:[[1606],256],126478:[[1587],256],126479:[[1593],256],126480:[[1601],256],126481:[[1589],256],126482:[[1602],256],126483:[[1585],256],126484:[[1588],256],126485:[[1578],256],126486:[[1579],256],126487:[[1582],256],126488:[[1584],256],126489:[[1590],256],126490:[[1592],256],126491:[[1594],256],126492:[[1646],256],126493:[[1722],256],126494:[[1697],256],126495:[[1647],256],126497:[[1576],256],126498:[[1580],256],126500:[[1607],256],126503:[[1581],256],126505:[[1610],256],126506:[[1603],256],126507:[[1604],256],126508:[[1605],256],126509:[[1606],256],126510:[[1587],256],126511:[[1593],256],126512:[[1601],256],126513:[[1589],256],126514:[[1602],256],126516:[[1588],256],126517:[[1578],256],126518:[[1579],256],126519:[[1582],256],126521:[[1590],256],126523:[[1594],256],126530:[[1580],256],126535:[[1581],256],126537:[[1610],256],126539:[[1604],256],126541:[[1606],256],126542:[[1587],256],126543:[[1593],256],126545:[[1589],256],126546:[[1602],256],126548:[[1588],256],126551:[[1582],256],126553:[[1590],256],126555:[[1594],256],126557:[[1722],256],126559:[[1647],256],126561:[[1576],256],126562:[[1580],256],126564:[[1607],256],126567:[[1581],256],126568:[[1591],256],126569:[[1610],256],126570:[[1603],256],126572:[[1605],256],126573:[[1606],256],126574:[[1587],256],126575:[[1593],256],126576:[[1601],256],126577:[[1589],256],126578:[[1602],256],126580:[[1588],256],126581:[[1578],256],126582:[[1579],256],126583:[[1582],256],126585:[[1590],256],126586:[[1592],256],126587:[[1594],256],126588:[[1646],256],126590:[[1697],256],126592:[[1575],256],126593:[[1576],256],126594:[[1580],256],126595:[[1583],256],126596:[[1607],256],126597:[[1608],256],126598:[[1586],256],126599:[[1581],256],126600:[[1591],256],126601:[[1610],256],126603:[[1604],256],126604:[[1605],256],126605:[[1606],256],126606:[[1587],256],126607:[[1593],256],126608:[[1601],256],126609:[[1589],256],126610:[[1602],256],126611:[[1585],256],126612:[[1588],256],126613:[[1578],256],126614:[[1579],256],126615:[[1582],256],126616:[[1584],256],126617:[[1590],256],126618:[[1592],256],126619:[[1594],256],126625:[[1576],256],126626:[[1580],256],126627:[[1583],256],126629:[[1608],256],126630:[[1586],256],126631:[[1581],256],126632:[[1591],256],126633:[[1610],256],126635:[[1604],256],126636:[[1605],256],126637:[[1606],256],126638:[[1587],256],126639:[[1593],256],126640:[[1601],256],126641:[[1589],256],126642:[[1602],256],126643:[[1585],256],126644:[[1588],256],126645:[[1578],256],126646:[[1579],256],126647:[[1582],256],126648:[[1584],256],126649:[[1590],256],126650:[[1592],256],126651:[[1594],256]}, + 61696:{127232:[[48,46],256],127233:[[48,44],256],127234:[[49,44],256],127235:[[50,44],256],127236:[[51,44],256],127237:[[52,44],256],127238:[[53,44],256],127239:[[54,44],256],127240:[[55,44],256],127241:[[56,44],256],127242:[[57,44],256],127248:[[40,65,41],256],127249:[[40,66,41],256],127250:[[40,67,41],256],127251:[[40,68,41],256],127252:[[40,69,41],256],127253:[[40,70,41],256],127254:[[40,71,41],256],127255:[[40,72,41],256],127256:[[40,73,41],256],127257:[[40,74,41],256],127258:[[40,75,41],256],127259:[[40,76,41],256],127260:[[40,77,41],256],127261:[[40,78,41],256],127262:[[40,79,41],256],127263:[[40,80,41],256],127264:[[40,81,41],256],127265:[[40,82,41],256],127266:[[40,83,41],256],127267:[[40,84,41],256],127268:[[40,85,41],256],127269:[[40,86,41],256],127270:[[40,87,41],256],127271:[[40,88,41],256],127272:[[40,89,41],256],127273:[[40,90,41],256],127274:[[12308,83,12309],256],127275:[[67],256],127276:[[82],256],127277:[[67,68],256],127278:[[87,90],256],127280:[[65],256],127281:[[66],256],127282:[[67],256],127283:[[68],256],127284:[[69],256],127285:[[70],256],127286:[[71],256],127287:[[72],256],127288:[[73],256],127289:[[74],256],127290:[[75],256],127291:[[76],256],127292:[[77],256],127293:[[78],256],127294:[[79],256],127295:[[80],256],127296:[[81],256],127297:[[82],256],127298:[[83],256],127299:[[84],256],127300:[[85],256],127301:[[86],256],127302:[[87],256],127303:[[88],256],127304:[[89],256],127305:[[90],256],127306:[[72,86],256],127307:[[77,86],256],127308:[[83,68],256],127309:[[83,83],256],127310:[[80,80,86],256],127311:[[87,67],256],127338:[[77,67],256],127339:[[77,68],256],127376:[[68,74],256]}, + 61952:{127488:[[12411,12363],256],127489:[[12467,12467],256],127490:[[12469],256],127504:[[25163],256],127505:[[23383],256],127506:[[21452],256],127507:[[12487],256],127508:[[20108],256],127509:[[22810],256],127510:[[35299],256],127511:[[22825],256],127512:[[20132],256],127513:[[26144],256],127514:[[28961],256],127515:[[26009],256],127516:[[21069],256],127517:[[24460],256],127518:[[20877],256],127519:[[26032],256],127520:[[21021],256],127521:[[32066],256],127522:[[29983],256],127523:[[36009],256],127524:[[22768],256],127525:[[21561],256],127526:[[28436],256],127527:[[25237],256],127528:[[25429],256],127529:[[19968],256],127530:[[19977],256],127531:[[36938],256],127532:[[24038],256],127533:[[20013],256],127534:[[21491],256],127535:[[25351],256],127536:[[36208],256],127537:[[25171],256],127538:[[31105],256],127539:[[31354],256],127540:[[21512],256],127541:[[28288],256],127542:[[26377],256],127543:[[26376],256],127544:[[30003],256],127545:[[21106],256],127546:[[21942],256],127552:[[12308,26412,12309],256],127553:[[12308,19977,12309],256],127554:[[12308,20108,12309],256],127555:[[12308,23433,12309],256],127556:[[12308,28857,12309],256],127557:[[12308,25171,12309],256],127558:[[12308,30423,12309],256],127559:[[12308,21213,12309],256],127560:[[12308,25943,12309],256],127568:[[24471],256],127569:[[21487],256]}, + 63488:{194560:[[20029]],194561:[[20024]],194562:[[20033]],194563:[[131362]],194564:[[20320]],194565:[[20398]],194566:[[20411]],194567:[[20482]],194568:[[20602]],194569:[[20633]],194570:[[20711]],194571:[[20687]],194572:[[13470]],194573:[[132666]],194574:[[20813]],194575:[[20820]],194576:[[20836]],194577:[[20855]],194578:[[132380]],194579:[[13497]],194580:[[20839]],194581:[[20877]],194582:[[132427]],194583:[[20887]],194584:[[20900]],194585:[[20172]],194586:[[20908]],194587:[[20917]],194588:[[168415]],194589:[[20981]],194590:[[20995]],194591:[[13535]],194592:[[21051]],194593:[[21062]],194594:[[21106]],194595:[[21111]],194596:[[13589]],194597:[[21191]],194598:[[21193]],194599:[[21220]],194600:[[21242]],194601:[[21253]],194602:[[21254]],194603:[[21271]],194604:[[21321]],194605:[[21329]],194606:[[21338]],194607:[[21363]],194608:[[21373]],194609:[[21375]],194610:[[21375]],194611:[[21375]],194612:[[133676]],194613:[[28784]],194614:[[21450]],194615:[[21471]],194616:[[133987]],194617:[[21483]],194618:[[21489]],194619:[[21510]],194620:[[21662]],194621:[[21560]],194622:[[21576]],194623:[[21608]],194624:[[21666]],194625:[[21750]],194626:[[21776]],194627:[[21843]],194628:[[21859]],194629:[[21892]],194630:[[21892]],194631:[[21913]],194632:[[21931]],194633:[[21939]],194634:[[21954]],194635:[[22294]],194636:[[22022]],194637:[[22295]],194638:[[22097]],194639:[[22132]],194640:[[20999]],194641:[[22766]],194642:[[22478]],194643:[[22516]],194644:[[22541]],194645:[[22411]],194646:[[22578]],194647:[[22577]],194648:[[22700]],194649:[[136420]],194650:[[22770]],194651:[[22775]],194652:[[22790]],194653:[[22810]],194654:[[22818]],194655:[[22882]],194656:[[136872]],194657:[[136938]],194658:[[23020]],194659:[[23067]],194660:[[23079]],194661:[[23000]],194662:[[23142]],194663:[[14062]],194664:[[14076]],194665:[[23304]],194666:[[23358]],194667:[[23358]],194668:[[137672]],194669:[[23491]],194670:[[23512]],194671:[[23527]],194672:[[23539]],194673:[[138008]],194674:[[23551]],194675:[[23558]],194676:[[24403]],194677:[[23586]],194678:[[14209]],194679:[[23648]],194680:[[23662]],194681:[[23744]],194682:[[23693]],194683:[[138724]],194684:[[23875]],194685:[[138726]],194686:[[23918]],194687:[[23915]],194688:[[23932]],194689:[[24033]],194690:[[24034]],194691:[[14383]],194692:[[24061]],194693:[[24104]],194694:[[24125]],194695:[[24169]],194696:[[14434]],194697:[[139651]],194698:[[14460]],194699:[[24240]],194700:[[24243]],194701:[[24246]],194702:[[24266]],194703:[[172946]],194704:[[24318]],194705:[[140081]],194706:[[140081]],194707:[[33281]],194708:[[24354]],194709:[[24354]],194710:[[14535]],194711:[[144056]],194712:[[156122]],194713:[[24418]],194714:[[24427]],194715:[[14563]],194716:[[24474]],194717:[[24525]],194718:[[24535]],194719:[[24569]],194720:[[24705]],194721:[[14650]],194722:[[14620]],194723:[[24724]],194724:[[141012]],194725:[[24775]],194726:[[24904]],194727:[[24908]],194728:[[24910]],194729:[[24908]],194730:[[24954]],194731:[[24974]],194732:[[25010]],194733:[[24996]],194734:[[25007]],194735:[[25054]],194736:[[25074]],194737:[[25078]],194738:[[25104]],194739:[[25115]],194740:[[25181]],194741:[[25265]],194742:[[25300]],194743:[[25424]],194744:[[142092]],194745:[[25405]],194746:[[25340]],194747:[[25448]],194748:[[25475]],194749:[[25572]],194750:[[142321]],194751:[[25634]],194752:[[25541]],194753:[[25513]],194754:[[14894]],194755:[[25705]],194756:[[25726]],194757:[[25757]],194758:[[25719]],194759:[[14956]],194760:[[25935]],194761:[[25964]],194762:[[143370]],194763:[[26083]],194764:[[26360]],194765:[[26185]],194766:[[15129]],194767:[[26257]],194768:[[15112]],194769:[[15076]],194770:[[20882]],194771:[[20885]],194772:[[26368]],194773:[[26268]],194774:[[32941]],194775:[[17369]],194776:[[26391]],194777:[[26395]],194778:[[26401]],194779:[[26462]],194780:[[26451]],194781:[[144323]],194782:[[15177]],194783:[[26618]],194784:[[26501]],194785:[[26706]],194786:[[26757]],194787:[[144493]],194788:[[26766]],194789:[[26655]],194790:[[26900]],194791:[[15261]],194792:[[26946]],194793:[[27043]],194794:[[27114]],194795:[[27304]],194796:[[145059]],194797:[[27355]],194798:[[15384]],194799:[[27425]],194800:[[145575]],194801:[[27476]],194802:[[15438]],194803:[[27506]],194804:[[27551]],194805:[[27578]],194806:[[27579]],194807:[[146061]],194808:[[138507]],194809:[[146170]],194810:[[27726]],194811:[[146620]],194812:[[27839]],194813:[[27853]],194814:[[27751]],194815:[[27926]]}, + 63744:{63744:[[35912]],63745:[[26356]],63746:[[36554]],63747:[[36040]],63748:[[28369]],63749:[[20018]],63750:[[21477]],63751:[[40860]],63752:[[40860]],63753:[[22865]],63754:[[37329]],63755:[[21895]],63756:[[22856]],63757:[[25078]],63758:[[30313]],63759:[[32645]],63760:[[34367]],63761:[[34746]],63762:[[35064]],63763:[[37007]],63764:[[27138]],63765:[[27931]],63766:[[28889]],63767:[[29662]],63768:[[33853]],63769:[[37226]],63770:[[39409]],63771:[[20098]],63772:[[21365]],63773:[[27396]],63774:[[29211]],63775:[[34349]],63776:[[40478]],63777:[[23888]],63778:[[28651]],63779:[[34253]],63780:[[35172]],63781:[[25289]],63782:[[33240]],63783:[[34847]],63784:[[24266]],63785:[[26391]],63786:[[28010]],63787:[[29436]],63788:[[37070]],63789:[[20358]],63790:[[20919]],63791:[[21214]],63792:[[25796]],63793:[[27347]],63794:[[29200]],63795:[[30439]],63796:[[32769]],63797:[[34310]],63798:[[34396]],63799:[[36335]],63800:[[38706]],63801:[[39791]],63802:[[40442]],63803:[[30860]],63804:[[31103]],63805:[[32160]],63806:[[33737]],63807:[[37636]],63808:[[40575]],63809:[[35542]],63810:[[22751]],63811:[[24324]],63812:[[31840]],63813:[[32894]],63814:[[29282]],63815:[[30922]],63816:[[36034]],63817:[[38647]],63818:[[22744]],63819:[[23650]],63820:[[27155]],63821:[[28122]],63822:[[28431]],63823:[[32047]],63824:[[32311]],63825:[[38475]],63826:[[21202]],63827:[[32907]],63828:[[20956]],63829:[[20940]],63830:[[31260]],63831:[[32190]],63832:[[33777]],63833:[[38517]],63834:[[35712]],63835:[[25295]],63836:[[27138]],63837:[[35582]],63838:[[20025]],63839:[[23527]],63840:[[24594]],63841:[[29575]],63842:[[30064]],63843:[[21271]],63844:[[30971]],63845:[[20415]],63846:[[24489]],63847:[[19981]],63848:[[27852]],63849:[[25976]],63850:[[32034]],63851:[[21443]],63852:[[22622]],63853:[[30465]],63854:[[33865]],63855:[[35498]],63856:[[27578]],63857:[[36784]],63858:[[27784]],63859:[[25342]],63860:[[33509]],63861:[[25504]],63862:[[30053]],63863:[[20142]],63864:[[20841]],63865:[[20937]],63866:[[26753]],63867:[[31975]],63868:[[33391]],63869:[[35538]],63870:[[37327]],63871:[[21237]],63872:[[21570]],63873:[[22899]],63874:[[24300]],63875:[[26053]],63876:[[28670]],63877:[[31018]],63878:[[38317]],63879:[[39530]],63880:[[40599]],63881:[[40654]],63882:[[21147]],63883:[[26310]],63884:[[27511]],63885:[[36706]],63886:[[24180]],63887:[[24976]],63888:[[25088]],63889:[[25754]],63890:[[28451]],63891:[[29001]],63892:[[29833]],63893:[[31178]],63894:[[32244]],63895:[[32879]],63896:[[36646]],63897:[[34030]],63898:[[36899]],63899:[[37706]],63900:[[21015]],63901:[[21155]],63902:[[21693]],63903:[[28872]],63904:[[35010]],63905:[[35498]],63906:[[24265]],63907:[[24565]],63908:[[25467]],63909:[[27566]],63910:[[31806]],63911:[[29557]],63912:[[20196]],63913:[[22265]],63914:[[23527]],63915:[[23994]],63916:[[24604]],63917:[[29618]],63918:[[29801]],63919:[[32666]],63920:[[32838]],63921:[[37428]],63922:[[38646]],63923:[[38728]],63924:[[38936]],63925:[[20363]],63926:[[31150]],63927:[[37300]],63928:[[38584]],63929:[[24801]],63930:[[20102]],63931:[[20698]],63932:[[23534]],63933:[[23615]],63934:[[26009]],63935:[[27138]],63936:[[29134]],63937:[[30274]],63938:[[34044]],63939:[[36988]],63940:[[40845]],63941:[[26248]],63942:[[38446]],63943:[[21129]],63944:[[26491]],63945:[[26611]],63946:[[27969]],63947:[[28316]],63948:[[29705]],63949:[[30041]],63950:[[30827]],63951:[[32016]],63952:[[39006]],63953:[[20845]],63954:[[25134]],63955:[[38520]],63956:[[20523]],63957:[[23833]],63958:[[28138]],63959:[[36650]],63960:[[24459]],63961:[[24900]],63962:[[26647]],63963:[[29575]],63964:[[38534]],63965:[[21033]],63966:[[21519]],63967:[[23653]],63968:[[26131]],63969:[[26446]],63970:[[26792]],63971:[[27877]],63972:[[29702]],63973:[[30178]],63974:[[32633]],63975:[[35023]],63976:[[35041]],63977:[[37324]],63978:[[38626]],63979:[[21311]],63980:[[28346]],63981:[[21533]],63982:[[29136]],63983:[[29848]],63984:[[34298]],63985:[[38563]],63986:[[40023]],63987:[[40607]],63988:[[26519]],63989:[[28107]],63990:[[33256]],63991:[[31435]],63992:[[31520]],63993:[[31890]],63994:[[29376]],63995:[[28825]],63996:[[35672]],63997:[[20160]],63998:[[33590]],63999:[[21050]],194816:[[27966]],194817:[[28023]],194818:[[27969]],194819:[[28009]],194820:[[28024]],194821:[[28037]],194822:[[146718]],194823:[[27956]],194824:[[28207]],194825:[[28270]],194826:[[15667]],194827:[[28363]],194828:[[28359]],194829:[[147153]],194830:[[28153]],194831:[[28526]],194832:[[147294]],194833:[[147342]],194834:[[28614]],194835:[[28729]],194836:[[28702]],194837:[[28699]],194838:[[15766]],194839:[[28746]],194840:[[28797]],194841:[[28791]],194842:[[28845]],194843:[[132389]],194844:[[28997]],194845:[[148067]],194846:[[29084]],194847:[[148395]],194848:[[29224]],194849:[[29237]],194850:[[29264]],194851:[[149000]],194852:[[29312]],194853:[[29333]],194854:[[149301]],194855:[[149524]],194856:[[29562]],194857:[[29579]],194858:[[16044]],194859:[[29605]],194860:[[16056]],194861:[[16056]],194862:[[29767]],194863:[[29788]],194864:[[29809]],194865:[[29829]],194866:[[29898]],194867:[[16155]],194868:[[29988]],194869:[[150582]],194870:[[30014]],194871:[[150674]],194872:[[30064]],194873:[[139679]],194874:[[30224]],194875:[[151457]],194876:[[151480]],194877:[[151620]],194878:[[16380]],194879:[[16392]],194880:[[30452]],194881:[[151795]],194882:[[151794]],194883:[[151833]],194884:[[151859]],194885:[[30494]],194886:[[30495]],194887:[[30495]],194888:[[30538]],194889:[[16441]],194890:[[30603]],194891:[[16454]],194892:[[16534]],194893:[[152605]],194894:[[30798]],194895:[[30860]],194896:[[30924]],194897:[[16611]],194898:[[153126]],194899:[[31062]],194900:[[153242]],194901:[[153285]],194902:[[31119]],194903:[[31211]],194904:[[16687]],194905:[[31296]],194906:[[31306]],194907:[[31311]],194908:[[153980]],194909:[[154279]],194910:[[154279]],194911:[[31470]],194912:[[16898]],194913:[[154539]],194914:[[31686]],194915:[[31689]],194916:[[16935]],194917:[[154752]],194918:[[31954]],194919:[[17056]],194920:[[31976]],194921:[[31971]],194922:[[32000]],194923:[[155526]],194924:[[32099]],194925:[[17153]],194926:[[32199]],194927:[[32258]],194928:[[32325]],194929:[[17204]],194930:[[156200]],194931:[[156231]],194932:[[17241]],194933:[[156377]],194934:[[32634]],194935:[[156478]],194936:[[32661]],194937:[[32762]],194938:[[32773]],194939:[[156890]],194940:[[156963]],194941:[[32864]],194942:[[157096]],194943:[[32880]],194944:[[144223]],194945:[[17365]],194946:[[32946]],194947:[[33027]],194948:[[17419]],194949:[[33086]],194950:[[23221]],194951:[[157607]],194952:[[157621]],194953:[[144275]],194954:[[144284]],194955:[[33281]],194956:[[33284]],194957:[[36766]],194958:[[17515]],194959:[[33425]],194960:[[33419]],194961:[[33437]],194962:[[21171]],194963:[[33457]],194964:[[33459]],194965:[[33469]],194966:[[33510]],194967:[[158524]],194968:[[33509]],194969:[[33565]],194970:[[33635]],194971:[[33709]],194972:[[33571]],194973:[[33725]],194974:[[33767]],194975:[[33879]],194976:[[33619]],194977:[[33738]],194978:[[33740]],194979:[[33756]],194980:[[158774]],194981:[[159083]],194982:[[158933]],194983:[[17707]],194984:[[34033]],194985:[[34035]],194986:[[34070]],194987:[[160714]],194988:[[34148]],194989:[[159532]],194990:[[17757]],194991:[[17761]],194992:[[159665]],194993:[[159954]],194994:[[17771]],194995:[[34384]],194996:[[34396]],194997:[[34407]],194998:[[34409]],194999:[[34473]],195000:[[34440]],195001:[[34574]],195002:[[34530]],195003:[[34681]],195004:[[34600]],195005:[[34667]],195006:[[34694]],195007:[[17879]],195008:[[34785]],195009:[[34817]],195010:[[17913]],195011:[[34912]],195012:[[34915]],195013:[[161383]],195014:[[35031]],195015:[[35038]],195016:[[17973]],195017:[[35066]],195018:[[13499]],195019:[[161966]],195020:[[162150]],195021:[[18110]],195022:[[18119]],195023:[[35488]],195024:[[35565]],195025:[[35722]],195026:[[35925]],195027:[[162984]],195028:[[36011]],195029:[[36033]],195030:[[36123]],195031:[[36215]],195032:[[163631]],195033:[[133124]],195034:[[36299]],195035:[[36284]],195036:[[36336]],195037:[[133342]],195038:[[36564]],195039:[[36664]],195040:[[165330]],195041:[[165357]],195042:[[37012]],195043:[[37105]],195044:[[37137]],195045:[[165678]],195046:[[37147]],195047:[[37432]],195048:[[37591]],195049:[[37592]],195050:[[37500]],195051:[[37881]],195052:[[37909]],195053:[[166906]],195054:[[38283]],195055:[[18837]],195056:[[38327]],195057:[[167287]],195058:[[18918]],195059:[[38595]],195060:[[23986]],195061:[[38691]],195062:[[168261]],195063:[[168474]],195064:[[19054]],195065:[[19062]],195066:[[38880]],195067:[[168970]],195068:[[19122]],195069:[[169110]],195070:[[38923]],195071:[[38923]]}, + 64000:{64000:[[20999]],64001:[[24230]],64002:[[25299]],64003:[[31958]],64004:[[23429]],64005:[[27934]],64006:[[26292]],64007:[[36667]],64008:[[34892]],64009:[[38477]],64010:[[35211]],64011:[[24275]],64012:[[20800]],64013:[[21952]],64016:[[22618]],64018:[[26228]],64021:[[20958]],64022:[[29482]],64023:[[30410]],64024:[[31036]],64025:[[31070]],64026:[[31077]],64027:[[31119]],64028:[[38742]],64029:[[31934]],64030:[[32701]],64032:[[34322]],64034:[[35576]],64037:[[36920]],64038:[[37117]],64042:[[39151]],64043:[[39164]],64044:[[39208]],64045:[[40372]],64046:[[37086]],64047:[[38583]],64048:[[20398]],64049:[[20711]],64050:[[20813]],64051:[[21193]],64052:[[21220]],64053:[[21329]],64054:[[21917]],64055:[[22022]],64056:[[22120]],64057:[[22592]],64058:[[22696]],64059:[[23652]],64060:[[23662]],64061:[[24724]],64062:[[24936]],64063:[[24974]],64064:[[25074]],64065:[[25935]],64066:[[26082]],64067:[[26257]],64068:[[26757]],64069:[[28023]],64070:[[28186]],64071:[[28450]],64072:[[29038]],64073:[[29227]],64074:[[29730]],64075:[[30865]],64076:[[31038]],64077:[[31049]],64078:[[31048]],64079:[[31056]],64080:[[31062]],64081:[[31069]],64082:[[31117]],64083:[[31118]],64084:[[31296]],64085:[[31361]],64086:[[31680]],64087:[[32244]],64088:[[32265]],64089:[[32321]],64090:[[32626]],64091:[[32773]],64092:[[33261]],64093:[[33401]],64094:[[33401]],64095:[[33879]],64096:[[35088]],64097:[[35222]],64098:[[35585]],64099:[[35641]],64100:[[36051]],64101:[[36104]],64102:[[36790]],64103:[[36920]],64104:[[38627]],64105:[[38911]],64106:[[38971]],64107:[[24693]],64108:[[148206]],64109:[[33304]],64112:[[20006]],64113:[[20917]],64114:[[20840]],64115:[[20352]],64116:[[20805]],64117:[[20864]],64118:[[21191]],64119:[[21242]],64120:[[21917]],64121:[[21845]],64122:[[21913]],64123:[[21986]],64124:[[22618]],64125:[[22707]],64126:[[22852]],64127:[[22868]],64128:[[23138]],64129:[[23336]],64130:[[24274]],64131:[[24281]],64132:[[24425]],64133:[[24493]],64134:[[24792]],64135:[[24910]],64136:[[24840]],64137:[[24974]],64138:[[24928]],64139:[[25074]],64140:[[25140]],64141:[[25540]],64142:[[25628]],64143:[[25682]],64144:[[25942]],64145:[[26228]],64146:[[26391]],64147:[[26395]],64148:[[26454]],64149:[[27513]],64150:[[27578]],64151:[[27969]],64152:[[28379]],64153:[[28363]],64154:[[28450]],64155:[[28702]],64156:[[29038]],64157:[[30631]],64158:[[29237]],64159:[[29359]],64160:[[29482]],64161:[[29809]],64162:[[29958]],64163:[[30011]],64164:[[30237]],64165:[[30239]],64166:[[30410]],64167:[[30427]],64168:[[30452]],64169:[[30538]],64170:[[30528]],64171:[[30924]],64172:[[31409]],64173:[[31680]],64174:[[31867]],64175:[[32091]],64176:[[32244]],64177:[[32574]],64178:[[32773]],64179:[[33618]],64180:[[33775]],64181:[[34681]],64182:[[35137]],64183:[[35206]],64184:[[35222]],64185:[[35519]],64186:[[35576]],64187:[[35531]],64188:[[35585]],64189:[[35582]],64190:[[35565]],64191:[[35641]],64192:[[35722]],64193:[[36104]],64194:[[36664]],64195:[[36978]],64196:[[37273]],64197:[[37494]],64198:[[38524]],64199:[[38627]],64200:[[38742]],64201:[[38875]],64202:[[38911]],64203:[[38923]],64204:[[38971]],64205:[[39698]],64206:[[40860]],64207:[[141386]],64208:[[141380]],64209:[[144341]],64210:[[15261]],64211:[[16408]],64212:[[16441]],64213:[[152137]],64214:[[154832]],64215:[[163539]],64216:[[40771]],64217:[[40846]],195072:[[38953]],195073:[[169398]],195074:[[39138]],195075:[[19251]],195076:[[39209]],195077:[[39335]],195078:[[39362]],195079:[[39422]],195080:[[19406]],195081:[[170800]],195082:[[39698]],195083:[[40000]],195084:[[40189]],195085:[[19662]],195086:[[19693]],195087:[[40295]],195088:[[172238]],195089:[[19704]],195090:[[172293]],195091:[[172558]],195092:[[172689]],195093:[[40635]],195094:[[19798]],195095:[[40697]],195096:[[40702]],195097:[[40709]],195098:[[40719]],195099:[[40726]],195100:[[40763]],195101:[[173568]]}, + 64256:{64256:[[102,102],256],64257:[[102,105],256],64258:[[102,108],256],64259:[[102,102,105],256],64260:[[102,102,108],256],64261:[[383,116],256],64262:[[115,116],256],64275:[[1396,1398],256],64276:[[1396,1381],256],64277:[[1396,1387],256],64278:[[1406,1398],256],64279:[[1396,1389],256],64285:[[1497,1460],512],64286:[,26],64287:[[1522,1463],512],64288:[[1506],256],64289:[[1488],256],64290:[[1491],256],64291:[[1492],256],64292:[[1499],256],64293:[[1500],256],64294:[[1501],256],64295:[[1512],256],64296:[[1514],256],64297:[[43],256],64298:[[1513,1473],512],64299:[[1513,1474],512],64300:[[64329,1473],512],64301:[[64329,1474],512],64302:[[1488,1463],512],64303:[[1488,1464],512],64304:[[1488,1468],512],64305:[[1489,1468],512],64306:[[1490,1468],512],64307:[[1491,1468],512],64308:[[1492,1468],512],64309:[[1493,1468],512],64310:[[1494,1468],512],64312:[[1496,1468],512],64313:[[1497,1468],512],64314:[[1498,1468],512],64315:[[1499,1468],512],64316:[[1500,1468],512],64318:[[1502,1468],512],64320:[[1504,1468],512],64321:[[1505,1468],512],64323:[[1507,1468],512],64324:[[1508,1468],512],64326:[[1510,1468],512],64327:[[1511,1468],512],64328:[[1512,1468],512],64329:[[1513,1468],512],64330:[[1514,1468],512],64331:[[1493,1465],512],64332:[[1489,1471],512],64333:[[1499,1471],512],64334:[[1508,1471],512],64335:[[1488,1500],256],64336:[[1649],256],64337:[[1649],256],64338:[[1659],256],64339:[[1659],256],64340:[[1659],256],64341:[[1659],256],64342:[[1662],256],64343:[[1662],256],64344:[[1662],256],64345:[[1662],256],64346:[[1664],256],64347:[[1664],256],64348:[[1664],256],64349:[[1664],256],64350:[[1658],256],64351:[[1658],256],64352:[[1658],256],64353:[[1658],256],64354:[[1663],256],64355:[[1663],256],64356:[[1663],256],64357:[[1663],256],64358:[[1657],256],64359:[[1657],256],64360:[[1657],256],64361:[[1657],256],64362:[[1700],256],64363:[[1700],256],64364:[[1700],256],64365:[[1700],256],64366:[[1702],256],64367:[[1702],256],64368:[[1702],256],64369:[[1702],256],64370:[[1668],256],64371:[[1668],256],64372:[[1668],256],64373:[[1668],256],64374:[[1667],256],64375:[[1667],256],64376:[[1667],256],64377:[[1667],256],64378:[[1670],256],64379:[[1670],256],64380:[[1670],256],64381:[[1670],256],64382:[[1671],256],64383:[[1671],256],64384:[[1671],256],64385:[[1671],256],64386:[[1677],256],64387:[[1677],256],64388:[[1676],256],64389:[[1676],256],64390:[[1678],256],64391:[[1678],256],64392:[[1672],256],64393:[[1672],256],64394:[[1688],256],64395:[[1688],256],64396:[[1681],256],64397:[[1681],256],64398:[[1705],256],64399:[[1705],256],64400:[[1705],256],64401:[[1705],256],64402:[[1711],256],64403:[[1711],256],64404:[[1711],256],64405:[[1711],256],64406:[[1715],256],64407:[[1715],256],64408:[[1715],256],64409:[[1715],256],64410:[[1713],256],64411:[[1713],256],64412:[[1713],256],64413:[[1713],256],64414:[[1722],256],64415:[[1722],256],64416:[[1723],256],64417:[[1723],256],64418:[[1723],256],64419:[[1723],256],64420:[[1728],256],64421:[[1728],256],64422:[[1729],256],64423:[[1729],256],64424:[[1729],256],64425:[[1729],256],64426:[[1726],256],64427:[[1726],256],64428:[[1726],256],64429:[[1726],256],64430:[[1746],256],64431:[[1746],256],64432:[[1747],256],64433:[[1747],256],64467:[[1709],256],64468:[[1709],256],64469:[[1709],256],64470:[[1709],256],64471:[[1735],256],64472:[[1735],256],64473:[[1734],256],64474:[[1734],256],64475:[[1736],256],64476:[[1736],256],64477:[[1655],256],64478:[[1739],256],64479:[[1739],256],64480:[[1733],256],64481:[[1733],256],64482:[[1737],256],64483:[[1737],256],64484:[[1744],256],64485:[[1744],256],64486:[[1744],256],64487:[[1744],256],64488:[[1609],256],64489:[[1609],256],64490:[[1574,1575],256],64491:[[1574,1575],256],64492:[[1574,1749],256],64493:[[1574,1749],256],64494:[[1574,1608],256],64495:[[1574,1608],256],64496:[[1574,1735],256],64497:[[1574,1735],256],64498:[[1574,1734],256],64499:[[1574,1734],256],64500:[[1574,1736],256],64501:[[1574,1736],256],64502:[[1574,1744],256],64503:[[1574,1744],256],64504:[[1574,1744],256],64505:[[1574,1609],256],64506:[[1574,1609],256],64507:[[1574,1609],256],64508:[[1740],256],64509:[[1740],256],64510:[[1740],256],64511:[[1740],256]}, + 64512:{64512:[[1574,1580],256],64513:[[1574,1581],256],64514:[[1574,1605],256],64515:[[1574,1609],256],64516:[[1574,1610],256],64517:[[1576,1580],256],64518:[[1576,1581],256],64519:[[1576,1582],256],64520:[[1576,1605],256],64521:[[1576,1609],256],64522:[[1576,1610],256],64523:[[1578,1580],256],64524:[[1578,1581],256],64525:[[1578,1582],256],64526:[[1578,1605],256],64527:[[1578,1609],256],64528:[[1578,1610],256],64529:[[1579,1580],256],64530:[[1579,1605],256],64531:[[1579,1609],256],64532:[[1579,1610],256],64533:[[1580,1581],256],64534:[[1580,1605],256],64535:[[1581,1580],256],64536:[[1581,1605],256],64537:[[1582,1580],256],64538:[[1582,1581],256],64539:[[1582,1605],256],64540:[[1587,1580],256],64541:[[1587,1581],256],64542:[[1587,1582],256],64543:[[1587,1605],256],64544:[[1589,1581],256],64545:[[1589,1605],256],64546:[[1590,1580],256],64547:[[1590,1581],256],64548:[[1590,1582],256],64549:[[1590,1605],256],64550:[[1591,1581],256],64551:[[1591,1605],256],64552:[[1592,1605],256],64553:[[1593,1580],256],64554:[[1593,1605],256],64555:[[1594,1580],256],64556:[[1594,1605],256],64557:[[1601,1580],256],64558:[[1601,1581],256],64559:[[1601,1582],256],64560:[[1601,1605],256],64561:[[1601,1609],256],64562:[[1601,1610],256],64563:[[1602,1581],256],64564:[[1602,1605],256],64565:[[1602,1609],256],64566:[[1602,1610],256],64567:[[1603,1575],256],64568:[[1603,1580],256],64569:[[1603,1581],256],64570:[[1603,1582],256],64571:[[1603,1604],256],64572:[[1603,1605],256],64573:[[1603,1609],256],64574:[[1603,1610],256],64575:[[1604,1580],256],64576:[[1604,1581],256],64577:[[1604,1582],256],64578:[[1604,1605],256],64579:[[1604,1609],256],64580:[[1604,1610],256],64581:[[1605,1580],256],64582:[[1605,1581],256],64583:[[1605,1582],256],64584:[[1605,1605],256],64585:[[1605,1609],256],64586:[[1605,1610],256],64587:[[1606,1580],256],64588:[[1606,1581],256],64589:[[1606,1582],256],64590:[[1606,1605],256],64591:[[1606,1609],256],64592:[[1606,1610],256],64593:[[1607,1580],256],64594:[[1607,1605],256],64595:[[1607,1609],256],64596:[[1607,1610],256],64597:[[1610,1580],256],64598:[[1610,1581],256],64599:[[1610,1582],256],64600:[[1610,1605],256],64601:[[1610,1609],256],64602:[[1610,1610],256],64603:[[1584,1648],256],64604:[[1585,1648],256],64605:[[1609,1648],256],64606:[[32,1612,1617],256],64607:[[32,1613,1617],256],64608:[[32,1614,1617],256],64609:[[32,1615,1617],256],64610:[[32,1616,1617],256],64611:[[32,1617,1648],256],64612:[[1574,1585],256],64613:[[1574,1586],256],64614:[[1574,1605],256],64615:[[1574,1606],256],64616:[[1574,1609],256],64617:[[1574,1610],256],64618:[[1576,1585],256],64619:[[1576,1586],256],64620:[[1576,1605],256],64621:[[1576,1606],256],64622:[[1576,1609],256],64623:[[1576,1610],256],64624:[[1578,1585],256],64625:[[1578,1586],256],64626:[[1578,1605],256],64627:[[1578,1606],256],64628:[[1578,1609],256],64629:[[1578,1610],256],64630:[[1579,1585],256],64631:[[1579,1586],256],64632:[[1579,1605],256],64633:[[1579,1606],256],64634:[[1579,1609],256],64635:[[1579,1610],256],64636:[[1601,1609],256],64637:[[1601,1610],256],64638:[[1602,1609],256],64639:[[1602,1610],256],64640:[[1603,1575],256],64641:[[1603,1604],256],64642:[[1603,1605],256],64643:[[1603,1609],256],64644:[[1603,1610],256],64645:[[1604,1605],256],64646:[[1604,1609],256],64647:[[1604,1610],256],64648:[[1605,1575],256],64649:[[1605,1605],256],64650:[[1606,1585],256],64651:[[1606,1586],256],64652:[[1606,1605],256],64653:[[1606,1606],256],64654:[[1606,1609],256],64655:[[1606,1610],256],64656:[[1609,1648],256],64657:[[1610,1585],256],64658:[[1610,1586],256],64659:[[1610,1605],256],64660:[[1610,1606],256],64661:[[1610,1609],256],64662:[[1610,1610],256],64663:[[1574,1580],256],64664:[[1574,1581],256],64665:[[1574,1582],256],64666:[[1574,1605],256],64667:[[1574,1607],256],64668:[[1576,1580],256],64669:[[1576,1581],256],64670:[[1576,1582],256],64671:[[1576,1605],256],64672:[[1576,1607],256],64673:[[1578,1580],256],64674:[[1578,1581],256],64675:[[1578,1582],256],64676:[[1578,1605],256],64677:[[1578,1607],256],64678:[[1579,1605],256],64679:[[1580,1581],256],64680:[[1580,1605],256],64681:[[1581,1580],256],64682:[[1581,1605],256],64683:[[1582,1580],256],64684:[[1582,1605],256],64685:[[1587,1580],256],64686:[[1587,1581],256],64687:[[1587,1582],256],64688:[[1587,1605],256],64689:[[1589,1581],256],64690:[[1589,1582],256],64691:[[1589,1605],256],64692:[[1590,1580],256],64693:[[1590,1581],256],64694:[[1590,1582],256],64695:[[1590,1605],256],64696:[[1591,1581],256],64697:[[1592,1605],256],64698:[[1593,1580],256],64699:[[1593,1605],256],64700:[[1594,1580],256],64701:[[1594,1605],256],64702:[[1601,1580],256],64703:[[1601,1581],256],64704:[[1601,1582],256],64705:[[1601,1605],256],64706:[[1602,1581],256],64707:[[1602,1605],256],64708:[[1603,1580],256],64709:[[1603,1581],256],64710:[[1603,1582],256],64711:[[1603,1604],256],64712:[[1603,1605],256],64713:[[1604,1580],256],64714:[[1604,1581],256],64715:[[1604,1582],256],64716:[[1604,1605],256],64717:[[1604,1607],256],64718:[[1605,1580],256],64719:[[1605,1581],256],64720:[[1605,1582],256],64721:[[1605,1605],256],64722:[[1606,1580],256],64723:[[1606,1581],256],64724:[[1606,1582],256],64725:[[1606,1605],256],64726:[[1606,1607],256],64727:[[1607,1580],256],64728:[[1607,1605],256],64729:[[1607,1648],256],64730:[[1610,1580],256],64731:[[1610,1581],256],64732:[[1610,1582],256],64733:[[1610,1605],256],64734:[[1610,1607],256],64735:[[1574,1605],256],64736:[[1574,1607],256],64737:[[1576,1605],256],64738:[[1576,1607],256],64739:[[1578,1605],256],64740:[[1578,1607],256],64741:[[1579,1605],256],64742:[[1579,1607],256],64743:[[1587,1605],256],64744:[[1587,1607],256],64745:[[1588,1605],256],64746:[[1588,1607],256],64747:[[1603,1604],256],64748:[[1603,1605],256],64749:[[1604,1605],256],64750:[[1606,1605],256],64751:[[1606,1607],256],64752:[[1610,1605],256],64753:[[1610,1607],256],64754:[[1600,1614,1617],256],64755:[[1600,1615,1617],256],64756:[[1600,1616,1617],256],64757:[[1591,1609],256],64758:[[1591,1610],256],64759:[[1593,1609],256],64760:[[1593,1610],256],64761:[[1594,1609],256],64762:[[1594,1610],256],64763:[[1587,1609],256],64764:[[1587,1610],256],64765:[[1588,1609],256],64766:[[1588,1610],256],64767:[[1581,1609],256]}, + 64768:{64768:[[1581,1610],256],64769:[[1580,1609],256],64770:[[1580,1610],256],64771:[[1582,1609],256],64772:[[1582,1610],256],64773:[[1589,1609],256],64774:[[1589,1610],256],64775:[[1590,1609],256],64776:[[1590,1610],256],64777:[[1588,1580],256],64778:[[1588,1581],256],64779:[[1588,1582],256],64780:[[1588,1605],256],64781:[[1588,1585],256],64782:[[1587,1585],256],64783:[[1589,1585],256],64784:[[1590,1585],256],64785:[[1591,1609],256],64786:[[1591,1610],256],64787:[[1593,1609],256],64788:[[1593,1610],256],64789:[[1594,1609],256],64790:[[1594,1610],256],64791:[[1587,1609],256],64792:[[1587,1610],256],64793:[[1588,1609],256],64794:[[1588,1610],256],64795:[[1581,1609],256],64796:[[1581,1610],256],64797:[[1580,1609],256],64798:[[1580,1610],256],64799:[[1582,1609],256],64800:[[1582,1610],256],64801:[[1589,1609],256],64802:[[1589,1610],256],64803:[[1590,1609],256],64804:[[1590,1610],256],64805:[[1588,1580],256],64806:[[1588,1581],256],64807:[[1588,1582],256],64808:[[1588,1605],256],64809:[[1588,1585],256],64810:[[1587,1585],256],64811:[[1589,1585],256],64812:[[1590,1585],256],64813:[[1588,1580],256],64814:[[1588,1581],256],64815:[[1588,1582],256],64816:[[1588,1605],256],64817:[[1587,1607],256],64818:[[1588,1607],256],64819:[[1591,1605],256],64820:[[1587,1580],256],64821:[[1587,1581],256],64822:[[1587,1582],256],64823:[[1588,1580],256],64824:[[1588,1581],256],64825:[[1588,1582],256],64826:[[1591,1605],256],64827:[[1592,1605],256],64828:[[1575,1611],256],64829:[[1575,1611],256],64848:[[1578,1580,1605],256],64849:[[1578,1581,1580],256],64850:[[1578,1581,1580],256],64851:[[1578,1581,1605],256],64852:[[1578,1582,1605],256],64853:[[1578,1605,1580],256],64854:[[1578,1605,1581],256],64855:[[1578,1605,1582],256],64856:[[1580,1605,1581],256],64857:[[1580,1605,1581],256],64858:[[1581,1605,1610],256],64859:[[1581,1605,1609],256],64860:[[1587,1581,1580],256],64861:[[1587,1580,1581],256],64862:[[1587,1580,1609],256],64863:[[1587,1605,1581],256],64864:[[1587,1605,1581],256],64865:[[1587,1605,1580],256],64866:[[1587,1605,1605],256],64867:[[1587,1605,1605],256],64868:[[1589,1581,1581],256],64869:[[1589,1581,1581],256],64870:[[1589,1605,1605],256],64871:[[1588,1581,1605],256],64872:[[1588,1581,1605],256],64873:[[1588,1580,1610],256],64874:[[1588,1605,1582],256],64875:[[1588,1605,1582],256],64876:[[1588,1605,1605],256],64877:[[1588,1605,1605],256],64878:[[1590,1581,1609],256],64879:[[1590,1582,1605],256],64880:[[1590,1582,1605],256],64881:[[1591,1605,1581],256],64882:[[1591,1605,1581],256],64883:[[1591,1605,1605],256],64884:[[1591,1605,1610],256],64885:[[1593,1580,1605],256],64886:[[1593,1605,1605],256],64887:[[1593,1605,1605],256],64888:[[1593,1605,1609],256],64889:[[1594,1605,1605],256],64890:[[1594,1605,1610],256],64891:[[1594,1605,1609],256],64892:[[1601,1582,1605],256],64893:[[1601,1582,1605],256],64894:[[1602,1605,1581],256],64895:[[1602,1605,1605],256],64896:[[1604,1581,1605],256],64897:[[1604,1581,1610],256],64898:[[1604,1581,1609],256],64899:[[1604,1580,1580],256],64900:[[1604,1580,1580],256],64901:[[1604,1582,1605],256],64902:[[1604,1582,1605],256],64903:[[1604,1605,1581],256],64904:[[1604,1605,1581],256],64905:[[1605,1581,1580],256],64906:[[1605,1581,1605],256],64907:[[1605,1581,1610],256],64908:[[1605,1580,1581],256],64909:[[1605,1580,1605],256],64910:[[1605,1582,1580],256],64911:[[1605,1582,1605],256],64914:[[1605,1580,1582],256],64915:[[1607,1605,1580],256],64916:[[1607,1605,1605],256],64917:[[1606,1581,1605],256],64918:[[1606,1581,1609],256],64919:[[1606,1580,1605],256],64920:[[1606,1580,1605],256],64921:[[1606,1580,1609],256],64922:[[1606,1605,1610],256],64923:[[1606,1605,1609],256],64924:[[1610,1605,1605],256],64925:[[1610,1605,1605],256],64926:[[1576,1582,1610],256],64927:[[1578,1580,1610],256],64928:[[1578,1580,1609],256],64929:[[1578,1582,1610],256],64930:[[1578,1582,1609],256],64931:[[1578,1605,1610],256],64932:[[1578,1605,1609],256],64933:[[1580,1605,1610],256],64934:[[1580,1581,1609],256],64935:[[1580,1605,1609],256],64936:[[1587,1582,1609],256],64937:[[1589,1581,1610],256],64938:[[1588,1581,1610],256],64939:[[1590,1581,1610],256],64940:[[1604,1580,1610],256],64941:[[1604,1605,1610],256],64942:[[1610,1581,1610],256],64943:[[1610,1580,1610],256],64944:[[1610,1605,1610],256],64945:[[1605,1605,1610],256],64946:[[1602,1605,1610],256],64947:[[1606,1581,1610],256],64948:[[1602,1605,1581],256],64949:[[1604,1581,1605],256],64950:[[1593,1605,1610],256],64951:[[1603,1605,1610],256],64952:[[1606,1580,1581],256],64953:[[1605,1582,1610],256],64954:[[1604,1580,1605],256],64955:[[1603,1605,1605],256],64956:[[1604,1580,1605],256],64957:[[1606,1580,1581],256],64958:[[1580,1581,1610],256],64959:[[1581,1580,1610],256],64960:[[1605,1580,1610],256],64961:[[1601,1605,1610],256],64962:[[1576,1581,1610],256],64963:[[1603,1605,1605],256],64964:[[1593,1580,1605],256],64965:[[1589,1605,1605],256],64966:[[1587,1582,1610],256],64967:[[1606,1580,1610],256],65008:[[1589,1604,1746],256],65009:[[1602,1604,1746],256],65010:[[1575,1604,1604,1607],256],65011:[[1575,1603,1576,1585],256],65012:[[1605,1581,1605,1583],256],65013:[[1589,1604,1593,1605],256],65014:[[1585,1587,1608,1604],256],65015:[[1593,1604,1610,1607],256],65016:[[1608,1587,1604,1605],256],65017:[[1589,1604,1609],256],65018:[[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605],256],65019:[[1580,1604,32,1580,1604,1575,1604,1607],256],65020:[[1585,1740,1575,1604],256]}, + 65024:{65040:[[44],256],65041:[[12289],256],65042:[[12290],256],65043:[[58],256],65044:[[59],256],65045:[[33],256],65046:[[63],256],65047:[[12310],256],65048:[[12311],256],65049:[[8230],256],65056:[,230],65057:[,230],65058:[,230],65059:[,230],65060:[,230],65061:[,230],65062:[,230],65072:[[8229],256],65073:[[8212],256],65074:[[8211],256],65075:[[95],256],65076:[[95],256],65077:[[40],256],65078:[[41],256],65079:[[123],256],65080:[[125],256],65081:[[12308],256],65082:[[12309],256],65083:[[12304],256],65084:[[12305],256],65085:[[12298],256],65086:[[12299],256],65087:[[12296],256],65088:[[12297],256],65089:[[12300],256],65090:[[12301],256],65091:[[12302],256],65092:[[12303],256],65095:[[91],256],65096:[[93],256],65097:[[8254],256],65098:[[8254],256],65099:[[8254],256],65100:[[8254],256],65101:[[95],256],65102:[[95],256],65103:[[95],256],65104:[[44],256],65105:[[12289],256],65106:[[46],256],65108:[[59],256],65109:[[58],256],65110:[[63],256],65111:[[33],256],65112:[[8212],256],65113:[[40],256],65114:[[41],256],65115:[[123],256],65116:[[125],256],65117:[[12308],256],65118:[[12309],256],65119:[[35],256],65120:[[38],256],65121:[[42],256],65122:[[43],256],65123:[[45],256],65124:[[60],256],65125:[[62],256],65126:[[61],256],65128:[[92],256],65129:[[36],256],65130:[[37],256],65131:[[64],256],65136:[[32,1611],256],65137:[[1600,1611],256],65138:[[32,1612],256],65140:[[32,1613],256],65142:[[32,1614],256],65143:[[1600,1614],256],65144:[[32,1615],256],65145:[[1600,1615],256],65146:[[32,1616],256],65147:[[1600,1616],256],65148:[[32,1617],256],65149:[[1600,1617],256],65150:[[32,1618],256],65151:[[1600,1618],256],65152:[[1569],256],65153:[[1570],256],65154:[[1570],256],65155:[[1571],256],65156:[[1571],256],65157:[[1572],256],65158:[[1572],256],65159:[[1573],256],65160:[[1573],256],65161:[[1574],256],65162:[[1574],256],65163:[[1574],256],65164:[[1574],256],65165:[[1575],256],65166:[[1575],256],65167:[[1576],256],65168:[[1576],256],65169:[[1576],256],65170:[[1576],256],65171:[[1577],256],65172:[[1577],256],65173:[[1578],256],65174:[[1578],256],65175:[[1578],256],65176:[[1578],256],65177:[[1579],256],65178:[[1579],256],65179:[[1579],256],65180:[[1579],256],65181:[[1580],256],65182:[[1580],256],65183:[[1580],256],65184:[[1580],256],65185:[[1581],256],65186:[[1581],256],65187:[[1581],256],65188:[[1581],256],65189:[[1582],256],65190:[[1582],256],65191:[[1582],256],65192:[[1582],256],65193:[[1583],256],65194:[[1583],256],65195:[[1584],256],65196:[[1584],256],65197:[[1585],256],65198:[[1585],256],65199:[[1586],256],65200:[[1586],256],65201:[[1587],256],65202:[[1587],256],65203:[[1587],256],65204:[[1587],256],65205:[[1588],256],65206:[[1588],256],65207:[[1588],256],65208:[[1588],256],65209:[[1589],256],65210:[[1589],256],65211:[[1589],256],65212:[[1589],256],65213:[[1590],256],65214:[[1590],256],65215:[[1590],256],65216:[[1590],256],65217:[[1591],256],65218:[[1591],256],65219:[[1591],256],65220:[[1591],256],65221:[[1592],256],65222:[[1592],256],65223:[[1592],256],65224:[[1592],256],65225:[[1593],256],65226:[[1593],256],65227:[[1593],256],65228:[[1593],256],65229:[[1594],256],65230:[[1594],256],65231:[[1594],256],65232:[[1594],256],65233:[[1601],256],65234:[[1601],256],65235:[[1601],256],65236:[[1601],256],65237:[[1602],256],65238:[[1602],256],65239:[[1602],256],65240:[[1602],256],65241:[[1603],256],65242:[[1603],256],65243:[[1603],256],65244:[[1603],256],65245:[[1604],256],65246:[[1604],256],65247:[[1604],256],65248:[[1604],256],65249:[[1605],256],65250:[[1605],256],65251:[[1605],256],65252:[[1605],256],65253:[[1606],256],65254:[[1606],256],65255:[[1606],256],65256:[[1606],256],65257:[[1607],256],65258:[[1607],256],65259:[[1607],256],65260:[[1607],256],65261:[[1608],256],65262:[[1608],256],65263:[[1609],256],65264:[[1609],256],65265:[[1610],256],65266:[[1610],256],65267:[[1610],256],65268:[[1610],256],65269:[[1604,1570],256],65270:[[1604,1570],256],65271:[[1604,1571],256],65272:[[1604,1571],256],65273:[[1604,1573],256],65274:[[1604,1573],256],65275:[[1604,1575],256],65276:[[1604,1575],256]}, + 65280:{65281:[[33],256],65282:[[34],256],65283:[[35],256],65284:[[36],256],65285:[[37],256],65286:[[38],256],65287:[[39],256],65288:[[40],256],65289:[[41],256],65290:[[42],256],65291:[[43],256],65292:[[44],256],65293:[[45],256],65294:[[46],256],65295:[[47],256],65296:[[48],256],65297:[[49],256],65298:[[50],256],65299:[[51],256],65300:[[52],256],65301:[[53],256],65302:[[54],256],65303:[[55],256],65304:[[56],256],65305:[[57],256],65306:[[58],256],65307:[[59],256],65308:[[60],256],65309:[[61],256],65310:[[62],256],65311:[[63],256],65312:[[64],256],65313:[[65],256],65314:[[66],256],65315:[[67],256],65316:[[68],256],65317:[[69],256],65318:[[70],256],65319:[[71],256],65320:[[72],256],65321:[[73],256],65322:[[74],256],65323:[[75],256],65324:[[76],256],65325:[[77],256],65326:[[78],256],65327:[[79],256],65328:[[80],256],65329:[[81],256],65330:[[82],256],65331:[[83],256],65332:[[84],256],65333:[[85],256],65334:[[86],256],65335:[[87],256],65336:[[88],256],65337:[[89],256],65338:[[90],256],65339:[[91],256],65340:[[92],256],65341:[[93],256],65342:[[94],256],65343:[[95],256],65344:[[96],256],65345:[[97],256],65346:[[98],256],65347:[[99],256],65348:[[100],256],65349:[[101],256],65350:[[102],256],65351:[[103],256],65352:[[104],256],65353:[[105],256],65354:[[106],256],65355:[[107],256],65356:[[108],256],65357:[[109],256],65358:[[110],256],65359:[[111],256],65360:[[112],256],65361:[[113],256],65362:[[114],256],65363:[[115],256],65364:[[116],256],65365:[[117],256],65366:[[118],256],65367:[[119],256],65368:[[120],256],65369:[[121],256],65370:[[122],256],65371:[[123],256],65372:[[124],256],65373:[[125],256],65374:[[126],256],65375:[[10629],256],65376:[[10630],256],65377:[[12290],256],65378:[[12300],256],65379:[[12301],256],65380:[[12289],256],65381:[[12539],256],65382:[[12530],256],65383:[[12449],256],65384:[[12451],256],65385:[[12453],256],65386:[[12455],256],65387:[[12457],256],65388:[[12515],256],65389:[[12517],256],65390:[[12519],256],65391:[[12483],256],65392:[[12540],256],65393:[[12450],256],65394:[[12452],256],65395:[[12454],256],65396:[[12456],256],65397:[[12458],256],65398:[[12459],256],65399:[[12461],256],65400:[[12463],256],65401:[[12465],256],65402:[[12467],256],65403:[[12469],256],65404:[[12471],256],65405:[[12473],256],65406:[[12475],256],65407:[[12477],256],65408:[[12479],256],65409:[[12481],256],65410:[[12484],256],65411:[[12486],256],65412:[[12488],256],65413:[[12490],256],65414:[[12491],256],65415:[[12492],256],65416:[[12493],256],65417:[[12494],256],65418:[[12495],256],65419:[[12498],256],65420:[[12501],256],65421:[[12504],256],65422:[[12507],256],65423:[[12510],256],65424:[[12511],256],65425:[[12512],256],65426:[[12513],256],65427:[[12514],256],65428:[[12516],256],65429:[[12518],256],65430:[[12520],256],65431:[[12521],256],65432:[[12522],256],65433:[[12523],256],65434:[[12524],256],65435:[[12525],256],65436:[[12527],256],65437:[[12531],256],65438:[[12441],256],65439:[[12442],256],65440:[[12644],256],65441:[[12593],256],65442:[[12594],256],65443:[[12595],256],65444:[[12596],256],65445:[[12597],256],65446:[[12598],256],65447:[[12599],256],65448:[[12600],256],65449:[[12601],256],65450:[[12602],256],65451:[[12603],256],65452:[[12604],256],65453:[[12605],256],65454:[[12606],256],65455:[[12607],256],65456:[[12608],256],65457:[[12609],256],65458:[[12610],256],65459:[[12611],256],65460:[[12612],256],65461:[[12613],256],65462:[[12614],256],65463:[[12615],256],65464:[[12616],256],65465:[[12617],256],65466:[[12618],256],65467:[[12619],256],65468:[[12620],256],65469:[[12621],256],65470:[[12622],256],65474:[[12623],256],65475:[[12624],256],65476:[[12625],256],65477:[[12626],256],65478:[[12627],256],65479:[[12628],256],65482:[[12629],256],65483:[[12630],256],65484:[[12631],256],65485:[[12632],256],65486:[[12633],256],65487:[[12634],256],65490:[[12635],256],65491:[[12636],256],65492:[[12637],256],65493:[[12638],256],65494:[[12639],256],65495:[[12640],256],65498:[[12641],256],65499:[[12642],256],65500:[[12643],256],65504:[[162],256],65505:[[163],256],65506:[[172],256],65507:[[175],256],65508:[[166],256],65509:[[165],256],65510:[[8361],256],65512:[[9474],256],65513:[[8592],256],65514:[[8593],256],65515:[[8594],256],65516:[[8595],256],65517:[[9632],256],65518:[[9675],256]} +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/implement.js new file mode 100644 index 00000000000000..cfc710ea439174 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'normalize', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/index.js new file mode 100644 index 00000000000000..619b0965d69b9e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.normalize + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/is-implemented.js new file mode 100644 index 00000000000000..67c8d8da5cad63 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'æøåäüö'; + +module.exports = function () { + if (typeof str.normalize !== 'function') return false; + return str.normalize('NFKD') === 'æøåäüö'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/shim.js new file mode 100644 index 00000000000000..a379989775737a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/normalize/shim.js @@ -0,0 +1,289 @@ +// Taken from: https://github.com/walling/unorm/blob/master/lib/unorm.js + +/* + * UnicodeNormalizer 1.0.0 + * Copyright (c) 2008 Matsuza + * Dual licensed under the MIT (MIT-LICENSE.txt) and + * GPL (GPL-LICENSE.txt) licenses. + * $Date: 2008-06-05 16:44:17 +0200 (Thu, 05 Jun 2008) $ + * $Rev: 13309 $ +*/ + +'use strict'; + +var primitiveSet = require('../../../object/primitive-set') + , validValue = require('../../../object/valid-value') + , data = require('./_data') + + , floor = Math.floor + , forms = primitiveSet('NFC', 'NFD', 'NFKC', 'NFKD') + + , DEFAULT_FEATURE = [null, 0, {}], CACHE_THRESHOLD = 10, SBase = 0xAC00 + , LBase = 0x1100, VBase = 0x1161, TBase = 0x11A7, LCount = 19, VCount = 21 + , TCount = 28, NCount = VCount * TCount, SCount = LCount * NCount + , UChar, cache = {}, cacheCounter = [], i, fromCache, fromData, fromCpOnly + , fromRuleBasedJamo, fromCpFilter, strategies, UCharIterator + , RecursDecompIterator, DecompIterator, CompIterator, createIterator + , normalize; + +UChar = function (cp, feature) { + this.codepoint = cp; + this.feature = feature; +}; + +// Strategies +for (i = 0; i <= 0xFF; ++i) cacheCounter[i] = 0; + +fromCache = function (next, cp, needFeature) { + var ret = cache[cp]; + if (!ret) { + ret = next(cp, needFeature); + if (!!ret.feature && ++cacheCounter[(cp >> 8) & 0xFF] > CACHE_THRESHOLD) { + cache[cp] = ret; + } + } + return ret; +}; + +fromData = function (next, cp, needFeature) { + var hash = cp & 0xFF00, dunit = UChar.udata[hash] || {}, f = dunit[cp]; + return f ? new UChar(cp, f) : new UChar(cp, DEFAULT_FEATURE); +}; +fromCpOnly = function (next, cp, needFeature) { + return !!needFeature ? next(cp, needFeature) : new UChar(cp, null); +}; + +fromRuleBasedJamo = function (next, cp, needFeature) { + var c, base, i, arr, SIndex, TIndex, feature, j; + if (cp < LBase || (LBase + LCount <= cp && cp < SBase) || + (SBase + SCount < cp)) { + return next(cp, needFeature); + } + if (LBase <= cp && cp < LBase + LCount) { + c = {}; + base = (cp - LBase) * VCount; + for (i = 0; i < VCount; ++i) { + c[VBase + i] = SBase + TCount * (i + base); + } + arr = new Array(3); + arr[2] = c; + return new UChar(cp, arr); + } + + SIndex = cp - SBase; + TIndex = SIndex % TCount; + feature = []; + if (TIndex !== 0) { + feature[0] = [SBase + SIndex - TIndex, TBase + TIndex]; + } else { + feature[0] = [LBase + floor(SIndex / NCount), VBase + + floor((SIndex % NCount) / TCount)]; + feature[2] = {}; + for (j = 1; j < TCount; ++j) { + feature[2][TBase + j] = cp + j; + } + } + return new UChar(cp, feature); +}; + +fromCpFilter = function (next, cp, needFeature) { + return (cp < 60) || ((13311 < cp) && (cp < 42607)) + ? new UChar(cp, DEFAULT_FEATURE) : next(cp, needFeature); +}; + +strategies = [fromCpFilter, fromCache, fromCpOnly, fromRuleBasedJamo, fromData]; + +UChar.fromCharCode = strategies.reduceRight(function (next, strategy) { + return function (cp, needFeature) { return strategy(next, cp, needFeature); }; +}, null); + +UChar.isHighSurrogate = function (cp) { return cp >= 0xD800 && cp <= 0xDBFF; }; +UChar.isLowSurrogate = function (cp) { return cp >= 0xDC00 && cp <= 0xDFFF; }; + +UChar.prototype.prepFeature = function () { + if (!this.feature) { + this.feature = UChar.fromCharCode(this.codepoint, true).feature; + } +}; + +UChar.prototype.toString = function () { + var x; + if (this.codepoint < 0x10000) return String.fromCharCode(this.codepoint); + x = this.codepoint - 0x10000; + return String.fromCharCode(floor(x / 0x400) + 0xD800, x % 0x400 + 0xDC00); +}; + +UChar.prototype.getDecomp = function () { + this.prepFeature(); + return this.feature[0] || null; +}; + +UChar.prototype.isCompatibility = function () { + this.prepFeature(); + return !!this.feature[1] && (this.feature[1] & (1 << 8)); +}; +UChar.prototype.isExclude = function () { + this.prepFeature(); + return !!this.feature[1] && (this.feature[1] & (1 << 9)); +}; +UChar.prototype.getCanonicalClass = function () { + this.prepFeature(); + return !!this.feature[1] ? (this.feature[1] & 0xff) : 0; +}; +UChar.prototype.getComposite = function (following) { + var cp; + this.prepFeature(); + if (!this.feature[2]) return null; + cp = this.feature[2][following.codepoint]; + return cp ? UChar.fromCharCode(cp) : null; +}; + +UCharIterator = function (str) { + this.str = str; + this.cursor = 0; +}; +UCharIterator.prototype.next = function () { + if (!!this.str && this.cursor < this.str.length) { + var cp = this.str.charCodeAt(this.cursor++), d; + if (UChar.isHighSurrogate(cp) && this.cursor < this.str.length && + UChar.isLowSurrogate((d = this.str.charCodeAt(this.cursor)))) { + cp = (cp - 0xD800) * 0x400 + (d - 0xDC00) + 0x10000; + ++this.cursor; + } + return UChar.fromCharCode(cp); + } + this.str = null; + return null; +}; + +RecursDecompIterator = function (it, cano) { + this.it = it; + this.canonical = cano; + this.resBuf = []; +}; + +RecursDecompIterator.prototype.next = function () { + var recursiveDecomp, uchar; + recursiveDecomp = function (cano, uchar) { + var decomp = uchar.getDecomp(), ret, i, a, j; + if (!!decomp && !(cano && uchar.isCompatibility())) { + ret = []; + for (i = 0; i < decomp.length; ++i) { + a = recursiveDecomp(cano, UChar.fromCharCode(decomp[i])); + //ret.concat(a); //<-why does not this work? + //following block is a workaround. + for (j = 0; j < a.length; ++j) ret.push(a[j]); + } + return ret; + } + return [uchar]; + }; + if (this.resBuf.length === 0) { + uchar = this.it.next(); + if (!uchar) return null; + this.resBuf = recursiveDecomp(this.canonical, uchar); + } + return this.resBuf.shift(); +}; + +DecompIterator = function (it) { + this.it = it; + this.resBuf = []; +}; + +DecompIterator.prototype.next = function () { + var cc, uchar, inspt, uchar2, cc2; + if (this.resBuf.length === 0) { + do { + uchar = this.it.next(); + if (!uchar) break; + cc = uchar.getCanonicalClass(); + inspt = this.resBuf.length; + if (cc !== 0) { + for (inspt; inspt > 0; --inspt) { + uchar2 = this.resBuf[inspt - 1]; + cc2 = uchar2.getCanonicalClass(); + if (cc2 <= cc) break; + } + } + this.resBuf.splice(inspt, 0, uchar); + } while (cc !== 0); + } + return this.resBuf.shift(); +}; + +CompIterator = function (it) { + this.it = it; + this.procBuf = []; + this.resBuf = []; + this.lastClass = null; +}; + +CompIterator.prototype.next = function () { + var uchar, starter, composite, cc; + while (this.resBuf.length === 0) { + uchar = this.it.next(); + if (!uchar) { + this.resBuf = this.procBuf; + this.procBuf = []; + break; + } + if (this.procBuf.length === 0) { + this.lastClass = uchar.getCanonicalClass(); + this.procBuf.push(uchar); + } else { + starter = this.procBuf[0]; + composite = starter.getComposite(uchar); + cc = uchar.getCanonicalClass(); + if (!!composite && (this.lastClass < cc || this.lastClass === 0)) { + this.procBuf[0] = composite; + } else { + if (cc === 0) { + this.resBuf = this.procBuf; + this.procBuf = []; + } + this.lastClass = cc; + this.procBuf.push(uchar); + } + } + } + return this.resBuf.shift(); +}; + +createIterator = function (mode, str) { + switch (mode) { + case "NFD": + return new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), true) + ); + case "NFKD": + return new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), false) + ); + case "NFC": + return new CompIterator(new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), true) + )); + case "NFKC": + return new CompIterator(new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), false) + )); + } + throw mode + " is invalid"; +}; +normalize = function (mode, str) { + var it = createIterator(mode, str), ret = "", uchar; + while (!!(uchar = it.next())) ret += uchar.toString(); + return ret; +}; + +/* Unicode data */ +UChar.udata = data; + +module.exports = function (/*form*/) { + var str = String(validValue(this)), form = arguments[0]; + if (form === undefined) form = 'NFC'; + else form = String(form); + if (!forms[form]) throw new RangeError('Invalid normalization form: ' + form); + return normalize(form, str); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/pad.js new file mode 100644 index 00000000000000..f227f239de98c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/pad.js @@ -0,0 +1,18 @@ +'use strict'; + +var toInteger = require('../../number/to-integer') + , value = require('../../object/valid-value') + , repeat = require('./repeat') + + , abs = Math.abs, max = Math.max; + +module.exports = function (fill/*, length*/) { + var self = String(value(this)) + , sLength = self.length + , length = arguments[1]; + + length = isNaN(length) ? 1 : toInteger(length); + fill = repeat.call(String(fill), abs(length)); + if (length >= 0) return fill.slice(0, max(0, length - sLength)) + self; + return self + (((sLength + length) >= 0) ? '' : fill.slice(length + sLength)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/plain-replace-all.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/plain-replace-all.js new file mode 100644 index 00000000000000..678b1cbcff4b8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/plain-replace-all.js @@ -0,0 +1,16 @@ +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function (search, replace) { + var index, pos = 0, str = String(value(this)), sl, rl; + search = String(search); + replace = String(replace); + sl = search.length; + rl = replace.length; + while ((index = str.indexOf(search, pos)) !== -1) { + str = str.slice(0, index) + replace + str.slice(index + sl); + pos = index + rl; + } + return str; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/plain-replace.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/plain-replace.js new file mode 100644 index 00000000000000..24ce16d3bce6e1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/plain-replace.js @@ -0,0 +1,10 @@ +'use strict'; + +var indexOf = String.prototype.indexOf, slice = String.prototype.slice; + +module.exports = function (search, replace) { + var index = indexOf.call(this, search); + if (index === -1) return String(this); + return slice.call(this, 0, index) + replace + + slice.call(this, index + String(search).length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/implement.js new file mode 100644 index 00000000000000..4c39b9fbe66cc6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'repeat', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/index.js new file mode 100644 index 00000000000000..15a800e8de9509 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.repeat + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/is-implemented.js new file mode 100644 index 00000000000000..f7b8750f0fd8be --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'foo'; + +module.exports = function () { + if (typeof str.repeat !== 'function') return false; + return (str.repeat(2) === 'foofoo'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/shim.js new file mode 100644 index 00000000000000..0a3928b2c0dd76 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/repeat/shim.js @@ -0,0 +1,22 @@ +// Thanks: http://www.2ality.com/2014/01/efficient-string-repeat.html + +'use strict'; + +var value = require('../../../object/valid-value') + , toInteger = require('../../../number/to-integer'); + +module.exports = function (count) { + var str = String(value(this)), result; + count = toInteger(count); + if (count < 0) throw new RangeError("Count must be >= 0"); + if (!isFinite(count)) throw new RangeError("Count must be < ∞"); + result = ''; + if (!count) return result; + while (true) { + if (count & 1) result += str; + count >>>= 1; + if (count <= 0) break; + str += str; + } + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/implement.js new file mode 100644 index 00000000000000..d4f1eaf547f4a8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'startsWith', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/index.js new file mode 100644 index 00000000000000..ec66a7c0057878 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.startsWith + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/is-implemented.js new file mode 100644 index 00000000000000..a0556f196e9afa --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.startsWith !== 'function') return false; + return ((str.startsWith('trzy') === false) && + (str.startsWith('raz') === true)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/shim.js new file mode 100644 index 00000000000000..aa5aaf4145ea58 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/#/starts-with/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var value = require('../../../object/valid-value') + , toInteger = require('../../../number/to-integer') + + , max = Math.max, min = Math.min; + +module.exports = function (searchString/*, position*/) { + var start, self = String(value(this)); + start = min(max(toInteger(arguments[1]), 0), self.length); + return (self.indexOf(searchString, start) === start); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/format-method.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/format-method.js new file mode 100644 index 00000000000000..f1de1e301d4238 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/format-method.js @@ -0,0 +1,24 @@ +'use strict'; + +var isCallable = require('../object/is-callable') + , value = require('../object/valid-value') + + , call = Function.prototype.call; + +module.exports = function (fmap) { + fmap = Object(value(fmap)); + return function (pattern) { + var context = value(this); + pattern = String(pattern); + return pattern.replace(/%([a-zA-Z]+)|\\([\u0000-\uffff])/g, + function (match, token, escape) { + var t, r; + if (escape) return escape; + t = token; + while (t && !(r = fmap[t])) t = t.slice(0, -1); + if (!r) return match; + if (isCallable(r)) r = call.call(r, context); + return r + token.slice(t.length); + }); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/implement.js new file mode 100644 index 00000000000000..b062331cc597e2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String, 'fromCodePoint', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/index.js new file mode 100644 index 00000000000000..3f3110b6eb1f5a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.fromCodePoint + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/is-implemented.js new file mode 100644 index 00000000000000..840a20e3f36d87 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var fromCodePoint = String.fromCodePoint; + if (typeof fromCodePoint !== 'function') return false; + return fromCodePoint(0x1D306, 0x61, 0x1D307) === '\ud834\udf06a\ud834\udf07'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/shim.js new file mode 100644 index 00000000000000..41fd7378f81c53 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/from-code-point/shim.js @@ -0,0 +1,30 @@ +// Based on: +// http://norbertlindenberg.com/2012/05/ecmascript-supplementary-characters/ +// and: +// https://github.com/mathiasbynens/String.fromCodePoint/blob/master +// /fromcodepoint.js + +'use strict'; + +var floor = Math.floor, fromCharCode = String.fromCharCode; + +module.exports = function (codePoint/*, …codePoints*/) { + var chars = [], l = arguments.length, i, c, result = ''; + for (i = 0; i < l; ++i) { + c = Number(arguments[i]); + if (!isFinite(c) || c < 0 || c > 0x10FFFF || floor(c) !== c) { + throw new RangeError("Invalid code point " + c); + } + + if (c < 0x10000) { + chars.push(c); + } else { + c -= 0x10000; + chars.push((c >> 10) + 0xD800, (c % 0x400) + 0xDC00); + } + if (i + 1 !== l && chars.length <= 0x4000) continue; + result += fromCharCode.apply(null, chars); + chars.length = 0; + } + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/index.js new file mode 100644 index 00000000000000..dbbcdf61f06cd8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + formatMethod: require('./format-method'), + fromCodePoint: require('./from-code-point'), + isString: require('./is-string'), + randomUniq: require('./random-uniq'), + raw: require('./raw') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/is-string.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/is-string.js new file mode 100644 index 00000000000000..719aeec16c5aa5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/is-string.js @@ -0,0 +1,10 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(''); + +module.exports = function (x) { + return (typeof x === 'string') || (x && (typeof x === 'object') && + ((x instanceof String) || (toString.call(x) === id))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/random-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/random-uniq.js new file mode 100644 index 00000000000000..54ae6f8c9fd3c3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/random-uniq.js @@ -0,0 +1,11 @@ +'use strict'; + +var generated = Object.create(null) + + , random = Math.random; + +module.exports = function () { + var str; + do { str = random().toString(36).slice(2); } while (generated[str]); + return str; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/implement.js new file mode 100644 index 00000000000000..c417e659b2086c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String, 'raw', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/index.js new file mode 100644 index 00000000000000..504a5de24bf3ce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.raw + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/is-implemented.js new file mode 100644 index 00000000000000..d7204c0c49e8a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function () { + var raw = String.raw, test; + if (typeof raw !== 'function') return false; + test = ['foo\nbar', 'marko\n']; + test.raw = ['foo\\nbar', 'marko\\n']; + return raw(test, 'INSE\nRT') === 'foo\\nbarINSE\nRTmarko\\n'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/shim.js new file mode 100644 index 00000000000000..7096efbc5671d1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/string/raw/shim.js @@ -0,0 +1,15 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , validValue = require('../../object/valid-value') + + , reduce = Array.prototype.reduce; + +module.exports = function (callSite/*, …substitutions*/) { + var args, rawValue = Object(validValue(Object(validValue(callSite)).raw)); + if (!toPosInt(rawValue.length)) return ''; + args = arguments; + return reduce.call(rawValue, function (a, b, i) { + return a + String(args[i]) + b; + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/__tad.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/__tad.js new file mode 100644 index 00000000000000..884577887f5704 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/__tad.js @@ -0,0 +1,3 @@ +'use strict'; + +exports.context = null; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/implement.js new file mode 100644 index 00000000000000..f0605399e0274e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/@@iterator/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/shim.js new file mode 100644 index 00000000000000..e590d8f28e7c0e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/@@iterator/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: '1', done: false }); + a.deep(iterator.next(), { value: '2', done: false }); + a.deep(iterator.next(), { value: '3', done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/_compare-by-length.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/_compare-by-length.js new file mode 100644 index 00000000000000..e40c305b98fe68 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/_compare-by-length.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + var x = [4, 5, 6], y = { length: 8 }, w = {}, z = { length: 1 }; + + a.deep([x, y, w, z].sort(t), [w, z, x, y]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/binary-search.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/binary-search.js new file mode 100644 index 00000000000000..cf3317371b3491 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/binary-search.js @@ -0,0 +1,15 @@ +'use strict'; + +var compare = function (value) { return this - value; }; + +module.exports = function (t, a) { + var arr; + arr = [2, 5, 5, 8, 34, 67, 98, 345, 678]; + + // highest, equal match + a(t.call(arr, compare.bind(1)), 0, "All higher"); + a(t.call(arr, compare.bind(679)), arr.length - 1, "All lower"); + a(t.call(arr, compare.bind(4)), 0, "Mid"); + a(t.call(arr, compare.bind(5)), 2, "Match"); + a(t.call(arr, compare.bind(6)), 2, "Above"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/clear.js new file mode 100644 index 00000000000000..a5b1c977ad98cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/clear.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + var x = [1, 2, {}, 4]; + a(t.call(x), x, "Returns same array"); + a.deep(x, [], "Empties array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/compact.js new file mode 100644 index 00000000000000..6390eb26dddf6b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/compact.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a(t.call(this).length, 3); + }, + "": function (t, a) { + var o, x, y, z; + o = {}; + x = [0, 1, "", null, o, false, undefined, true]; + y = x.slice(0); + + a.not(z = t.call(x), x, "Returns different object"); + a.deep(x, y, "Origin not changed"); + a.deep(z, [0, 1, "", o, false, true], "Result"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/implement.js new file mode 100644 index 00000000000000..3bdbe86812aaaa --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/concat/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/shim.js new file mode 100644 index 00000000000000..c30eb7eab08178 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/concat/shim.js @@ -0,0 +1,26 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr = [1, 3, 45], x = {}, subArr, subArr2, result; + + a.deep(t.call(arr, '2d', x, ['ere', 'fe', x], false, null), + [1, 3, 45, '2d', x, 'ere', 'fe', x, false, null], "Plain array"); + + subArr = new SubArray('lol', 'miszko'); + subArr2 = new SubArray('elo', 'fol'); + + result = t.call(subArr, 'df', arr, 'fef', subArr2, null); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, ['lol', 'miszko', 'df', 1, 3, 45, 'fef', 'elo', 'fol', null], + "Spreable by default"); + + SubArray.prototype['@@isConcatSpreadable'] = false; + + result = t.call(subArr, 'df', arr, 'fef', subArr2, null); + a.deep(result, ['lol', 'miszko', 'df', 1, 3, 45, 'fef', subArr2, null], + "Non spreadable"); + + delete SubArray.prototype['@@isConcatSpreadable']; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/contains.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/contains.js new file mode 100644 index 00000000000000..21404a17a61358 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/contains.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a(t.call(this, this[1]), true, "Contains"); + a(t.call(this, {}), false, "Does Not contain"); + }, + "": function (t, a) { + var o, x = {}, y = {}; + + o = [1, 'raz', x]; + + a(t.call(o, 1), true, "First"); + a(t.call(o, '1'), false, "Type coercion"); + a(t.call(o, 'raz'), true, "Primitive"); + a(t.call(o, 'foo'), false, "Primitive not found"); + a(t.call(o, x), true, "Object found"); + a(t.call(o, y), false, "Object not found"); + a(t.call(o, 1, 1), false, "Position"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/implement.js new file mode 100644 index 00000000000000..36070477d66802 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/copy-within/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/shim.js new file mode 100644 index 00000000000000..93c85ea3114c24 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/copy-within/shim.js @@ -0,0 +1,29 @@ +'use strict'; + +module.exports = function (t, a) { + var args, x; + + a.h1("2 args"); + x = [1, 2, 3, 4, 5]; + t.call(x, 0, 3); + a.deep(x, [4, 5, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 3), [1, 4, 5, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 2), [1, 3, 4, 5, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 2, 2), [1, 2, 3, 4, 5]); + + a.h1("3 args"); + a.deep(t.call([1, 2, 3, 4, 5], 0, 3, 4), [4, 2, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 3, 4), [1, 4, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 2, 4), [1, 3, 4, 4, 5]); + + a.h1("Negative args"); + a.deep(t.call([1, 2, 3, 4, 5], 0, -2), [4, 5, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 0, -2, -1), [4, 2, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], -4, -3, -2), [1, 3, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], -4, -3, -1), [1, 3, 4, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], -4, -3), [1, 3, 4, 5, 5]); + + a.h1("Array-likes"); + args = { 0: 1, 1: 2, 2: 3, length: 3 }; + a.deep(t.call(args, -2, 0), { '0': 1, '1': 1, '2': 2, length: 3 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/diff.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/diff.js new file mode 100644 index 00000000000000..bcfa3a0bd12f84 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/diff.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a.deep(t.call(this, this), []); + }, + "": function (t, a) { + var x = {}, y = {}; + + a.deep(t.call([1, 'raz', x, 2, 'trzy', y], [x, 2, 'trzy']), [1, 'raz', y], + "Scope longer"); + a.deep(t.call([1, 'raz', x], [x, 2, 'trzy', 1, y]), ['raz'], + "Arg longer"); + a.deep(t.call([1, 'raz', x], []), [1, 'raz', x], "Empty arg"); + a.deep(t.call([], [1, y, 'sdfs']), [], "Empty scope"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/e-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/e-index-of.js new file mode 100644 index 00000000000000..4cf6c6359d44ee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/e-index-of.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([3, 'raz', {}, x, {}], x), 3, "Regular"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN), 2, "NaN"); + a(t.call([3, 'raz', 0, {}, -0], -0), 2, "-0"); + a(t.call([3, 'raz', -0, {}, 0], +0), 2, "+0"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, 3), 4, "fromIndex"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, -1), 4, "fromIndex negative #1"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, -2), 4, "fromIndex negative #2"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, -3), 2, "fromIndex negative #3"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/e-last-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/e-last-index-of.js new file mode 100644 index 00000000000000..ed4f700421a8f1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/e-last-index-of.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([3, 'raz', {}, x, {}, x], x), 5, "Regular"); + a(t.call([3, 'raz', NaN, {}, x], NaN), 2, "NaN"); + a(t.call([3, 'raz', 0, {}, -0], -0), 4, "-0"); + a(t.call([3, 'raz', -0, {}, 0], +0), 4, "+0"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, 3), 2, "fromIndex"); + a(t.call([3, 'raz', NaN, 2, NaN], NaN, -1), 4, "Negative fromIndex #1"); + a(t.call([3, 'raz', NaN, 2, NaN], NaN, -2), 2, "Negative fromIndex #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/implement.js new file mode 100644 index 00000000000000..733209a1c80653 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/entries/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/shim.js new file mode 100644 index 00000000000000..bf40d31005df45 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/entries/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: [0, '1'], done: false }); + a.deep(iterator.next(), { value: [1, '2'], done: false }); + a.deep(iterator.next(), { value: [2, '3'], done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/exclusion.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/exclusion.js new file mode 100644 index 00000000000000..07b32d8e8cbf9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/exclusion.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var x = {}; + a.deep(t.call(this, this, [this[0], this[2], x]), [x]); + }, + "": function (t, a) { + var x = {}, y = {}; + + a.deep(t.call([x, y]), [x, y], "No arguments"); + a.deep(t.call([x, 1], [], []), [x, 1], "Empty arguments"); + a.deep(t.call([1, 'raz', x], [2, 'raz', y], [2, 'raz', x]), [1, y]); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/implement.js new file mode 100644 index 00000000000000..2a01d2850a18a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/fill/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/shim.js new file mode 100644 index 00000000000000..d67300fcc23be8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/fill/shim.js @@ -0,0 +1,18 @@ +// Taken from https://github.com/paulmillr/es6-shim/blob/master/test/array.js + +'use strict'; + +module.exports = function (t, a) { + var x; + + x = [1, 2, 3, 4, 5, 6]; + a(t.call(x, -1), x, "Returns self object"); + a.deep(x, [-1, -1, -1, -1, -1, -1], "Value"); + + a.deep(t.call([1, 2, 3, 4, 5, 6], -1, 3), [1, 2, 3, -1, -1, -1], + "Positive start"); + a.deep(t.call([1, 2, 3, 4, 5, 6], -1, -3), [1, 2, 3, -1, -1, -1], + "Negative start"); + a.deep(t.call([1, 2, 3, 4, 5, 6], -1, 9), [1, 2, 3, 4, 5, 6], + "Large start"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/implement.js new file mode 100644 index 00000000000000..6d6b87cc30a651 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/filter/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/shim.js new file mode 100644 index 00000000000000..e8b5c39849097f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/filter/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, Boolean), ['foo', '2d', x], "Plain array"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, Boolean); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, ['foo', '2d', x], "Result of subclass"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/implement.js new file mode 100644 index 00000000000000..8d85e618ccd6bc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/find-index/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/shim.js new file mode 100644 index 00000000000000..b5fee463811d49 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find-index/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +exports.__generic = function (t, a) { + var count = 0, o = {}, self = Object(this); + a(t.call(self, function (value, i, scope) { + a(value, this[i], "Value"); + a(i, count++, "Index"); + a(scope, this, "Scope"); + }, self), -1, "Falsy result"); + a(count, 3); + + count = -1; + a(t.call(this, function () { + return ++count ? o : null; + }, this), 1, "Truthy result"); + a(count, 1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/implement.js new file mode 100644 index 00000000000000..29fac41e013353 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/find/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/shim.js new file mode 100644 index 00000000000000..ad2e645067db5d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/find/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +exports.__generic = function (t, a) { + var count = 0, o = {}, self = Object(this); + a(t.call(self, function (value, i, scope) { + a(value, this[i], "Value"); + a(i, count++, "Index"); + a(scope, this, "Scope"); + }, self), undefined, "Falsy result"); + a(count, 3); + + count = -1; + a(t.call(this, function () { + return ++count ? o : null; + }, this), this[1], "Truthy result"); + a(count, 1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/first-index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/first-index.js new file mode 100644 index 00000000000000..4aebad64b44e51 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/first-index.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a(t.call([]), null, "Empty"); + a(t.call([null]), 0, "One value"); + a(t.call([1, 2, 3]), 0, "Many values"); + a(t.call(new Array(1000)), null, "Sparse empty"); + x = []; + x[883] = undefined; + x[890] = null; + a(t.call(x), 883, "Manual sparse, distant value"); + x = new Array(1000); + x[657] = undefined; + x[700] = null; + a(t.call(x), 657, "Sparse, distant value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/first.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/first.js new file mode 100644 index 00000000000000..87fde0357ef1b0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/first.js @@ -0,0 +1,13 @@ +'use strict'; + +exports.__generic = function (t, a) { + a(t.call(this), this[0]); +}; +exports[''] = function (t, a) { + var x; + a(t.call([]), undefined, "Empty"); + a(t.call(new Array(234), undefined, "Sparse empty")); + x = new Array(2342); + x[434] = {}; + a(t.call(x), x[434], "Sparse"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/flatten.js new file mode 100644 index 00000000000000..65f1214b04da93 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/flatten.js @@ -0,0 +1,12 @@ +'use strict'; + +var o = [1, 2, [3, 4, [5, 6], 7, 8], 9, 10]; + +module.exports = { + __generic: function (t, a) { + a(t.call(this).length, 3); + }, + "Nested Arrays": function (t, a) { + a(t.call(o).length, 10); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/for-each-right.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/for-each-right.js new file mode 100644 index 00000000000000..2d24569d94d86d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/for-each-right.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var count = 0, first, last, x, icount = this.length; + t.call(this, function (item, index, col) { + ++count; + if (!first) { + first = item; + } + last = item; + x = col; + a(index, --icount, "Index"); + }); + a(count, this.length, "Iterated"); + a(first, this[this.length - 1], "First is last"); + a(last, this[0], "Last is first"); + a.deep(x, Object(this), "Collection as third argument"); //jslint: skip + }, + "": function (t, a) { + var x = {}, y, count; + t.call([1], function () { y = this; }, x); + a(y, x, "Scope"); + y = 0; + t.call([3, 4, 4], function (a, i) { y += i; }); + a(y, 3, "Indexes"); + + x = [1, 3]; + x[5] = 'x'; + y = 0; + count = 0; + t.call(x, function (a, i) { ++count; y += i; }); + a(y, 6, "Misssing Indexes"); + a(count, 3, "Misssing Indexes, count"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/group.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/group.js new file mode 100644 index 00000000000000..32dc8c2dbb68bf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/group.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var count = 0, self; + + self = Object(this); + a.deep(t.call(self, function (v, i, scope) { + a(v, this[i], "Value"); + a(i, count++, "Index"); + a(scope, this, "Scope"); + return i; + }, self), { 0: [this[0]], 1: [this[1]], 2: [this[2]] }); + }, + "": function (t, a) { + var r; + r = t.call([2, 3, 3, 4, 5, 6, 7, 7, 23, 45, 34, 56], + function (v) { + return v % 2 ? 'odd' : 'even'; + }); + a.deep(r.odd, [3, 3, 5, 7, 7, 23, 45]); + a.deep(r.even, [2, 4, 6, 34, 56]); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/indexes-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/indexes-of.js new file mode 100644 index 00000000000000..3364170f1ec4a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/indexes-of.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a.deep(t.call(this, this[1]), [1]); + }, + "": function (t, a) { + var x = {}; + a.deep(t.call([1, 3, 5, 3, 5], 6), [], "No result"); + a.deep(t.call([1, 3, 5, 1, 3, 5, 1], 1), [0, 3, 6], "Some results"); + a.deep(t.call([], x), [], "Empty array"); + a.deep(t.call([x, 3, {}, x, 3, 5, x], x), [0, 3, 6], "Search for object"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/intersection.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/intersection.js new file mode 100644 index 00000000000000..b72b2fb074fc46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/intersection.js @@ -0,0 +1,24 @@ +'use strict'; + +var toArray = require('../../../array/to-array'); + +module.exports = { + __generic: function (t, a) { + a.deep(t.call(this, this, this), toArray(this)); + }, + "": function (t, a) { + var x = {}, y = {}, p, r; + a.deep(t.call([], [2, 3, 4]), [], "Empty #1"); + a.deep(t.call([2, 3, 4], []), [], "Empty #2"); + a.deep(t.call([2, 3, x], [y, 5, 7]), [], "Different"); + p = t.call([3, 5, 'raz', {}, 'dwa', x], [1, 3, 'raz', 'dwa', 'trzy', x, {}], + [3, 'raz', x, 65]); + r = [3, 'raz', x]; + p.sort(); + r.sort(); + a.deep(p, r, "Same parts"); + a.deep(t.call(r, r), r, "Same"); + a.deep(t.call([1, 2, x, 4, 5, y, 7], [7, y, 5, 4, x, 2, 1]), + [1, 2, x, 4, 5, y, 7], "Long reverse same"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/is-copy.js new file mode 100644 index 00000000000000..e7f80e7a8d4ebc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/is-copy.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([], []), true, "Empty"); + a(t.call([], {}), true, "Empty lists"); + a(t.call([1, x, 'raz'], [1, x, 'raz']), true, "Same"); + a(t.call([1, x, 'raz'], { 0: 1, 1: x, 2: 'raz', length: 3 }), true, + "Same lists"); + a(t.call([1, x, 'raz'], [x, 1, 'raz']), false, "Diff order"); + a(t.call([1, x], [1, x, 'raz']), false, "Diff length #1"); + a(t.call([1, x, 'raz'], [1, x]), false, "Diff length #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/is-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/is-uniq.js new file mode 100644 index 00000000000000..7349ba337135a7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/is-uniq.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([]), true, "Empty"); + a(t.call({}), true, "Empty lists"); + a(t.call([1, x, 'raz']), true, "Uniq"); + a(t.call([1, x, 1, 'raz']), false, "Not Uniq: primitive"); + a(t.call([1, x, '1', 'raz']), true, "Uniq: primitive"); + a(t.call([1, x, 1, {}, 'raz']), false, "Not Uniq: Obj"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/implement.js new file mode 100644 index 00000000000000..b0c1aa078f190e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/keys/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/shim.js new file mode 100644 index 00000000000000..a43c04cac103a6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/keys/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: 0, done: false }); + a.deep(iterator.next(), { value: 1, done: false }); + a.deep(iterator.next(), { value: 2, done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/last-index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/last-index.js new file mode 100644 index 00000000000000..a1cac1073f8862 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/last-index.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a(t.call([]), null, "Empty"); + a(t.call([null]), 0, "One value"); + a(t.call([1, 2, 3]), 2, "Many values"); + a(t.call(new Array(1000)), null, "Sparse empty"); + x = []; + x[883] = null; + x[890] = undefined; + a(t.call(x), 890, "Manual sparse, distant value"); + x = new Array(1000); + x[657] = null; + x[700] = undefined; + a(t.call(x), 700, "Sparse, distant value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/last.js new file mode 100644 index 00000000000000..8d051bc8d2f5df --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/last.js @@ -0,0 +1,15 @@ +'use strict'; + +exports.__generic = function (t, a) { + a(t.call(this), this[this.length - 1]); +}; + +exports[''] = function (t, a) { + var x; + a(t.call([]), undefined, "Empty"); + a(t.call(new Array(234), undefined, "Sparse empty")); + x = new Array(2342); + x[434] = {}; + x[450] = {}; + a(t.call(x), x[450], "Sparse"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/implement.js new file mode 100644 index 00000000000000..cdcbc8df6206a5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/map/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/shim.js new file mode 100644 index 00000000000000..bbfefe8e333dc8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/map/shim.js @@ -0,0 +1,19 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, Boolean), [true, false, false, true, false, true, false], + "Plain array"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, Boolean); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, [true, false, false, true, false, true, false], + "Result of subclass"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/remove.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/remove.js new file mode 100644 index 00000000000000..3ebdca2d0183df --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/remove.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + var y = {}, z = {}, x = [9, z, 5, y, 'foo']; + t.call(x, y); + a.deep(x, [9, z, 5, 'foo']); + t.call(x, {}); + a.deep(x, [9, z, 5, 'foo'], "Not existing"); + t.call(x, 5); + a.deep(x, [9, z, 'foo'], "Primitive"); + x = [9, z, 5, y, 'foo']; + t.call(x, z, 5, 'foo'); + a.deep(x, [9, y], "More than one argument"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/separate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/separate.js new file mode 100644 index 00000000000000..42918b59711e32 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/separate.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x = [], y = {}, z = {}; + a.deep(t.call(x, y), [], "Empty"); + a.not(t.call(x), x, "Returns copy"); + a.deep(t.call([1], y), [1], "One"); + a.deep(t.call([1, 'raz'], y), [1, y, 'raz'], "One"); + a.deep(t.call([1, 'raz', x], y), [1, y, 'raz', y, x], "More"); + x = new Array(1000); + x[23] = 2; + x[3453] = 'raz'; + x[500] = z; + a.deep(t.call(x, y), [2, y, z, y, 'raz'], "Sparse"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/implement.js new file mode 100644 index 00000000000000..855ae2fa4df88e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/slice/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/shim.js new file mode 100644 index 00000000000000..f674f3470037f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/slice/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, 2, 4), [0, '2d'], "Plain array: result"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, 2, 4); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, [0, '2d'], "Subclass: result"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/some-right.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/some-right.js new file mode 100644 index 00000000000000..900771a6f818a4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/some-right.js @@ -0,0 +1,43 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var count = 0, first, last, x, icount = this.length; + t.call(this, function (item, index, col) { + ++count; + if (!first) { + first = item; + } + last = item; + x = col; + a(index, --icount, "Index"); + }); + a(count, this.length, "Iterated"); + a(first, this[this.length - 1], "First is last"); + a(last, this[0], "Last is first"); + a.deep(x, Object(this), "Collection as third argument"); //jslint: skip + }, + "": function (t, a) { + var x = {}, y, count; + t.call([1], function () { y = this; }, x); + a(y, x, "Scope"); + y = 0; + t.call([3, 4, 4], function (a, i) { y += i; }); + a(y, 3, "Indexes"); + + x = [1, 3]; + x[5] = 'x'; + y = 0; + count = 0; + a(t.call(x, function (a, i) { ++count; y += i; }), false, "Return"); + a(y, 6, "Misssing Indexes"); + a(count, 3, "Misssing Indexes, count"); + + count = 0; + a(t.call([-2, -3, -4, 2, -5], function (item) { + ++count; + return item > 0; + }), true, "Return"); + a(count, 2, "Break after true is returned"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/implement.js new file mode 100644 index 00000000000000..0d9f46188b528b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/splice/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/shim.js new file mode 100644 index 00000000000000..2c751e672400e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/splice/shim.js @@ -0,0 +1,19 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, 2, 2, 'bar'), [0, '2d'], "Plain array: result"); + a.deep(arr, ["foo", undefined, "bar", false, x, null], "Plain array: change"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, 2, 2, 'bar'); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, [0, '2d'], "Subclass: result"); + a.deep(subArr, ["foo", undefined, "bar", false, x, null], "Subclass: change"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/uniq.js new file mode 100644 index 00000000000000..2f7e6c4ed1feb5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/uniq.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a(t.call(this).length, 3); + }, + "": function (t, a) { + var o, x = {}, y = {}, z = {}, w; + o = [1, 2, x, 3, 1, 'raz', '1', y, x, 'trzy', z, 'raz']; + + a.not(w = t.call(o), o, "Returns different object"); + a.deep(w, [1, 2, x, 3, 'raz', '1', y, 'trzy', z], "Result"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/implement.js new file mode 100644 index 00000000000000..9f40138c254b30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/values/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/shim.js new file mode 100644 index 00000000000000..e590d8f28e7c0e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/#/values/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: '1', done: false }); + a.deep(iterator.next(), { value: '2', done: false }); + a.deep(iterator.next(), { value: '3', done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/__scopes.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/__scopes.js new file mode 100644 index 00000000000000..fc240d304869bb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/__scopes.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.Array = ['1', '2', '3']; + +exports.Arguments = (function () { + return arguments; +}('1', '2', '3')); + +exports.String = "123"; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_is-extensible.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_is-extensible.js new file mode 100644 index 00000000000000..d387126fe111ed --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_is-extensible.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'boolean'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_sub-array-dummy-safe.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_sub-array-dummy-safe.js new file mode 100644 index 00000000000000..29d8699d461a85 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_sub-array-dummy-safe.js @@ -0,0 +1,7 @@ +'use strict'; + +var isArray = Array.isArray; + +module.exports = function (t, a) { + t((t === null) || isArray(t.prototype), true); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_sub-array-dummy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_sub-array-dummy.js new file mode 100644 index 00000000000000..29d8699d461a85 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/_sub-array-dummy.js @@ -0,0 +1,7 @@ +'use strict'; + +var isArray = Array.isArray; + +module.exports = function (t, a) { + t((t === null) || isArray(t.prototype), true); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/implement.js new file mode 100644 index 00000000000000..e0db846f99a0d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../array/from/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/shim.js new file mode 100644 index 00000000000000..310302ac486645 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/from/shim.js @@ -0,0 +1,60 @@ +// Some tests taken from: https://github.com/mathiasbynens/Array.from/blob/master/tests/tests.js + +'use strict'; + +module.exports = function (t, a) { + var o = [1, 2, 3], MyType; + a.not(t(o), o, "Array"); + a.deep(t(o), o, "Array: same content"); + a.deep(t('12r3v'), ['1', '2', 'r', '3', 'v'], "String"); + a.deep(t((function () { return arguments; }(3, o, 'raz'))), + [3, o, 'raz'], "Arguments"); + a.deep(t((function () { return arguments; }(3))), [3], + "Arguments with one numeric value"); + + a.deep(t({ 0: 'raz', 1: 'dwa', length: 2 }), ['raz', 'dwa'], "Other"); + + a.deep(t(o, function (val) { return (val + 2) * 10; }, 10), [30, 40, 50], + "Mapping"); + + a.throws(function () { t(); }, TypeError, "Undefined"); + a.deep(t(3), [], "Primitive"); + + a(t.length, 1, "Length"); + a.deep(t({ length: 0 }), [], "No values Array-like"); + a.deep(t({ length: -1 }), [], "Invalid length Array-like"); + a.deep(t({ length: -Infinity }), [], "Invalid length Array-like #2"); + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.deep(t(false), [], "Boolean"); + a.deep(t(-Infinity), [], "Inifity"); + a.deep(t(-0), [], "-0"); + a.deep(t(+0), [], "+0"); + a.deep(t(1), [], "1"); + a.deep(t(+Infinity), [], "+Infinity"); + a.deep(t({}), [], "Plain object"); + a.deep(t({ length: 1 }), [undefined], "Sparse array-like"); + a.deep(t({ '0': 'a', '1': 'b', length: 2 }, function (x) { return x + x; }), ['aa', 'bb'], + "Map"); + a.deep(t({ '0': 'a', '1': 'b', length: 2 }, function (x) { return String(this); }, undefined), + ['undefined', 'undefined'], "Map context"); + a.deep(t({ '0': 'a', '1': 'b', length: 2 }, function (x) { return String(this); }, 'x'), + ['x', 'x'], "Map primitive context"); + a.throws(function () { t({}, 'foo', 'x'); }, TypeError, "Non callable for map"); + + a.deep(t.call(null, { length: 1, '0': 'a' }), ['a'], "Null context"); + + a(t({ __proto__: { '0': 'abc', length: 1 } })[0], 'abc', "Values on prototype"); + + a.throws(function () { t.call(function () { return Object.freeze({}); }, {}); }, + TypeError, "Contructor producing freezed objects"); + + // Ensure no setters are called for the indexes + // Ensure no setters are called for the indexes + MyType = function () {}; + Object.defineProperty(MyType.prototype, '0', { + set: function (x) { throw new Error('Setter called: ' + x); } + }); + a.deep(t.call(MyType, { '0': 'abc', length: 1 }), { '0': 'abc', length: 1 }, + "Defined not set"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/generate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/generate.js new file mode 100644 index 00000000000000..d72e056887838b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/generate.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = {}; + a.deep(t(3), [undefined, undefined, undefined], "Just length"); + a.deep(t(0, 'x'), [], "No repeat"); + a.deep(t(1, x, y), [x], "Arguments length larger than repeat number"); + a.deep(t(3, x), [x, x, x], "Single argument"); + a.deep(t(5, x, y), [x, y, x, y, x], "Many arguments"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/is-plain-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/is-plain-array.js new file mode 100644 index 00000000000000..871a08aec21ff9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/is-plain-array.js @@ -0,0 +1,18 @@ +'use strict'; + +var SubArray = require('../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr = [1, 2, 3]; + a(t(arr), true, "Array"); + a(t(null), false, "Null"); + a(t(), false, "Undefined"); + a(t('234'), false, "String"); + a(t(23), false, "Number"); + a(t({}), false, "Plain object"); + a(t({ length: 1, 0: 'raz' }), false, "Array-like"); + a(t(Object.create(arr)), false, "Array extension"); + if (!SubArray) return; + a(t(new SubArray(23)), false, "Subclass instance"); + a(t(Array.prototype), false, "Array.prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/implement.js new file mode 100644 index 00000000000000..30d53be2d7abbe --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../array/of/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/shim.js new file mode 100644 index 00000000000000..e6974420c1c274 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/of/shim.js @@ -0,0 +1,68 @@ +// Most tests taken from https://github.com/mathiasbynens/Array.of/blob/master/tests/tests.js +// Thanks @mathiasbynens + +'use strict'; + +var defineProperty = Object.defineProperty; + +module.exports = function (t, a) { + var x = {}, testObject, MyType; + + a.deep(t(), [], "No arguments"); + a.deep(t(3), [3], "One numeric argument"); + a.deep(t(3, 'raz', null, x, undefined), [3, 'raz', null, x, undefined], + "Many arguments"); + + a(t.length, 0, "Length"); + + a.deep(t('abc'), ['abc'], "String"); + a.deep(t(undefined), [undefined], "Undefined"); + a.deep(t(null), [null], "Null"); + a.deep(t(false), [false], "Boolean"); + a.deep(t(-Infinity), [-Infinity], "Infinity"); + a.deep(t(-0), [-0], "-0"); + a.deep(t(+0), [+0], "+0"); + a.deep(t(1), [1], "1"); + a.deep(t(1, 2, 3), [1, 2, 3], "Numeric args"); + a.deep(t(+Infinity), [+Infinity], "+Infinity"); + a.deep(t({ '0': 'a', '1': 'b', '2': 'c', length: 3 }), + [{ '0': 'a', '1': 'b', '2': 'c', length: 3 }], "Array like"); + a.deep(t(undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity), + [undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity], "Falsy arguments"); + + a.h1("Null context"); + a.deep(t.call(null, 'abc'), ['abc'], "String"); + a.deep(t.call(null, undefined), [undefined], "Undefined"); + a.deep(t.call(null, null), [null], "Null"); + a.deep(t.call(null, false), [false], "Boolean"); + a.deep(t.call(null, -Infinity), [-Infinity], "-Infinity"); + a.deep(t.call(null, -0), [-0], "-0"); + a.deep(t.call(null, +0), [+0], "+0"); + a.deep(t.call(null, 1), [1], "1"); + a.deep(t.call(null, 1, 2, 3), [1, 2, 3], "Numeric"); + a.deep(t.call(null, +Infinity), [+Infinity], "+Infinity"); + a.deep(t.call(null, { '0': 'a', '1': 'b', '2': 'c', length: 3 }), + [{ '0': 'a', '1': 'b', '2': 'c', length: 3 }], "Array-like"); + a.deep(t.call(null, undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity), + [undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity], "Falsy"); + + a.h1("Other constructor context"); + a.deep(t.call(Object, 1, 2, 3), { '0': 1, '1': 2, '2': 3, length: 3 }, "Many arguments"); + + testObject = Object(3); + testObject[0] = 1; + testObject[1] = 2; + testObject[2] = 3; + testObject.length = 3; + a.deep(t.call(Object, 1, 2, 3), testObject, "Test object"); + a(t.call(Object).length, 0, "No arguments"); + a.throws(function () { t.call(function () { return Object.freeze({}); }); }, TypeError, + "Frozen instance"); + + // Ensure no setters are called for the indexes + MyType = function () {}; + defineProperty(MyType.prototype, '0', { + set: function (x) { throw new Error('Setter called: ' + x); } + }); + a.deep(t.call(MyType, 'abc'), { '0': 'abc', length: 1 }, "Define, not set"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/to-array.js new file mode 100644 index 00000000000000..4985b5eaee9769 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/to-array.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var o = [1, 2, 3]; + a(t(o), o, "Array"); + a.deep(t('12r3v'), ['1', '2', 'r', '3', 'v'], "String"); + a.deep(t((function () { return arguments; }(3, o, 'raz'))), + [3, o, 'raz'], "Arguments"); + a.deep(t((function () { return arguments; }(3))), [3], + "Arguments with one numeric value"); + + a.deep(t({ 0: 'raz', 1: 'dwa', length: 2 }), ['raz', 'dwa'], "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/valid-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/valid-array.js new file mode 100644 index 00000000000000..3732192d1bbd1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/array/valid-array.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(0); }, TypeError, "Number"); + a.throws(function () { t(true); }, TypeError, "Boolean"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + a(t(x = []), x, "Array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/boolean/is-boolean.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/boolean/is-boolean.js new file mode 100644 index 00000000000000..4e6b3cb73e4f3b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/boolean/is-boolean.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(false), true, "Boolean"); + a(t(new Boolean(false)), true, "Boolean object"); + a(t(new Date()), false, "Date"); + a(t(new String('raz')), false, "String object"); + a(t({}), false, "Plain object"); + a(t(/a/), false, "Regular expression"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/copy.js new file mode 100644 index 00000000000000..767c5e16a4d053 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/copy.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var o = new Date(), o2; + + o2 = t.call(o); + a.not(o, o2, "Different objects"); + a.ok(o2 instanceof Date, "Instance of Date"); + a(o.getTime(), o2.getTime(), "Same time"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/days-in-month.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/days-in-month.js new file mode 100644 index 00000000000000..9ddba55f74ac40 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/days-in-month.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2001, 0, 1)), 31, "January"); + a(t.call(new Date(2001, 1, 1)), 28, "February"); + a(t.call(new Date(2000, 1, 1)), 29, "February (leap)"); + a(t.call(new Date(2001, 2, 1)), 31, "March"); + a(t.call(new Date(2001, 3, 1)), 30, "April"); + a(t.call(new Date(2001, 4, 1)), 31, "May"); + a(t.call(new Date(2001, 5, 1)), 30, "June"); + a(t.call(new Date(2001, 6, 1)), 31, "July"); + a(t.call(new Date(2001, 7, 1)), 31, "August"); + a(t.call(new Date(2001, 8, 1)), 30, "September"); + a(t.call(new Date(2001, 9, 1)), 31, "October"); + a(t.call(new Date(2001, 10, 1)), 30, "November"); + a(t.call(new Date(2001, 11, 1)), 31, "December"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-day.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-day.js new file mode 100644 index 00000000000000..d4f4a9087c059e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-day.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2000, 0, 1, 13, 32, 34, 234)).valueOf(), + new Date(2000, 0, 1).valueOf()); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-month.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-month.js new file mode 100644 index 00000000000000..b4a81bef6d0850 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-month.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2000, 0, 15, 13, 32, 34, 234)).valueOf(), + new Date(2000, 0, 1).valueOf()); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-year.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-year.js new file mode 100644 index 00000000000000..aae117e769b52c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/floor-year.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2000, 5, 13, 13, 32, 34, 234)).valueOf(), + new Date(2000, 0, 1).valueOf()); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/format.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/format.js new file mode 100644 index 00000000000000..e68e4bf782ef30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/#/format.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + var dt = new Date(2011, 2, 3, 3, 5, 5, 32); + a(t.call(dt, ' %Y.%y.%m.%d.%H.%M.%S.%L '), ' 2011.11.03.03.03.05.05.032 '); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/is-date.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/is-date.js new file mode 100644 index 00000000000000..109093dfbe32f8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/is-date.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(true), false, "Boolean"); + a(t(new Date()), true, "Date"); + a(t(new String('raz')), false, "String object"); + a(t({}), false, "Plain object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/valid-date.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/valid-date.js new file mode 100644 index 00000000000000..98787e40781687 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/date/valid-date.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var d = new Date(); + a(t(d), d, "Date"); + a.throws(function () { + t({}); + }, "Object"); + a.throws(function () { + t({ valueOf: function () { return 20; } }); + }, "Number object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/#/throw.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/#/throw.js new file mode 100644 index 00000000000000..1213cfc3b12791 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/#/throw.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var e = new Error(); + try { + t.call(e); + } catch (e2) { + a(e2, e); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/custom.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/custom.js new file mode 100644 index 00000000000000..d4ff500c9b30f2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/custom.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var T = t, err = new T('My Error', 'MY_ERROR', { errno: 123 }); + a(err instanceof Error, true, "Instance of error"); + a(err.constructor, Error, "Constructor"); + a(err.name, 'Error', "Name"); + a(String(err), 'Error: My Error', "String representation"); + a(err.code, 'MY_ERROR', "Code"); + a(err.errno, 123, "Errno"); + a(typeof err.stack, 'string', "Stack trace"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/is-error.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/is-error.js new file mode 100644 index 00000000000000..f8b5e2000eb769 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/is-error.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(), false, "Undefined"); + a(t(1), false, "Primitive"); + a(t({}), false, "Objectt"); + a(t({ toString: function () { return '[object Error]'; } }), false, + "Fake error"); + a(t(new Error()), true, "Error"); + a(t(new EvalError()), true, "EvalError"); + a(t(new RangeError()), true, "RangeError"); + a(t(new ReferenceError()), true, "ReferenceError"); + a(t(new SyntaxError()), true, "SyntaxError"); + a(t(new TypeError()), true, "TypeError"); + a(t(new URIError()), true, "URIError"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/valid-error.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/valid-error.js new file mode 100644 index 00000000000000..e04cdb33b7cdf4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/error/valid-error.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var e = new Error(); + a(t(e), e, "Error"); + a.throws(function () { + t({}); + }, "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/compose.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/compose.js new file mode 100644 index 00000000000000..83de5e844ac87d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/compose.js @@ -0,0 +1,9 @@ +'use strict'; + +var f = function (a, b) { return ['a', arguments.length, a, b]; } + , g = function (a) { return ['b', arguments.length].concat(a); } + , h = function (a) { return ['c', arguments.length].concat(a); }; + +module.exports = function (t, a) { + a.deep(t.call(h, g, f)(1, 2), ['c', 1, 'b', 1, 'a', 2, 1, 2]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/copy.js new file mode 100644 index 00000000000000..7a22e2f249276e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/copy.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = function (t, a) { + var foo = 'raz', bar = 'dwa' + , fn = function marko(a, b) { return this + a + b + foo + bar; } + , result, o = {}; + + fn.prototype = o; + + fn.foo = 'raz'; + + result = t.call(fn); + + a(result.length, fn.length, "Length"); + a(result.name, fn.name, "Length"); + a(result.call('marko', 'el', 'fe'), 'markoelferazdwa', "Body"); + a(result.prototype, fn.prototype, "Prototype"); + a(result.foo, fn.foo, "Custom property"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/curry.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/curry.js new file mode 100644 index 00000000000000..18fb0389e79b26 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/curry.js @@ -0,0 +1,18 @@ +'use strict'; + +var toArray = require('../../../array/to-array') + + , f = function () { return toArray(arguments); }; + +module.exports = function (t, a) { + var x, y = {}, z; + a.deep(t.call(f, 0, 1, 2)(3), [], "0 arguments"); + x = t.call(f, 5, {}); + a(x.length, 5, "Length #1"); + z = x(1, 2); + a(z.length, 3, "Length #2"); + z = z(3, 4); + a(z.length, 1, "Length #1"); + a.deep(z(5, 6), [1, 2, 3, 4, 5], "Many arguments"); + a.deep(x(8, 3)(y, 45)('raz', 6), [8, 3, y, 45, 'raz'], "Many arguments #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/lock.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/lock.js new file mode 100644 index 00000000000000..44a12d7b56c748 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/lock.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(function () { + return arguments.length; + })(1, 2, 3), 0); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/not.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/not.js new file mode 100644 index 00000000000000..c0f5e9d4b989a5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/not.js @@ -0,0 +1,11 @@ +'use strict'; + +var identity = require('../../../function/identity') + , noop = require('../../../function/noop'); + +module.exports = function (t, a) { + a(t.call(identity)(''), true, "Falsy"); + a(t.call(noop)(), true, "Undefined"); + a(t.call(identity)({}), false, "Any object"); + a(t.call(identity)(true), false, "True"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/partial.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/partial.js new file mode 100644 index 00000000000000..bd00ce752f5202 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/partial.js @@ -0,0 +1,9 @@ +'use strict'; + +var toArray = require('../../../array/to-array') + + , f = function () { return toArray(arguments); }; + +module.exports = function (t, a) { + a.deep(t.call(f, 1)(2, 3), [1, 2, 3]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/spread.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/spread.js new file mode 100644 index 00000000000000..b82dfecfe95045 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/spread.js @@ -0,0 +1,8 @@ +'use strict'; + +var f = function (a, b) { return this[a] + this[b]; } + , o = { a: 3, b: 4 }; + +module.exports = function (t, a) { + a(t.call(f).call(o, ['a', 'b']), 7); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/to-string-tokens.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/to-string-tokens.js new file mode 100644 index 00000000000000..4c54d30354b405 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/#/to-string-tokens.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t.call(function (a, b) { return this[a] + this[b]; }), + { args: 'a, b', body: ' return this[a] + this[b]; ' }); + a.deep(t.call(function () {}), + { args: '', body: '' }); + a.deep(t.call(function (raz) {}), + { args: 'raz', body: '' }); + a.deep(t.call(function () { Object(); }), + { args: '', body: ' Object(); ' }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/_define-length.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/_define-length.js new file mode 100644 index 00000000000000..8f037e857eaa09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/_define-length.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var foo = 'raz', bar = 'dwa' + , fn = function (a, b) { return this + a + b + foo + bar; } + , result; + + result = t(fn, 3); + a(result.call('marko', 'el', 'fe'), 'markoelferazdwa', "Content"); + a(result.length, 3, "Length"); + a(result.prototype, fn.prototype, "Prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/constant.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/constant.js new file mode 100644 index 00000000000000..fda52aa43710c1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/constant.js @@ -0,0 +1,7 @@ +'use strict'; + +var o = {}; + +module.exports = function (t, a) { + a(t(o)(), o); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/identity.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/identity.js new file mode 100644 index 00000000000000..8013e2e5af1288 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/identity.js @@ -0,0 +1,7 @@ +'use strict'; + +var o = {}; + +module.exports = function (t, a) { + a(t(o), o); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/invoke.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/invoke.js new file mode 100644 index 00000000000000..fcce4aaaaafb87 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/invoke.js @@ -0,0 +1,9 @@ +'use strict'; + +var constant = require('../../function/constant') + + , o = { b: constant('c') }; + +module.exports = function (t, a) { + a(t('b')(o), 'c'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/is-arguments.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/is-arguments.js new file mode 100644 index 00000000000000..f8de8812a5035d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/is-arguments.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + var args, dummy; + args = (function () { return arguments; }()); + dummy = { '0': 1, '1': 2 }; + Object.defineProperty(dummy, 'length', { value: 2 }); + a(t(args), true, "Arguments"); + a(t(dummy), false, "Dummy"); + a(t([]), false, "Array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/is-function.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/is-function.js new file mode 100644 index 00000000000000..83acc42f9a6637 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/is-function.js @@ -0,0 +1,8 @@ +'use strict'; + +var o = { call: Function.prototype.call, apply: Function.prototype.apply }; + +module.exports = function (t, a) { + a(t(function () {}), true, "Function is function"); + a(t(o), false, "Plain object is not function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/noop.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/noop.js new file mode 100644 index 00000000000000..4305c6fcfd51cd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/noop.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t(1, 2, 3), 'undefined'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/pluck.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/pluck.js new file mode 100644 index 00000000000000..5bf9583ad52b3e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/pluck.js @@ -0,0 +1,7 @@ +'use strict'; + +var o = { foo: 'bar' }; + +module.exports = function (t, a) { + a(t('foo')(o), o.foo); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/valid-function.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/valid-function.js new file mode 100644 index 00000000000000..59b16233b37978 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/function/valid-function.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var f = function () {}; + a(t(f), f, "Function"); + f = new Function(); + a(t(f), f, "Function"); + a.throws(function () { + t({}); + }, "Object"); + a.throws(function () { + t(/re/); + }, "RegExp"); + a.throws(function () { + t({ call: function () { return 20; } }); + }, "Plain object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/global.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/global.js new file mode 100644 index 00000000000000..1f452aefb09827 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/global.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.ok(t && typeof t === 'object'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/for-each.js new file mode 100644 index 00000000000000..0fed8ad898990e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/for-each.js @@ -0,0 +1,40 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array') + + , slice = Array.prototype.slice; + +module.exports = function (t, a) { + var i = 0, x = ['raz', 'dwa', 'trzy'], y = {}; + t(x, function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Array " + i + "#"); + a(this, y, "Array: context: " + (i++) + "#"); + }, y); + i = 0; + t((function () { return arguments; }('raz', 'dwa', 'trzy')), function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Arguments" + i + "#"); + a(this, y, "Arguments: context: " + (i++) + "#"); + }, y); + i = 0; + t({ 0: 'raz', 1: 'dwa', 2: 'trzy', length: 3 }, function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Array-like" + i + "#"); + a(this, y, "Array-like: context: " + (i++) + "#"); + }, y); + i = 0; + t(x = 'foo', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Regular String: context: " + (i++) + "#"); + }, y); + i = 0; + x = ['r', '💩', 'z']; + t('r💩z', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Unicode String: context: " + (i++) + "#"); + }, y); + i = 0; + t(new ArrayIterator(x), function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Iterator " + i + "#"); + a(this, y, "Iterator: context: " + (i++) + "#"); + }, y); + +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/is.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/is.js new file mode 100644 index 00000000000000..c0d2a43ebfe17c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/is.js @@ -0,0 +1,20 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (t, a) { + var x; + a(t([]), true, "Array"); + a(t(""), true, "String"); + a(t((function () { return arguments; }())), true, "Arguments"); + a(t({ length: 0 }), true, "List object"); + a(t(function () {}), false, "Function"); + a(t({}), false, "Plain object"); + a(t(/raz/), false, "Regexp"); + a(t(), false, "No argument"); + a(t(null), false, "Null"); + a(t(undefined), false, "Undefined"); + x = {}; + x[iteratorSymbol] = function () {}; + a(t(x), true, "Iterable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/validate-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/validate-object.js new file mode 100644 index 00000000000000..da12529bc0368c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/validate-object.js @@ -0,0 +1,20 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a.throws(function () { t(''); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); + x = {}; + x[iteratorSymbol] = function () {}; + a(t(x), x, "Iterable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/validate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/validate.js new file mode 100644 index 00000000000000..bcc2ad3d0aa1c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/iterable/validate.js @@ -0,0 +1,20 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a(t(''), '', "''"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); + x = {}; + x[iteratorSymbol] = function () {}; + a(t(x), x, "Iterable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/_pack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/_pack-ieee754.js new file mode 100644 index 00000000000000..9041431d7769c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/_pack-ieee754.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t(1.337, 8, 23), [63, 171, 34, 209]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/_unpack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/_unpack-ieee754.js new file mode 100644 index 00000000000000..ca30b8208dbb95 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/_unpack-ieee754.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t([63, 171, 34, 209], 8, 23), 1.3370000123977661); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/implement.js new file mode 100644 index 00000000000000..01fb6d08224e2a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/acosh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/shim.js new file mode 100644 index 00000000000000..3d710c7930d454 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/acosh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-1), NaN, "Negative"); + a(t(0), NaN, "Zero"); + a(t(0.5), NaN, "Below 1"); + a(t(1), 0, "1"); + a(t(2), 1.3169578969248166, "Other"); + a(t(Infinity), Infinity, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/implement.js new file mode 100644 index 00000000000000..d1fceceee13449 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/asinh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/shim.js new file mode 100644 index 00000000000000..d9fbe49edc2d99 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/asinh/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(-2), -1.4436354751788103, "Negative"); + a(t(2), 1.4436354751788103, "Positive"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/implement.js new file mode 100644 index 00000000000000..cba8fad83e4082 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/atanh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/shim.js new file mode 100644 index 00000000000000..a857b496686048 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/atanh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-2), NaN, "Less than -1"); + a(t(2), NaN, "Greater than 1"); + a(t(-1), -Infinity, "-1"); + a(t(1), Infinity, "1"); + a(t(0), 0, "Zero"); + a(t(0.5), 0.5493061443340549, "Ohter"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/implement.js new file mode 100644 index 00000000000000..374d4b383f5c5f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/cbrt/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/shim.js new file mode 100644 index 00000000000000..43ab68b848f61a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cbrt/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(-1), -1, "-1"); + a(t(1), 1, "1"); + a(t(2), 1.2599210498948732, "Ohter"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/implement.js new file mode 100644 index 00000000000000..44f8815526b7ec --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/clz32/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/shim.js new file mode 100644 index 00000000000000..a769b39b85b644 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/clz32/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(1), 31, "1"); + a(t(1000), 22, "1000"); + a(t(), 32, "No arguments"); + a(t(Infinity), 32, "Infinity"); + a(t(-Infinity), 32, "-Infinity"); + a(t("foo"), 32, "String"); + a(t(true), 31, "Boolean"); + a(t(3.5), 30, "Float"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/implement.js new file mode 100644 index 00000000000000..f3c712b1dfc977 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/cosh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/shim.js new file mode 100644 index 00000000000000..419c12367dbcd2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/cosh/shim.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 1, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), Infinity, "-Infinity"); + a(t(1), 1.5430806348152437, "1"); + a(t(Number.MAX_VALUE), Infinity); + a(t(-Number.MAX_VALUE), Infinity); + a(t(Number.MIN_VALUE), 1); + a(t(-Number.MIN_VALUE), 1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/implement.js new file mode 100644 index 00000000000000..c21296725dc07b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/expm1/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/shim.js new file mode 100644 index 00000000000000..15f0e796ce565b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/expm1/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -1, "-Infinity"); + a(t(1).toFixed(15), '1.718281828459045', "1"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/implement.js new file mode 100644 index 00000000000000..c909af7c300b22 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/fround/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/shim.js new file mode 100644 index 00000000000000..4ef6d4ea9b199b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/fround/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(1.337), 1.3370000123977661, "1"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/implement.js new file mode 100644 index 00000000000000..99466464c122bc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/hypot/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/shim.js new file mode 100644 index 00000000000000..91d950a5d32899 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/hypot/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(), 0, "No arguments"); + a(t(0, -0, 0), 0, "Zeros"); + a(t(4, NaN, Infinity), Infinity, "Infinity"); + a(t(4, NaN, -Infinity), Infinity, "Infinity"); + a(t(4, NaN, 34), NaN, "NaN"); + a(t(3, 4), 5, "#1"); + a(t(3, 4, 5), 7.0710678118654755, "#2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/implement.js new file mode 100644 index 00000000000000..7b2a2a61653299 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/imul/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/shim.js new file mode 100644 index 00000000000000..a2ca7fe78321ce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/imul/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(), 0, "No arguments"); + a(t(0, 0), 0, "Zeros"); + a(t(2, 4), 8, "#1"); + a(t(-1, 8), -8, "#2"); + a(t(0xfffffffe, 5), -10, "#3"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/implement.js new file mode 100644 index 00000000000000..4b3b4a4569fb81 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/log10/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/shim.js new file mode 100644 index 00000000000000..5fa0d5be3af861 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log10/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-0.5), NaN, "Less than 0"); + a(t(0), -Infinity, "0"); + a(t(1), 0, "1"); + a(t(Infinity), Infinity, "Infinity"); + a(t(2), 0.3010299956639812, "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/implement.js new file mode 100644 index 00000000000000..5d269bd3eaf09b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/log1p/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/shim.js new file mode 100644 index 00000000000000..d495ce0496b76d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log1p/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-1.5), NaN, "Less than -1"); + a(t(-1), -Infinity, "-1"); + a(t(0), 0, "0"); + a(t(Infinity), Infinity, "Infinity"); + a(t(1), 0.6931471805599453, "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/implement.js new file mode 100644 index 00000000000000..92b501ac72abed --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/log2/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/shim.js new file mode 100644 index 00000000000000..faa9c32a8537ab --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/log2/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-0.5), NaN, "Less than 0"); + a(t(0), -Infinity, "0"); + a(t(1), 0, "1"); + a(t(Infinity), Infinity, "Infinity"); + a(t(3).toFixed(15), '1.584962500721156', "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/implement.js new file mode 100644 index 00000000000000..5875c42d608eb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/sign/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/shim.js new file mode 100644 index 00000000000000..b6b89c15889dc4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sign/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +var is = require('../../../object/is'); + +module.exports = function (t, a) { + a(is(t(0), +0), true, "+0"); + a(is(t(-0), -0), true, "-0"); + a(t({}), NaN, true, "NaN"); + a(t(-234234234), -1, "Negative"); + a(t(234234234), 1, "Positive"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/implement.js new file mode 100644 index 00000000000000..e52089e4507156 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/sinh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/shim.js new file mode 100644 index 00000000000000..4f63b59e735bf0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/sinh/shim.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(1), 1.1752011936438014, "1"); + a(t(Number.MAX_VALUE), Infinity); + a(t(-Number.MAX_VALUE), -Infinity); + a(t(Number.MIN_VALUE), 5e-324); + a(t(-Number.MIN_VALUE), -5e-324); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/implement.js new file mode 100644 index 00000000000000..a96bf193366b30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/tanh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/shim.js new file mode 100644 index 00000000000000..2c67aaf47049fd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/tanh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), 1, "Infinity"); + a(t(-Infinity), -1, "-Infinity"); + a(t(1), 0.7615941559557649, "1"); + a(t(Number.MAX_VALUE), 1); + a(t(-Number.MAX_VALUE), -1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/implement.js new file mode 100644 index 00000000000000..1830e61f69794d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/trunc/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/shim.js new file mode 100644 index 00000000000000..9e5eed7910e13c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/math/trunc/shim.js @@ -0,0 +1,16 @@ +'use strict'; + +var is = require('../../../object/is'); + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(is(t(0.234), 0), true, "0"); + a(is(t(-0.234), -0), true, "-0"); + a(t(13.7), 13, "Positive #1"); + a(t(12.3), 12, "Positive #2"); + a(t(-12.3), -12, "Negative #1"); + a(t(-14.7), -14, "Negative #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/#/pad.js new file mode 100644 index 00000000000000..e02082353348dc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/#/pad.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(78, 4), '0078'); + a(t.call(65.12323, 4, 3), '0065.123', "Precision"); + a(t.call(65, 4, 3), '0065.000', "Precision integer"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/implement.js new file mode 100644 index 00000000000000..574da75dcebb7f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/epsilon/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/index.js new file mode 100644 index 00000000000000..c892fd47d41c16 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/epsilon/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/implement.js new file mode 100644 index 00000000000000..b35345fa6ee762 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-finite/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/shim.js new file mode 100644 index 00000000000000..5205d1c2602520 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-finite/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), true, "Number"); + a(t('23'), false, "Not numeric"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/implement.js new file mode 100644 index 00000000000000..127149ceeda9b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/shim.js new file mode 100644 index 00000000000000..3f3985c3a05522 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-integer/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), true, "Number"); + a(t(2.34), false, "Float"); + a(t('23'), false, "Not numeric"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/implement.js new file mode 100644 index 00000000000000..2f01d6d30ad9f6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-nan/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/shim.js new file mode 100644 index 00000000000000..425723e74b07b9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-nan/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), false, "Number"); + a(t({}), false, "Not numeric"); + a(t(NaN), true, "NaN"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-number.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-number.js new file mode 100644 index 00000000000000..275133476a61ff --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-number.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(0), true, "Zero"); + a(t(NaN), true, "NaN"); + a(t(Infinity), true, "Infinity"); + a(t(12), true, "Number"); + a(t(false), false, "Boolean"); + a(t(new Date()), false, "Date"); + a(t(new Number(2)), true, "Number object"); + a(t('asdfaf'), false, "String"); + a(t(''), false, "Empty String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/implement.js new file mode 100644 index 00000000000000..33667e2e9afb60 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-safe-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/shim.js new file mode 100644 index 00000000000000..77e06674711795 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/is-safe-integer/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), true, "Number"); + a(t(2.34), false, "Float"); + a(t(Math.pow(2, 53)), false, "Too large"); + a(t(Math.pow(2, 53) - 1), true, "Maximum"); + a(t('23'), false, "Not numeric"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/implement.js new file mode 100644 index 00000000000000..bef00ca413d3cb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/max-safe-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/index.js new file mode 100644 index 00000000000000..c892fd47d41c16 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/max-safe-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/implement.js new file mode 100644 index 00000000000000..fa440248bf47a6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/min-safe-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/index.js new file mode 100644 index 00000000000000..c892fd47d41c16 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/min-safe-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-integer.js new file mode 100644 index 00000000000000..ff326ba7a95bbb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-integer.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "NaN"); + a(t(20), 20, "Positive integer"); + a(t('-20'), -20, "String negative integer"); + a(t(Infinity), Infinity, "Infinity"); + a(t(15.343), 15, "Float"); + a(t(-15.343), -15, "Negative float"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-pos-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-pos-integer.js new file mode 100644 index 00000000000000..2f3b4e674ecc4b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-pos-integer.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "NaN"); + a(t(20), 20, "Positive integer"); + a(t(-20), 0, "Negative integer"); + a(t(Infinity), Infinity, "Infinity"); + a(t(15.343), 15, "Float"); + a(t(-15.343), 0, "Negative float"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-uint32.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-uint32.js new file mode 100644 index 00000000000000..00d05bdfe346d7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/number/to-uint32.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "Not numeric"); + a(t(-4), 4294967292, "Negative"); + a(t(133432), 133432, "Positive"); + a(t(8589934592), 0, "Greater than maximum"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/_iterate.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/_iterate.js new file mode 100644 index 00000000000000..179afed88ee845 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/_iterate.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { raz: 1, dwa: 2, trzy: 3 } + , o2 = {}, o3 = {}, arr, i = -1; + + t = t('forEach'); + t(o, function (value, name, self, index) { + o2[name] = value; + a(index, ++i, "Index"); + a(self, o, "Self"); + a(this, o3, "Scope"); + }, o3); + a.deep(o2, o); + + arr = []; + o2 = {}; + i = -1; + t(o, function (value, name, self, index) { + arr.push(value); + o2[name] = value; + a(index, ++i, "Index"); + a(self, o, "Self"); + a(this, o3, "Scope"); + }, o3, function (a, b) { + return o[b] - o[a]; + }); + a.deep(o2, o, "Sort by Values: Content"); + a.deep(arr, [3, 2, 1], "Sort by Values: Order"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/implement.js new file mode 100644 index 00000000000000..40065594187cb9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../object/assign/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/shim.js new file mode 100644 index 00000000000000..9afe5f658c45b7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/assign/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + var o1 = { a: 1, b: 2 } + , o2 = { b: 3, c: 4 }; + + a(t(o1, o2), o1, "Returns self"); + a.deep(o1, { a: 1, b: 3, c: 4 }, "Single: content"); + + a.deep(t({}, o1, o2), { a: 1, b: 3, c: 4 }, "Multi argument"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/clear.js new file mode 100644 index 00000000000000..bfc08cc208420b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/clear.js @@ -0,0 +1,13 @@ +'use strict'; + +var isEmpty = require('../../object/is-empty'); + +module.exports = function (t, a) { + var x = {}; + a(t(x), x, "Empty: Returns same object"); + a(isEmpty(x), true, "Empty: Not changed"); + x.foo = 'raz'; + x.bar = 'dwa'; + a(t(x), x, "Same object"); + a(isEmpty(x), true, "Emptied"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/compact.js new file mode 100644 index 00000000000000..9c9064c7886445 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/compact.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = {}, z; + z = t(x); + a.not(z, x, "Returns different object"); + a.deep(z, {}, "Empty on empty"); + + x = { foo: 'bar', a: 0, b: false, c: '', d: '0', e: null, bar: y, + elo: undefined }; + z = t(x); + a.deep(z, { foo: 'bar', a: 0, b: false, c: '', d: '0', bar: y }, + "Cleared null values"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/compare.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/compare.js new file mode 100644 index 00000000000000..cb9424109c334b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/compare.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var d = new Date(); + + a.ok(t(12, 3) > 0, "Numbers"); + a.ok(t(2, 13) < 0, "Numbers #2"); + a.ok(t("aaa", "aa") > 0, "Strings"); + a.ok(t("aa", "ab") < 0, "Strings #2"); + a(t("aa", "aa"), 0, "Strings same"); + a(t(d, new Date(d.getTime())), 0, "Same date"); + a.ok(t(d, new Date(d.getTime() + 1)) < 0, "Different date"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/copy-deep.js new file mode 100644 index 00000000000000..a4023bc8ac4bf6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/copy-deep.js @@ -0,0 +1,24 @@ +'use strict'; + +var stringify = JSON.stringify; + +module.exports = function (t, a) { + var o = { 1: 'raz', 2: 'dwa', 3: 'trzy' } + , no = t(o); + + a.not(no, o, "Return different object"); + a(stringify(no), stringify(o), "Match properties and values"); + + o = { foo: 'bar', raz: { dwa: 'dwa', + trzy: { cztery: 'pięć', 'sześć': 'siedem' }, osiem: {}, + 'dziewięć': function () { } }, 'dziesięć': 10 }; + o.raz.rec = o; + + no = t(o); + a.not(o.raz, no.raz, "Deep"); + a.not(o.raz.trzy, no.raz.trzy, "Deep #2"); + a(stringify(o.raz.trzy), stringify(no.raz.trzy), "Deep content"); + a(no.raz.rec, no, "Recursive"); + a.not(o.raz.osiem, no.raz.osiem, "Empty object"); + a(o.raz['dziewięć'], no.raz['dziewięć'], "Function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/copy.js new file mode 100644 index 00000000000000..2f222ef809c6d7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/copy.js @@ -0,0 +1,19 @@ +'use strict'; + +var stringify = JSON.stringify; + +module.exports = function (t, a) { + var o = { 1: 'raz', 2: 'dwa', 3: 'trzy' } + , no = t(o); + + a.not(no, o, "Return different object"); + a(stringify(no), stringify(o), "Match properties and values"); + + o = { foo: 'bar', raz: { dwa: 'dwa', + trzy: { cztery: 'pięć', 'sześć': 'siedem' }, osiem: {}, + 'dziewięć': function () { } }, 'dziesięć': 10 }; + o.raz.rec = o; + + no = t(o); + a(o.raz, no.raz, "Shallow"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/count.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/count.js new file mode 100644 index 00000000000000..494f4f163515eb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/count.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "Empty"); + a(t({ raz: 1, dwa: null, trzy: undefined, cztery: 0 }), 4, + "Some properties"); + a(t(Object.defineProperties({}, { + raz: { value: 'raz' }, + dwa: { value: 'dwa', enumerable: true } + })), 1, "Some properties hidden"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/create.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/create.js new file mode 100644 index 00000000000000..8b7be214136d2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/create.js @@ -0,0 +1,22 @@ +'use strict'; + +var setPrototypeOf = require('../../object/set-prototype-of') + + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (t, a) { + var x = {}, obj; + + a(getPrototypeOf(t(x)), x, "Normal object"); + a(getPrototypeOf(t(null)), + (setPrototypeOf && setPrototypeOf.nullPolyfill) || null, "Null"); + + a.h1("Properties"); + a.h2("Normal object"); + a(getPrototypeOf(obj = t(x, { foo: { value: 'bar' } })), x, "Prototype"); + a(obj.foo, 'bar', "Property"); + a.h2("Null"); + a(getPrototypeOf(obj = t(null, { foo: { value: 'bar2' } })), + (setPrototypeOf && setPrototypeOf.nullPolyfill) || null, "Prototype"); + a(obj.foo, 'bar2', "Property"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/eq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/eq.js new file mode 100644 index 00000000000000..02b3f0027cbf82 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/eq.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var o = {}; + a(t(o, {}), false, "Different objects"); + a(t(o, o), true, "Same objects"); + a(t('1', '1'), true, "Same primitive"); + a(t('1', 1), false, "Different primitive types"); + a(t(NaN, NaN), true, "NaN"); + a(t(0, 0), true, "0,0"); + a(t(0, -0), true, "0,-0"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/every.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/every.js new file mode 100644 index 00000000000000..07d5bbbd61f7af --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/every.js @@ -0,0 +1,21 @@ +'use strict'; + +var o = { 1: 1, 2: 2, 3: 3 }; + +module.exports = function (t, a) { + var o2 = {}; + t(o, function (value, name) { + o2[name] = value; + return true; + }); + a(JSON.stringify(o2), JSON.stringify(o), "Iterates"); + + a(t(o, function () { + return true; + }), true, "Succeeds"); + + a(t(o, function () { + return false; + }), false, "Fails"); + +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/filter.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/filter.js new file mode 100644 index 00000000000000..7307da8640fcd1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/filter.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ 1: 1, 2: 2, 3: 3, 4: 4 }, + function (value) { return Boolean(value % 2); }), { 1: 1, 3: 3 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/first-key.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/first-key.js new file mode 100644 index 00000000000000..8169cd235344d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/first-key.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = Object.create(null); + a(t(x), null, "Normal: Empty"); + a(t(y), null, "Null extension: Empty"); + x.foo = 'raz'; + x.bar = 343; + a(['foo', 'bar'].indexOf(t(x)) !== -1, true, "Normal"); + y.elo = 'foo'; + y.mar = 'wew'; + a(['elo', 'mar'].indexOf(t(y)) !== -1, true, "Null extension"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/flatten.js new file mode 100644 index 00000000000000..ca342eab9c8ae4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/flatten.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ a: { aa: 1, ab: 2 }, b: { ba: 3, bb: 4 } }), + { aa: 1, ab: 2, ba: 3, bb: 4 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/for-each.js new file mode 100644 index 00000000000000..8690d1e82179aa --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/for-each.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { raz: 1, dwa: 2, trzy: 3 } + , o2 = {}; + a(t(o, function (value, name) { + o2[name] = value; + }), undefined, "Return"); + a.deep(o2, o); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/get-property-names.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/get-property-names.js new file mode 100644 index 00000000000000..b91c3dd50e7bbf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/get-property-names.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { first: 1, second: 4 }, r1, r2; + o = Object.create(o, { + third: { value: null } + }); + o.first = 2; + o = Object.create(o); + o.fourth = 3; + + r1 = t(o); + r1.sort(); + r2 = ['first', 'second', 'third', 'fourth'] + .concat(Object.getOwnPropertyNames(Object.prototype)); + r2.sort(); + a.deep(r1, r2); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-array-like.js new file mode 100644 index 00000000000000..6295973ca81acd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-array-like.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + a(t([]), true, "Array"); + a(t(""), true, "String"); + a(t((function () { return arguments; }())), true, "Arguments"); + a(t({ length: 0 }), true, "List object"); + a(t(function () {}), false, "Function"); + a(t({}), false, "Plain object"); + a(t(/raz/), false, "Regexp"); + a(t(), false, "No argument"); + a(t(null), false, "Null"); + a(t(undefined), false, "Undefined"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-callable.js new file mode 100644 index 00000000000000..625e221d2c3811 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-callable.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(function () {}), true, "Function"); + a(t({}), false, "Object"); + a(t(), false, "Undefined"); + a(t(null), false, "Null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-copy-deep.js new file mode 100644 index 00000000000000..4f14cbbe8108b2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-copy-deep.js @@ -0,0 +1,46 @@ +'use strict'; + +module.exports = function (t, a) { + var x, y; + + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 3 }), true, "Same"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 4 }), false, + "Different property value"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2 }), false, + "Property only in source"); + a(t({ 1: 1, 2: 2 }, { 1: 1, 2: 2, 3: 4 }), false, + "Property only in target"); + + a(t("raz", "dwa"), false, "String: diff"); + a(t("raz", "raz"), true, "String: same"); + a(t("32", 32), false, "String & Number"); + + a(t([1, 'raz', true], [1, 'raz', true]), true, "Array: same"); + a(t([1, 'raz', undefined], [1, 'raz']), false, "Array: diff"); + a(t(['foo'], ['one']), false, "Array: One value comparision"); + + x = { foo: { bar: { mar: {} } } }; + y = { foo: { bar: { mar: {} } } }; + a(t(x, y), true, "Deep"); + + a(t({ foo: { bar: { mar: 'foo' } } }, { foo: { bar: { mar: {} } } }), + false, "Deep: false"); + + x = { foo: { bar: { mar: {} } } }; + x.rec = { foo: x }; + + y = { foo: { bar: { mar: {} } } }; + y.rec = { foo: x }; + + a(t(x, y), true, "Object: Infinite Recursion: Same #1"); + + x.rec.foo = y; + a(t(x, y), true, "Object: Infinite Recursion: Same #2"); + + x.rec.foo = x; + y.rec.foo = y; + a(t(x, y), true, "Object: Infinite Recursion: Same #3"); + + y.foo.bar.mar = 'raz'; + a(t(x, y), false, "Object: Infinite Recursion: Diff"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-copy.js new file mode 100644 index 00000000000000..394e2ed94c09f0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-copy.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 3 }), true, "Same"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 4 }), false, + "Different property value"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2 }), false, + "Property only in source"); + a(t({ 1: 1, 2: 2 }, { 1: 1, 2: 2, 3: 4 }), false, + "Property only in target"); + + a(t("raz", "dwa"), false, "String: diff"); + a(t("raz", "raz"), true, "String: same"); + a(t("32", 32), false, "String & Number"); + + a(t([1, 'raz', true], [1, 'raz', true]), true, "Array: same"); + a(t([1, 'raz', undefined], [1, 'raz']), false, "Array: diff"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-empty.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-empty.js new file mode 100644 index 00000000000000..b560c2c36b0d4b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-empty.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), true, "Empty"); + a(t({ 1: 1 }), false, "Not empty"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-object.js new file mode 100644 index 00000000000000..72c8aa6daf4a3a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-object.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(true), false, "Boolean"); + a(t(null), false, "Null"); + a(t(new Date()), true, "Date"); + a(t(new String('raz')), true, "String object"); + a(t({}), true, "Plain object"); + a(t(/a/), true, "Regular expression"); + a(t(function () {}), true, "Function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-plain-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-plain-object.js new file mode 100644 index 00000000000000..e988829d558ad0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is-plain-object.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), true, "Empty {} is plain object"); + a(t({ a: true }), true, "{} with property is plain object"); + a(t({ prototype: 1, constructor: 2, __proto__: 3 }), true, + "{} with any property keys is plain object"); + a(t(null), false, "Null is not plain object"); + a(t('string'), false, "Primitive is not plain object"); + a(t(function () {}), false, "Function is not plain object"); + a(t(Object.create({})), false, + "Object whose prototype is not Object.prototype is not plain object"); + a(t(Object.create(Object.prototype)), true, + "Object whose prototype is Object.prototype is plain object"); + a(t(Object.create(null)), true, + "Object whose prototype is null is plain object"); + a(t(Object.prototype), false, "Object.prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is.js new file mode 100644 index 00000000000000..4f8948cbf344e1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/is.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var o = {}; + a(t(o, {}), false, "Different objects"); + a(t(o, o), true, "Same objects"); + a(t('1', '1'), true, "Same primitive"); + a(t('1', 1), false, "Different primitive types"); + a(t(NaN, NaN), true, "NaN"); + a(t(0, 0), true, "0,0"); + a(t(0, -0), false, "0,-0"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/key-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/key-of.js new file mode 100644 index 00000000000000..a9225a048c5c91 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/key-of.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = {} + , o = { foo: 'bar', raz: x, trzy: 'cztery', five: '6' }; + + a(t(o, 'bar'), 'foo', "First property"); + a(t(o, 6), null, "Primitive that's not there"); + a(t(o, x), 'raz', "Object"); + a(t(o, y), null, "Object that's not there"); + a(t(o, '6'), 'five', "Last property"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/implement.js new file mode 100644 index 00000000000000..179e1e5612ea8f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../object/keys/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/shim.js new file mode 100644 index 00000000000000..ed29eebcd751f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/keys/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ foo: 'bar' }), ['foo'], "Object"); + a.deep(t('raz'), ['0', '1', '2'], "Primitive"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Undefined"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/map-keys.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/map-keys.js new file mode 100644 index 00000000000000..be84825b1be711 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/map-keys.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ 1: 1, 2: 2, 3: 3 }, function (key, value) { + return 'x' + (key + value); + }), { x11: 1, x22: 2, x33: 3 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/map.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/map.js new file mode 100644 index 00000000000000..f9cc09c01b3933 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/map.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var obj = { 1: 1, 2: 2, 3: 3 }; + a.deep(t(obj, function (value, key, context) { + a(context, obj, "Context argument"); + return (value + 1) + key; + }), { 1: '21', 2: '32', 3: '43' }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/mixin-prototypes.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/mixin-prototypes.js new file mode 100644 index 00000000000000..d1c727a95a7371 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/mixin-prototypes.js @@ -0,0 +1,67 @@ +'use strict'; + +module.exports = function (t, a) { + var o, o1, o2, x, y = {}, z = {}; + o = { inherited: true, visible: 23 }; + o1 = Object.create(o); + o1.visible = z; + o1.nonremovable = 'raz'; + Object.defineProperty(o1, 'hidden', { value: 'hidden' }); + + o2 = Object.defineProperties({}, { nonremovable: { value: y } }); + o2.other = 'other'; + + try { t(o2, o1); } catch (ignore) {} + + a(o2.visible, z, "Enumerable"); + a(o1.hidden, 'hidden', "Not Enumerable"); + a(o2.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(o2.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(o2.inherited, true, "Extend deep"); + + a(o2.nonremovable, y, "Do not overwrite non configurable"); + a(o2.other, 'other', "Own kept"); + + x = {}; + t(x, o2); + try { t(x, o1); } catch (ignore) {} + + a(x.visible, z, "Enumerable"); + a(x.hidden, 'hidden', "Not Enumerable"); + a(x.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(x.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(x.inherited, true, "Extend deep"); + + a(x.nonremovable, y, "Ignored non configurable"); + a(x.other, 'other', "Other"); + + x.visible = 3; + a(x.visible, 3, "Writable is writable"); + + x = {}; + t(x, o1); + a.throws(function () { + x.hidden = 3; + }, "Not writable is not writable"); + + x = {}; + t(x, o1); + delete x.visible; + a.ok(!x.hasOwnProperty('visible'), "Configurable is configurable"); + + x = {}; + t(x, o1); + a.throws(function () { + delete x.hidden; + }, "Not configurable is not configurable"); + + x = Object.defineProperty({}, 'foo', + { configurable: false, writable: true, enumerable: false, value: 'bar' }); + + try { t(x, { foo: 'lorem' }); } catch (ignore) {} + a(x.foo, 'bar', "Writable, not enumerable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/mixin.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/mixin.js new file mode 100644 index 00000000000000..866005b03df29b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/mixin.js @@ -0,0 +1,69 @@ +'use strict'; + +module.exports = function (t, a) { + var o, o1, o2, x, y = {}, z = {}; + o = { inherited: true }; + o1 = Object.create(o); + o1.visible = z; + o1.nonremovable = 'raz'; + Object.defineProperty(o1, 'hidden', { value: 'hidden' }); + + o2 = Object.defineProperties({}, { nonremovable: { value: y } }); + o2.other = 'other'; + + try { t(o2, o1); } catch (ignore) {} + + a(o2.visible, z, "Enumerable"); + a(o1.hidden, 'hidden', "Not Enumerable"); + a(o2.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(o2.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(o2.hasOwnProperty('inherited'), false, "Extend only own"); + a(o2.inherited, undefined, "Extend ony own: value"); + + a(o2.nonremovable, y, "Do not overwrite non configurable"); + a(o2.other, 'other', "Own kept"); + + x = {}; + t(x, o2); + try { t(x, o1); } catch (ignore) {} + + a(x.visible, z, "Enumerable"); + a(x.hidden, 'hidden', "Not Enumerable"); + a(x.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(x.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(x.hasOwnProperty('inherited'), false, "Extend only own"); + a(x.inherited, undefined, "Extend ony own: value"); + + a(x.nonremovable, y, "Ignored non configurable"); + a(x.other, 'other', "Other"); + + x.visible = 3; + a(x.visible, 3, "Writable is writable"); + + x = {}; + t(x, o1); + a.throws(function () { + x.hidden = 3; + }, "Not writable is not writable"); + + x = {}; + t(x, o1); + delete x.visible; + a.ok(!x.hasOwnProperty('visible'), "Configurable is configurable"); + + x = {}; + t(x, o1); + a.throws(function () { + delete x.hidden; + }, "Not configurable is not configurable"); + + x = Object.defineProperty({}, 'foo', + { configurable: false, writable: true, enumerable: false, value: 'bar' }); + + try { t(x, { foo: 'lorem' }); } catch (ignore) {} + a(x.foo, 'bar', "Writable, not enumerable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/normalize-options.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/normalize-options.js new file mode 100644 index 00000000000000..0d2d4da04a53b1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/normalize-options.js @@ -0,0 +1,32 @@ +'use strict'; + +var create = Object.create, defineProperty = Object.defineProperty; + +module.exports = function (t, a) { + var x = { foo: 'raz', bar: 'dwa' }, y; + y = t(x); + a.not(y, x, "Returns copy"); + a.deep(y, x, "Plain"); + + x = { raz: 'one', dwa: 'two' }; + defineProperty(x, 'get', { + configurable: true, + enumerable: true, + get: function () { return this.dwa; } + }); + x = create(x); + x.trzy = 'three'; + x.cztery = 'four'; + x = create(x); + x.dwa = 'two!'; + x.trzy = 'three!'; + x.piec = 'five'; + x.szesc = 'six'; + + a.deep(t(x), { raz: 'one', dwa: 'two!', trzy: 'three!', cztery: 'four', + piec: 'five', szesc: 'six', get: 'two!' }, "Deep object"); + + a.deep(t({ marko: 'raz', raz: 'foo' }, x, { szesc: 'elo', siedem: 'bibg' }), + { marko: 'raz', raz: 'one', dwa: 'two!', trzy: 'three!', cztery: 'four', + piec: 'five', szesc: 'elo', siedem: 'bibg', get: 'two!' }, "Multiple options"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/primitive-set.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/primitive-set.js new file mode 100644 index 00000000000000..839857eab3dd85 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/primitive-set.js @@ -0,0 +1,15 @@ +'use strict'; + +var getPropertyNames = require('../../object/get-property-names') + , isPlainObject = require('../../object/is-plain-object'); + +module.exports = function (t, a) { + var x = t(); + a(isPlainObject(x), true, "Plain object"); + a.deep(getPropertyNames(x), [], "No properties"); + x.foo = 'bar'; + a.deep(getPropertyNames(x), ['foo'], "Extensible"); + + a.deep(t('raz', 'dwa', 3), { raz: true, dwa: true, 3: true }, + "Arguments handling"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/safe-traverse.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/safe-traverse.js new file mode 100644 index 00000000000000..d30cdefe68b8b6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/safe-traverse.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var obj = { foo: { bar: { lorem: 12 } } }; + a(t(obj), obj, "No props"); + a(t(obj, 'foo'), obj.foo, "One"); + a(t(obj, 'raz'), undefined, "One: Fail"); + a(t(obj, 'foo', 'bar'), obj.foo.bar, "Two"); + a(t(obj, 'dsd', 'raz'), undefined, "Two: Fail #1"); + a(t(obj, 'foo', 'raz'), undefined, "Two: Fail #2"); + a(t(obj, 'foo', 'bar', 'lorem'), obj.foo.bar.lorem, "Three"); + a(t(obj, 'dsd', 'raz', 'fef'), undefined, "Three: Fail #1"); + a(t(obj, 'foo', 'raz', 'asdf'), undefined, "Three: Fail #2"); + a(t(obj, 'foo', 'bar', 'asd'), undefined, "Three: Fail #3"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/serialize.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/serialize.js new file mode 100644 index 00000000000000..43eed6a8616f9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/serialize.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = function (t, a) { + var fn = function (raz, dwa) { return raz + dwa; }; + a(t(), 'undefined', "Undefined"); + a(t(null), 'null', "Null"); + a(t(null), 'null', "Null"); + a(t('raz'), '"raz"', "String"); + a(t('raz"ddwa\ntrzy'), '"raz\\"ddwa\\ntrzy"', "String with escape"); + a(t(false), 'false', "Booelean"); + a(t(fn), String(fn), "Function"); + + a(t(/raz-dwa/g), '/raz-dwa/g', "RegExp"); + a(t(new Date(1234567)), 'new Date(1234567)', "Date"); + a(t([]), '[]', "Empty array"); + a(t([undefined, false, null, 'raz"ddwa\ntrzy', fn, /raz/g, new Date(1234567), ['foo']]), + '[undefined,false,null,"raz\\"ddwa\\ntrzy",' + String(fn) + + ',/raz/g,new Date(1234567),["foo"]]', "Rich Array"); + a(t({}), '{}', "Empty object"); + a(t({ raz: undefined, dwa: false, trzy: null, cztery: 'raz"ddwa\ntrzy', piec: fn, szesc: /raz/g, + siedem: new Date(1234567), osiem: ['foo', 32], dziewiec: { foo: 'bar', dwa: 343 } }), + '{"raz":undefined,"dwa":false,"trzy":null,"cztery":"raz\\"ddwa\\ntrzy","piec":' + String(fn) + + ',"szesc":/raz/g,"siedem":new Date(1234567),"osiem":["foo",32],' + + '"dziewiec":{"foo":"bar","dwa":343}}', "Rich object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/implement.js new file mode 100644 index 00000000000000..30b2ac4b96ba2e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +var create = require('../../../object/create') + , isImplemented = require('../../../object/set-prototype-of/is-implemented'); + +module.exports = function (a) { a(isImplemented(create), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/index.js new file mode 100644 index 00000000000000..aec2605cc2661a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var create = require('../../../object/create') + + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (t, a) { + var x = {}, y = {}; + + if (t === null) return; + a(t(x, y), x, "Return self object"); + a(getPrototypeOf(x), y, "Object"); + a.throws(function () { t(x); }, TypeError, "Undefined"); + a.throws(function () { t('foo'); }, TypeError, "Primitive"); + a(getPrototypeOf(t(x, null)), t.nullPolyfill || null, "Null"); + x = create(null); + a.h1("Change null prototype"); + a(t(x, y), x, "Result"); + a(getPrototypeOf(x), y, "Prototype"); + a.h1("Set null prototype"); + a(t(y, null), y, "Result"); + a(getPrototypeOf(y), t.nullPolyfill || null, "Prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/shim.js new file mode 100644 index 00000000000000..aec2605cc2661a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/set-prototype-of/shim.js @@ -0,0 +1,23 @@ +'use strict'; + +var create = require('../../../object/create') + + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (t, a) { + var x = {}, y = {}; + + if (t === null) return; + a(t(x, y), x, "Return self object"); + a(getPrototypeOf(x), y, "Object"); + a.throws(function () { t(x); }, TypeError, "Undefined"); + a.throws(function () { t('foo'); }, TypeError, "Primitive"); + a(getPrototypeOf(t(x, null)), t.nullPolyfill || null, "Null"); + x = create(null); + a.h1("Change null prototype"); + a(t(x, y), x, "Result"); + a(getPrototypeOf(x), y, "Prototype"); + a.h1("Set null prototype"); + a(t(y, null), y, "Result"); + a(getPrototypeOf(y), t.nullPolyfill || null, "Prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/some.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/some.js new file mode 100644 index 00000000000000..490431e7acd543 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/some.js @@ -0,0 +1,23 @@ +'use strict'; + +var o = { 1: 1, 2: 2, 3: 3 }; + +module.exports = function (t, a) { + var o2 = {}, i = 0; + t(o, function (value, name) { + o2[name] = value; + return false; + }); + a(JSON.stringify(o2), JSON.stringify(o), "Iterates"); + + a(t(o, function () { + ++i; + return true; + }), true, "Succeeds"); + a(i, 1, "Stops iteration after condition is met"); + + a(t(o, function () { + return false; + }), false, "Fails"); + +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/to-array.js new file mode 100644 index 00000000000000..1f4beef7eae835 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/to-array.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { 1: 1, 2: 2, 3: 3 }, o1 = {} + , o2 = t(o, function (value, name, self) { + a(self, o, "Self"); + a(this, o1, "Scope"); + return value + Number(name); + }, o1); + a.deep(o2, [2, 4, 6]); + + t(o).sort().forEach(function (item) { + a.deep(item, [item[0], o[item[0]]], "Default"); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/unserialize.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/unserialize.js new file mode 100644 index 00000000000000..405eef112ff76e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/unserialize.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = function (t, a) { + var fn = function (raz, dwa) { return raz + dwa; }; + a(t('undefined'), undefined, "Undefined"); + a(t('null'), null, "Null"); + a(t('"raz"'), 'raz', "String"); + a(t('"raz\\"ddwa\\ntrzy"'), 'raz"ddwa\ntrzy', "String with escape"); + a(t('false'), false, "Booelean"); + a(String(t(String(fn))), String(fn), "Function"); + + a.deep(t('/raz-dwa/g'), /raz-dwa/g, "RegExp"); + a.deep(t('new Date(1234567)'), new Date(1234567), "Date"); + a.deep(t('[]'), [], "Empty array"); + a.deep(t('[undefined,false,null,"raz\\"ddwa\\ntrzy",/raz/g,new Date(1234567),["foo"]]'), + [undefined, false, null, 'raz"ddwa\ntrzy', /raz/g, new Date(1234567), ['foo']], "Rich Array"); + a.deep(t('{}'), {}, "Empty object"); + a.deep(t('{"raz":undefined,"dwa":false,"trzy":null,"cztery":"raz\\"ddwa\\ntrzy",' + + '"szesc":/raz/g,"siedem":new Date(1234567),"osiem":["foo",32],' + + '"dziewiec":{"foo":"bar","dwa":343}}'), + { raz: undefined, dwa: false, trzy: null, cztery: 'raz"ddwa\ntrzy', szesc: /raz/g, + siedem: new Date(1234567), osiem: ['foo', 32], dziewiec: { foo: 'bar', dwa: 343 } }, + "Rich object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-callable.js new file mode 100644 index 00000000000000..b40540b6ba61b0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-callable.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var f = function () {}; + a(t(f), f, "Function"); + a.throws(function () { + t({}); + }, "Not Function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-object.js new file mode 100644 index 00000000000000..eaa8e7bcb364b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-object.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a.throws(function () { t(''); }, TypeError, "''"); + a(t(x = {}), x, "Object"); + a(t(x = function () {}), x, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + a(t(x = new Date()), x, "Date"); + + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-value.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-value.js new file mode 100644 index 00000000000000..f1eeafa9778863 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/valid-value.js @@ -0,0 +1,19 @@ +'use strict'; + +var numIsNaN = require('../../number/is-nan'); + +module.exports = function (t, a) { + var x; + a(t(0), 0, "0"); + a(t(false), false, "false"); + a(t(''), '', "''"); + a(numIsNaN(t(NaN)), true, "NaN"); + a(t(x = {}), x, "{}"); + + a.throws(function () { + t(); + }, "Undefined"); + a.throws(function () { + t(null); + }, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-array-like-object.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-array-like-object.js new file mode 100644 index 00000000000000..2f3e31b442ebcb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-array-like-object.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a.throws(function () { t(''); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-array-like.js new file mode 100644 index 00000000000000..53bd11249e3d04 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-array-like.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a(t(''), '', "''"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-stringifiable-value.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-stringifiable-value.js new file mode 100644 index 00000000000000..ae9bd17a59a028 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-stringifiable-value.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a(t(0), "0"); + a(t(false), "false"); + a(t(''), ""); + a(t({}), String({}), "Object"); + a(t(x = function () {}), String(x), "Function"); + a(t(x = new String('raz')), String(x), "String object"); //jslint: ignore + a(t(x = new Date()), String(x), "Date"); + + a.throws(function () { t(Object.create(null)); }, TypeError, "Null prototype object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-stringifiable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-stringifiable.js new file mode 100644 index 00000000000000..4a46bb521900db --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/object/validate-stringifiable.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a(t(), 'undefined', "Undefined"); + a(t(null), 'null', "Null"); + a(t(0), "0"); + a(t(false), "false"); + a(t(''), ""); + a(t({}), String({}), "Object"); + a(t(x = function () {}), String(x), "Function"); + a(t(x = new String('raz')), String(x), "String object"); //jslint: ignore + a(t(x = new Date()), String(x), "Date"); + + a.throws(function () { t(Object.create(null)); }, TypeError, "Null prototype object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/index.js new file mode 100644 index 00000000000000..ca2bd650615889 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexTest = require('tad/lib/utils/index-test') + + , path = require('path').resolve(__dirname, '../../../reg-exp/#'); + +module.exports = function (t, a, d) { + indexTest(indexTest.readDir(path).aside(function (data) { + delete data.sticky; + delete data.unicode; + }))(t, a, d); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/is-sticky.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/is-sticky.js new file mode 100644 index 00000000000000..e154ac2916557f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/is-sticky.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var re; + a(t.call(/raz/), false, "Normal"); + a(t.call(/raz/g), false, "Global"); + try { re = new RegExp('raz', 'y'); } catch (ignore) {} + if (!re) return; + a(t.call(re), true, "Sticky"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/is-unicode.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/is-unicode.js new file mode 100644 index 00000000000000..2ffb9e869bd6a3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/is-unicode.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var re; + a(t.call(/raz/), false, "Normal"); + a(t.call(/raz/g), false, "Global"); + try { re = new RegExp('raz', 'u'); } catch (ignore) {} + if (!re) return; + a(t.call(re), true, "Unicode"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/implement.js new file mode 100644 index 00000000000000..89825a45f6148d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/match/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/shim.js new file mode 100644 index 00000000000000..5249139fff2277 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/match/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + var result = ['foo']; + result.index = 0; + result.input = 'foobar'; + a.deep(t.call(/foo/, 'foobar'), result); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/implement.js new file mode 100644 index 00000000000000..c32b23a6d03e79 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/replace/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/shim.js new file mode 100644 index 00000000000000..2b378fd594e2ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/replace/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(/foo/, 'foobar', 'mar'), 'marbar'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/implement.js new file mode 100644 index 00000000000000..ff1b8087f2c697 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/search/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/shim.js new file mode 100644 index 00000000000000..596bcdb92ed203 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/search/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(/foo/, 'barfoo'), 3); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/implement.js new file mode 100644 index 00000000000000..1cee441806c065 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/split/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/shim.js new file mode 100644 index 00000000000000..6a95cd03d6ce68 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/split/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t.call(/\|/, 'bar|foo'), ['bar', 'foo']); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/sticky/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/sticky/implement.js new file mode 100644 index 00000000000000..d94e7b98d8fe46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/sticky/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/sticky/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/sticky/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/sticky/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/sticky/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/unicode/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/unicode/implement.js new file mode 100644 index 00000000000000..9b1aa0f2ab992d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/unicode/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/unicode/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/unicode/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/unicode/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/#/unicode/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/escape.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/escape.js new file mode 100644 index 00000000000000..5b00f67f28ce45 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/escape.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + var str = "(?:^te|er)s{2}t\\[raz]+$"; + a(RegExp('^' + t(str) + '$').test(str), true); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/is-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/is-reg-exp.js new file mode 100644 index 00000000000000..785ca28c2ecb2c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/is-reg-exp.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(true), false, "Boolean"); + a(t(new Date()), false, "Date"); + a(t(new String('raz')), false, "String object"); + a(t({}), false, "Plain object"); + a(t(/a/), true, "Regular expression"); + a(t(new RegExp('a')), true, "Regular expression via constructor"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/valid-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/valid-reg-exp.js new file mode 100644 index 00000000000000..cd12cf126a609a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/reg-exp/valid-reg-exp.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var r = /raz/; + a(t(r), r, "Direct"); + r = new RegExp('foo'); + a(t(r), r, "Constructor"); + a.throws(function () { + t({}); + }, "Object"); + a.throws(function () { + t(function () {}); + }, "Function"); + a.throws(function () { + t({ exec: function () { return 20; } }); + }, "Plain object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/implement.js new file mode 100644 index 00000000000000..09bf3361acd6a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/@@iterator/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/shim.js new file mode 100644 index 00000000000000..3b0e0b7547ece9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/@@iterator/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var it = t.call('r💩z'); + a.deep(it.next(), { done: false, value: 'r' }, "#1"); + a.deep(it.next(), { done: false, value: '💩' }, "#2"); + a.deep(it.next(), { done: false, value: 'z' }, "#3"); + a.deep(it.next(), { done: true, value: undefined }, "End"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/at.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/at.js new file mode 100644 index 00000000000000..2447a9f64d5d83 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/at.js @@ -0,0 +1,97 @@ +// See tests at https://github.com/mathiasbynens/String.prototype.at + +'use strict'; + +module.exports = function (t, a) { + a(t.length, 1, "Length"); + + a.h1("BMP"); + a(t.call('abc\uD834\uDF06def', -Infinity), '', "-Infinity"); + a(t.call('abc\uD834\uDF06def', -1), '', "-1"); + a(t.call('abc\uD834\uDF06def', -0), 'a', "-0"); + a(t.call('abc\uD834\uDF06def', +0), 'a', "+0"); + a(t.call('abc\uD834\uDF06def', 1), 'b', "1"); + a(t.call('abc\uD834\uDF06def', 3), '\uD834\uDF06', "3"); + a(t.call('abc\uD834\uDF06def', 4), '\uDF06', "4"); + a(t.call('abc\uD834\uDF06def', 5), 'd', "5"); + a(t.call('abc\uD834\uDF06def', 42), '', "42"); + a(t.call('abc\uD834\uDF06def', +Infinity), '', "+Infinity"); + a(t.call('abc\uD834\uDF06def', null), 'a', "null"); + a(t.call('abc\uD834\uDF06def', undefined), 'a', "undefined"); + a(t.call('abc\uD834\uDF06def'), 'a', "No argument"); + a(t.call('abc\uD834\uDF06def', false), 'a', "false"); + a(t.call('abc\uD834\uDF06def', NaN), 'a', "NaN"); + a(t.call('abc\uD834\uDF06def', ''), 'a', "Empty string"); + a(t.call('abc\uD834\uDF06def', '_'), 'a', "_"); + a(t.call('abc\uD834\uDF06def', '1'), 'b', "'1'"); + a(t.call('abc\uD834\uDF06def', []), 'a', "[]"); + a(t.call('abc\uD834\uDF06def', {}), 'a', "{}"); + a(t.call('abc\uD834\uDF06def', -0.9), 'a', "-0.9"); + a(t.call('abc\uD834\uDF06def', 1.9), 'b', "1.9"); + a(t.call('abc\uD834\uDF06def', 7.9), 'f', "7.9"); + a(t.call('abc\uD834\uDF06def', Math.pow(2, 32)), '', "Big number"); + + a.h1("Astral symbol"); + a(t.call('\uD834\uDF06def', -Infinity), '', "-Infinity"); + a(t.call('\uD834\uDF06def', -1), '', "-1"); + a(t.call('\uD834\uDF06def', -0), '\uD834\uDF06', "-0"); + a(t.call('\uD834\uDF06def', +0), '\uD834\uDF06', "+0"); + a(t.call('\uD834\uDF06def', 1), '\uDF06', "1"); + a(t.call('\uD834\uDF06def', 2), 'd', "2"); + a(t.call('\uD834\uDF06def', 3), 'e', "3"); + a(t.call('\uD834\uDF06def', 4), 'f', "4"); + a(t.call('\uD834\uDF06def', 42), '', "42"); + a(t.call('\uD834\uDF06def', +Infinity), '', "+Infinity"); + a(t.call('\uD834\uDF06def', null), '\uD834\uDF06', "null"); + a(t.call('\uD834\uDF06def', undefined), '\uD834\uDF06', "undefined"); + a(t.call('\uD834\uDF06def'), '\uD834\uDF06', "No arguments"); + a(t.call('\uD834\uDF06def', false), '\uD834\uDF06', "false"); + a(t.call('\uD834\uDF06def', NaN), '\uD834\uDF06', "NaN"); + a(t.call('\uD834\uDF06def', ''), '\uD834\uDF06', "Empty string"); + a(t.call('\uD834\uDF06def', '_'), '\uD834\uDF06', "_"); + a(t.call('\uD834\uDF06def', '1'), '\uDF06', "'1'"); + + a.h1("Lone high surrogates"); + a(t.call('\uD834abc', -Infinity), '', "-Infinity"); + a(t.call('\uD834abc', -1), '', "-1"); + a(t.call('\uD834abc', -0), '\uD834', "-0"); + a(t.call('\uD834abc', +0), '\uD834', "+0"); + a(t.call('\uD834abc', 1), 'a', "1"); + a(t.call('\uD834abc', 42), '', "42"); + a(t.call('\uD834abc', +Infinity), '', "Infinity"); + a(t.call('\uD834abc', null), '\uD834', "null"); + a(t.call('\uD834abc', undefined), '\uD834', "undefined"); + a(t.call('\uD834abc'), '\uD834', "No arguments"); + a(t.call('\uD834abc', false), '\uD834', "false"); + a(t.call('\uD834abc', NaN), '\uD834', "NaN"); + a(t.call('\uD834abc', ''), '\uD834', "Empty string"); + a(t.call('\uD834abc', '_'), '\uD834', "_"); + a(t.call('\uD834abc', '1'), 'a', "'a'"); + + a.h1("Lone low surrogates"); + a(t.call('\uDF06abc', -Infinity), '', "-Infinity"); + a(t.call('\uDF06abc', -1), '', "-1"); + a(t.call('\uDF06abc', -0), '\uDF06', "-0"); + a(t.call('\uDF06abc', +0), '\uDF06', "+0"); + a(t.call('\uDF06abc', 1), 'a', "1"); + a(t.call('\uDF06abc', 42), '', "42"); + a(t.call('\uDF06abc', +Infinity), '', "+Infinity"); + a(t.call('\uDF06abc', null), '\uDF06', "null"); + a(t.call('\uDF06abc', undefined), '\uDF06', "undefined"); + a(t.call('\uDF06abc'), '\uDF06', "No arguments"); + a(t.call('\uDF06abc', false), '\uDF06', "false"); + a(t.call('\uDF06abc', NaN), '\uDF06', "NaN"); + a(t.call('\uDF06abc', ''), '\uDF06', "Empty string"); + a(t.call('\uDF06abc', '_'), '\uDF06', "_"); + a(t.call('\uDF06abc', '1'), 'a', "'1'"); + + a.h1("Context"); + a.throws(function () { t.call(undefined); }, TypeError, "Undefined"); + a.throws(function () { t.call(undefined, 4); }, TypeError, + "Undefined + argument"); + a.throws(function () { t.call(null); }, TypeError, "Null"); + a.throws(function () { t.call(null, 4); }, TypeError, "Null + argument"); + a(t.call(42, 0), '4', "Number #1"); + a(t.call(42, 1), '2', "Number #2"); + a(t.call({ toString: function () { return 'abc'; } }, 2), 'c', "Object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/camel-to-hyphen.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/camel-to-hyphen.js new file mode 100644 index 00000000000000..8b47a8158a29d3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/camel-to-hyphen.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('razDwaTRzy4yFoo45My'), 'raz-dwa-t-rzy4y-foo45-my'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/capitalize.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/capitalize.js new file mode 100644 index 00000000000000..fa11ff8eeff856 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/capitalize.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('raz'), 'Raz', "Word"); + a(t.call('BLA'), 'BLA', "Uppercase"); + a(t.call(''), '', "Empty"); + a(t.call('a'), 'A', "One letter"); + a(t.call('this is a test'), 'This is a test', "Sentence"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/case-insensitive-compare.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/case-insensitive-compare.js new file mode 100644 index 00000000000000..01a90c39ce8307 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/case-insensitive-compare.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call("AA", "aa"), 0, "Same"); + a.ok(t.call("Amber", "zebra") < 0, "Less"); + a.ok(t.call("Zebra", "amber") > 0, "Greater"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/implement.js new file mode 100644 index 00000000000000..5e33cd715ff47b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +var isImplemented = + require('../../../../string/#/code-point-at/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/shim.js new file mode 100644 index 00000000000000..0df4751c564421 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/code-point-at/shim.js @@ -0,0 +1,81 @@ +// Taken from: https://github.com/mathiasbynens/String.prototype.codePointAt +// /blob/master/tests/tests.js + +'use strict'; + +module.exports = function (t, a) { + a(t.length, 1, "Length"); + + // String that starts with a BMP symbol + a(t.call('abc\uD834\uDF06def', ''), 0x61); + a(t.call('abc\uD834\uDF06def', '_'), 0x61); + a(t.call('abc\uD834\uDF06def'), 0x61); + a(t.call('abc\uD834\uDF06def', -Infinity), undefined); + a(t.call('abc\uD834\uDF06def', -1), undefined); + a(t.call('abc\uD834\uDF06def', -0), 0x61); + a(t.call('abc\uD834\uDF06def', 0), 0x61); + a(t.call('abc\uD834\uDF06def', 3), 0x1D306); + a(t.call('abc\uD834\uDF06def', 4), 0xDF06); + a(t.call('abc\uD834\uDF06def', 5), 0x64); + a(t.call('abc\uD834\uDF06def', 42), undefined); + a(t.call('abc\uD834\uDF06def', Infinity), undefined); + a(t.call('abc\uD834\uDF06def', Infinity), undefined); + a(t.call('abc\uD834\uDF06def', NaN), 0x61); + a(t.call('abc\uD834\uDF06def', false), 0x61); + a(t.call('abc\uD834\uDF06def', null), 0x61); + a(t.call('abc\uD834\uDF06def', undefined), 0x61); + + // String that starts with an astral symbol + a(t.call('\uD834\uDF06def', ''), 0x1D306); + a(t.call('\uD834\uDF06def', '1'), 0xDF06); + a(t.call('\uD834\uDF06def', '_'), 0x1D306); + a(t.call('\uD834\uDF06def'), 0x1D306); + a(t.call('\uD834\uDF06def', -1), undefined); + a(t.call('\uD834\uDF06def', -0), 0x1D306); + a(t.call('\uD834\uDF06def', 0), 0x1D306); + a(t.call('\uD834\uDF06def', 1), 0xDF06); + a(t.call('\uD834\uDF06def', 42), undefined); + a(t.call('\uD834\uDF06def', false), 0x1D306); + a(t.call('\uD834\uDF06def', null), 0x1D306); + a(t.call('\uD834\uDF06def', undefined), 0x1D306); + + // Lone high surrogates + a(t.call('\uD834abc', ''), 0xD834); + a(t.call('\uD834abc', '_'), 0xD834); + a(t.call('\uD834abc'), 0xD834); + a(t.call('\uD834abc', -1), undefined); + a(t.call('\uD834abc', -0), 0xD834); + a(t.call('\uD834abc', 0), 0xD834); + a(t.call('\uD834abc', false), 0xD834); + a(t.call('\uD834abc', NaN), 0xD834); + a(t.call('\uD834abc', null), 0xD834); + a(t.call('\uD834abc', undefined), 0xD834); + + // Lone low surrogates + a(t.call('\uDF06abc', ''), 0xDF06); + a(t.call('\uDF06abc', '_'), 0xDF06); + a(t.call('\uDF06abc'), 0xDF06); + a(t.call('\uDF06abc', -1), undefined); + a(t.call('\uDF06abc', -0), 0xDF06); + a(t.call('\uDF06abc', 0), 0xDF06); + a(t.call('\uDF06abc', false), 0xDF06); + a(t.call('\uDF06abc', NaN), 0xDF06); + a(t.call('\uDF06abc', null), 0xDF06); + a(t.call('\uDF06abc', undefined), 0xDF06); + + a.throws(function () { t.call(undefined); }, TypeError); + a.throws(function () { t.call(undefined, 4); }, TypeError); + a.throws(function () { t.call(null); }, TypeError); + a.throws(function () { t.call(null, 4); }, TypeError); + a(t.call(42, 0), 0x34); + a(t.call(42, 1), 0x32); + a(t.call({ toString: function () { return 'abc'; } }, 2), 0x63); + + a.throws(function () { t.apply(undefined); }, TypeError); + a.throws(function () { t.apply(undefined, [4]); }, TypeError); + a.throws(function () { t.apply(null); }, TypeError); + a.throws(function () { t.apply(null, [4]); }, TypeError); + a(t.apply(42, [0]), 0x34); + a(t.apply(42, [1]), 0x32); + a(t.apply({ toString: function () { return 'abc'; } }, [2]), 0x63); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/implement.js new file mode 100644 index 00000000000000..220f50d4672f13 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/contains/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/shim.js new file mode 100644 index 00000000000000..a0ea4db20812e5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/contains/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('raz', ''), true, "Empty"); + a(t.call('', ''), true, "Both Empty"); + a(t.call('raz', 'raz'), true, "Same"); + a(t.call('razdwa', 'raz'), true, "Starts with"); + a(t.call('razdwa', 'dwa'), true, "Ends with"); + a(t.call('razdwa', 'zdw'), true, "In middle"); + a(t.call('', 'raz'), false, "Something in empty"); + a(t.call('az', 'raz'), false, "Longer"); + a(t.call('azasdfasdf', 'azff'), false, "Not found"); + a(t.call('razdwa', 'raz', 1), false, "Position"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/implement.js new file mode 100644 index 00000000000000..93bd2ddcd6dc20 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/ends-with/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/shim.js new file mode 100644 index 00000000000000..e4b93c407bc2b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/ends-with/shim.js @@ -0,0 +1,16 @@ +// In some parts copied from: +// http://closure-library.googlecode.com/svn/trunk/closure/goog/ +// string/string_test.html + +'use strict'; + +module.exports = function (t, a) { + a(t.call('abc', ''), true, "Empty needle"); + a(t.call('abcd', 'cd'), true, "Ends with needle"); + a(t.call('abcd', 'abcd'), true, "Needle equals haystack"); + a(t.call('abcd', 'ab'), false, "Doesn't end with needle"); + a(t.call('abc', 'defg'), false, "Length trick"); + a(t.call('razdwa', 'zd', 3), false, "Position: false"); + a(t.call('razdwa', 'zd', 4), true, "Position: true"); + a(t.call('razdwa', 'zd', 5), false, "Position: false #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/hyphen-to-camel.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/hyphen-to-camel.js new file mode 100644 index 00000000000000..bd7ded4befbc7d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/hyphen-to-camel.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('raz-dwa-t-rzy-4y-rtr4-tiu-45-pa'), 'razDwaTRzy4yRtr4Tiu45Pa'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/indent.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/indent.js new file mode 100644 index 00000000000000..eb92b36f5438d6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/indent.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('ra\nzz', ''), 'ra\nzz', "Empty"); + a(t.call('ra\nzz', '\t', 3), '\t\t\tra\n\t\t\tzz', "String repeat"); + a(t.call('ra\nzz\nsss\nfff\n', '\t'), '\tra\n\tzz\n\tsss\n\tfff\n', + "Multi-line"); + a(t.call('ra\n\nzz\n', '\t'), '\tra\n\n\tzz\n', "Don't touch empty lines"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/last.js new file mode 100644 index 00000000000000..ad36a213c6053e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/last.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(''), null, "Null"); + a(t.call('abcdef'), 'f', "String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/_data.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/_data.js new file mode 100644 index 00000000000000..c741addb0055a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/_data.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t[0], 'object'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/implement.js new file mode 100644 index 00000000000000..4886c9b834285b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/normalize/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/shim.js new file mode 100644 index 00000000000000..28e27f595247be --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/normalize/shim.js @@ -0,0 +1,13 @@ +// Taken from: https://github.com/walling/unorm/blob/master/test/es6-shim.js + +'use strict'; + +var str = 'äiti'; + +module.exports = function (t, a) { + a(t.call(str), "\u00e4iti"); + a(t.call(str, "NFC"), "\u00e4iti"); + a(t.call(str, "NFD"), "a\u0308iti"); + a(t.call(str, "NFKC"), "\u00e4iti"); + a(t.call(str, "NFKD"), "a\u0308iti"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/pad.js new file mode 100644 index 00000000000000..28c3fcaa10c4da --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/pad.js @@ -0,0 +1,24 @@ +'use strict'; + +var partial = require('../../../function/#/partial'); + +module.exports = { + Left: function (t, a) { + t = partial.call(t, 'x', 5); + + a(t.call('yy'), 'xxxyy'); + a(t.call(''), 'xxxxx', "Empty string"); + + a(t.call('yyyyy'), 'yyyyy', 'Equal length'); + a(t.call('yyyyyyy'), 'yyyyyyy', 'Longer'); + }, + Right: function (t, a) { + t = partial.call(t, 'x', -5); + + a(t.call('yy'), 'yyxxx'); + a(t.call(''), 'xxxxx', "Empty string"); + + a(t.call('yyyyy'), 'yyyyy', 'Equal length'); + a(t.call('yyyyyyy'), 'yyyyyyy', 'Longer'); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/plain-replace-all.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/plain-replace-all.js new file mode 100644 index 00000000000000..a425c87a40553b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/plain-replace-all.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('razdwatrzy', 'dwa', 'olera'), 'razoleratrzy', "Basic"); + a(t.call('razdwatrzy', 'dwa', 'ole$&a'), 'razole$&atrzy', "Inserts"); + a(t.call('razdwa', 'ola', 'sdfs'), 'razdwa', "No replace"); + + a(t.call('$raz$$dwa$trzy$', '$', '&&'), '&&raz&&&&dwa&&trzy&&', "Multi"); + a(t.call('$raz$$dwa$$$$trzy$', '$$', '&'), '$raz&dwa&&trzy$', + "Multi many chars"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/plain-replace.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/plain-replace.js new file mode 100644 index 00000000000000..54522ed749fe37 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/plain-replace.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('razdwatrzy', 'dwa', 'olera'), 'razoleratrzy', "Basic"); + a(t.call('razdwatrzy', 'dwa', 'ole$&a'), 'razole$&atrzy', "Inserts"); + a(t.call('razdwa', 'ola', 'sdfs'), 'razdwa', "No replace"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/implement.js new file mode 100644 index 00000000000000..7ff65a811068b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/repeat/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/shim.js new file mode 100644 index 00000000000000..7e0d077ec4bdb6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/repeat/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('a', 0), '', "Empty"); + a(t.call('a', 1), 'a', "1"); + a(t.call('\t', 5), '\t\t\t\t\t', "Whitespace"); + a(t.call('raz', 3), 'razrazraz', "Many chars"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/implement.js new file mode 100644 index 00000000000000..fc8490fc916ac3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/starts-with/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/shim.js new file mode 100644 index 00000000000000..e0e123b324e115 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/#/starts-with/shim.js @@ -0,0 +1,14 @@ +// Inspired and in some parts copied from: +// http://closure-library.googlecode.com/svn/trunk/closure/goog +// /string/string_test.html + +'use strict'; + +module.exports = function (t, a) { + a(t.call('abc', ''), true, "Empty needle"); + a(t.call('abcd', 'ab'), true, "Starts with needle"); + a(t.call('abcd', 'abcd'), true, "Needle equals haystack"); + a(t.call('abcd', 'bcde', 1), false, "Needle larger than haystack"); + a(!t.call('abcd', 'cd'), true, "Doesn't start with needle"); + a(t.call('abcd', 'bc', 1), true, "Position"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/format-method.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/format-method.js new file mode 100644 index 00000000000000..bb5561ee45bb59 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/format-method.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + t = t({ a: 'A', aa: 'B', ab: 'C', b: 'D', + c: function () { return ++this.a; } }); + a(t.call({ a: 0 }, ' %a%aab%abb%b\\%aa%ab%c%c '), ' ABbCbD%aaC12 '); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/implement.js new file mode 100644 index 00000000000000..0aceb97efdcf36 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../string/from-code-point/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/shim.js new file mode 100644 index 00000000000000..88cda3d6364719 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/from-code-point/shim.js @@ -0,0 +1,47 @@ +// Taken from: https://github.com/mathiasbynens/String.fromCodePoint/blob/master +// /tests/tests.js + +'use strict'; + +var pow = Math.pow; + +module.exports = function (t, a) { + var counter, result; + + a(t.length, 1, "Length"); + a(String.propertyIsEnumerable('fromCodePoint'), false, "Not enumerable"); + + a(t(''), '\0', "Empty string"); + a(t(), '', "No arguments"); + a(t(-0), '\0', "-0"); + a(t(0), '\0', "0"); + a(t(0x1D306), '\uD834\uDF06', "Unicode"); + a(t(0x1D306, 0x61, 0x1D307), '\uD834\uDF06a\uD834\uDF07', "Complex unicode"); + a(t(0x61, 0x62, 0x1D307), 'ab\uD834\uDF07', "Complex"); + a(t(false), '\0', "false"); + a(t(null), '\0', "null"); + + a.throws(function () { t('_'); }, RangeError, "_"); + a.throws(function () { t(Infinity); }, RangeError, "Infinity"); + a.throws(function () { t(-Infinity); }, RangeError, "-Infinity"); + a.throws(function () { t(-1); }, RangeError, "-1"); + a.throws(function () { t(0x10FFFF + 1); }, RangeError, "Range error #1"); + a.throws(function () { t(3.14); }, RangeError, "Range error #2"); + a.throws(function () { t(3e-2); }, RangeError, "Range error #3"); + a.throws(function () { t(-Infinity); }, RangeError, "Range error #4"); + a.throws(function () { t(+Infinity); }, RangeError, "Range error #5"); + a.throws(function () { t(NaN); }, RangeError, "Range error #6"); + a.throws(function () { t(undefined); }, RangeError, "Range error #7"); + a.throws(function () { t({}); }, RangeError, "Range error #8"); + a.throws(function () { t(/re/); }, RangeError, "Range error #9"); + + counter = pow(2, 15) * 3 / 2; + result = []; + while (--counter >= 0) result.push(0); // one code unit per symbol + t.apply(null, result); // must not throw + + counter = pow(2, 15) * 3 / 2; + result = []; + while (--counter >= 0) result.push(0xFFFF + 1); // two code units per symbol + t.apply(null, result); // must not throw +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/is-string.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/is-string.js new file mode 100644 index 00000000000000..32f595829168ee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/is-string.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(null), false, "Null"); + a(t(''), true, "Empty string"); + a(t(12), false, "Number"); + a(t(false), false, "Boolean"); + a(t(new Date()), false, "Date"); + a(t(new String('raz')), true, "String object"); + a(t('asdfaf'), true, "String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/random-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/random-uniq.js new file mode 100644 index 00000000000000..6791ac266e7530 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/random-uniq.js @@ -0,0 +1,14 @@ +'use strict'; + +var isValidFormat = RegExp.prototype.test.bind(/^[a-z0-9]+$/); + +module.exports = function (t, a) { + a(typeof t(), 'string'); + a.ok(t().length > 7); + a.not(t(), t()); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/implement.js new file mode 100644 index 00000000000000..59416de3af53ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../string/raw/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/shim.js new file mode 100644 index 00000000000000..025ed780455667 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es5-ext/test/string/raw/shim.js @@ -0,0 +1,15 @@ +// Partially taken from: +// https://github.com/paulmillr/es6-shim/blob/master/test/string.js + +'use strict'; + +module.exports = function (t, a) { + var callSite = []; + + callSite.raw = ["The total is ", " ($", " with tax)"]; + a(t(callSite, '{total}', '{total * 1.01}'), + 'The total is {total} (${total * 1.01} with tax)'); + + callSite.raw = []; + a(t(callSite, '{total}', '{total * 1.01}'), ''); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/#/chain.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/#/chain.js new file mode 100644 index 00000000000000..6dc1543b354531 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/#/chain.js @@ -0,0 +1,40 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('../') + , validIterable = require('../valid-iterable') + + , push = Array.prototype.push + , defineProperties = Object.defineProperties + , IteratorChain; + +IteratorChain = function (iterators) { + defineProperties(this, { + __iterators__: d('', iterators), + __current__: d('w', iterators.shift()) + }); +}; +if (setPrototypeOf) setPrototypeOf(IteratorChain, Iterator); + +IteratorChain.prototype = Object.create(Iterator.prototype, { + constructor: d(IteratorChain), + next: d(function () { + var result; + if (!this.__current__) return { done: true, value: undefined }; + result = this.__current__.next(); + while (result.done) { + this.__current__ = this.__iterators__.shift(); + if (!this.__current__) return { done: true, value: undefined }; + result = this.__current__.next(); + } + return result; + }) +}); + +module.exports = function () { + var iterators = [this]; + push.apply(iterators, arguments); + iterators.forEach(validIterable); + return new IteratorChain(iterators); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.lint new file mode 100644 index 00000000000000..cf54d815684b2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.lint @@ -0,0 +1,11 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.travis.yml new file mode 100644 index 00000000000000..02c277cf565442 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-iterator@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/CHANGES new file mode 100644 index 00000000000000..a2d1ec7c2af31c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/CHANGES @@ -0,0 +1,28 @@ +v0.1.3 -- 2015.02.02 +* Update dependencies +* Fix spelling of LICENSE + +v0.1.2 -- 2014.11.19 +* Optimise internal `_next` to not verify internal's list length at all times + (#2 thanks @RReverser) +* Fix documentation examples +* Configure lint scripts + +v0.1.1 -- 2014.04.29 +* Fix es6-symbol dependency version + +v0.1.0 -- 2014.04.29 +* Assure strictly npm hosted dependencies +* Remove sparse arrays dedicated handling (as per spec) +* Add: isIterable, validIterable and chain (method) +* Remove toArray, it's addressed by Array.from (polyfil can be found in es5-ext/array/from) +* Add break possiblity to 'forOf' via 'doBreak' function argument +* Provide dedicated iterator for array-likes (ArrayIterator) and for strings (StringIterator) +* Provide @@toStringTag symbol +* When available rely on @@iterator symbol +* Remove 32bit integer maximum list length restriction +* Improve Iterator internals +* Update to use latest version of dependencies + +v0.0.0 -- 2013.10.12 +Initial (dev version) \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/LICENSE new file mode 100644 index 00000000000000..04724a3ab1b70b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/README.md new file mode 100644 index 00000000000000..288373da7ab506 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/README.md @@ -0,0 +1,148 @@ +# es6-iterator +## ECMAScript 6 Iterator interface + +### Installation + + $ npm install es6-iterator + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +## API + +### Constructors + +#### Iterator(list) _(es6-iterator)_ + +Abstract Iterator interface. Meant for extensions and not to be used on its own. + +Accepts any _list_ object (technically object with numeric _length_ property). + +_Mind it doesn't iterate strings properly, for that use dedicated [StringIterator](#string-iterator)_ + +```javascript +var Iterator = require('es6-iterator') +var iterator = new Iterator([1, 2, 3]); + +iterator.next(); // { value: 1, done: false } +iterator.next(); // { value: 2, done: false } +iterator.next(); // { value: 3, done: false } +iterator.next(); // { value: undefined, done: true } +``` + + +#### ArrayIterator(arrayLike[, kind]) _(es6-iterator/array)_ + +Dedicated for arrays and array-likes. Supports three iteration kinds: +* __value__ _(default)_ - Iterates values +* __key__ - Iterates indexes +* __key+value__ - Iterates keys and indexes, each iteration value is in _[key, value]_ form. + + +```javascript +var ArrayIterator = require('es6-iterator/array') +var iterator = new ArrayIterator([1, 2, 3], 'key+value'); + +iterator.next(); // { value: [0, 1], done: false } +iterator.next(); // { value: [1, 2], done: false } +iterator.next(); // { value: [2, 3], done: false } +iterator.next(); // { value: undefined, done: true } +``` + +May also be used for _arguments_ objects: + +```javascript +(function () { + var iterator = new ArrayIterator(arguments); + + iterator.next(); // { value: 1, done: false } + iterator.next(); // { value: 2, done: false } + iterator.next(); // { value: 3, done: false } + iterator.next(); // { value: undefined, done: true } +}(1, 2, 3)); +``` + +#### StringIterator(str) _(es6-iterator/string)_ + +Assures proper iteration over unicode symbols. +See: http://mathiasbynens.be/notes/javascript-unicode + +```javascript +var StringIterator = require('es6-iterator/string'); +var iterator = new StringIterator('f🙈o🙉o🙊'); + +iterator.next(); // { value: 'f', done: false } +iterator.next(); // { value: '🙈', done: false } +iterator.next(); // { value: 'o', done: false } +iterator.next(); // { value: '🙉', done: false } +iterator.next(); // { value: 'o', done: false } +iterator.next(); // { value: '🙊', done: false } +iterator.next(); // { value: undefined, done: true } +``` + +### Function utilities + +#### forOf(iterable, callback[, thisArg]) _(es6-iterator/for-of)_ + +Polyfill for ECMAScript 6 [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) statement. + +``` +var forOf = require('es6-iterator/for-of'); +var result = []; + +forOf('🙈🙉🙊', function (monkey) { result.push(monkey); }); +console.log(result); // ['🙈', '🙉', '🙊']; +``` + +Optionally you can break iteration at any point: + +```javascript +var result = []; + +forOf([1,2,3,4]', function (val, doBreak) { + result.push(monkey); + if (val >= 3) doBreak(); +}); +console.log(result); // [1, 2, 3]; +``` + +#### get(obj) _(es6-iterator/get)_ + +Return iterator for any iterable object. + +```javascript +var getIterator = require('es6-iterator/get'); +var iterator = get([1,2,3]); + +iterator.next(); // { value: 1, done: false } +iterator.next(); // { value: 2, done: false } +iterator.next(); // { value: 3, done: false } +iterator.next(); // { value: undefined, done: true } +``` + +#### isIterable(obj) _(es6-iterator/is-iterable)_ + +Whether _obj_ is iterable + +```javascript +var isIterable = require('es6-iterator/is-iterable'); + +isIterable(null); // false +isIterable(true); // false +isIterable('str'); // true +isIterable(['a', 'r', 'r']); // true +isIterable(new ArrayIterator([])); // true +``` + +#### validIterable(obj) _(es6-iterator/valid-iterable)_ + +If _obj_ is an iterable it is returned. Otherwise _TypeError_ is thrown. + +### Method extensions + +#### iterator.chain(iterator1[, …iteratorn]) _(es6-iterator/#/chain)_ + +Chain multiple iterators into one. + +### Tests [![Build Status](https://travis-ci.org/medikoo/es6-iterator.png)](https://travis-ci.org/medikoo/es6-iterator) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/array.js new file mode 100644 index 00000000000000..885ad0a4fd7870 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/array.js @@ -0,0 +1,30 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , contains = require('es5-ext/string/#/contains') + , d = require('d') + , Iterator = require('./') + + , defineProperty = Object.defineProperty + , ArrayIterator; + +ArrayIterator = module.exports = function (arr, kind) { + if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); + Iterator.call(this, arr); + if (!kind) kind = 'value'; + else if (contains.call(kind, 'key+value')) kind = 'key+value'; + else if (contains.call(kind, 'key')) kind = 'key'; + else kind = 'value'; + defineProperty(this, '__kind__', d('', kind)); +}; +if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); + +ArrayIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(ArrayIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__list__[i]; + if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; + return i; + }), + toString: d(function () { return '[object Array Iterator]'; }) +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/for-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/for-of.js new file mode 100644 index 00000000000000..111f5522735204 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/for-of.js @@ -0,0 +1,44 @@ +'use strict'; + +var callable = require('es5-ext/object/valid-callable') + , isString = require('es5-ext/string/is-string') + , get = require('./get') + + , isArray = Array.isArray, call = Function.prototype.call; + +module.exports = function (iterable, cb/*, thisArg*/) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; + if (isArray(iterable)) mode = 'array'; + else if (isString(iterable)) mode = 'string'; + else iterable = get(iterable); + + callable(cb); + doBreak = function () { broken = true; }; + if (mode === 'array') { + iterable.some(function (value) { + call.call(cb, thisArg, value, doBreak); + if (broken) return true; + }); + return; + } + if (mode === 'string') { + l = iterable.length; + for (i = 0; i < l; ++i) { + char = iterable[i]; + if ((i + 1) < l) { + code = char.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; + } + call.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); + + while (!result.done) { + call.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/get.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/get.js new file mode 100644 index 00000000000000..38230fd85a2101 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/get.js @@ -0,0 +1,13 @@ +'use strict'; + +var isString = require('es5-ext/string/is-string') + , ArrayIterator = require('./array') + , StringIterator = require('./string') + , iterable = require('./valid-iterable') + , iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (obj) { + if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); + if (isString(obj)) return new StringIterator(obj); + return new ArrayIterator(obj); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/index.js new file mode 100644 index 00000000000000..10fd08958f68c7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/index.js @@ -0,0 +1,90 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , assign = require('es5-ext/object/assign') + , callable = require('es5-ext/object/valid-callable') + , value = require('es5-ext/object/valid-value') + , d = require('d') + , autoBind = require('d/auto-bind') + , Symbol = require('es6-symbol') + + , defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , Iterator; + +module.exports = Iterator = function (list, context) { + if (!(this instanceof Iterator)) return new Iterator(list, context); + defineProperties(this, { + __list__: d('w', value(list)), + __context__: d('w', context), + __nextIndex__: d('w', 0) + }); + if (!context) return; + callable(context.on); + context.on('_add', this._onAdd); + context.on('_delete', this._onDelete); + context.on('_clear', this._onClear); +}; + +defineProperties(Iterator.prototype, assign({ + constructor: d(Iterator), + _next: d(function () { + var i; + if (!this.__list__) return; + if (this.__redo__) { + i = this.__redo__.shift(); + if (i !== undefined) return i; + } + if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; + this._unBind(); + }), + next: d(function () { return this._createResult(this._next()); }), + _createResult: d(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: d(function (i) { return this.__list__[i]; }), + _unBind: d(function () { + this.__list__ = null; + delete this.__redo__; + if (!this.__context__) return; + this.__context__.off('_add', this._onAdd); + this.__context__.off('_delete', this._onDelete); + this.__context__.off('_clear', this._onClear); + this.__context__ = null; + }), + toString: d(function () { return '[object Iterator]'; }) +}, autoBind({ + _onAdd: d(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + defineProperty(this, '__redo__', d('c', [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: d(function (index) { + var i; + if (index >= this.__nextIndex__) return; + --this.__nextIndex__; + if (!this.__redo__) return; + i = this.__redo__.indexOf(index); + if (i !== -1) this.__redo__.splice(i, 1); + this.__redo__.forEach(function (redo, i) { + if (redo > index) this.__redo__[i] = --redo; + }, this); + }), + _onClear: d(function () { + if (this.__redo__) clear.call(this.__redo__); + this.__nextIndex__ = 0; + }) +}))); + +defineProperty(Iterator.prototype, Symbol.iterator, d(function () { + return this; +})); +defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/is-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/is-iterable.js new file mode 100644 index 00000000000000..bbcf10492e1dc0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/is-iterable.js @@ -0,0 +1,13 @@ +'use strict'; + +var isString = require('es5-ext/string/is-string') + , iteratorSymbol = require('es6-symbol').iterator + + , isArray = Array.isArray; + +module.exports = function (value) { + if (value == null) return false; + if (isArray(value)) return true; + if (isString(value)) return true; + return (typeof value[iteratorSymbol] === 'function'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.lint new file mode 100644 index 00000000000000..1851752f99bfda --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.lint @@ -0,0 +1,13 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus +newcap +vars diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.travis.yml new file mode 100644 index 00000000000000..afd3509a26b27d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-symbol@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/CHANGES new file mode 100644 index 00000000000000..df8c27efc38de2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/CHANGES @@ -0,0 +1,34 @@ +v2.0.1 -- 2015.01.28 +* Fix Symbol.prototype[Symbol.isPrimitive] implementation +* Improve validation within Symbol.prototype.toString and + Symbol.prototype.valueOf + +v2.0.0 -- 2015.01.28 +* Update up to changes in specification: + * Implement `for` and `keyFor` + * Remove `Symbol.create` and `Symbol.isRegExp` + * Add `Symbol.match`, `Symbol.replace`, `Symbol.search`, `Symbol.species` and + `Symbol.split` +* Rename `validSymbol` to `validateSymbol` +* Improve documentation +* Remove dead test modules + +v1.0.0 -- 2015.01.26 +* Fix enumerability for symbol properties set normally (e.g. obj[symbol] = value) +* Introduce initialization via hidden constructor +* Fix isSymbol handling of polyfill values when native Symbol is present +* Fix spelling of LICENSE +* Configure lint scripts + +v0.1.1 -- 2014.10.07 +* Fix isImplemented, so it returns true in case of polyfill +* Improve documentations + +v0.1.0 -- 2014.04.28 +* Assure strictly npm dependencies +* Update to use latest versions of dependencies +* Fix implementation detection so it doesn't crash on `String(symbol)` +* throw on `new Symbol()` (as decided by TC39) + +v0.0.0 -- 2013.11.15 +* Initial (dev) version \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/LICENSE new file mode 100644 index 00000000000000..04724a3ab1b70b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/README.md new file mode 100644 index 00000000000000..95d6780ba78cb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/README.md @@ -0,0 +1,71 @@ +# es6-symbol +## ECMAScript 6 Symbol polyfill + +For more information about symbols see following links +- [Symbols in ECMAScript 6 by Axel Rauschmayer](http://www.2ality.com/2014/12/es6-symbols.html) +- [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) +- [Specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-constructor) + +### Limitations + +Underneath it uses real string property names which can easily be retrieved, however accidental collision with other property names is unlikely. + +### Usage + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't (but without implementing `Symbol` on global scope), do: + +```javascript +var Symbol = require('es6-symbol'); +``` + +If you want to make sure your environment implements `Symbol`, do: + +```javascript +require('es6-symbol/implement'); +``` + +If you strictly want to use polyfill even if native `Symbol` exists (hard to find a good reason for that), do: + +```javascript +var Symbol = require('es6-symbol/polyfill'); +``` + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-objects). Still if you want quick look, follow examples: + +```javascript +var Symbol = require('es6-symbol'); + +var symbol = Symbol('My custom symbol'); +var x = {}; + +x[symbol] = 'foo'; +console.log(x[symbol]); 'foo' + +// Detect iterable: +var iterator, result; +if (possiblyIterable[Symbol.iterator]) { + iterator = possiblyIterable[Symbol.iterator](); + result = iterator.next(); + while(!result.done) { + console.log(result.value); + result = iterator.next(); + } +} +``` + +### Installation +#### NPM + +In your project path: + + $ npm install es6-symbol + +##### Browser + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-symbol.png)](https://travis-ci.org/medikoo/es6-symbol) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/implement.js new file mode 100644 index 00000000000000..153edacdbedf9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'Symbol', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/index.js new file mode 100644 index 00000000000000..609f1faf551164 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-implemented.js new file mode 100644 index 00000000000000..53759f32124b1c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-implemented.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + if (typeof Symbol.iterator === 'symbol') return true; + + // Return 'true' for polyfills + if (typeof Symbol.isConcatSpreadable !== 'object') return false; + if (typeof Symbol.iterator !== 'object') return false; + if (typeof Symbol.toPrimitive !== 'object') return false; + if (typeof Symbol.toStringTag !== 'object') return false; + if (typeof Symbol.unscopables !== 'object') return false; + + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-native-implemented.js new file mode 100644 index 00000000000000..a8cb8b8681ee69 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-native-implemented.js @@ -0,0 +1,8 @@ +// Exports true if environment provides native `Symbol` implementation + +'use strict'; + +module.exports = (function () { + if (typeof Symbol !== 'function') return false; + return (typeof Symbol.iterator === 'symbol'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-symbol.js new file mode 100644 index 00000000000000..beeba2cb4fa23f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/is-symbol.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x) { + return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/package.json new file mode 100644 index 00000000000000..0efffeaec90658 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/package.json @@ -0,0 +1,63 @@ +{ + "name": "es6-symbol", + "version": "2.0.1", + "description": "ECMAScript6 Symbol polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "symbol", + "private", + "property", + "es6", + "ecmascript", + "harmony" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-symbol.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.5" + }, + "devDependencies": { + "tad": "~0.2.1", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "51f6938d7830269fefa38f02eb912f5472b3ccd7", + "bugs": { + "url": "https://github.com/medikoo/es6-symbol/issues" + }, + "homepage": "https://github.com/medikoo/es6-symbol", + "_id": "es6-symbol@2.0.1", + "_shasum": "761b5c67cfd4f1d18afb234f691d678682cb3bf3", + "_from": "es6-symbol@>=2.0.1 <2.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "761b5c67cfd4f1d18afb234f691d678682cb3bf3", + "tarball": "http://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/polyfill.js new file mode 100644 index 00000000000000..735eb676b23c9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/polyfill.js @@ -0,0 +1,77 @@ +'use strict'; + +var d = require('d') + , validateSymbol = require('./validate-symbol') + + , create = Object.create, defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty, objPrototype = Object.prototype + , Symbol, HiddenSymbol, globalSymbols = create(null); + +var generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0, name; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + defineProperty(objPrototype, name, d.gs(null, function (value) { + defineProperty(this, name, d(value)); + })); + return name; + }; +}()); + +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); + return Symbol(description); +}; +module.exports = Symbol = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); + symbol = create(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: d('', description), + __name__: d('', generateName(description)) + }); +}; +defineProperties(Symbol, { + for: d(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = Symbol(String(key))); + }), + keyFor: d(function (s) { + var key; + validateSymbol(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + hasInstance: d('', Symbol('hasInstance')), + isConcatSpreadable: d('', Symbol('isConcatSpreadable')), + iterator: d('', Symbol('iterator')), + match: d('', Symbol('match')), + replace: d('', Symbol('replace')), + search: d('', Symbol('search')), + species: d('', Symbol('species')), + split: d('', Symbol('split')), + toPrimitive: d('', Symbol('toPrimitive')), + toStringTag: d('', Symbol('toStringTag')), + unscopables: d('', Symbol('unscopables')) +}); +defineProperties(HiddenSymbol.prototype, { + constructor: d(Symbol), + toString: d('', function () { return this.__name__; }) +}); + +defineProperties(Symbol.prototype, { + toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), + valueOf: d(function () { return validateSymbol(this); }) +}); +defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', + function () { return validateSymbol(this); })); +defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); + +defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, + d('c', Symbol.prototype[Symbol.toPrimitive])); +defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, + d('c', Symbol.prototype[Symbol.toStringTag])); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/implement.js new file mode 100644 index 00000000000000..eb35c3018835c7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof Symbol, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/index.js new file mode 100644 index 00000000000000..62b3296df6fc5e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var d = require('d') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-implemented.js new file mode 100644 index 00000000000000..bb0d64536ebbae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +var global = require('es5-ext/global') + , polyfill = require('../polyfill'); + +module.exports = function (t, a) { + var cache; + a(typeof t(), 'boolean'); + cache = global.Symbol; + global.Symbol = polyfill; + a(t(), true); + if (cache === undefined) delete global.Symbol; + else global.Symbol = cache; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-symbol.js new file mode 100644 index 00000000000000..ac24b9abbff4e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/is-symbol.js @@ -0,0 +1,16 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof Symbol !== 'undefined') { + a(t(Symbol()), true, "Native"); + } + a(t(SymbolPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/polyfill.js new file mode 100644 index 00000000000000..83fb5e9253677b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/polyfill.js @@ -0,0 +1,27 @@ +'use strict'; + +var d = require('d') + , isSymbol = require('../is-symbol') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); + a(x instanceof T, false); + + a(isSymbol(symbol), true, "Symbol"); + a(isSymbol(T.iterator), true, "iterator"); + a(isSymbol(T.toStringTag), true, "toStringTag"); + + x = {}; + x[symbol] = 'foo'; + a.deep(Object.getOwnPropertyDescriptor(x, symbol), { configurable: true, enumerable: false, + value: 'foo', writable: true }); + symbol = T.for('marko'); + a(isSymbol(symbol), true); + a(T.for('marko'), symbol); + a(T.keyFor(symbol), 'marko'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/validate-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/validate-symbol.js new file mode 100644 index 00000000000000..2c8f84c8239b6e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/test/validate-symbol.js @@ -0,0 +1,19 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + var symbol; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof Symbol !== 'undefined') { + symbol = Symbol(); + a(t(symbol), symbol, "Native"); + } + symbol = SymbolPoly(); + a(t(symbol), symbol, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/validate-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/validate-symbol.js new file mode 100644 index 00000000000000..42750043d4271c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/node_modules/es6-symbol/validate-symbol.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSymbol = require('./is-symbol'); + +module.exports = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/package.json new file mode 100644 index 00000000000000..593d080e609275 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/package.json @@ -0,0 +1,66 @@ +{ + "name": "es6-iterator", + "version": "0.1.3", + "description": "Iterator abstraction based on ES6 specification", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "iterator", + "array", + "list", + "set", + "map", + "generator" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-iterator.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.5", + "es6-symbol": "~2.0.1" + }, + "devDependencies": { + "event-emitter": "~0.3.3", + "tad": "~0.2.1", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "2addc362c6f139e4941cf4726eeb59e5960c5cef", + "bugs": { + "url": "https://github.com/medikoo/es6-iterator/issues" + }, + "homepage": "https://github.com/medikoo/es6-iterator", + "_id": "es6-iterator@0.1.3", + "_shasum": "d6f58b8c4fc413c249b4baa19768f8e4d7c8944e", + "_from": "es6-iterator@>=0.1.1 <0.2.0", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.11.16", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "d6f58b8c4fc413c249b4baa19768f8e4d7c8944e", + "tarball": "http://registry.npmjs.org/es6-iterator/-/es6-iterator-0.1.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-0.1.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/string.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/string.js new file mode 100644 index 00000000000000..cdb39ea4e49931 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/string.js @@ -0,0 +1,37 @@ +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols + +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('./') + + , defineProperty = Object.defineProperty + , StringIterator; + +StringIterator = module.exports = function (str) { + if (!(this instanceof StringIterator)) return new StringIterator(str); + str = String(str); + Iterator.call(this, str); + defineProperty(this, '__length__', d('', str.length)); + +}; +if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); + +StringIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(StringIterator), + _next: d(function () { + if (!this.__list__) return; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + }), + _resolve: d(function (i) { + var char = this.__list__[i], code; + if (this.__nextIndex__ === this.__length__) return char; + code = char.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; + return char; + }), + toString: d(function () { return '[object String Iterator]'; }) +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/#/chain.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/#/chain.js new file mode 100644 index 00000000000000..a414c66d78f44f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/#/chain.js @@ -0,0 +1,23 @@ +'use strict'; + +var Iterator = require('../../'); + +module.exports = function (t, a) { + var i1 = new Iterator(['raz', 'dwa', 'trzy']) + , i2 = new Iterator(['cztery', 'pięć', 'sześć']) + , i3 = new Iterator(['siedem', 'osiem', 'dziewięć']) + + , iterator = t.call(i1, i2, i3); + + a.deep(iterator.next(), { done: false, value: 'raz' }, "#1"); + a.deep(iterator.next(), { done: false, value: 'dwa' }, "#2"); + a.deep(iterator.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(iterator.next(), { done: false, value: 'cztery' }, "#4"); + a.deep(iterator.next(), { done: false, value: 'pięć' }, "#5"); + a.deep(iterator.next(), { done: false, value: 'sześć' }, "#6"); + a.deep(iterator.next(), { done: false, value: 'siedem' }, "#7"); + a.deep(iterator.next(), { done: false, value: 'osiem' }, "#8"); + a.deep(iterator.next(), { done: false, value: 'dziewięć' }, "#9"); + a.deep(iterator.next(), { done: true, value: undefined }, "Done #1"); + a.deep(iterator.next(), { done: true, value: undefined }, "Done #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/array.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/array.js new file mode 100644 index 00000000000000..ae7c2199e84a72 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/array.js @@ -0,0 +1,67 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (T) { + return { + Values: function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it; + + it = new T(x); + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.splice(1, 0, 'elo'); + a.deep(it.next(), { done: false, value: 'dwa' }, "Insert"); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + x.pop(); + a.deep(it.next(), { done: false, value: 'pięć' }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Keys & Values": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it; + + it = new T(x, 'key+value'); + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: [0, 'raz'] }, "#1"); + a.deep(it.next(), { done: false, value: [1, 'dwa'] }, "#2"); + x.splice(1, 0, 'elo'); + a.deep(it.next(), { done: false, value: [2, 'dwa'] }, "Insert"); + a.deep(it.next(), { done: false, value: [3, 'trzy'] }, "#3"); + a.deep(it.next(), { done: false, value: [4, 'cztery'] }, "#4"); + x.pop(); + a.deep(it.next(), { done: false, value: [5, 'pięć'] }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + Keys: function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it; + + it = new T(x, 'key'); + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: 0 }, "#1"); + a.deep(it.next(), { done: false, value: 1 }, "#2"); + x.splice(1, 0, 'elo'); + a.deep(it.next(), { done: false, value: 2 }, "Insert"); + a.deep(it.next(), { done: false, value: 3 }, "#3"); + a.deep(it.next(), { done: false, value: 4 }, "#4"); + x.pop(); + a.deep(it.next(), { done: false, value: 5 }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + Sparse: function (a) { + var x = new Array(6), it; + + x[2] = 'raz'; + x[4] = 'dwa'; + it = new T(x); + a.deep(it.next(), { done: false, value: undefined }, "#1"); + a.deep(it.next(), { done: false, value: undefined }, "#2"); + a.deep(it.next(), { done: false, value: 'raz' }, "#3"); + a.deep(it.next(), { done: false, value: undefined }, "#4"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#5"); + a.deep(it.next(), { done: false, value: undefined }, "#6"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/for-of.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/for-of.js new file mode 100644 index 00000000000000..502e7b767f61b2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/for-of.js @@ -0,0 +1,35 @@ +'use strict'; + +var ArrayIterator = require('../array') + + , slice = Array.prototype.slice; + +module.exports = function (t, a) { + var i = 0, x = ['raz', 'dwa', 'trzy'], y = {}, called = 0; + t(x, function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Array " + i + "#"); + a(this, y, "Array: context: " + (i++) + "#"); + }, y); + i = 0; + t(x = 'foo', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Regular String: context: " + (i++) + "#"); + }, y); + i = 0; + x = ['r', '💩', 'z']; + t('r💩z', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Unicode String: context: " + (i++) + "#"); + }, y); + i = 0; + t(new ArrayIterator(x), function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Iterator " + i + "#"); + a(this, y, "Iterator: context: " + (i++) + "#"); + }, y); + + t(x = ['raz', 'dwa', 'trzy'], function (value, doBreak) { + ++called; + return doBreak(); + }); + a(called, 1, "Break"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/get.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/get.js new file mode 100644 index 00000000000000..7309590cba5689 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/get.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , Iterator = require('../'); + +module.exports = function (t, a) { + var iterator; + a.throws(function () { t(); }, TypeError, "Null"); + a.throws(function () { t({}); }, TypeError, "Plain object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + iterator = {}; + iterator[iteratorSymbol] = function () { return new Iterator([]); }; + a(t(iterator) instanceof Iterator, true, "Iterator"); + a(String(t([])), '[object Array Iterator]', " Array"); + a(String(t('foo')), '[object String Iterator]', "String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/index.js new file mode 100644 index 00000000000000..ea3621adfebeb5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/index.js @@ -0,0 +1,99 @@ +'use strict'; + +var ee = require('event-emitter') + , iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (T) { + return { + "": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć'], it, y, z; + + it = new T(x); + a(it[iteratorSymbol](), it, "@@iterator"); + y = it.next(); + a.deep(y, { done: false, value: 'raz' }, "#1"); + z = it.next(); + a.not(y, z, "Recreate result"); + a.deep(z, { done: false, value: 'dwa' }, "#2"); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + a.deep(it.next(), { done: false, value: 'pięć' }, "#5"); + a.deep(y = it.next(), { done: true, value: undefined }, "End"); + a.not(y, it.next(), "Recreate result on dead"); + }, + Emited: function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + y.emit('_add', x.push('sześć') - 1); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + x.splice(1, 0, 'półtora'); + y.emit('_add', 1); + a.deep(it.next(), { done: false, value: 'półtora' }, "Insert"); + x.splice(5, 1); + y.emit('_delete', 5); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + a.deep(it.next(), { done: false, value: 'sześć' }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited #2": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.splice(1, 0, 'półtora'); + y.emit('_add', 1); + x.splice(1, 0, '1.25'); + y.emit('_add', 1); + x.splice(0, 1); + y.emit('_delete', 0); + a.deep(it.next(), { done: false, value: 'półtora' }, "Insert"); + a.deep(it.next(), { done: false, value: '1.25' }, "Insert #2"); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + x.splice(5, 1); + y.emit('_delete', 5); + a.deep(it.next(), { done: false, value: 'sześć' }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #1": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.length = 0; + y.emit('_clear'); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #2": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.length = 0; + y.emit('_clear'); + x.push('foo'); + x.push('bar'); + a.deep(it.next(), { done: false, value: 'foo' }, "#3"); + a.deep(it.next(), { done: false, value: 'bar' }, "#4"); + x.splice(1, 0, 'półtora'); + y.emit('_add', 1); + x.splice(1, 0, '1.25'); + y.emit('_add', 1); + x.splice(0, 1); + y.emit('_delete', 0); + a.deep(it.next(), { done: false, value: 'półtora' }, "Insert"); + a.deep(it.next(), { done: false, value: '1.25' }, "Insert #2"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/is-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/is-iterable.js new file mode 100644 index 00000000000000..7c5c59b6d75a62 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/is-iterable.js @@ -0,0 +1,18 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , Iterator = require('../'); + +module.exports = function (t, a) { + var iterator; + a(t(), false, "Undefined"); + a(t(123), false, "Number"); + a(t({}), false, "Plain object"); + a(t({ length: 0 }), false, "Array-like"); + iterator = {}; + iterator[iteratorSymbol] = function () { return new Iterator([]); }; + a(t(iterator), true, "Iterator"); + a(t([]), true, "Array"); + a(t('foo'), true, "String"); + a(t(''), true, "Empty string"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/string.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/string.js new file mode 100644 index 00000000000000..d11855f2511609 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/string.js @@ -0,0 +1,23 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (T, a) { + var it = new T('foobar'); + + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: 'f' }, "#1"); + a.deep(it.next(), { done: false, value: 'o' }, "#2"); + a.deep(it.next(), { done: false, value: 'o' }, "#3"); + a.deep(it.next(), { done: false, value: 'b' }, "#4"); + a.deep(it.next(), { done: false, value: 'a' }, "#5"); + a.deep(it.next(), { done: false, value: 'r' }, "#6"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + + a.h1("Outside of BMP"); + it = new T('r💩z'); + a.deep(it.next(), { done: false, value: 'r' }, "#1"); + a.deep(it.next(), { done: false, value: '💩' }, "#2"); + a.deep(it.next(), { done: false, value: 'z' }, "#3"); + a.deep(it.next(), { done: true, value: undefined }, "End"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/valid-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/valid-iterable.js new file mode 100644 index 00000000000000..7760b017826085 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/test/valid-iterable.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , Iterator = require('../'); + +module.exports = function (t, a) { + var obj; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t({}); }, TypeError, "Plain object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + obj = {}; + obj[iteratorSymbol] = function () { return new Iterator([]); }; + a(t(obj), obj, "Iterator"); + obj = []; + a(t(obj), obj, 'Array'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/valid-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/valid-iterable.js new file mode 100644 index 00000000000000..d330997cb1d6af --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-iterator/valid-iterable.js @@ -0,0 +1,8 @@ +'use strict'; + +var isIterable = require('./is-iterable'); + +module.exports = function (value) { + if (!isIterable(value)) throw new TypeError(value + " is not iterable"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.lint new file mode 100644 index 00000000000000..cf54d815684b2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.lint @@ -0,0 +1,11 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.travis.yml new file mode 100644 index 00000000000000..4c4accb6b1ffb0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-set@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/CHANGES new file mode 100644 index 00000000000000..79603bf8cf2cfb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/CHANGES @@ -0,0 +1,18 @@ +v0.1.1 -- 2014.10.07 +* Fix isImplemented so it validates native Set properly +* Add getFirst and getLast extensions +* Configure linter scripts + +v0.1.0 -- 2014.04.29 +* Assure strictly npm hosted dependencies +* Introduce faster 'primitive' alternative (doesn't guarantee order of iteration) +* Add isNativeImplemented, and some, every and copy method extensions +* If native Set is provided polyfill extends it +* Optimize forEach iteration +* Remove comparator support (as it was removed from spec) +* Provide @@toStringTag symbol, ad @@iterator symbols on iterators +* Update to use latest dependencies versions +* Improve interals + +v0.0.0 -- 2013.10.12 +Initial (dev) version diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/LICENCE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/LICENCE new file mode 100644 index 00000000000000..aaf35282f41f57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/LICENCE @@ -0,0 +1,19 @@ +Copyright (C) 2013 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/README.md new file mode 100644 index 00000000000000..95e9d35861533d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/README.md @@ -0,0 +1,71 @@ +# es6-set +## Set collection as specified in ECMAScript6 + +### Usage + +If you want to make sure your environment implements `Set`, do: + +```javascript +require('es6-set/implement'); +``` + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't, but without implementing `Set` on global scope, do: + +```javascript +var Set = require('es6-set'); +``` + +If you strictly want to use polyfill even if native `Set` exists, do: + +```javascript +var Set = require('es6-set/polyfill'); +``` + +### Installation + + $ npm install es6-set + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-set-objects). Still if you want quick look, follow examples: + +```javascript +var Set = require('es6-set'); + +var set = new Set(['raz', 'dwa', {}]); + +set.size; // 3 +set.has('raz'); // true +set.has('foo'); // false +set.add('foo'); // set +set.size // 4 +set.has('foo'); // true +set.has('dwa'); // true +set.delete('dwa'); // true +set.size; // 3 + +set.forEach(function (value) { + // 'raz', {}, 'foo' iterated +}); + +// FF nightly only: +for (value of set) { + // 'raz', {}, 'foo' iterated +} + +var iterator = set.values(); + +iterator.next(); // { done: false, value: 'raz' } +iterator.next(); // { done: false, value: {} } +iterator.next(); // { done: false, value: 'foo' } +iterator.next(); // { done: true, value: undefined } + +set.clear(); // undefined +set.size; // 0 +``` + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-set.png)](https://travis-ci.org/medikoo/es6-set) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/copy.js new file mode 100644 index 00000000000000..a8fd5c20c888d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/copy.js @@ -0,0 +1,5 @@ +'use strict'; + +var Set = require('../'); + +module.exports = function () { return new Set(this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/every.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/every.js new file mode 100644 index 00000000000000..ea64ebc56f38ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/every.js @@ -0,0 +1,18 @@ +'use strict'; + +var callable = require('es5-ext/object/valid-callable') + , forOf = require('es6-iterator/for-of') + + , call = Function.prototype.call; + +module.exports = function (cb/*, thisArg*/) { + var thisArg = arguments[1], result = true; + callable(cb); + forOf(this, function (value, doBreak) { + if (!call.call(cb, thisArg, value)) { + result = false; + doBreak(); + } + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/get-first.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/get-first.js new file mode 100644 index 00000000000000..b5d89fc13fffb6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/get-first.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return this.values().next().value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/get-last.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/get-last.js new file mode 100644 index 00000000000000..d22ce737bccecc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/get-last.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function () { + var value, iterator = this.values(), item; + while (true) { + item = iterator.next(); + if (item.done) break; + value = item.value; + } + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/some.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/some.js new file mode 100644 index 00000000000000..400a5a0c626b27 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/ext/some.js @@ -0,0 +1,18 @@ +'use strict'; + +var callable = require('es5-ext/object/valid-callable') + , forOf = require('es6-iterator/for-of') + + , call = Function.prototype.call; + +module.exports = function (cb/*, thisArg*/) { + var thisArg = arguments[1], result = false; + callable(cb); + forOf(this, function (value, doBreak) { + if (call.call(cb, thisArg, value)) { + result = true; + doBreak(); + } + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/implement.js new file mode 100644 index 00000000000000..f03362e083dd7d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'Set', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/index.js new file mode 100644 index 00000000000000..daa788619542d3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Set : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-implemented.js new file mode 100644 index 00000000000000..d8b0cd7d2d78e5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-implemented.js @@ -0,0 +1,22 @@ +'use strict'; + +module.exports = function () { + var set, iterator, result; + if (typeof Set !== 'function') return false; + set = new Set(['raz', 'dwa', 'trzy']); + if (set.size !== 3) return false; + if (typeof set.add !== 'function') return false; + if (typeof set.clear !== 'function') return false; + if (typeof set.delete !== 'function') return false; + if (typeof set.entries !== 'function') return false; + if (typeof set.forEach !== 'function') return false; + if (typeof set.has !== 'function') return false; + if (typeof set.keys !== 'function') return false; + if (typeof set.values !== 'function') return false; + + iterator = set.values(); + result = iterator.next(); + if (result.done !== false) return false; + if (result.value !== 'raz') return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-native-implemented.js new file mode 100644 index 00000000000000..e8b0160ec097d3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-native-implemented.js @@ -0,0 +1,9 @@ +// Exports true if environment provides native `Set` implementation, +// whatever that is. + +'use strict'; + +module.exports = (function () { + if (typeof Set === 'undefined') return false; + return (Object.prototype.toString.call(Set.prototype) === '[object Set]'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-set.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-set.js new file mode 100644 index 00000000000000..19e47929356ab6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/is-set.js @@ -0,0 +1,12 @@ +'use strict'; + +var toString = Object.prototype.toString + , toStringTagSymbol = require('es6-symbol').toStringTag + + , id = '[object Set]' + , Global = (typeof Set === 'undefined') ? null : Set; + +module.exports = function (x) { + return (x && ((Global && (x instanceof Global)) || + (toString.call(x) === id) || (x[toStringTagSymbol] === 'Set'))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/lib/iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/lib/iterator.js new file mode 100644 index 00000000000000..4a7dac7ebdc648 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/lib/iterator.js @@ -0,0 +1,31 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , contains = require('es5-ext/string/#/contains') + , d = require('d') + , Iterator = require('es6-iterator') + , toStringTagSymbol = require('es6-symbol').toStringTag + + , defineProperty = Object.defineProperty + , SetIterator; + +SetIterator = module.exports = function (set, kind) { + if (!(this instanceof SetIterator)) return new SetIterator(set, kind); + Iterator.call(this, set.__setData__, set); + if (!kind) kind = 'value'; + else if (contains.call(kind, 'key+value')) kind = 'key+value'; + else kind = 'value'; + defineProperty(this, '__kind__', d('', kind)); +}; +if (setPrototypeOf) setPrototypeOf(SetIterator, Iterator); + +SetIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(SetIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__list__[i]; + return [this.__list__[i], this.__list__[i]]; + }), + toString: d(function () { return '[object Set Iterator]'; }) +}); +defineProperty(SetIterator.prototype, toStringTagSymbol, + d('c', 'Set Iterator')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/lib/primitive-iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/lib/primitive-iterator.js new file mode 100644 index 00000000000000..1f0326a3b5d923 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/lib/primitive-iterator.js @@ -0,0 +1,53 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , assign = require('es5-ext/object/assign') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , contains = require('es5-ext/string/#/contains') + , d = require('d') + , autoBind = require('d/auto-bind') + , Iterator = require('es6-iterator') + , toStringTagSymbol = require('es6-symbol').toStringTag + + , defineProperties = Object.defineProperties, keys = Object.keys + , unBind = Iterator.prototype._unBind + , PrimitiveSetIterator; + +PrimitiveSetIterator = module.exports = function (set, kind) { + if (!(this instanceof PrimitiveSetIterator)) { + return new PrimitiveSetIterator(set, kind); + } + Iterator.call(this, keys(set.__setData__), set); + kind = (!kind || !contains.call(kind, 'key+value')) ? 'value' : 'key+value'; + defineProperties(this, { + __kind__: d('', kind), + __data__: d('w', set.__setData__) + }); +}; +if (setPrototypeOf) setPrototypeOf(PrimitiveSetIterator, Iterator); + +PrimitiveSetIterator.prototype = Object.create(Iterator.prototype, assign({ + constructor: d(PrimitiveSetIterator), + _resolve: d(function (i) { + var value = this.__data__[this.__list__[i]]; + return (this.__kind__ === 'value') ? value : [value, value]; + }), + _unBind: d(function () { + this.__data__ = null; + unBind.call(this); + }), + toString: d(function () { return '[object Set Iterator]'; }) +}, autoBind({ + _onAdd: d(function (key) { this.__list__.push(key); }), + _onDelete: d(function (key) { + var index = this.__list__.lastIndexOf(key); + if (index < this.__nextIndex__) return; + this.__list__.splice(index, 1); + }), + _onClear: d(function () { + clear.call(this.__list__); + this.__nextIndex__ = 0; + }) +}))); +Object.defineProperty(PrimitiveSetIterator.prototype, toStringTagSymbol, + d('c', 'Set Iterator')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/package.json new file mode 100644 index 00000000000000..dd1720921250e4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/package.json @@ -0,0 +1,66 @@ +{ + "name": "es6-set", + "version": "0.1.1", + "description": "ECMAScript6 Set polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "set", + "collection", + "es6", + "harmony", + "list", + "hash" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-set.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.4", + "es6-iterator": "~0.1.1", + "es6-symbol": "~0.1.1", + "event-emitter": "~0.3.1" + }, + "devDependencies": { + "tad": "0.2.x", + "xlint": "~0.2.1", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "769f7391b194b25900a79d132d21f4abefb14201", + "bugs": { + "url": "https://github.com/medikoo/es6-set/issues" + }, + "homepage": "https://github.com/medikoo/es6-set", + "_id": "es6-set@0.1.1", + "_shasum": "497cd235c9a2691f4caa0e33dd73ef86bde738ac", + "_from": "es6-set@>=0.1.1 <0.2.0", + "_npmVersion": "2.0.0", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "497cd235c9a2691f4caa0e33dd73ef86bde738ac", + "tarball": "http://registry.npmjs.org/es6-set/-/es6-set-0.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-set/-/es6-set-0.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/polyfill.js new file mode 100644 index 00000000000000..d272429ffcea1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/polyfill.js @@ -0,0 +1,79 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , eIndexOf = require('es5-ext/array/#/e-index-of') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , callable = require('es5-ext/object/valid-callable') + , d = require('d') + , ee = require('event-emitter') + , Symbol = require('es6-symbol') + , iterator = require('es6-iterator/valid-iterable') + , forOf = require('es6-iterator/for-of') + , Iterator = require('./lib/iterator') + , isNative = require('./is-native-implemented') + + , call = Function.prototype.call, defineProperty = Object.defineProperty + , SetPoly, getValues; + +module.exports = SetPoly = function (/*iterable*/) { + var iterable = arguments[0]; + if (!(this instanceof SetPoly)) return new SetPoly(iterable); + if (this.__setData__ !== undefined) { + throw new TypeError(this + " cannot be reinitialized"); + } + if (iterable != null) iterator(iterable); + defineProperty(this, '__setData__', d('c', [])); + if (!iterable) return; + forOf(iterable, function (value) { + if (eIndexOf.call(this, value) !== -1) return; + this.push(value); + }, this.__setData__); +}; + +if (isNative) { + if (setPrototypeOf) setPrototypeOf(SetPoly, Set); + SetPoly.prototype = Object.create(Set.prototype, { + constructor: d(SetPoly) + }); +} + +ee(Object.defineProperties(SetPoly.prototype, { + add: d(function (value) { + if (this.has(value)) return this; + this.emit('_add', this.__setData__.push(value) - 1, value); + return this; + }), + clear: d(function () { + if (!this.__setData__.length) return; + clear.call(this.__setData__); + this.emit('_clear'); + }), + delete: d(function (value) { + var index = eIndexOf.call(this.__setData__, value); + if (index === -1) return false; + this.__setData__.splice(index, 1); + this.emit('_delete', index, value); + return true; + }), + entries: d(function () { return new Iterator(this, 'key+value'); }), + forEach: d(function (cb/*, thisArg*/) { + var thisArg = arguments[1], iterator, result, value; + callable(cb); + iterator = this.values(); + result = iterator._next(); + while (result !== undefined) { + value = iterator._resolve(result); + call.call(cb, thisArg, value, value, this); + result = iterator._next(); + } + }), + has: d(function (value) { + return (eIndexOf.call(this.__setData__, value) !== -1); + }), + keys: d(getValues = function () { return this.values(); }), + size: d.gs(function () { return this.__setData__.length; }), + values: d(function () { return new Iterator(this); }), + toString: d(function () { return '[object Set]'; }) +})); +defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues)); +defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/primitive/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/primitive/index.js new file mode 100644 index 00000000000000..4565887d415a9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/primitive/index.js @@ -0,0 +1,88 @@ +'use strict'; + +var callable = require('es5-ext/object/valid-callable') + , clear = require('es5-ext/object/clear') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , iterator = require('es6-iterator/valid-iterable') + , forOf = require('es6-iterator/for-of') + , Set = require('../polyfill') + , Iterator = require('../lib/primitive-iterator') + + , create = Object.create, defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty + , hasOwnProperty = Object.prototype.hasOwnProperty + , PrimitiveSet; + +module.exports = PrimitiveSet = function (/*iterable, serialize*/) { + var iterable = arguments[0], serialize = arguments[1]; + if (!(this instanceof PrimitiveSet)) { + return new PrimitiveSet(iterable, serialize); + } + if (this.__setData__ !== undefined) { + throw new TypeError(this + " cannot be reinitialized"); + } + if (iterable != null) iterator(iterable); + if (serialize !== undefined) { + callable(serialize); + defineProperty(this, '_serialize', d('', serialize)); + } + defineProperties(this, { + __setData__: d('c', create(null)), + __size__: d('w', 0) + }); + if (!iterable) return; + forOf(iterable, function (value) { + var key = this._serialize(value); + if (key == null) throw new TypeError(value + " cannot be serialized"); + if (hasOwnProperty.call(this.__setData__, key)) return; + this.__setData__[key] = value; + ++this.__size__; + }, this); +}; +if (setPrototypeOf) setPrototypeOf(PrimitiveSet, Set); + +PrimitiveSet.prototype = create(Set.prototype, { + constructor: d(PrimitiveSet), + _serialize: d(function (value) { + if (value && (typeof value.toString !== 'function')) return null; + return String(value); + }), + add: d(function (value) { + var key = this._serialize(value); + if (key == null) throw new TypeError(value + " cannot be serialized"); + if (hasOwnProperty.call(this.__setData__, key)) return this; + this.__setData__[key] = value; + ++this.__size__; + this.emit('_add', key); + return this; + }), + clear: d(function () { + if (!this.__size__) return; + clear(this.__setData__); + this.__size__ = 0; + this.emit('_clear'); + }), + delete: d(function (value) { + var key = this._serialize(value); + if (key == null) return false; + if (!hasOwnProperty.call(this.__setData__, key)) return false; + delete this.__setData__[key]; + --this.__size__; + this.emit('_delete', key); + return true; + }), + entries: d(function () { return new Iterator(this, 'key+value'); }), + get: d(function (key) { + key = this._serialize(key); + if (key == null) return; + return this.__setData__[key]; + }), + has: d(function (value) { + var key = this._serialize(value); + if (key == null) return false; + return hasOwnProperty.call(this.__setData__, key); + }), + size: d.gs(function () { return this.__size__; }), + values: d(function () { return new Iterator(this); }) +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/copy.js new file mode 100644 index 00000000000000..84fe912a36f735 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/copy.js @@ -0,0 +1,12 @@ +'use strict'; + +var toArray = require('es5-ext/array/to-array') + , Set = require('../../'); + +module.exports = function (t, a) { + var content = ['raz', 2, true], set = new Set(content), copy; + + copy = t.call(set); + a.not(copy, set, "Copy"); + a.deep(toArray(copy), content, "Content"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/every.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/every.js new file mode 100644 index 00000000000000..f56ca385fa5a73 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/every.js @@ -0,0 +1,9 @@ +'use strict'; + +var Set = require('../../'); + +module.exports = function (t, a) { + a(t.call(new Set(), Boolean), true, "Empty set"); + a(t.call(new Set([2, 3, 4]), Boolean), true, "Truthy"); + a(t.call(new Set([2, 0, 4]), Boolean), false, "Falsy"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/get-first.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/get-first.js new file mode 100644 index 00000000000000..f99829e5afe0bc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/get-first.js @@ -0,0 +1,12 @@ +'use strict'; + +var Set = require('../../'); + +module.exports = function (t, a) { + var content = ['raz', 2, true], set = new Set(content); + + a(t.call(set), 'raz'); + + set = new Set(); + a(t.call(set), undefined); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/get-last.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/get-last.js new file mode 100644 index 00000000000000..1dcc993ed0ec73 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/get-last.js @@ -0,0 +1,12 @@ +'use strict'; + +var Set = require('../../'); + +module.exports = function (t, a) { + var content = ['raz', 2, true], set = new Set(content); + + a(t.call(set), true); + + set = new Set(); + a(t.call(set), undefined); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/some.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/some.js new file mode 100644 index 00000000000000..84ce11916a8bb9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/ext/some.js @@ -0,0 +1,10 @@ +'use strict'; + +var Set = require('../../'); + +module.exports = function (t, a) { + a(t.call(new Set(), Boolean), false, "Empty set"); + a(t.call(new Set([2, 3, 4]), Boolean), true, "All true"); + a(t.call(new Set([0, false, 4]), Boolean), true, "Some false"); + a(t.call(new Set([0, false, null]), Boolean), false, "All false"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/implement.js new file mode 100644 index 00000000000000..4882d3786a62d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof Set, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/index.js new file mode 100644 index 00000000000000..19c64865097d31 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (T, a) { a((new T(['raz', 'dwa'])).size, 2); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-implemented.js new file mode 100644 index 00000000000000..124793e7373f1c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +var global = require('es5-ext/global') + , polyfill = require('../polyfill'); + +module.exports = function (t, a) { + var cache; + a(typeof t(), 'boolean'); + cache = global.Set; + global.Set = polyfill; + a(t(), true); + if (cache === undefined) delete global.Set; + else global.Set = cache; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-set.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-set.js new file mode 100644 index 00000000000000..c969cce232f0d6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/is-set.js @@ -0,0 +1,16 @@ +'use strict'; + +var SetPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof Set !== 'undefined') { + a(t(new Set()), true, "Native"); + } + a(t(new SetPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/lib/iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/lib/iterator.js new file mode 100644 index 00000000000000..9e5cfb91b9217f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/lib/iterator.js @@ -0,0 +1,13 @@ +'use strict'; + +var Set = require('../../polyfill') + , toArray = require('es5-ext/array/to-array'); + +module.exports = function (T, a) { + var set = new Set(['raz', 'dwa']); + + a.deep(toArray(new T(set)), ['raz', 'dwa'], "Default"); + a.deep(toArray(new T(set, 'key+value')), [['raz', 'raz'], ['dwa', 'dwa']], + "Key & Value"); + a.deep(toArray(new T(set, 'value')), ['raz', 'dwa'], "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/lib/primitive-iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/lib/primitive-iterator.js new file mode 100644 index 00000000000000..2a4956b80b3877 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/lib/primitive-iterator.js @@ -0,0 +1,113 @@ +'use strict'; + +var Set = require('../../primitive') + , toArray = require('es5-ext/array/to-array') + , iteratorSymbol = require('es6-symbol').iterator + + , compare, map; + +compare = function (a, b) { + if (!a.value) return -1; + if (!b.value) return 1; + return a.value.localeCompare(b.value); +}; + +map = function (arr) { + return arr.sort().map(function (value) { + return { done: false, value: value }; + }); +}; + +module.exports = function (T) { + return { + "": function (a) { + var arr = ['raz', 'dwa', 'trzy', 'cztery', 'pięć'], it, y, z + , set = new Set(arr), result = []; + + it = new T(set); + a(it[iteratorSymbol](), it, "@@iterator"); + y = it.next(); + result.push(y); + z = it.next(); + a.not(y, z, "Recreate result"); + result.push(z); + result.push(it.next()); + result.push(it.next()); + result.push(it.next()); + a.deep(result.sort(compare), map(arr)); + a.deep(y = it.next(), { done: true, value: undefined }, "End"); + a.not(y, it.next(), "Recreate result on dead"); + }, + Emited: function (a) { + var arr = ['raz', 'dwa', 'trzy', 'cztery', 'pięć'], it + , set = new Set(arr), result = []; + + it = new T(set); + result.push(it.next()); + result.push(it.next()); + set.add('sześć'); + arr.push('sześć'); + result.push(it.next()); + set.delete('pięć'); + arr.splice(4, 1); + result.push(it.next()); + result.push(it.next()); + a.deep(result.sort(compare), map(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited #2": function (a) { + var arr = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it + , set = new Set(arr), result = []; + + it = new T(set); + result.push(it.next()); + result.push(it.next()); + set.add('siedem'); + set.delete('siedem'); + result.push(it.next()); + result.push(it.next()); + set.delete('pięć'); + arr.splice(4, 1); + result.push(it.next()); + a.deep(result.sort(compare), map(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #1": function (a) { + var arr = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it + , set = new Set(arr), result = []; + + it = new T(set); + result.push(it.next()); + result.push(it.next()); + arr = ['raz', 'dwa']; + set.clear(); + a.deep(result.sort(compare), map(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #2": function (a) { + var arr = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it + , set = new Set(arr), result = []; + + it = new T(set); + result.push(it.next()); + result.push(it.next()); + set.clear(); + set.add('foo'); + set.add('bar'); + arr = ['raz', 'dwa', 'foo', 'bar']; + result.push(it.next()); + result.push(it.next()); + a.deep(result.sort(compare), map(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + Kinds: function (a) { + var set = new Set(['raz', 'dwa']); + + a.deep(toArray(new T(set)).sort(), ['raz', 'dwa'].sort(), "Default"); + a.deep(toArray(new T(set, 'key+value')).sort(), + [['raz', 'raz'], ['dwa', 'dwa']].sort(), "Key & Value"); + a.deep(toArray(new T(set, 'value')).sort(), ['raz', 'dwa'].sort(), + "Other"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/polyfill.js new file mode 100644 index 00000000000000..10ce6d39eb2b7a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/polyfill.js @@ -0,0 +1,44 @@ +'use strict'; + +var aFrom = require('es5-ext/array/from') + , toArray = require('es5-ext/array/to-array'); + +module.exports = function (T, a) { + var arr = ['raz', 'dwa', 'trzy'], set = new T(arr), x = {}, y = {}, i = 0; + + a(set instanceof T, true, "Set"); + a(set.size, 3, "Size"); + a(set.has('raz'), true, "Has: true"); + a(set.has(x), false, "Has: false"); + a(set.add(x), set, "Add: return"); + a(set.has(x), true, "Add"); + a(set.size, 4, "Add: Size"); + a(set.delete({}), false, "Delete: false"); + + arr.push(x); + set.forEach(function () { + a.deep(aFrom(arguments), [arr[i], arr[i], set], + "ForEach: Arguments: #" + i); + a(this, y, "ForEach: Context: #" + i); + if (i === 0) { + a(set.delete('raz'), true, "Delete: true"); + a(set.has('raz'), false, "Delete"); + a(set.size, 3, "Delete: size"); + set.add('cztery'); + arr.push('cztery'); + } + i++; + }, y); + arr.splice(0, 1); + + a.deep(toArray(set.entries()), [['dwa', 'dwa'], ['trzy', 'trzy'], [x, x], + ['cztery', 'cztery']], "Entries"); + a.deep(toArray(set.keys()), ['dwa', 'trzy', x, 'cztery'], "Keys"); + a.deep(toArray(set.values()), ['dwa', 'trzy', x, 'cztery'], "Values"); + a.deep(toArray(set), ['dwa', 'trzy', x, 'cztery'], "Iterator"); + + set.clear(); + a(set.size, 0, "Clear: size"); + a(set.has('trzy'), false, "Clear: has"); + a.deep(toArray(set), [], "Clear: Values"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/primitive/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/primitive/index.js new file mode 100644 index 00000000000000..54765d2ae2b925 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/primitive/index.js @@ -0,0 +1,44 @@ +'use strict'; + +var aFrom = require('es5-ext/array/from') + , getIterator = require('es6-iterator/get') + , toArray = require('es5-ext/array/to-array'); + +module.exports = function (T, a) { + var arr = ['raz', 'dwa', 'trzy'], set = new T(arr), x = 'other', y = 'other2' + , i = 0, result = []; + + a(set instanceof T, true, "Set"); + a(set.size, 3, "Size"); + a(set.has('raz'), true, "Has: true"); + a(set.has(x), false, "Has: false"); + a(set.add(x), set, "Add: return"); + a(set.has(x), true, "Add"); + a(set.size, 4, "Add: Size"); + a(set.delete('else'), false, "Delete: false"); + a(set.get('raz'), 'raz', "Get"); + + arr.push(x); + set.forEach(function () { + result.push(aFrom(arguments)); + a(this, y, "ForEach: Context: #" + i); + }, y); + + a.deep(result.sort(function (a, b) { + return a[0].localeCompare(b[0]); + }), arr.sort().map(function (val) { return [val, val, set]; })); + + a.deep(toArray(set.entries()).sort(), [['dwa', 'dwa'], ['trzy', 'trzy'], + [x, x], ['raz', 'raz']].sort(), "Entries"); + a.deep(toArray(set.keys()).sort(), ['dwa', 'trzy', x, 'raz'].sort(), + "Keys"); + a.deep(toArray(set.values()).sort(), ['dwa', 'trzy', x, 'raz'].sort(), + "Values"); + a.deep(toArray(getIterator(set)).sort(), ['dwa', 'trzy', x, 'raz'].sort(), + "Iterator"); + + set.clear(); + a(set.size, 0, "Clear: size"); + a(set.has('trzy'), false, "Clear: has"); + a.deep(toArray(set.values()), [], "Clear: Values"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/valid-set.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/valid-set.js new file mode 100644 index 00000000000000..8c71f5f8c709e4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/test/valid-set.js @@ -0,0 +1,19 @@ +'use strict'; + +var SetPoly = require('../polyfill'); + +module.exports = function (t, a) { + var set; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof Set !== 'undefined') { + set = new Set(); + a(t(set), set, "Native"); + } + set = new SetPoly(); + a(t(set), set, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/valid-set.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/valid-set.js new file mode 100644 index 00000000000000..9336fd355a7146 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-set/valid-set.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSet = require('./is-set'); + +module.exports = function (x) { + if (!isSet(x)) throw new TypeError(x + " is not a Set"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.lint new file mode 100644 index 00000000000000..701a50ce430c63 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.lint @@ -0,0 +1,13 @@ +@root + +module + +tabs +indent 2 +maxlen 80 + +ass +nomen +plusplus + +newcap diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.travis.yml new file mode 100644 index 00000000000000..afd3509a26b27d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-symbol@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/CHANGES new file mode 100644 index 00000000000000..ff5e1b480cb2bb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/CHANGES @@ -0,0 +1,12 @@ +v0.1.1 -- 2014.10.07 +* Fix isImplemented, so it returns true in case of polyfill +* Improve documentations + +v0.1.0 -- 2014.04.28 +* Assure strictly npm dependencies +* Update to use latest versions of dependencies +* Fix implementation detection so it doesn't crash on `String(symbol)` +* throw on `new Symbol()` (as decided by TC39) + +v0.0.0 -- 2013.11.15 +* Initial (dev) version \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/LICENCE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/LICENCE new file mode 100644 index 00000000000000..aaf35282f41f57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/LICENCE @@ -0,0 +1,19 @@ +Copyright (C) 2013 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/README.md new file mode 100644 index 00000000000000..978eb59d8d55be --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/README.md @@ -0,0 +1,67 @@ +# es6-symbol +## ECMAScript6 Symbol polyfill + +### Limitations + +- Underneath it uses real string property names which can easily be retrieved (however accidental collision with other property names is unlikely) +- As it needs custom `toString` behavior to work properly. Original `Symbol.prototype.toString` couldn't be implemented as specified, still it's accessible as `Symbol.prototoype.properToString` + +### Usage + +If you want to make sure your environment implements `Symbol`, do: + +```javascript +require('es6-symbol/implement'); +``` + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't, but without implementing `Symbol` on global scope, do: + +```javascript +var Symbol = require('es6-symbol'); +``` + +If you strictly want to use polyfill even if native `Symbol` exists (hard to find a good reason for that), do: + +```javascript +var Symbol = require('es6-symbol/polyfill'); +``` + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-objects). Still if you want quick look, follow examples: + +```javascript +var Symbol = require('es6-symbol'); + +var symbol = Symbol('My custom symbol'); +var x = {}; + +x[symbol] = 'foo'; +console.log(x[symbol]); 'foo' + +// Detect iterable: +var iterator, result; +if (possiblyIterable[Symbol.iterator]) { + iterator = possiblyIterable[Symbol.iterator](); + result = iterator.next(); + while(!result.done) { + console.log(result.value); + result = iterator.next(); + } +} +``` + +### Installation +#### NPM + +In your project path: + + $ npm install es6-symbol + +##### Browser + +You can easily bundle _es6-symbol_ for browser with [modules-webmake](https://github.com/medikoo/modules-webmake) + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-symbol.png)](https://travis-ci.org/medikoo/es6-symbol) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/implement.js new file mode 100644 index 00000000000000..153edacdbedf9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'Symbol', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/index.js new file mode 100644 index 00000000000000..609f1faf551164 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-implemented.js new file mode 100644 index 00000000000000..02a06b5a80c16b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-implemented.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + if (typeof Symbol.iterator === 'symbol') return true; + + // Return 'true' for polyfills + if (typeof Symbol.isConcatSpreadable !== 'object') return false; + if (typeof Symbol.isRegExp !== 'object') return false; + if (typeof Symbol.iterator !== 'object') return false; + if (typeof Symbol.toPrimitive !== 'object') return false; + if (typeof Symbol.toStringTag !== 'object') return false; + if (typeof Symbol.unscopables !== 'object') return false; + + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-native-implemented.js new file mode 100644 index 00000000000000..a8cb8b8681ee69 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-native-implemented.js @@ -0,0 +1,8 @@ +// Exports true if environment provides native `Symbol` implementation + +'use strict'; + +module.exports = (function () { + if (typeof Symbol !== 'function') return false; + return (typeof Symbol.iterator === 'symbol'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-symbol.js new file mode 100644 index 00000000000000..dcf72c9aaa353e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/is-symbol.js @@ -0,0 +1,12 @@ +'use strict'; + +var toString = Object.prototype.toString + , toStringTag = require('./').toStringTag + + , id = '[object Symbol]' + , Global = (typeof Symbol === 'undefined') ? null : Symbol; + +module.exports = function (x) { + return (x && ((Global && (x instanceof Global)) || + (toString.call(x) === id) || (x[toStringTag] === 'Symbol'))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/package.json new file mode 100644 index 00000000000000..a6ddc1a46c29b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/package.json @@ -0,0 +1,59 @@ +{ + "name": "es6-symbol", + "version": "0.1.1", + "description": "ECMAScript6 Symbol polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "symbol", + "private", + "property", + "es6", + "ecmascript", + "harmony" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-symbol.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.4" + }, + "devDependencies": { + "tad": "0.2.x" + }, + "scripts": { + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "2ca76a05feafaa14c838337722562625fb5072b4", + "bugs": { + "url": "https://github.com/medikoo/es6-symbol/issues" + }, + "homepage": "https://github.com/medikoo/es6-symbol", + "_id": "es6-symbol@0.1.1", + "_shasum": "9cf7fab2edaff1b1da8fe8e68bfe3f5aca6ca218", + "_from": "es6-symbol@>=0.1.1 <0.2.0", + "_npmVersion": "2.0.0", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "9cf7fab2edaff1b1da8fe8e68bfe3f5aca6ca218", + "tarball": "http://registry.npmjs.org/es6-symbol/-/es6-symbol-0.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-0.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/polyfill.js new file mode 100644 index 00000000000000..f7dfa258720d9f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/polyfill.js @@ -0,0 +1,53 @@ +'use strict'; + +var d = require('d') + + , create = Object.create, defineProperties = Object.defineProperties + , generateName, Symbol; + +generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + return '@@' + desc; + }; +}()); + +module.exports = Symbol = function (description) { + var symbol; + if (this instanceof Symbol) { + throw new TypeError('TypeError: Symbol is not a constructor'); + } + symbol = create(Symbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: d('', description), + __name__: d('', generateName(description)) + }); +}; + +Object.defineProperties(Symbol, { + create: d('', Symbol('create')), + hasInstance: d('', Symbol('hasInstance')), + isConcatSpreadable: d('', Symbol('isConcatSpreadable')), + isRegExp: d('', Symbol('isRegExp')), + iterator: d('', Symbol('iterator')), + toPrimitive: d('', Symbol('toPrimitive')), + toStringTag: d('', Symbol('toStringTag')), + unscopables: d('', Symbol('unscopables')) +}); + +defineProperties(Symbol.prototype, { + properToString: d(function () { + return 'Symbol (' + this.__description__ + ')'; + }), + toString: d('', function () { return this.__name__; }) +}); +Object.defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', + function (hint) { + throw new TypeError("Conversion of symbol objects is not allowed"); + })); +Object.defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/implement.js new file mode 100644 index 00000000000000..eb35c3018835c7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof Symbol, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/index.js new file mode 100644 index 00000000000000..62b3296df6fc5e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var d = require('d') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-implemented.js new file mode 100644 index 00000000000000..bb0d64536ebbae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +var global = require('es5-ext/global') + , polyfill = require('../polyfill'); + +module.exports = function (t, a) { + var cache; + a(typeof t(), 'boolean'); + cache = global.Symbol; + global.Symbol = polyfill; + a(t(), true); + if (cache === undefined) delete global.Symbol; + else global.Symbol = cache; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-symbol.js new file mode 100644 index 00000000000000..ac24b9abbff4e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/is-symbol.js @@ -0,0 +1,16 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof Symbol !== 'undefined') { + a(t(Symbol()), true, "Native"); + } + a(t(SymbolPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/polyfill.js new file mode 100644 index 00000000000000..cac9cd51935301 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/polyfill.js @@ -0,0 +1,17 @@ +'use strict'; + +var d = require('d') + , isSymbol = require('../is-symbol') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); + + a(isSymbol(symbol), true, "Symbol"); + a(isSymbol(T.iterator), true, "iterator"); + a(isSymbol(T.toStringTag), true, "toStringTag"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/valid-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/valid-iterable.js new file mode 100644 index 00000000000000..d277bc97f41125 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/valid-iterable.js @@ -0,0 +1,14 @@ +'use strict'; + +var Iterator = require('../'); + +module.exports = function (t, a) { + var obj; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t({}); }, TypeError, "Plain object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + obj = { '@@iterator': function () { return new Iterator([]); } }; + a(t(obj), obj, "Iterator"); + obj = []; + a(t(obj), obj, 'Array'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/valid-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/valid-symbol.js new file mode 100644 index 00000000000000..2c8f84c8239b6e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/test/valid-symbol.js @@ -0,0 +1,19 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + var symbol; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof Symbol !== 'undefined') { + symbol = Symbol(); + a(t(symbol), symbol, "Native"); + } + symbol = SymbolPoly(); + a(t(symbol), symbol, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/valid-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/valid-symbol.js new file mode 100644 index 00000000000000..42750043d4271c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/es6-symbol/valid-symbol.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSymbol = require('./is-symbol'); + +module.exports = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.lint b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.lint new file mode 100644 index 00000000000000..f76e528ef6a974 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.lint @@ -0,0 +1,15 @@ +@root + +module +es5 + +indent 2 +maxlen 80 +tabs + +ass +plusplus +nomen + +./benchmark +predef+ console diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.npmignore new file mode 100644 index 00000000000000..68ebfddd24fb33 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.npmignore @@ -0,0 +1,3 @@ +.DS_Store +/.lintcache +/node_modules diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.testignore b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.testignore new file mode 100644 index 00000000000000..f9c8c381d16290 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.testignore @@ -0,0 +1 @@ +/benchmark diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.travis.yml new file mode 100644 index 00000000000000..a6ec240dfdf156 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/.travis.yml @@ -0,0 +1,14 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +before_install: + - mkdir node_modules; ln -s ../ node_modules/event-emitter + +notifications: + email: + - medikoo+event-emitter@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/CHANGES new file mode 100644 index 00000000000000..dbc1b1777e9194 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/CHANGES @@ -0,0 +1,66 @@ +v0.3.3 -- 2015.01.30 +* Fix reference to module in benchmarks + +v0.3.2 -- 2015.01.20 +* Improve documentation +* Configure lint scripts +* Fix spelling of LICENSE + +v0.3.1 -- 2014.04.25 +* Fix redefinition of emit method in `pipe` +* Allow custom emit method name in `pipe` + +v0.3.0 -- 2014.04.24 +* Move out from lib folder +* Do not expose all utilities on main module +* Support objects which do not inherit from Object.prototype +* Improve arguments validation +* Improve internals +* Remove Makefile +* Improve documentation + +v0.2.2 -- 2013.06.05 +* `unify` functionality + +v0.2.1 -- 2012.09.21 +* hasListeners module +* Simplified internal id (improves performance a little), now it starts with + underscore (hint it's private). Abstracted it to external module to have it + one place +* Documentation cleanup + +v0.2.0 -- 2012.09.19 +* Trashed poor implementation of v0.1 and came up with something solid + +Changes: +* Improved performance +* Fixed bugs event-emitter is now cross-prototype safe and not affected by + unexpected methods attached to Object.prototype +* Removed support for optional "emitter" argument in `emit` method, it was + cumbersome to use, and should be solved just with event objects + +v0.1.5 -- 2012.08.06 +* (maintanance) Do not use descriptors for internal objects, it exposes V8 bugs + (only Node v0.6 branch) + +v0.1.4 -- 2012.06.13 +* Fix detachment of listeners added with 'once' + +v0.1.3 -- 2012.05.28 +* Updated es5-ext to latest version (v0.8) +* Cleared package.json so it's in npm friendly format + +v0.1.2 -- 2012.01.22 +* Support for emitter argument in emit function, this allows some listeners not + to be notified about event +* allOff - removes all listeners from object +* All methods returns self object +* Internal fixes +* Travis CI integration + +v0.1.1 -- 2011.08.08 +* Added TAD test suite to devDependencies, configured test commands. + Tests can be run with 'make test' or 'npm test' + +v0.1.0 -- 2011.08.08 +Initial version diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/LICENSE new file mode 100644 index 00000000000000..ccb76f6e9a0311 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/README.md b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/README.md new file mode 100644 index 00000000000000..17f4524fd75403 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/README.md @@ -0,0 +1,95 @@ +# event-emitter +## Environment agnostic event emitter + +### Installation + + $ npm install event-emitter + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +### Usage + +```javascript +var ee = require('event-emitter'); + +var emitter = ee({}), listener; + +emitter.on('test', listener = function (args) { + // …emitter logic +}); + +emitter.once('test', function (args) { + // …invoked only once(!) +}); + +emitter.emit('test', arg1, arg2/*…args*/); // Two above listeners invoked +emitter.emit('test', arg1, arg2/*…args*/); // Only first listener invoked + +emitter.off('test', listener); // Removed first listener +emitter.emit('test', arg1, arg2/*…args*/); // No listeners invoked +``` +### Additional utilities + +#### allOff(obj) _(event-emitter/all-off)_ + +Removes all listeners from given event emitter object + +#### hasListeners(obj[, name]) _(event-emitter/has-listeners)_ + +Whether object has some listeners attached to the object. +When `name` is provided, it checks listeners for specific event name + +```javascript +var emitter = ee(); +var hasListeners = require('event-emitter/has-listeners'); +var listener = function () {}; + +hasListeners(emitter); // false + +emitter.on('foo', listener); +hasListeners(emitter); // true +hasListeners(emitter, 'foo'); // true +hasListeners(emitter, 'bar'); // false + +emitter.off('foo', listener); +hasListeners(emitter, 'foo'); // false +``` + +#### pipe(source, target[, emitMethodName]) _(event-emitter/pipe)_ + +Pipes all events from _source_ emitter onto _target_ emitter (all events from _source_ emitter will be emitted also on _target_ emitter, but not other way). +Returns _pipe_ object which exposes `pipe.close` function. Invoke it to close configured _pipe_. +It works internally by redefinition of `emit` method, if in your interface this method is referenced differently, provide its name (or symbol) with third argument. + +#### unify(emitter1, emitter2) _(event-emitter/unify)_ + +Unifies event handling for two objects. Events emitted on _emitter1_ would be also emitter on _emitter2_, and other way back. +Non reversible. + +```javascript +var eeUnify = require('event-emitter/unify'); + +var emitter1 = ee(), listener1, listener3; +var emitter2 = ee(), listener2, listener4; + +emitter1.on('test', listener1 = function () { }); +emitter2.on('test', listener2 = function () { }); + +emitter1.emit('test'); // Invoked listener1 +emitter2.emit('test'); // Invoked listener2 + +var unify = eeUnify(emitter1, emitter2); + +emitter1.emit('test'); // Invoked listener1 and listener2 +emitter2.emit('test'); // Invoked listener1 and listener2 + +emitter1.on('test', listener3 = function () { }); +emitter2.on('test', listener4 = function () { }); + +emitter1.emit('test'); // Invoked listener1, listener2, listener3 and listener4 +emitter2.emit('test'); // Invoked listener1, listener2, listener3 and listener4 +``` + +### Tests [![Build Status](https://travis-ci.org/medikoo/event-emitter.png)](https://travis-ci.org/medikoo/event-emitter) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/all-off.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/all-off.js new file mode 100644 index 00000000000000..829be65c22b293 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/all-off.js @@ -0,0 +1,19 @@ +'use strict'; + +var value = require('es5-ext/object/valid-object') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function (emitter/*, type*/) { + var type = arguments[1], data; + + value(emitter); + + if (type !== undefined) { + data = hasOwnProperty.call(emitter, '__ee__') && emitter.__ee__; + if (!data) return; + if (data[type]) delete data[type]; + return; + } + if (hasOwnProperty.call(emitter, '__ee__')) delete emitter.__ee__; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/benchmark/many-on.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/benchmark/many-on.js new file mode 100644 index 00000000000000..e09bfde8489386 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/benchmark/many-on.js @@ -0,0 +1,83 @@ +'use strict'; + +// Benchmark comparing performance of event emit for many listeners +// To run it, do following in memoizee package path: +// +// $ npm install eventemitter2 signals +// $ node benchmark/many-on.js + +var forEach = require('es5-ext/object/for-each') + , pad = require('es5-ext/string/#/pad') + + , now = Date.now + + , time, count = 1000000, i, data = {} + , ee, native, ee2, signals, a = {}, b = {}; + +ee = (function () { + var ee = require('../')(); + ee.on('test', function () { return arguments; }); + ee.on('test', function () { return arguments; }); + return ee.on('test', function () { return arguments; }); +}()); + +native = (function () { + var ee = require('events'); + ee = new ee.EventEmitter(); + ee.on('test', function () { return arguments; }); + ee.on('test', function () { return arguments; }); + return ee.on('test', function () { return arguments; }); +}()); + +ee2 = (function () { + var ee = require('eventemitter2'); + ee = new ee.EventEmitter2(); + ee.on('test', function () { return arguments; }); + ee.on('test', function () { return arguments; }); + return ee.on('test', function () { return arguments; }); +}()); + +signals = (function () { + var Signal = require('signals') + , ee = { test: new Signal() }; + ee.test.add(function () { return arguments; }); + ee.test.add(function () { return arguments; }); + ee.test.add(function () { return arguments; }); + return ee; +}()); + +console.log("Emit for 3 listeners", "x" + count + ":\n"); + +i = count; +time = now(); +while (i--) { + ee.emit('test', a, b); +} +data["event-emitter (this implementation)"] = now() - time; + +i = count; +time = now(); +while (i--) { + native.emit('test', a, b); +} +data["EventEmitter (Node.js native)"] = now() - time; + +i = count; +time = now(); +while (i--) { + ee2.emit('test', a, b); +} +data.EventEmitter2 = now() - time; + +i = count; +time = now(); +while (i--) { + signals.test.dispatch(a, b); +} +data.Signals = now() - time; + +forEach(data, function (value, name, obj, index) { + console.log(index + 1 + ":", pad.call(value, " ", 5), name); +}, null, function (a, b) { + return this[a] - this[b]; +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/benchmark/single-on.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/benchmark/single-on.js new file mode 100644 index 00000000000000..99decbdae72566 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/benchmark/single-on.js @@ -0,0 +1,73 @@ +'use strict'; + +// Benchmark comparing performance of event emit for single listener +// To run it, do following in memoizee package path: +// +// $ npm install eventemitter2 signals +// $ node benchmark/single-on.js + +var forEach = require('es5-ext/object/for-each') + , pad = require('es5-ext/string/#/pad') + + , now = Date.now + + , time, count = 1000000, i, data = {} + , ee, native, ee2, signals, a = {}, b = {}; + +ee = (function () { + var ee = require('../'); + return ee().on('test', function () { return arguments; }); +}()); + +native = (function () { + var ee = require('events'); + return (new ee.EventEmitter()).on('test', function () { return arguments; }); +}()); + +ee2 = (function () { + var ee = require('eventemitter2'); + return (new ee.EventEmitter2()).on('test', function () { return arguments; }); +}()); + +signals = (function () { + var Signal = require('signals') + , ee = { test: new Signal() }; + ee.test.add(function () { return arguments; }); + return ee; +}()); + +console.log("Emit for single listener", "x" + count + ":\n"); + +i = count; +time = now(); +while (i--) { + ee.emit('test', a, b); +} +data["event-emitter (this implementation)"] = now() - time; + +i = count; +time = now(); +while (i--) { + native.emit('test', a, b); +} +data["EventEmitter (Node.js native)"] = now() - time; + +i = count; +time = now(); +while (i--) { + ee2.emit('test', a, b); +} +data.EventEmitter2 = now() - time; + +i = count; +time = now(); +while (i--) { + signals.test.dispatch(a, b); +} +data.Signals = now() - time; + +forEach(data, function (value, name, obj, index) { + console.log(index + 1 + ":", pad.call(value, " ", 5), name); +}, null, function (a, b) { + return this[a] - this[b]; +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/has-listeners.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/has-listeners.js new file mode 100644 index 00000000000000..8744522e28c72a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/has-listeners.js @@ -0,0 +1,16 @@ +'use strict'; + +var isEmpty = require('es5-ext/object/is-empty') + , value = require('es5-ext/object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function (obj/*, type*/) { + var type; + value(obj); + type = arguments[1]; + if (arguments.length > 1) { + return hasOwnProperty.call(obj, '__ee__') && Boolean(obj.__ee__[type]); + } + return obj.hasOwnProperty('__ee__') && !isEmpty(obj.__ee__); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/index.js new file mode 100644 index 00000000000000..c36d3e49a2d562 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/index.js @@ -0,0 +1,132 @@ +'use strict'; + +var d = require('d') + , callable = require('es5-ext/object/valid-callable') + + , apply = Function.prototype.apply, call = Function.prototype.call + , create = Object.create, defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , hasOwnProperty = Object.prototype.hasOwnProperty + , descriptor = { configurable: true, enumerable: false, writable: true } + + , on, once, off, emit, methods, descriptors, base; + +on = function (type, listener) { + var data; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) { + data = descriptor.value = create(null); + defineProperty(this, '__ee__', descriptor); + descriptor.value = null; + } else { + data = this.__ee__; + } + if (!data[type]) data[type] = listener; + else if (typeof data[type] === 'object') data[type].push(listener); + else data[type] = [data[type], listener]; + + return this; +}; + +once = function (type, listener) { + var once, self; + + callable(listener); + self = this; + on.call(this, type, once = function () { + off.call(self, type, once); + apply.call(listener, this, arguments); + }); + + once.__eeOnceListener__ = listener; + return this; +}; + +off = function (type, listener) { + var data, listeners, candidate, i; + + callable(listener); + + if (!hasOwnProperty.call(this, '__ee__')) return this; + data = this.__ee__; + if (!data[type]) return this; + listeners = data[type]; + + if (typeof listeners === 'object') { + for (i = 0; (candidate = listeners[i]); ++i) { + if ((candidate === listener) || + (candidate.__eeOnceListener__ === listener)) { + if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; + else listeners.splice(i, 1); + } + } + } else { + if ((listeners === listener) || + (listeners.__eeOnceListener__ === listener)) { + delete data[type]; + } + } + + return this; +}; + +emit = function (type) { + var i, l, listener, listeners, args; + + if (!hasOwnProperty.call(this, '__ee__')) return; + listeners = this.__ee__[type]; + if (!listeners) return; + + if (typeof listeners === 'object') { + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + + listeners = listeners.slice(); + for (i = 0; (listener = listeners[i]); ++i) { + apply.call(listener, this, args); + } + } else { + switch (arguments.length) { + case 1: + call.call(listeners, this); + break; + case 2: + call.call(listeners, this, arguments[1]); + break; + case 3: + call.call(listeners, this, arguments[1], arguments[2]); + break; + default: + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + apply.call(listeners, this, args); + } + } +}; + +methods = { + on: on, + once: once, + off: off, + emit: emit +}; + +descriptors = { + on: d(on), + once: d(once), + off: d(off), + emit: d(emit) +}; + +base = defineProperties({}, descriptors); + +module.exports = exports = function (o) { + return (o == null) ? create(base) : defineProperties(Object(o), descriptors); +}; +exports.methods = methods; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/package.json new file mode 100644 index 00000000000000..17a904eabba836 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/package.json @@ -0,0 +1,64 @@ +{ + "name": "event-emitter", + "version": "0.3.3", + "description": "Environment agnostic event emitter", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "event", + "events", + "trigger", + "observer", + "listener", + "emitter", + "pubsub" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/event-emitter.git" + }, + "dependencies": { + "es5-ext": "~0.10.5", + "d": "~0.1.1" + }, + "devDependencies": { + "tad": "~0.2.1", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "13f184ab039e3559164691d3a6a3d6b8c84aed3e", + "bugs": { + "url": "https://github.com/medikoo/event-emitter/issues" + }, + "homepage": "https://github.com/medikoo/event-emitter", + "_id": "event-emitter@0.3.3", + "_shasum": "df8e806541c68ab8ff20a79a1841b91abaa1bee4", + "_from": "event-emitter@>=0.3.1 <0.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "df8e806541c68ab8ff20a79a1841b91abaa1bee4", + "tarball": "http://registry.npmjs.org/event-emitter/-/event-emitter-0.3.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/pipe.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/pipe.js new file mode 100644 index 00000000000000..0088efefa2e2c0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/pipe.js @@ -0,0 +1,42 @@ +'use strict'; + +var aFrom = require('es5-ext/array/from') + , remove = require('es5-ext/array/#/remove') + , value = require('es5-ext/object/valid-object') + , d = require('d') + , emit = require('./').methods.emit + + , defineProperty = Object.defineProperty + , hasOwnProperty = Object.prototype.hasOwnProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +module.exports = function (e1, e2/*, name*/) { + var pipes, pipe, desc, name; + + (value(e1) && value(e2)); + name = arguments[2]; + if (name === undefined) name = 'emit'; + + pipe = { + close: function () { remove.call(pipes, e2); } + }; + if (hasOwnProperty.call(e1, '__eePipes__')) { + (pipes = e1.__eePipes__).push(e2); + return pipe; + } + defineProperty(e1, '__eePipes__', d('c', pipes = [e2])); + desc = getOwnPropertyDescriptor(e1, name); + if (!desc) { + desc = d('c', undefined); + } else { + delete desc.get; + delete desc.set; + } + desc.value = function () { + var i, emitter, data = aFrom(pipes); + emit.apply(this, arguments); + for (i = 0; (emitter = data[i]); ++i) emit.apply(emitter, arguments); + }; + defineProperty(e1, name, desc); + return pipe; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/all-off.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/all-off.js new file mode 100644 index 00000000000000..8aa872e9c9478d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/all-off.js @@ -0,0 +1,48 @@ +'use strict'; + +var ee = require('../'); + +module.exports = function (t, a) { + var x, count, count2; + + x = ee(); + count = 0; + count2 = 0; + x.on('foo', function () { + ++count; + }); + x.on('foo', function () { + ++count; + }); + x.on('bar', function () { + ++count2; + }); + x.on('bar', function () { + ++count2; + }); + t(x, 'foo'); + x.emit('foo'); + x.emit('bar'); + a(count, 0, "All off: type"); + a(count2, 2, "All off: ohter type"); + + count = 0; + count2 = 0; + x.on('foo', function () { + ++count; + }); + x.on('foo', function () { + ++count; + }); + x.on('bar', function () { + ++count2; + }); + x.on('bar', function () { + ++count2; + }); + t(x); + x.emit('foo'); + x.emit('bar'); + a(count, 0, "All off: type"); + a(count2, 0, "All off: other type"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/has-listeners.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/has-listeners.js new file mode 100644 index 00000000000000..875b048a4193cb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/has-listeners.js @@ -0,0 +1,42 @@ +'use strict'; + +var ee = require('../'); + +module.exports = function (t) { + var x, y; + return { + Any: function (a) { + a(t(true), false, "Primitive"); + a(t({ events: [] }), false, "Other object"); + a(t(x = ee()), false, "Emitter: empty"); + + x.on('test', y = function () {}); + a(t(x), true, "Emitter: full"); + x.off('test', y); + a(t(x), false, "Emitter: empty but touched"); + x.once('test', y = function () {}); + a(t(x), true, "Emitter: full: Once"); + x.off('test', y); + a(t(x), false, "Emitter: empty but touched by once"); + }, + Specific: function (a) { + a(t(true, 'test'), false, "Primitive"); + a(t({ events: [] }, 'test'), false, "Other object"); + a(t(x = ee(), 'test'), false, "Emitter: empty"); + + x.on('test', y = function () {}); + a(t(x, 'test'), true, "Emitter: full"); + a(t(x, 'foo'), false, "Emitter: full, other event"); + x.off('test', y); + a(t(x, 'test'), false, "Emitter: empty but touched"); + a(t(x, 'foo'), false, "Emitter: empty but touched, other event"); + + x.once('test', y = function () {}); + a(t(x, 'test'), true, "Emitter: full: Once"); + a(t(x, 'foo'), false, "Emitter: full: Once, other event"); + x.off('test', y); + a(t(x, 'test'), false, "Emitter: empty but touched by once"); + a(t(x, 'foo'), false, "Emitter: empty but touched by once, other event"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/index.js new file mode 100644 index 00000000000000..c7c3f24c476862 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/index.js @@ -0,0 +1,107 @@ +'use strict'; + +module.exports = function (t, a) { + var x = t(), y, count, count2, count3, count4, test, listener1, listener2; + + x.emit('none'); + + test = "Once: "; + count = 0; + x.once('foo', function (a1, a2, a3) { + a(this, x, test + "Context"); + a.deep([a1, a2, a3], ['foo', x, 15], test + "Arguments"); + ++count; + }); + + x.emit('foobar'); + a(count, 0, test + "Not invoked on other event"); + x.emit('foo', 'foo', x, 15); + a(count, 1, test + "Emitted"); + x.emit('foo'); + a(count, 1, test + "Emitted once"); + + test = "On & Once: "; + count = 0; + x.on('foo', listener1 = function (a1, a2, a3) { + a(this, x, test + "Context"); + a.deep([a1, a2, a3], ['foo', x, 15], test + "Arguments"); + ++count; + }); + count2 = 0; + x.once('foo', listener2 = function (a1, a2, a3) { + a(this, x, test + "Context"); + a.deep([a1, a2, a3], ['foo', x, 15], test + "Arguments"); + ++count2; + }); + + x.emit('foobar'); + a(count, 0, test + "Not invoked on other event"); + x.emit('foo', 'foo', x, 15); + a(count, 1, test + "Emitted"); + x.emit('foo', 'foo', x, 15); + a(count, 2, test + "Emitted twice"); + a(count2, 1, test + "Emitted once"); + x.off('foo', listener1); + x.emit('foo'); + a(count, 2, test + "Not emitter after off"); + + count = 0; + x.once('foo', listener1 = function () { ++count; }); + + x.off('foo', listener1); + x.emit('foo'); + a(count, 0, "Once Off: Not emitted"); + + count = 0; + x.on('foo', listener2 = function () {}); + x.once('foo', listener1 = function () { ++count; }); + + x.off('foo', listener1); + x.emit('foo'); + a(count, 0, "Once Off (multi): Not emitted"); + x.off('foo', listener2); + + test = "Prototype Share: "; + + y = Object.create(x); + + count = 0; + count2 = 0; + count3 = 0; + count4 = 0; + x.on('foo', function () { + ++count; + }); + y.on('foo', function () { + ++count2; + }); + x.once('foo', function () { + ++count3; + }); + y.once('foo', function () { + ++count4; + }); + x.emit('foo'); + a(count, 1, test + "x on count"); + a(count2, 0, test + "y on count"); + a(count3, 1, test + "x once count"); + a(count4, 0, test + "y once count"); + + y.emit('foo'); + a(count, 1, test + "x on count"); + a(count2, 1, test + "y on count"); + a(count3, 1, test + "x once count"); + a(count4, 1, test + "y once count"); + + x.emit('foo'); + a(count, 2, test + "x on count"); + a(count2, 1, test + "y on count"); + a(count3, 1, test + "x once count"); + a(count4, 1, test + "y once count"); + + y.emit('foo'); + a(count, 2, test + "x on count"); + a(count2, 2, test + "y on count"); + a(count3, 1, test + "x once count"); + a(count4, 1, test + "y once count"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/pipe.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/pipe.js new file mode 100644 index 00000000000000..9d15d6dae308dc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/pipe.js @@ -0,0 +1,53 @@ +'use strict'; + +var ee = require('../'); + +module.exports = function (t, a) { + var x = {}, y = {}, z = {}, count, count2, count3, pipe; + + ee(x); + x = Object.create(x); + ee(y); + ee(z); + + count = 0; + count2 = 0; + count3 = 0; + x.on('foo', function () { + ++count; + }); + y.on('foo', function () { + ++count2; + }); + z.on('foo', function () { + ++count3; + }); + + x.emit('foo'); + a(count, 1, "Pre pipe, x"); + a(count2, 0, "Pre pipe, y"); + a(count3, 0, "Pre pipe, z"); + + pipe = t(x, y); + x.emit('foo'); + a(count, 2, "Post pipe, x"); + a(count2, 1, "Post pipe, y"); + a(count3, 0, "Post pipe, z"); + + y.emit('foo'); + a(count, 2, "Post pipe, on y, x"); + a(count2, 2, "Post pipe, on y, y"); + a(count3, 0, "Post pipe, on y, z"); + + t(x, z); + x.emit('foo'); + a(count, 3, "Post pipe z, x"); + a(count2, 3, "Post pipe z, y"); + a(count3, 1, "Post pipe z, z"); + + pipe.close(); + x.emit('foo'); + a(count, 4, "Close pipe y, x"); + a(count2, 3, "Close pipe y, y"); + a(count3, 2, "Close pipe y, z"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/unify.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/unify.js new file mode 100644 index 00000000000000..69295e0657ad50 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/test/unify.js @@ -0,0 +1,123 @@ +'use strict'; + +var ee = require('../'); + +module.exports = function (t) { + + return { + "": function (a) { + var x = {}, y = {}, z = {}, count, count2, count3; + + ee(x); + ee(y); + ee(z); + + count = 0; + count2 = 0; + count3 = 0; + x.on('foo', function () { ++count; }); + y.on('foo', function () { ++count2; }); + z.on('foo', function () { ++count3; }); + + x.emit('foo'); + a(count, 1, "Pre unify, x"); + a(count2, 0, "Pre unify, y"); + a(count3, 0, "Pre unify, z"); + + t(x, y); + a(x.__ee__, y.__ee__, "Post unify y"); + x.emit('foo'); + a(count, 2, "Post unify, x"); + a(count2, 1, "Post unify, y"); + a(count3, 0, "Post unify, z"); + + y.emit('foo'); + a(count, 3, "Post unify, on y, x"); + a(count2, 2, "Post unify, on y, y"); + a(count3, 0, "Post unify, on y, z"); + + t(x, z); + a(x.__ee__, x.__ee__, "Post unify z"); + x.emit('foo'); + a(count, 4, "Post unify z, x"); + a(count2, 3, "Post unify z, y"); + a(count3, 1, "Post unify z, z"); + }, + "On empty": function (a) { + var x = {}, y = {}, z = {}, count, count2, count3; + + ee(x); + ee(y); + ee(z); + + count = 0; + count2 = 0; + count3 = 0; + y.on('foo', function () { ++count2; }); + x.emit('foo'); + a(count, 0, "Pre unify, x"); + a(count2, 0, "Pre unify, y"); + a(count3, 0, "Pre unify, z"); + + t(x, y); + a(x.__ee__, y.__ee__, "Post unify y"); + x.on('foo', function () { ++count; }); + x.emit('foo'); + a(count, 1, "Post unify, x"); + a(count2, 1, "Post unify, y"); + a(count3, 0, "Post unify, z"); + + y.emit('foo'); + a(count, 2, "Post unify, on y, x"); + a(count2, 2, "Post unify, on y, y"); + a(count3, 0, "Post unify, on y, z"); + + t(x, z); + a(x.__ee__, z.__ee__, "Post unify z"); + z.on('foo', function () { ++count3; }); + x.emit('foo'); + a(count, 3, "Post unify z, x"); + a(count2, 3, "Post unify z, y"); + a(count3, 1, "Post unify z, z"); + }, + Many: function (a) { + var x = {}, y = {}, z = {}, count, count2, count3; + + ee(x); + ee(y); + ee(z); + + count = 0; + count2 = 0; + count3 = 0; + x.on('foo', function () { ++count; }); + y.on('foo', function () { ++count2; }); + y.on('foo', function () { ++count2; }); + z.on('foo', function () { ++count3; }); + + x.emit('foo'); + a(count, 1, "Pre unify, x"); + a(count2, 0, "Pre unify, y"); + a(count3, 0, "Pre unify, z"); + + t(x, y); + a(x.__ee__, y.__ee__, "Post unify y"); + x.emit('foo'); + a(count, 2, "Post unify, x"); + a(count2, 2, "Post unify, y"); + a(count3, 0, "Post unify, z"); + + y.emit('foo'); + a(count, 3, "Post unify, on y, x"); + a(count2, 4, "Post unify, on y, y"); + a(count3, 0, "Post unify, on y, z"); + + t(x, z); + a(x.__ee__, x.__ee__, "Post unify z"); + x.emit('foo'); + a(count, 4, "Post unify z, x"); + a(count2, 6, "Post unify z, y"); + a(count3, 1, "Post unify z, z"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/unify.js b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/unify.js new file mode 100644 index 00000000000000..c6a858a0be5df5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/node_modules/event-emitter/unify.js @@ -0,0 +1,50 @@ +'use strict'; + +var forEach = require('es5-ext/object/for-each') + , validValue = require('es5-ext/object/valid-object') + + , push = Array.prototype.apply, defineProperty = Object.defineProperty + , create = Object.create, hasOwnProperty = Object.prototype.hasOwnProperty + , d = { configurable: true, enumerable: false, writable: true }; + +module.exports = function (e1, e2) { + var data; + (validValue(e1) && validValue(e2)); + if (!hasOwnProperty.call(e1, '__ee__')) { + if (!hasOwnProperty.call(e2, '__ee__')) { + d.value = create(null); + defineProperty(e1, '__ee__', d); + defineProperty(e2, '__ee__', d); + d.value = null; + return; + } + d.value = e2.__ee__; + defineProperty(e1, '__ee__', d); + d.value = null; + return; + } + data = d.value = e1.__ee__; + if (!hasOwnProperty.call(e2, '__ee__')) { + defineProperty(e2, '__ee__', d); + d.value = null; + return; + } + if (data === e2.__ee__) return; + forEach(e2.__ee__, function (listener, name) { + if (!data[name]) { + data[name] = listener; + return; + } + if (typeof data[name] === 'object') { + if (typeof listener === 'object') push.apply(data[name], listener); + else data[name].push(listener); + } else if (typeof listener === 'object') { + listener.unshift(data[name]); + data[name] = listener; + } else { + data[name] = [data[name], listener]; + } + }); + defineProperty(e2, '__ee__', d); + d.value = null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/package.json b/tools/eslint/node_modules/escope/node_modules/es6-map/package.json new file mode 100644 index 00000000000000..51b50e23531fdb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/package.json @@ -0,0 +1,70 @@ +{ + "name": "es6-map", + "version": "0.1.1", + "description": "ECMAScript6 Map polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "collection", + "es6", + "shim", + "harmony", + "list", + "hash", + "map", + "polyfill", + "ecmascript" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-map.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.4", + "es6-iterator": "~0.1.1", + "es6-set": "~0.1.1", + "es6-symbol": "~0.1.1", + "event-emitter": "~0.3.1" + }, + "devDependencies": { + "tad": "0.2.x", + "xlint": "~0.2.1", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "16b0bce8defe9742a40b9cac1eed194ee4e2d820", + "bugs": { + "url": "https://github.com/medikoo/es6-map/issues" + }, + "homepage": "https://github.com/medikoo/es6-map", + "_id": "es6-map@0.1.1", + "_shasum": "b879239ed7819e0b08c40ba6e19fa047ca7c8d1d", + "_from": "es6-map@>=0.1.1 <0.2.0", + "_npmVersion": "2.0.0", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "b879239ed7819e0b08c40ba6e19fa047ca7c8d1d", + "tarball": "http://registry.npmjs.org/es6-map/-/es6-map-0.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-map/-/es6-map-0.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/polyfill.js new file mode 100644 index 00000000000000..fc44527f54d869 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/polyfill.js @@ -0,0 +1,100 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , eIndexOf = require('es5-ext/array/#/e-index-of') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , callable = require('es5-ext/object/valid-callable') + , validValue = require('es5-ext/object/valid-value') + , d = require('d') + , ee = require('event-emitter') + , Symbol = require('es6-symbol') + , iterator = require('es6-iterator/valid-iterable') + , forOf = require('es6-iterator/for-of') + , Iterator = require('./lib/iterator') + , isNative = require('./is-native-implemented') + + , call = Function.prototype.call, defineProperties = Object.defineProperties + , MapPoly; + +module.exports = MapPoly = function (/*iterable*/) { + var iterable = arguments[0], keys, values; + if (!(this instanceof MapPoly)) return new MapPoly(iterable); + if (this.__mapKeysData__ !== undefined) { + throw new TypeError(this + " cannot be reinitialized"); + } + if (iterable != null) iterator(iterable); + defineProperties(this, { + __mapKeysData__: d('c', keys = []), + __mapValuesData__: d('c', values = []) + }); + if (!iterable) return; + forOf(iterable, function (value) { + var key = validValue(value)[0]; + value = value[1]; + if (eIndexOf.call(keys, key) !== -1) return; + keys.push(key); + values.push(value); + }, this); +}; + +if (isNative) { + if (setPrototypeOf) setPrototypeOf(MapPoly, Map); + MapPoly.prototype = Object.create(Map.prototype, { + constructor: d(MapPoly) + }); +} + +ee(defineProperties(MapPoly.prototype, { + clear: d(function () { + if (!this.__mapKeysData__.length) return; + clear.call(this.__mapKeysData__); + clear.call(this.__mapValuesData__); + this.emit('_clear'); + }), + delete: d(function (key) { + var index = eIndexOf.call(this.__mapKeysData__, key); + if (index === -1) return false; + this.__mapKeysData__.splice(index, 1); + this.__mapValuesData__.splice(index, 1); + this.emit('_delete', index, key); + return true; + }), + entries: d(function () { return new Iterator(this, 'key+value'); }), + forEach: d(function (cb/*, thisArg*/) { + var thisArg = arguments[1], iterator, result; + callable(cb); + iterator = this.entries(); + result = iterator._next(); + while (result !== undefined) { + call.call(cb, thisArg, this.__mapValuesData__[result], + this.__mapKeysData__[result], this); + result = iterator._next(); + } + }), + get: d(function (key) { + var index = eIndexOf.call(this.__mapKeysData__, key); + if (index === -1) return; + return this.__mapValuesData__[index]; + }), + has: d(function (key) { + return (eIndexOf.call(this.__mapKeysData__, key) !== -1); + }), + keys: d(function () { return new Iterator(this, 'key'); }), + set: d(function (key, value) { + var index = eIndexOf.call(this.__mapKeysData__, key), emit; + if (index === -1) { + index = this.__mapKeysData__.push(key) - 1; + emit = true; + } + this.__mapValuesData__[index] = value; + if (emit) this.emit('_add', index, key); + return this; + }), + size: d.gs(function () { return this.__mapKeysData__.length; }), + values: d(function () { return new Iterator(this, 'value'); }), + toString: d(function () { return '[object Map]'; }) +})); +Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { + return this.entries(); +})); +Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/primitive/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/primitive/index.js new file mode 100644 index 00000000000000..425d48265aa0f8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/primitive/index.js @@ -0,0 +1,115 @@ +'use strict'; + +var clear = require('es5-ext/object/clear') + , setPrototypeOf = require('es5-ext/object/set-prototype-of') + , validValue = require('es5-ext/object/valid-value') + , callable = require('es5-ext/object/valid-callable') + , d = require('d') + , iterator = require('es6-iterator/valid-iterable') + , forOf = require('es6-iterator/for-of') + , Map = require('../polyfill') + , Iterator = require('../lib/primitive-iterator') + + , call = Function.prototype.call + , defineProperty = Object.defineProperty + , create = Object.create, defineProperties = Object.defineProperties + , hasOwnProperty = Object.prototype.hasOwnProperty + , PrimitiveMap; + +module.exports = PrimitiveMap = function (/*iterable, serialize*/) { + var iterable = arguments[0], serialize = arguments[1]; + if (!(this instanceof PrimitiveMap)) { + return new PrimitiveMap(iterable, serialize); + } + if (this.__mapData__ !== undefined) { + throw new TypeError(this + " cannot be reinitialized"); + } + if (iterable != null) iterator(iterable); + if (serialize !== undefined) { + callable(serialize); + defineProperty(this, '_serialize', d('', serialize)); + } + defineProperties(this, { + __mapKeysData__: d('c', create(null)), + __mapValuesData__: d('c', create(null)), + __size__: d('w', 0) + }); + if (!iterable) return; + forOf(iterable, function (value) { + var key = validValue(value)[0], sKey = this._serialize(key); + if (sKey == null) throw new TypeError(key + " cannot be serialized"); + value = value[1]; + if (hasOwnProperty.call(this.__mapKeysData__, sKey)) { + if (this.__mapValuesData__[sKey] === value) return; + } else { + ++this.__size__; + } + this.__mapKeysData__[sKey] = key; + this.__mapValuesData__[sKey] = value; + }, this); +}; +if (setPrototypeOf) setPrototypeOf(PrimitiveMap, Map); + +PrimitiveMap.prototype = create(Map.prototype, { + constructor: d(PrimitiveMap), + _serialize: d(function (value) { + if (value && (typeof value.toString !== 'function')) return null; + return String(value); + }), + clear: d(function () { + if (!this.__size__) return; + clear(this.__mapKeysData__); + clear(this.__mapValuesData__); + this.__size__ = 0; + this.emit('_clear'); + }), + delete: d(function (key) { + var sKey = this._serialize(key); + if (sKey == null) return false; + if (!hasOwnProperty.call(this.__mapKeysData__, sKey)) return false; + delete this.__mapKeysData__[sKey]; + delete this.__mapValuesData__[sKey]; + --this.__size__; + this.emit('_delete', sKey); + return true; + }), + entries: d(function () { return new Iterator(this, 'key+value'); }), + forEach: d(function (cb/*, thisArg*/) { + var thisArg = arguments[1], iterator, result, sKey; + callable(cb); + iterator = this.entries(); + result = iterator._next(); + while (result !== undefined) { + sKey = iterator.__list__[result]; + call.call(cb, thisArg, this.__mapValuesData__[sKey], + this.__mapKeysData__[sKey], this); + result = iterator._next(); + } + }), + get: d(function (key) { + var sKey = this._serialize(key); + if (sKey == null) return; + return this.__mapValuesData__[sKey]; + }), + has: d(function (key) { + var sKey = this._serialize(key); + if (sKey == null) return false; + return hasOwnProperty.call(this.__mapKeysData__, sKey); + }), + keys: d(function () { return new Iterator(this, 'key'); }), + size: d.gs(function () { return this.__size__; }), + set: d(function (key, value) { + var sKey = this._serialize(key); + if (sKey == null) throw new TypeError(key + " cannot be serialized"); + if (hasOwnProperty.call(this.__mapKeysData__, sKey)) { + if (this.__mapValuesData__[sKey] === value) return this; + } else { + ++this.__size__; + } + this.__mapKeysData__[sKey] = key; + this.__mapValuesData__[sKey] = value; + this.emit('_add', sKey); + return this; + }), + values: d(function () { return new Iterator(this, 'value'); }) +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/implement.js new file mode 100644 index 00000000000000..3569df61d221ff --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof Map, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/index.js new file mode 100644 index 00000000000000..907b8c5a7bb2e7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (T, a) { + a((new T([['raz', 1], ['dwa', 2]])).size, 2); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-implemented.js new file mode 100644 index 00000000000000..06df91cc529c02 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +var global = require('es5-ext/global') + , polyfill = require('../polyfill'); + +module.exports = function (t, a) { + var cache; + a(typeof t(), 'boolean'); + cache = global.Map; + global.Map = polyfill; + a(t(), true); + if (cache === undefined) delete global.Map; + else global.Map = cache; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-map.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-map.js new file mode 100644 index 00000000000000..f600b2298b8e7a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-map.js @@ -0,0 +1,16 @@ +'use strict'; + +var MapPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof Map !== 'undefined') { + a(t(new Map()), true, "Native"); + } + a(t(new MapPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/iterator-kinds.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/iterator-kinds.js new file mode 100644 index 00000000000000..41ea10c57deffc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/iterator-kinds.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t, { key: true, value: true, 'key+value': true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/iterator.js new file mode 100644 index 00000000000000..2688ed26cb7a73 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/iterator.js @@ -0,0 +1,13 @@ +'use strict'; + +var Map = require('../../polyfill') + , toArray = require('es5-ext/array/to-array'); + +module.exports = function (T, a) { + var arr = [['raz', 'one'], ['dwa', 'two']], map = new Map(arr); + + a.deep(toArray(new T(map)), arr, "Default"); + a.deep(toArray(new T(map, 'key+value')), arr, "Key & Value"); + a.deep(toArray(new T(map, 'value')), ['one', 'two'], "Value"); + a.deep(toArray(new T(map, 'key')), ['raz', 'dwa'], "Value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/primitive-iterator.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/primitive-iterator.js new file mode 100644 index 00000000000000..ed2790de9b5cc6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/lib/primitive-iterator.js @@ -0,0 +1,130 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , toArray = require('es5-ext/array/to-array') + , Map = require('../../primitive') + + , compare, mapToResults; + +compare = function (a, b) { + if (!a.value) return -1; + if (!b.value) return 1; + return a.value[0].localeCompare(b.value[0]); +}; + +mapToResults = function (arr) { + return arr.sort().map(function (value) { + return { done: false, value: value }; + }); +}; + +module.exports = function (T) { + return { + "": function (a) { + var arr, it, y, z, map, result = []; + + arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three'], + ['cztery', 'four'], ['pięć', 'five']]; + map = new Map(arr); + + it = new T(map); + a(it[iteratorSymbol](), it, "@@iterator"); + y = it.next(); + result.push(y); + z = it.next(); + a.not(y, z, "Recreate result"); + result.push(z); + result.push(it.next()); + result.push(it.next()); + result.push(it.next()); + a.deep(result.sort(compare), mapToResults(arr)); + a.deep(y = it.next(), { done: true, value: undefined }, "End"); + a.not(y, it.next(), "Recreate result on dead"); + }, + Emited: function (a) { + var arr, it, map, result = []; + + arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three'], + ['cztery', 'four'], ['pięć', 'five']]; + map = new Map(arr); + + it = new T(map); + result.push(it.next()); + result.push(it.next()); + map.set('sześć', 'six'); + arr.push(['sześć', 'six']); + result.push(it.next()); + map.delete('pięć'); + arr.splice(4, 1); + result.push(it.next()); + result.push(it.next()); + a.deep(result.sort(compare), mapToResults(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited #2": function (a) { + var arr, it, map, result = []; + + arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three'], + ['cztery', 'four'], ['pięć', 'five'], ['sześć', 'six']]; + map = new Map(arr); + + it = new T(map); + result.push(it.next()); + result.push(it.next()); + map.set('siedem', 'seven'); + map.delete('siedem'); + result.push(it.next()); + result.push(it.next()); + map.delete('pięć'); + arr.splice(4, 1); + result.push(it.next()); + a.deep(result.sort(compare), mapToResults(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #1": function (a) { + var arr, it, map, result = []; + + arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three'], + ['cztery', 'four'], ['pięć', 'five'], ['sześć', 'six']]; + map = new Map(arr); + + it = new T(map); + result.push(it.next()); + result.push(it.next()); + arr = [['raz', 'one'], ['dwa', 'two']]; + map.clear(); + a.deep(result.sort(compare), mapToResults(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #2": function (a) { + var arr, it, map, result = []; + + arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three'], + ['cztery', 'four'], ['pięć', 'five'], ['sześć', 'six']]; + map = new Map(arr); + + it = new T(map); + result.push(it.next()); + result.push(it.next()); + map.clear(); + map.set('foo', 'bru'); + map.set('bar', 'far'); + arr = [['raz', 'one'], ['dwa', 'two'], ['foo', 'bru'], ['bar', 'far']]; + result.push(it.next()); + result.push(it.next()); + a.deep(result.sort(compare), mapToResults(arr)); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + Kinds: function (a) { + var arr = [['raz', 'one'], ['dwa', 'two']], map = new Map(arr); + + a.deep(toArray(new T(map)).sort(), arr.sort(), "Default"); + a.deep(toArray(new T(map, 'key+value')).sort(), arr.sort(), + "Key + Value"); + a.deep(toArray(new T(map, 'value')).sort(), ['one', 'two'].sort(), + "Value"); + a.deep(toArray(new T(map, 'key')).sort(), ['raz', 'dwa'].sort(), + "Key"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/polyfill.js new file mode 100644 index 00000000000000..6640e359dec76a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/polyfill.js @@ -0,0 +1,54 @@ +'use strict'; + +var aFrom = require('es5-ext/array/from') + , toArray = require('es5-ext/array/to-array'); + +module.exports = function (T, a) { + var arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']] + , map = new T(arr), x = {}, y = {}, i = 0; + + a(map instanceof T, true, "Map"); + a(map.size, 3, "Size"); + a(map.get('raz'), 'one', "Get: contained"); + a(map.get(x), undefined, "Get: not contained"); + a(map.has('raz'), true, "Has: contained"); + a(map.has(x), false, "Has: not contained"); + a(map.set(x, y), map, "Set: return"); + a(map.has(x), true, "Set: has"); + a(map.get(x), y, "Set: get"); + a(map.size, 4, "Set: Size"); + map.set('dwa', x); + a(map.get('dwa'), x, "Overwrite: get"); + a(map.size, 4, "Overwrite: size"); + + a(map.delete({}), false, "Delete: false"); + + arr.push([x, y]); + arr[1][1] = x; + map.forEach(function () { + a.deep(aFrom(arguments), [arr[i][1], arr[i][0], map], + "ForEach: Arguments: #" + i); + a(this, y, "ForEach: Context: #" + i); + if (i === 0) { + a(map.delete('raz'), true, "Delete: true"); + a(map.has('raz'), false, "Delete"); + a(map.size, 3, "Delete: size"); + map.set('cztery', 'four'); + arr.push(['cztery', 'four']); + } + i++; + }, y); + arr.splice(0, 1); + + a.deep(toArray(map.entries()), [['dwa', x], ['trzy', 'three'], [x, y], + ['cztery', 'four']], "Entries"); + a.deep(toArray(map.keys()), ['dwa', 'trzy', x, 'cztery'], "Keys"); + a.deep(toArray(map.values()), [x, 'three', y, 'four'], "Values"); + a.deep(toArray(map), [['dwa', x], ['trzy', 'three'], [x, y], + ['cztery', 'four']], "Iterator"); + + map.clear(); + a(map.size, 0, "Clear: size"); + a(map.has('trzy'), false, "Clear: has"); + a.deep(toArray(map), [], "Clear: Values"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/primitive/index.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/primitive/index.js new file mode 100644 index 00000000000000..1167d2ebdfb8d4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/primitive/index.js @@ -0,0 +1,53 @@ +'use strict'; + +var aFrom = require('es5-ext/array/from') + , getIterator = require('es6-iterator/get') + , toArray = require('es5-ext/array/to-array'); + +module.exports = function (T, a) { + var arr = [['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']] + , map = new T(arr), x = 'other', y = 'other2' + , i = 0, result = []; + + a(map instanceof T, true, "Map"); + a(map.size, 3, "Size"); + a(map.get('raz'), 'one', "Get: contained"); + a(map.get(x), undefined, "Get: not contained"); + a(map.has('raz'), true, "Has: true"); + a(map.has(x), false, "Has: false"); + a(map.set(x, y), map, "Add: return"); + a(map.has(x), true, "Add"); + a(map.size, 4, "Add: Size"); + map.set('dwa', x); + a(map.get('dwa'), x, "Overwrite: get"); + a(map.size, 4, "Overwrite: size"); + + a(map.delete('else'), false, "Delete: false"); + + arr.push([x, y]); + arr[1][1] = x; + map.forEach(function () { + result.push(aFrom(arguments)); + a(this, y, "ForEach: Context: #" + i); + }, y); + + a.deep(result.sort(function (a, b) { + return String([a[1], a[0]]).localeCompare([b[1], b[0]]); + }), arr.sort().map(function (val) { return [val[1], val[0], map]; }), + "ForEach: Arguments"); + + a.deep(toArray(map.entries()).sort(), [['dwa', x], ['trzy', 'three'], + [x, y], ['raz', 'one']].sort(), "Entries"); + a.deep(toArray(map.keys()).sort(), ['dwa', 'trzy', x, 'raz'].sort(), + "Keys"); + a.deep(toArray(map.values()).sort(), [x, 'three', y, 'one'].sort(), + "Values"); + a.deep(toArray(getIterator(map)).sort(), [['dwa', x], ['trzy', 'three'], + [x, y], ['raz', 'one']].sort(), + "Iterator"); + + map.clear(); + a(map.size, 0, "Clear: size"); + a(map.has('trzy'), false, "Clear: has"); + a.deep(toArray(map.values()), [], "Clear: Values"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/test/valid-map.js b/tools/eslint/node_modules/escope/node_modules/es6-map/test/valid-map.js new file mode 100644 index 00000000000000..ac0314949a3009 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/test/valid-map.js @@ -0,0 +1,19 @@ +'use strict'; + +var MapPoly = require('../polyfill'); + +module.exports = function (t, a) { + var map; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof Map !== 'undefined') { + map = new Map(); + a(t(map), map, "Native"); + } + map = new MapPoly(); + a(t(map), map, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-map/valid-map.js b/tools/eslint/node_modules/escope/node_modules/es6-map/valid-map.js new file mode 100644 index 00000000000000..e2aca87a4544a8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-map/valid-map.js @@ -0,0 +1,8 @@ +'use strict'; + +var isMap = require('./is-map'); + +module.exports = function (x) { + if (!isMap(x)) throw new TypeError(x + " is not a Map"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.lint b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.lint new file mode 100644 index 00000000000000..cf54d815684b2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.lint @@ -0,0 +1,11 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.travis.yml new file mode 100644 index 00000000000000..08f04a1b297e57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/.travis.yml @@ -0,0 +1,10 @@ +sudo: false # use faster docker infrastructure +language: node_js +node_js: + - 0.10 + - 0.12 + - iojs + +notifications: + email: + - medikoo+es6-weak-map@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/CHANGES new file mode 100644 index 00000000000000..33944088485291 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/CHANGES @@ -0,0 +1,24 @@ +v0.1.4 -- 2015.04.13 +* Republish v0.1.2 as v0.1.4 due to breaking changes + (v0.1.3 should have been published as next major) + +v0.1.3 -- 2015.04.12 +* Update up to changes in specification (require new, remove clear method) +* Improve native implementation validation +* Configure lint scripts +* Rename LICENCE to LICENSE + +v0.1.2 -- 2014.09.01 +* Use internal random and unique id generator instead of external (time-uuid based). + Global uniqueness is not needed in scope of this module. Fixes #1 + +v0.1.1 -- 2014.05.15 +* Improve valid WeakMap detection + +v0.1.0 -- 2014.04.29 +* Assure to depend only npm hosted dependencies +* Update to use latest versions of dependencies +* Use ES6 symbols internally + +v0.0.0 -- 2013.10.24 +Initial (dev version) diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/LICENCE b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/LICENCE new file mode 100644 index 00000000000000..aaf35282f41f57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/LICENCE @@ -0,0 +1,19 @@ +Copyright (C) 2013 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/README.md b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/README.md new file mode 100644 index 00000000000000..dd91b469a4249e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/README.md @@ -0,0 +1,65 @@ +# es6-weak-map +## WeakMap collection as specified in ECMAScript6 + +_Roughly inspired by Mark Miller's and Kris Kowal's [WeakMap implementation](https://github.com/drses/weak-map)_. + +Differences are: +- Assumes compliant ES5 environment (no weird ES3 workarounds or hacks) +- Well modularized CJS style +- Based on one solution. + +### Limitations + +- Will fail on non extensible objects provided as keys +- While `clear` method is provided, it's not perfectly spec compliant. If some objects were saved as _values_, they need to be removed via `delete`. Otherwise they'll remain infinitely attached to _key_ object (that means, they'll be free for GC only if _key_ object was collected as well). + +### Installation + + $ npm install es6-weak-map + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +### Usage + +If you want to make sure your environment implements `WeakMap`, do: + +```javascript +require('es6-weak-map/implement'); +``` + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't, but without implementing `WeakMap` on global scope, do: + +```javascript +var WeakMap = require('es6-weak-map'); +``` + +If you strictly want to use polyfill even if native `WeakMap` exists, do: + +```javascript +var WeakMap = require('es6-weak-map/polyfill'); +``` + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-weakmap-objects). Still if you want quick look, follow example: + +```javascript +var WeakMap = require('es6-weak-map'); + +var map = new WeakMap(); +var obj = {}; + +map.set(obj, 'foo'); // map +map.get(obj); // 'foo' +map.has(obj); // true +map.delete(obj); // true +map.get(obj); // undefined +map.has(obj); // false +map.set(obj, 'bar'); // map +map.clear(); // undefined +map.has(obj); // false +``` + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-weak-map.png)](https://travis-ci.org/medikoo/es6-weak-map) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/implement.js new file mode 100644 index 00000000000000..6c3f306b9d5f43 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'WeakMap', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/index.js new file mode 100644 index 00000000000000..5edc4cc8fb5730 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + WeakMap : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-implemented.js new file mode 100644 index 00000000000000..455ff812522e34 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function () { + var map; + if (typeof WeakMap !== 'function') return false; + map = new WeakMap(); + if (typeof map.set !== 'function') return false; + if (map.set({}, 1) !== map) return false; + if (typeof map.clear !== 'function') return false; + if (typeof map.delete !== 'function') return false; + if (typeof map.has !== 'function') return false; + + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-native-implemented.js new file mode 100644 index 00000000000000..b3fe5a594d253e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-native-implemented.js @@ -0,0 +1,10 @@ +// Exports true if environment provides native `WeakMap` implementation, +// whatever that is. + +'use strict'; + +module.exports = (function () { + if (typeof WeakMap === 'undefined') return false; + return (Object.prototype.toString.call(WeakMap.prototype) === + '[object WeakMap]'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-weak-map.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-weak-map.js new file mode 100644 index 00000000000000..10bb2a156183a3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/is-weak-map.js @@ -0,0 +1,13 @@ +'use strict'; + +var toStringTagSymbol = require('es6-symbol').toStringTag + + , toString = Object.prototype.toString + , id = '[object WeakMap]' + , Global = (typeof WeakMap === 'undefined') ? null : WeakMap; + +module.exports = function (x) { + return (x && ((Global && (x instanceof Global)) || + (toString.call(x) === id) || (x[toStringTagSymbol] === 'WeakMap'))) || + false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.lint b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.lint new file mode 100644 index 00000000000000..858b75353b331c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.lint @@ -0,0 +1,12 @@ +@root + +es5 +module + +tabs +indent 2 +maxlen 80 + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.travis.yml new file mode 100644 index 00000000000000..50008b23e6bcb9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+d@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/CHANGES new file mode 100644 index 00000000000000..45233f747eca72 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/CHANGES @@ -0,0 +1,7 @@ +v0.1.1 -- 2014.04.24 +- Add `autoBind` and `lazy` utilities +- Allow to pass other options to be merged onto created descriptor. + Useful when used with other custom utilties + +v0.1.0 -- 2013.06.20 +Initial (derived from es5-ext project) diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/LICENCE b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/LICENCE new file mode 100644 index 00000000000000..aaf35282f41f57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/LICENCE @@ -0,0 +1,19 @@ +Copyright (C) 2013 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/README.md b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/README.md new file mode 100644 index 00000000000000..872d493ed86b6b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/README.md @@ -0,0 +1,108 @@ +# D - Property descriptor factory + +_Originally derived from [es5-ext](https://github.com/medikoo/es5-ext) package._ + +Defining properties with descriptors is very verbose: + +```javascript +var Account = function () {}; +Object.defineProperties(Account.prototype, { + deposit: { value: function () { + /* ... */ + }, configurable: true, enumerable: false, writable: true }, + whithdraw: { value: function () { + /* ... */ + }, configurable: true, enumerable: false, writable: true }, + balance: { get: function () { + /* ... */ + }, configurable: true, enumerable: false } +}); +``` + +D cuts that to: + +```javascript +var d = require('d'); + +var Account = function () {}; +Object.defineProperties(Account.prototype, { + deposit: d(function () { + /* ... */ + }), + whithdraw: d(function () { + /* ... */ + }), + balance: d.gs(function () { + /* ... */ + }) +}); +``` + +By default, created descriptor follow characteristics of native ES5 properties, and defines values as: + +```javascript +{ configurable: true, enumerable: false, writable: true } +``` + +You can overwrite it by preceding _value_ argument with instruction: +```javascript +d('c', value); // { configurable: true, enumerable: false, writable: false } +d('ce', value); // { configurable: true, enumerable: true, writable: false } +d('e', value); // { configurable: false, enumerable: true, writable: false } + +// Same way for get/set: +d.gs('e', value); // { configurable: false, enumerable: true } +``` + +### Other utilities + +#### autoBind(obj, props) _(d/auto-bind)_ + +Define methods which will be automatically bound to its instances + +```javascript +var d = require('d'); +var autoBind = require('d/auto-bind'); + +var Foo = function () { this._count = 0; }; +autoBind(Foo.prototype, { + increment: d(function () { ++this._count; }); +}); + +var foo = new Foo(); + +// Increment foo counter on each domEl click +domEl.addEventListener('click', foo.increment, false); +``` + +#### lazy(obj, props) _(d/lazy)_ + +Define lazy properties, which will be resolved on first access + +```javascript +var d = require('d'); +var lazy = require('d/lazy'); + +var Foo = function () {}; +lazy(Foo.prototype, { + items: d(function () { return []; }) +}); + +var foo = new Foo(); +foo.items.push(1, 2); // foo.items array created +``` + +## Installation +### NPM + +In your project path: + + $ npm install d + +### Browser + +You can easily bundle _D_ for browser with [modules-webmake](https://github.com/medikoo/modules-webmake) + +## Tests [![Build Status](https://travis-ci.org/medikoo/d.png)](https://travis-ci.org/medikoo/d) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/auto-bind.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/auto-bind.js new file mode 100644 index 00000000000000..1b00dba3cc3ddf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/auto-bind.js @@ -0,0 +1,31 @@ +'use strict'; + +var copy = require('es5-ext/object/copy') + , map = require('es5-ext/object/map') + , callable = require('es5-ext/object/valid-callable') + , validValue = require('es5-ext/object/valid-value') + + , bind = Function.prototype.bind, defineProperty = Object.defineProperty + , hasOwnProperty = Object.prototype.hasOwnProperty + , define; + +define = function (name, desc, bindTo) { + var value = validValue(desc) && callable(desc.value), dgs; + dgs = copy(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function () { + if (hasOwnProperty.call(this, name)) return value; + desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); + defineProperty(this, name, desc); + return this[name]; + }; + return dgs; +}; + +module.exports = function (props/*, bindTo*/) { + var bindTo = arguments[1]; + return map(props, function (desc, name) { + return define(name, desc, bindTo); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/index.js new file mode 100644 index 00000000000000..076ae465f60c4b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/index.js @@ -0,0 +1,63 @@ +'use strict'; + +var assign = require('es5-ext/object/assign') + , normalizeOpts = require('es5-ext/object/normalize-options') + , isCallable = require('es5-ext/object/is-callable') + , contains = require('es5-ext/string/#/contains') + + , d; + +d = module.exports = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + w = contains.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!isCallable(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!isCallable(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = contains.call(dscr, 'c'); + e = contains.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : assign(normalizeOpts(options), desc); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/lazy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/lazy.js new file mode 100644 index 00000000000000..61e466535f3dab --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/lazy.js @@ -0,0 +1,111 @@ +'use strict'; + +var map = require('es5-ext/object/map') + , isCallable = require('es5-ext/object/is-callable') + , validValue = require('es5-ext/object/valid-value') + , contains = require('es5-ext/string/#/contains') + + , call = Function.prototype.call + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getPrototypeOf = Object.getPrototypeOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , cacheDesc = { configurable: false, enumerable: false, writable: false, + value: null } + , define; + +define = function (name, options) { + var value, dgs, cacheName, desc, writable = false, resolvable + , flat; + options = Object(validValue(options)); + cacheName = options.cacheName; + flat = options.flat; + if (cacheName == null) cacheName = name; + delete options.cacheName; + value = options.value; + resolvable = isCallable(value); + delete options.value; + dgs = { configurable: Boolean(options.configurable), + enumerable: Boolean(options.enumerable) }; + if (name !== cacheName) { + dgs.get = function () { + if (hasOwnProperty.call(this, cacheName)) return this[cacheName]; + cacheDesc.value = resolvable ? call.call(value, this, options) : value; + cacheDesc.writable = writable; + defineProperty(this, cacheName, cacheDesc); + cacheDesc.value = null; + if (desc) defineProperty(this, name, desc); + return this[cacheName]; + }; + } else if (!flat) { + dgs.get = function self() { + var ownDesc; + if (hasOwnProperty.call(this, name)) { + ownDesc = getOwnPropertyDescriptor(this, name); + // It happens in Safari, that getter is still called after property + // was defined with a value, following workarounds that + if (ownDesc.hasOwnProperty('value')) return ownDesc.value; + if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) { + return ownDesc.get.call(this); + } + return value; + } + desc.value = resolvable ? call.call(value, this, options) : value; + defineProperty(this, name, desc); + desc.value = null; + return this[name]; + }; + } else { + dgs.get = function self() { + var base = this, ownDesc; + if (hasOwnProperty.call(this, name)) { + // It happens in Safari, that getter is still called after property + // was defined with a value, following workarounds that + ownDesc = getOwnPropertyDescriptor(this, name); + if (ownDesc.hasOwnProperty('value')) return ownDesc.value; + if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) { + return ownDesc.get.call(this); + } + } + while (!hasOwnProperty.call(base, name)) base = getPrototypeOf(base); + desc.value = resolvable ? call.call(value, base, options) : value; + defineProperty(base, name, desc); + desc.value = null; + return base[name]; + }; + } + dgs.set = function (value) { + dgs.get.call(this); + this[cacheName] = value; + }; + if (options.desc) { + desc = { + configurable: contains.call(options.desc, 'c'), + enumerable: contains.call(options.desc, 'e') + }; + if (cacheName === name) { + desc.writable = contains.call(options.desc, 'w'); + desc.value = null; + } else { + writable = contains.call(options.desc, 'w'); + desc.get = dgs.get; + desc.set = dgs.set; + } + delete options.desc; + } else if (cacheName === name) { + desc = { + configurable: Boolean(options.configurable), + enumerable: Boolean(options.enumerable), + writable: Boolean(options.writable), + value: null + }; + } + delete options.configurable; + delete options.enumerable; + delete options.writable; + return dgs; +}; + +module.exports = function (props) { + return map(props, function (desc, name) { return define(name, desc); }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/package.json b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/package.json new file mode 100644 index 00000000000000..03d81db13be8d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/package.json @@ -0,0 +1,59 @@ +{ + "name": "d", + "version": "0.1.1", + "description": "Property descriptor factory", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "scripts": { + "test": "node node_modules/tad/bin/tad" + }, + "repository": { + "type": "git", + "url": "git://github.com/medikoo/d.git" + }, + "keywords": [ + "descriptor", + "es", + "ecmascript", + "ecma", + "property", + "descriptors", + "meta", + "properties" + ], + "dependencies": { + "es5-ext": "~0.10.2" + }, + "devDependencies": { + "tad": "~0.1.21" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/medikoo/d/issues" + }, + "homepage": "https://github.com/medikoo/d", + "_id": "d@0.1.1", + "dist": { + "shasum": "da184c535d18d8ee7ba2aa229b914009fae11309", + "tarball": "http://registry.npmjs.org/d/-/d-0.1.1.tgz" + }, + "_from": "d@>=0.1.1 <0.2.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "directories": {}, + "_shasum": "da184c535d18d8ee7ba2aa229b914009fae11309", + "_resolved": "https://registry.npmjs.org/d/-/d-0.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/auto-bind.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/auto-bind.js new file mode 100644 index 00000000000000..89edfb88bbec53 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/auto-bind.js @@ -0,0 +1,12 @@ +'use strict'; + +var d = require('../'); + +module.exports = function (t, a) { + var o = Object.defineProperties({}, t({ + bar: d(function () { return this === o; }), + bar2: d(function () { return this; }) + })); + + a.deep([(o.bar)(), (o.bar2)()], [true, o]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/index.js new file mode 100644 index 00000000000000..3db0af10acd3ca --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/index.js @@ -0,0 +1,182 @@ +'use strict'; + +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +module.exports = function (t, a) { + var o, c, cg, cs, ce, ceg, ces, cew, cw, e, eg, es, ew, v, vg, vs, w, df, dfg + , dfs; + + o = Object.create(Object.prototype, { + c: t('c', c = {}), + cgs: t.gs('c', cg = function () {}, cs = function () {}), + ce: t('ce', ce = {}), + cegs: t.gs('ce', ceg = function () {}, ces = function () {}), + cew: t('cew', cew = {}), + cw: t('cw', cw = {}), + e: t('e', e = {}), + egs: t.gs('e', eg = function () {}, es = function () {}), + ew: t('ew', ew = {}), + v: t('', v = {}), + vgs: t.gs('', vg = function () {}, vs = function () {}), + w: t('w', w = {}), + + df: t(df = {}), + dfgs: t.gs(dfg = function () {}, dfs = function () {}) + }); + + return { + c: function (a) { + var d = getOwnPropertyDescriptor(o, 'c'); + a(d.value, c, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'cgs'); + a(d.value, undefined, "GS Value"); + a(d.get, cg, "GS Get"); + a(d.set, cs, "GS Set"); + a(d.configurable, true, "GS Configurable"); + a(d.enumerable, false, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + ce: function (a) { + var d = getOwnPropertyDescriptor(o, 'ce'); + a(d.value, ce, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'cegs'); + a(d.value, undefined, "GS Value"); + a(d.get, ceg, "GS Get"); + a(d.set, ces, "GS Set"); + a(d.configurable, true, "GS Configurable"); + a(d.enumerable, true, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + cew: function (a) { + var d = getOwnPropertyDescriptor(o, 'cew'); + a(d.value, cew, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, true, "Writable"); + }, + cw: function (a) { + var d = getOwnPropertyDescriptor(o, 'cw'); + a(d.value, cw, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, true, "Writable"); + }, + e: function (a) { + var d = getOwnPropertyDescriptor(o, 'e'); + a(d.value, e, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'egs'); + a(d.value, undefined, "GS Value"); + a(d.get, eg, "GS Get"); + a(d.set, es, "GS Set"); + a(d.configurable, false, "GS Configurable"); + a(d.enumerable, true, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + ew: function (a) { + var d = getOwnPropertyDescriptor(o, 'ew'); + a(d.value, ew, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, true, "Enumerable"); + a(d.writable, true, "Writable"); + }, + v: function (a) { + var d = getOwnPropertyDescriptor(o, 'v'); + a(d.value, v, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, false, "Writable"); + + d = getOwnPropertyDescriptor(o, 'vgs'); + a(d.value, undefined, "GS Value"); + a(d.get, vg, "GS Get"); + a(d.set, vs, "GS Set"); + a(d.configurable, false, "GS Configurable"); + a(d.enumerable, false, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + w: function (a) { + var d = getOwnPropertyDescriptor(o, 'w'); + a(d.value, w, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, false, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, true, "Writable"); + }, + d: function (a) { + var d = getOwnPropertyDescriptor(o, 'df'); + a(d.value, df, "Value"); + a(d.get, undefined, "Get"); + a(d.set, undefined, "Set"); + a(d.configurable, true, "Configurable"); + a(d.enumerable, false, "Enumerable"); + a(d.writable, true, "Writable"); + + d = getOwnPropertyDescriptor(o, 'dfgs'); + a(d.value, undefined, "GS Value"); + a(d.get, dfg, "GS Get"); + a(d.set, dfs, "GS Set"); + a(d.configurable, true, "GS Configurable"); + a(d.enumerable, false, "GS Enumerable"); + a(d.writable, undefined, "GS Writable"); + }, + Options: { + v: function (a) { + var x = {}, d = t(x, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, writable: true, + value: x, foo: true }, "No descriptor"); + d = t('c', 'foo', { marko: 'elo' }); + a.deep(d, { configurable: true, enumerable: false, writable: false, + value: 'foo', marko: 'elo' }, "Descriptor"); + }, + gs: function (a) { + var gFn = function () {}, sFn = function () {}, d; + d = t.gs(gFn, sFn, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, get: gFn, set: sFn, + foo: true }, "No descriptor"); + d = t.gs(null, sFn, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, get: undefined, + set: sFn, foo: true }, "No descriptor: Just set"); + d = t.gs(gFn, { foo: true }); + a.deep(d, { configurable: true, enumerable: false, get: gFn, + set: undefined, foo: true }, "No descriptor: Just get"); + + d = t.gs('e', gFn, sFn, { bar: true }); + a.deep(d, { configurable: false, enumerable: true, get: gFn, set: sFn, + bar: true }, "Descriptor"); + d = t.gs('e', null, sFn, { bar: true }); + a.deep(d, { configurable: false, enumerable: true, get: undefined, + set: sFn, bar: true }, "Descriptor: Just set"); + d = t.gs('e', gFn, { bar: true }); + a.deep(d, { configurable: false, enumerable: true, get: gFn, + set: undefined, bar: true }, "Descriptor: Just get"); + } + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/lazy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/lazy.js new file mode 100644 index 00000000000000..8266deb240fda3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/d/test/lazy.js @@ -0,0 +1,77 @@ +'use strict'; + +var d = require('../') + + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + +module.exports = function (t, a) { + var Foo = function () {}, i = 1, o, o2, desc; + Object.defineProperties(Foo.prototype, t({ + bar: d(function () { return ++i; }), + bar2: d(function () { return this.bar + 23; }), + bar3: d(function () { return this.bar2 + 34; }, { desc: 'ew' }), + bar4: d(function () { return this.bar3 + 12; }, { cacheName: '_bar4_' }), + bar5: d(function () { return this.bar4 + 3; }, + { cacheName: '_bar5_', desc: 'e' }) + })); + + desc = getOwnPropertyDescriptor(Foo.prototype, 'bar'); + a(desc.configurable, true, "Configurable: default"); + a(desc.enumerable, false, "Enumerable: default"); + + o = new Foo(); + a.deep([o.bar, o.bar2, o.bar3, o.bar4, o.bar5], [2, 25, 59, 71, 74], + "Values"); + + a.deep(getOwnPropertyDescriptor(o, 'bar3'), { configurable: false, + enumerable: true, writable: true, value: 59 }, "Desc"); + a(o.hasOwnProperty('bar4'), false, "Cache not exposed"); + desc = getOwnPropertyDescriptor(o, 'bar5'); + a.deep(desc, { configurable: false, + enumerable: true, get: desc.get, set: desc.set }, "Cache & Desc: desc"); + + o2 = Object.create(o); + o2.bar = 30; + o2.bar3 = 100; + + a.deep([o2.bar, o2.bar2, o2.bar3, o2.bar4, o2.bar5], [30, 25, 100, 112, 115], + "Extension Values"); + + Foo = function () {}; + Object.defineProperties(Foo.prototype, t({ + test: d('w', function () { return 'raz'; }), + test2: d('', function () { return 'raz'; }, { desc: 'w' }), + test3: d('', function () { return 'raz'; }, + { cacheName: '__test3__', desc: 'w' }), + test4: d('w', 'bar') + })); + + o = new Foo(); + o.test = 'marko'; + a.deep(getOwnPropertyDescriptor(o, 'test'), + { configurable: false, enumerable: false, writable: true, value: 'marko' }, + "Set before get"); + o.test2 = 'marko2'; + a.deep(getOwnPropertyDescriptor(o, 'test2'), + { configurable: false, enumerable: false, writable: true, value: 'marko2' }, + "Set before get: Custom desc"); + o.test3 = 'marko3'; + a.deep(getOwnPropertyDescriptor(o, '__test3__'), + { configurable: false, enumerable: false, writable: true, value: 'marko3' }, + "Set before get: Custom cache name"); + a(o.test4, 'bar', "Resolve by value"); + + a.h1("Flat"); + Object.defineProperties(Foo.prototype, t({ + flat: d(function () { return 'foo'; }, { flat: true }), + flat2: d(function () { return 'bar'; }, { flat: true }) + })); + + a.h2("Instance"); + a(o.flat, 'foo', "Value"); + a(o.hasOwnProperty('flat'), false, "Instance"); + a(Foo.prototype.flat, 'foo', "Prototype"); + + a.h2("Direct"); + a(Foo.prototype.flat2, 'bar'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.lint b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.lint new file mode 100644 index 00000000000000..d1da610376a524 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.lint @@ -0,0 +1,38 @@ +@root + +module + +indent 2 +maxlen 100 +tabs + +ass +continue +forin +nomen +plusplus +vars + +./global.js +./function/_define-length.js +./function/#/copy.js +./object/unserialize.js +./test/function/valid-function.js +evil + +./math/_pack-ieee754.js +./math/_unpack-ieee754.js +./math/clz32/shim.js +./math/imul/shim.js +./number/to-uint32.js +./string/#/at.js +bitwise + +./math/fround/shim.js +predef+ Float32Array + +./object/first-key.js +forin + +./test/reg-exp/#/index.js +predef+ __dirname diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.lintignore b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.lintignore new file mode 100644 index 00000000000000..ed703ed7662c89 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.lintignore @@ -0,0 +1,8 @@ +/string/#/normalize/_data.js +/test/boolean/is-boolean.js +/test/date/is-date.js +/test/number/is-number.js +/test/object/is-copy.js +/test/object/is-object.js +/test/reg-exp/is-reg-exp.js +/test/string/is-string.js diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.npmignore new file mode 100644 index 00000000000000..eb09b500d63ec8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/.lintcache +/npm-debug.log diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.travis.yml new file mode 100644 index 00000000000000..a183dbcec61795 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/.travis.yml @@ -0,0 +1,15 @@ +sudo: false # http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +language: node_js +node_js: + - 0.10 + - 0.12 + - iojs + +before_install: + - mkdir node_modules; ln -s ../ node_modules/es5-ext + +notifications: + email: + - medikoo+es5-ext@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/CHANGES new file mode 100644 index 00000000000000..5d0ace5bfe2f8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/CHANGES @@ -0,0 +1,611 @@ +v0.10.7 -- 2015.04.22 +* New utlitities. They're convention differs from v0.10, as they were supposed to land in v1. + Still they're non breaking and start the conventions to be used in v1 + * Object.validateArrayLike + * Object.validateArrayLikeObject + * Object.validateStringifiable + * Object.validateStringifiableValue + * Universal utilities for array-like/iterable objects + * Iterable.is + * Iterable.validate + * Iterable.validateObject + * Iterable.forEach +* Fix camelToHyphen resolution, it must be absolutely reversable by hyphenToCamel +* Fix calculations of large numbers in Math.tanh +* Fix algorithm of Math.sinh +* Fix indexes to not use real symbols +* Fix length of String.fromCodePoint +* Fix tests of Array#copyWithin +* Update Travis CI configuration + +v0.10.6 -- 2015.02.02 +* Fix handling of infinite values in Math.trunc +* Fix handling of getters in Object.normalizeOptions + +v0.10.5 -- 2015.01.20 +* Add Function#toStringTokens +* Add Object.serialize and Object.unserialize +* Add String.randomUniq +* Fix Strin#camelToHyphen issue with tokens that end with digit +* Optimise Number.isInteger logic +* Improve documentation +* Configure lint scripts +* Fix spelling of LICENSE + +v0.10.4 -- 2014.04.30 +* Assure maximum spec compliance of Array.of and Array.from (thanks @mathiasbynens) +* Improve documentations + +v0.10.3 -- 2014.04.29 +Provide accurate iterators handling: +* Array.from improvements: + * Assure right unicode symbols resolution when processing strings in Array.from + * Rely on ES6 symbol shim and use native @@iterator Symbol if provided by environment +* Add methods: + * Array.prototype.entries + * Array.prototype.keys + * Array.prototype.values + * Array.prototype[@@iterator] + * String.prototype[@@iterator] + +Improve documentation + +v0.10.2 -- 2014.04.24 +- Simplify and deprecate `isCallable`. It seems in ES5 based engines there are + no callable objects which are `typeof obj !== 'function'` +- Update Array.from map callback signature (up to latest resolution of TC39) +- Improve documentation + +v0.10.1 -- 2014.04.14 +Bump version for npm +(Workaround for accidental premature publish & unpublish of v0.10.0 a while ago) + +v0.10.0 -- 2014.04.13 +Major update: +- All methods and function specified for ECMAScript 6 are now introduced as + shims accompanied with functions through which (optionally) they can be + implementend on native objects +- Filename convention was changed to shorter and strictly lower case names. e.g. + `lib/String/prototype/starts-with` became `string/#/starts-with` +- Generated functions are guaranteed to have expected length +- Objects with null prototype (created via `Object.create(null)`) are widely + supported (older version have crashed due to implied `obj.hasOwnProperty` and + related invocations) +- Support array subclasses +- When handling lists do not limit its length to Uint32 range +- Use newly introduced `Object.eq` for strict equality in place of `Object.is` +- Iteration of Object have been improved so properties that were hidden or + removed after iteration started are not iterated. + +Additions: +- `Array.isPlainArray` +- `Array.validArray` +- `Array.prototype.concat` (as updated with ES6) +- `Array.prototype.copyWithin` (as introduced with ES6) +- `Array.prototype.fill` (as introduced with ES6) +- `Array.prototype.filter` (as updated with ES6) +- `Array.prototype.findIndex` (as introduced with ES6) +- `Array.prototype.map` (as updated with ES6) +- `Array.prototype.separate` +- `Array.prototype.slice` (as updated with ES6) +- `Array.prototype.splice` (as updated with ES6) +- `Function.prototype.copy` +- `Math.acosh` (as introduced with ES6) +- `Math.atanh` (as introduced with ES6) +- `Math.cbrt` (as introduced with ES6) +- `Math.clz32` (as introduced with ES6) +- `Math.cosh` (as introduced with ES6) +- `Math.expm1` (as introduced with ES6) +- `Math.fround` (as introduced with ES6) +- `Math.hypot` (as introduced with ES6) +- `Math.imul` (as introduced with ES6) +- `Math.log2` (as introduced with ES6) +- `Math.log10` (as introduced with ES6) +- `Math.log1p` (as introduced with ES6) +- `Math.sinh` (as introduced with ES6) +- `Math.tanh` (as introduced with ES6) +- `Math.trunc` (as introduced with ES6) +- `Number.EPSILON` (as introduced with ES6) +- `Number.MIN_SAFE_INTEGER` (as introduced with ES6) +- `Number.MAX_SAFE_INTEGER` (as introduced with ES6) +- `Number.isFinite` (as introduced with ES6) +- `Number.isInteger` (as introduced with ES6) +- `Number.isSafeInteger` (as introduced with ES6) +- `Object.create` (with fix for V8 issue which disallows prototype turn of + objects derived from null +- `Object.eq` - Less restrictive version of `Object.is` based on SameValueZero + algorithm +- `Object.firstKey` +- `Object.keys` (as updated with ES6) +- `Object.mixinPrototypes` +- `Object.primitiveSet` +- `Object.setPrototypeOf` (as introduced with ES6) +- `Object.validObject` +- `RegExp.escape` +- `RegExp.prototype.match` (as introduced with ES6) +- `RegExp.prototype.replace` (as introduced with ES6) +- `RegExp.prototype.search` (as introduced with ES6) +- `RegExp.prototype.split` (as introduced with ES6) +- `RegExp.prototype.sticky` (as introduced with ES6) +- `RegExp.prototype.unicode` (as introduced with ES6) +- `String.fromCodePoint` (as introduced with ES6) +- `String.raw` (as introduced with ES6) +- `String.prototype.at` +- `String.prototype.codePointAt` (as introduced with ES6) +- `String.prototype.normalize` (as introduced with ES6) +- `String.prototype.plainReplaceAll` + +Removals: +- `reserved` set +- `Array.prototype.commonLeft` +- `Function.insert` +- `Function.remove` +- `Function.prototype.silent` +- `Function.prototype.wrap` +- `Object.descriptor` Move to external `d` project. + See: https://github.com/medikoo/d +- `Object.diff` +- `Object.extendDeep` +- `Object.reduce` +- `Object.values` +- `String.prototype.trimCommonLeft` + +Renames: +- `Function.i` into `Function.identity` +- `Function.k` into `Function.constant` +- `Number.toInt` into `Number.toInteger` +- `Number.toUint` into `Number.toPosInteger` +- `Object.extend` into `Object.assign` (as introduced in ES 6) +- `Object.extendProperties` into `Object.mixin`, with improved internal + handling, so it matches temporarily specified `Object.mixin` for ECMAScript 6 +- `Object.isList` into `Object.isArrayLike` +- `Object.mapToArray` into `Object.toArray` (with fixed function length) +- `Object.toPlainObject` into `Object.normalizeOptions` (as this is the real + use case where we use this function) +- `Function.prototype.chain` into `Function.prototype.compose` +- `Function.prototype.match` into `Function.prototype.spread` +- `String.prototype.format` into `String.formatMethod` + +Improvements & Fixes: +- Remove workaround for primitive values handling in object iterators +- `Array.from`: Update so it follows ES 6 spec +- `Array.prototype.compact`: filters just null and undefined values + (not all falsies) +- `Array.prototype.eIndexOf` and `Array.prototype.eLastIndexOf`: fix position + handling, improve internals +- `Array.prototype.find`: return undefined not null, in case of not found + (follow ES 6) +- `Array.prototype.remove` fix function length +- `Error.custom`: simplify, Custom class case is addressed by outer + `error-create` project -> https://github.com/medikoo/error-create +- `Error.isError` true only for Error instances (remove detection of host + Exception objects) +- `Number.prototype.pad`: Normalize negative pad +- `Object.clear`: Handle errors same way as in `Object.assign` +- `Object.compact`: filters just null and undefined values (not all falsies) +- `Object.compare`: Take into account NaN values +- `Object.copy`: Split into `Object.copy` and `Object.copyDeep` +- `Object.isCopy`: Separate into `Object.isCopy` and `Object.isCopyDeep`, where + `isCopyDeep` handles nested plain objects and plain arrays only +- `String.prototype.endsWith`: Adjust up to ES6 specification +- `String.prototype.repeat`: Adjust up to ES6 specification and improve algorithm +- `String.prototype.simpleReplace`: Rename into `String.prototype.plainReplace` +- `String.prototype.startsWith`: Adjust up to ES6 specification +- Update lint rules, and adjust code to that +- Update Travis CI configuration +- Remove Makefile (it's cross-env utility) + +v0.9.2 -- 2013.03.11 +Added: +* Array.prototype.isCopy +* Array.prototype.isUniq +* Error.CustomError +* Function.validFunction +* Object.extendDeep +* Object.descriptor.binder +* Object.safeTraverse +* RegExp.validRegExp +* String.prototype.capitalize +* String.prototype.simpleReplace + +Fixed: +* Fix Array.prototype.diff for sparse arrays +* Accept primitive objects as input values in Object iteration methods and + Object.clear, Object.count, Object.diff, Object.extend, + Object.getPropertyNames, Object.values +* Pass expected arguments to callbacks of Object.filter, Object.mapKeys, + Object.mapToArray, Object.map +* Improve callable callback support in Object.mapToArray + +v0.9.1 -- 2012.09.17 +* Object.reduce - reduce for hash-like collections +* Accapt any callable object as callback in Object.filter, mapKeys and map +* Convention cleanup + +v0.9.0 -- 2012.09.13 +We're getting to real solid API + +Removed: +* Function#memoize - it's grown up to be external package, to be soon published + as 'memoizee' +* String.guid - it doesn't fit es5-ext (extensions) concept, will be provided as + external package +# Function.arguments - obsolete +# Function.context - obsolete +# Function#flip - not readable when used, so it was never used +# Object.clone - obsolete and confusing + +Added: +* String#camelToHyphen - String format convertion + +Renamed: +* String#dashToCamelCase -> String#hyphenToCamel + +Fixes: +* Object.isObject - Quote names in literals that match reserved keywords + (older implementations crashed on that) +* String#repeat - Do not accept negative values (coerce them to 1) + +Improvements: +* Array#remove - Accepts many arguments, we can now remove many values at once +* Object iterators (forEach, map, some) - Compare function invoked with scope + object bound to this +* Function#curry - Algorithm cleanup +* Object.isCopy - Support for all types, not just plain objects +* Object.isPlainObject - Support for cross-frame objects +* Do not memoize any of the functions, it shouldn't be decided internally +* Remove Object.freeze calls in reserved, it's not up to convention +* Improved documentation +* Better linting (hard-core approach using both JSLint mod and JSHint) +* Optional arguments are now documented in funtions signature + +v0.8.2 -- 2012.06.22 +Fix errors in Array's intersection and exclusion methods, related to improper +usage of contains method + +v0.8.1 -- 2012.06.13 +Reorganized internal logic of Function.prototype.memoize. So it's more safe now +and clears cache properly. Additionally preventCache option was provided. + +v0.8.0 -- 2012.05.28 +Again, major overhaul. Probably last experimental stuff was trashed, all API +looks more like standard extensions now. + +Changes: +* Turn all Object.prototype extensions into functions and move them to Object +namespace. We learned that extending Object.prototype is bad idea in any case. +* Rename Function.prototype.curry into Function.prototype.partial. This function + is really doing partial application while currying is slightly different + concept. +* Convert Function.prototype.ncurry to new implementation of + Function.prototype.curry, it now serves real curry concept additionaly it + covers use cases for aritize and hold, which were removed. +* Rename Array's peek to last, and provide support for sparse arrays in it +* Rename Date's monthDaysCount into daysInMonth +* Simplify object iterators, now order of iteration can be configured with just + compareFn argument (no extra byKeys option) +* Rename Object.isDuplicate to Object.isCopy +* Rename Object.isEqual to Object.is which is compatible with future 'is' + keyword +* Function.memoize is now Function.prototype.memoize. Additionally clear cache + functionality is added, and access to original arguments object. +* Rename validation functions: assertNotNull to validValue, assertCallable to + validCallable. validValue was moved to Object namespace. On success they now + return validated value instead of true, it supports better composition. + Additionally created Date.validDate and Error.validError +* All documentation is now held in README.md not in code files. +* Move guid to String namespace. All guids now start with numbers. +* Array.generate: fill argument is now optional +* Object.toArray is now Array.from (as new ES6 specification draft suggests) +* All methods that rely on indexOf or lastIndexOf, now rely on egal (Object.is) + versions of them (eIndexOf, eLastIndexOf) +* Turn all get* functions that returned methods into actuall methods (get* + functionality can still be achieved with help of Function.prototype.partial). + So: Date.getFormat is now Date.prototype.format, + Number.getPad is now Number.prototype.pad, + String.getFormat is now String.prototype.format, + String.getIndent is now String.prototype.indent, + String.getPad is now String.prototype.pad +* Refactored Object.descriptor, it is now just two functions, main one and + main.gs, main is for describing values, and gs for describing getters and + setters. Configuration is passed with first argument as string e.g. 'ce' for + configurable and enumerable. If no configuration string is provided then by + default it returns configurable and writable but not enumerable for value or + configurable but not enumerable for getter/setter +* Function.prototype.silent now returns prepared function (it was + expected to be fixed for 0.7) +* Reserved keywords map (reserved) is now array not hash. +* Object.merge is now Object.extend (while former Object.extend was completely + removed) - 'extend' implies that we change object, not creating new one (as + 'merge' may imply). Similarily Object.mergeProperties was renamed to + Object.extendProperties +* Position argument support in Array.prototype.contains and + String.prototype.contains (so it follows ES6 specification draft) +* endPosition argument support in String.prototype.endsWith and fromPosition + argument support in String.prototype.startsWith (so it follows ES6 + specification draft) +* Better and cleaner String.prototype.indent implementation. No default value + for indent string argument, optional nest value (defaults to 1), remove + nostart argument +* Correct length values for most methods (so they reflect length of similar + methods in standard) +* Length argument is now optional in number and string pad methods. +* Improve arguments validation in general, so it adheres to standard conventions +* Fixed format of package.json + +Removed methods and functions: +* Object.prototype.slice - Object is not ordered collection, so slice doesn't + make sense. +* Function's rcurry, rncurry, s - too cumbersome for JS, not many use cases for + that +* Function.prototype.aritize and Function.prototype.hold - same functionality + can be achieved with new Function.prototype.curry +* Function.prototype.log - provided more generic Function.prototype.wrap for + same use case +* getNextIdGenerator - no use case for that (String.guid should be used if + needed) +* Object.toObject - Can be now acheived with Object(validValue(x)) +* Array.prototype.someValue - no real use case (personally used once and + case was already controversial) +* Date.prototype.duration - moved to external package +* Number.getAutoincrement - No real use case +* Object.prototype.extend, Object.prototype.override, + Object.prototype.plainCreate, Object.prototype.plainExtend - It was probably + too complex, same should be achieved just with Object.create, + Object.descriptor and by saving references to super methods in local scope. +* Object.getCompareBy - Functions should be created individually for each use + case +* Object.get, Object.getSet, Object.set, Object.unset - Not many use cases and + same can be easily achieved with simple inline function +* String.getPrefixWith - Not real use case for something that can be easily + achieved with '+' operator +* Object.isPrimitive - It's just negation of Object.isObject +* Number.prototype.isLess, Number.prototype.isLessOrEqual - they shouldn't be in + Number namespace and should rather be addressed with simple inline functions. +* Number.prototype.subtract - Should rather be addressed with simple inline + function + +New methods and functions: +* Array.prototype.lastIndex - Returns last declared index in array +* String.prototype.last - last for strings +* Function.prototype.wrap - Wrap function with other, it allows to specify + before and after behavior transform return value or prevent original function + from being called. +* Math.sign - Returns sign of a number (already in ES6 specification draft) +* Number.toInt - Converts value to integer (already in ES6 specification draft) +* Number.isNaN - Returns true if value is NaN (already in ES6 specification + draft) +* Number.toUint - Converts value to unsigned integer +* Number.toUint32 - Converts value to 32bit unsigned integer +* Array.prototype.eIndexOf, eLastIndexOf - Egal version (that uses Object.is) of + standard methods (all methods that were using native indexOf or lastIndexOf + now uses eIndexOf and elastIndexOf respectively) +* Array.of - as it's specified for ES6 + +Fixes: +* Fixed binarySearch so it always returns valid list index +* Object.isList - it failed on lists that are callable (e.g. NodeList in Nitro + engine) +* Object.map now supports third argument for callback + +v0.7.1 -- 2012.01.05 +New methods: +* Array.prototype.firstIndex - returns first valid index of array (for + sparse arrays it may not be '0' + +Improvements: +* Array.prototype.first - now returns value for index returned by firstIndex +* Object.prototype.mapToArray - can be called without callback, then array of + key-value pairs is returned + +Fixes +* Array.prototype.forEachRight, object's length read through UInt32 conversion + +v0.7.0 -- 2011.12.27 +Major update. +Stepped back from experimental ideas and introduced more standard approach +taking example from how ES5 methods and functions are designed. One exceptions +is that, we don’t refrain from declaring methods for Object.prototype - it’s up +to developer whether how he decides to use it in his context (as function or as +method). + +In general: +* Removed any method 'functionalization' and functionalize method itself. + es5-ext declares plain methods, which can be configured to work as functions + with call.bind(method) - see documentation. +* Removed separation of Object methods for ES5 (with descriptors) and + ES3 (plain) - we're following ES5 idea on that, some methods are intended just + for enumerable properties and some are for all properties, all are declared + for Object.prototype +* Removed separation of Array generic (collected in List folder) and not generic + methods (collected in Array folder). Now all methods are generic and are in + Array/prototype folder. This separation also meant, that methods in Array are + usually destructive. We don’t do that separation now, there’s generally no use + case for destructive iterators, we should be fine with one version of each + method, (same as ES5 is fine with e.g. one, non destructive 'filter' method) +* Folder structure resembles tree of native ES5 Objects +* All methods are written with ES5 conventions in mind, it means that most + methods are generic and can be run on any object. In more detail: + ** Array.prototype and Object.prototype methods can be run on any object (any + not null or undefined value), + ** Date.prototype methods should be called only on Date instances. + ** Function.prototype methods can be called on any callable objects (not + necessarily functions) + ** Number.prototype & String.prototype methods can be called on any value, in + case of Number it it’ll be degraded to number, in case of string it’ll be + degraded to string. +* Travis CI support (only for Node v0.6 branch, as v0.4 has buggy V8 version) + +Improvements for existing functions and methods: +* Function.memoize (was Function.cache) is now fully generic, can operate on any + type of arguments and it’s NaN safe (all NaN objects are considered equal) +* Method properties passed to Object.prototype.extend or + Object.prototype.override can aside of _super optionally take prototype object + via _proto argument +* Object iterators: forEach, mapToArray and every can now iterate in specified + order +* pluck, invoke and other functions that return reusable functions or methods + have now their results memoized. + +New methods: +* Global: assertNotNull, getNextIdGenerator, guid, isEqual, isPrimitive, + toObject +* Array: generate +* Array.prototype: binarySearch, clear, contains, diff, exclusion, find, first, + forEachRight, group, indexesOf, intersection, remove, someRight, someValue +* Boolean: isBoolean +* Date: isDate +* Function: arguments, context, insert, isArguments, remove +* Function.prototype: not, silent +* Number: getAutoincrement, isNumber +* Number.prototype: isLessOrEqual, isLess, subtract +* Object: assertCallable, descriptor (functions for clean descriptors), + getCompareBy, isCallable, isObject +* Object.prototype: clone (real clone), compact, count, diff, empty, + getPropertyNames, get, keyOf, mapKeys, override, plainCreate, plainExtend, + slice, some, unset +* RegExp: isRegExp +* String: getPrefixWith, isString +* String.prototype: caseInsensitiveCompare, contains, isNumeric + +Renamed methods: +* Date.clone -> Date.prototype.copy +* Date.format -> Date.getFormat +* Date/day/floor -> Date.prototype.floorDay +* Date/month/floor -> Date.prototype.floorMonth +* Date/month/year -> Date.prototype.floorYear +* Function.cache -> Function.memoize +* Function.getApplyArg -> Function.prototype.match +* Function.sequence -> Function.prototype.chain +* List.findSameStartLength -> Array.prototype.commonLeft +* Number.pad -> Number.getPad +* Object/plain/clone -> Object.prototype.copy +* Object/plain/elevate -> Object.prototype.flatten +* Object/plain/same -> Object.prototype.isDuplicate +* Object/plain/setValue -> Object.getSet +* String.format -> String.getFormat +* String.indent -> String.getIndent +* String.pad -> String.getPad +* String.trimLeftStr -> String.prototype.trimCommonLeft +* Object.merge -> Object.prototype.mergeProperties +* Object/plain/pluck -> Object.prototype.get +* Array.clone is now Array.prototype.copy and can be used also on any array-like + objects +* List.isList -> Object.isList +* List.toArray -> Object.prototype.toArray +* String/convert/dashToCamelCase -> String.prototype.dashToCamelCase + +Removed methods: +* Array.compact - removed destructive version (that operated on same array), we + have now non destructive version as Array.prototype.compact. +* Function.applyBind -> use apply.bind directly +* Function.bindBind -> use bind.bind directly +* Function.callBind -> use call.bind directly +* Fuction.clone -> no valid use case +* Function.dscope -> controversial approach, shouldn’t be considered seriously +* Function.functionalize -> It was experimental but standards are standards +* List/sort/length -> It can be easy obtained by Object.getCompareBy(‘length’) +* List.concat -> Concat’s for array-like’s makes no sense, just convert to array + first +* List.every -> Use Array.prototype.every directly +* List.filter -> Use Array.prototype.filter directly +* List.forEach -> User Array.prototype.forEach directly +* List.isListObject -> No valid use case, do: isList(list) && (typeof list === + 'object’) +* List.map -> Use Array.prototype.map directly +* List.reduce -> Use Array.prototype.reduce directly +* List.shiftSame -> Use Array.prototype.commonLeft and do slice +* List.slice -> Use Array.prototype.slice directly +* List.some -> Use Array.prototype.some directly +* Object.bindMethods -> it was version that considered descriptors, we have now + Object.prototype.bindMethods which operates only on enumerable properties +* Object.every -> version that considered all properties, we have now + Object.prototype.every which iterates only enumerables +* Object.invoke -> no use case +* Object.mergeDeep -> no use case +* Object.pluck -> no use case +* Object.same -> it considered descriptors, now there’s only Object.isDuplicate + which compares only enumerable properties +* Object.sameType -> no use case +* Object.toDescriptor and Object.toDescriptors -> replaced by much nicer + Object.descriptor functions +* Object/plain/link -> no use case (it was used internally only by + Object/plain/merge) +* Object/plain/setTrue -> now easily configurable by more universal + Object.getSet(true) +* String.trimRightStr -> Eventually String.prototype.trimCommonRight will be + added + +v0.6.3 -- 2011.12.12 +* Cleared npm warning for misnamed property in package.json + +v0.6.2 -- 2011.08.12 +* Calling String.indent without scope (global scope then) now treated as calling + it with null scope, it allows more direct invocations when using default nest + string: indent().call(str, nest) + +v0.6.1 -- 2011.08.08 +* Added TAD test suite to devDependencies, configured test commands. + Tests can be run with 'make test' or 'npm test' + +v0.6.0 -- 2011.08.07 +New methods: +* Array: clone, compact (in place) +* Date: format, duration, clone, monthDaysCount, day.floor, month.floor, + year.floor +* Function: getApplyArg, , ncurry, rncurry, hold, cache, log +* List: findSameStartLength, shiftSame, peek, isListObject +* Number: pad +* Object: sameType, toString, mapToArray, mergeDeep, toDescriptor, + toDescriptors, invoke +* String: startsWith, endsWith, indent, trimLeftStr, trimRightStr, pad, format + +Fixed: +* Object.extend does now prototypal extend as exptected +* Object.merge now tries to overwrite only configurable properties +* Function.flip + +Improved: +* Faster List.toArray +* Better global retrieval +* Functionalized all Function methods +* Renamed bindApply and bindCall to applyBind and callBind +* Removed Function.inherit (as it's unintuitive curry clone) +* Straightforward logic in Function.k +* Fixed naming of some tests files (letter case issue) +* Renamed Function.saturate into Function.lock +* String.dashToCamelCase digits support +* Strings now considered as List objects +* Improved List.compact +* Concise logic for List.concat +* Test wit TAD in clean ES5 context + +v0.5.1 -- 2011.07.11 +* Function's bindBind, bindCall and bindApply now more versatile + +v0.5.0 -- 2011.07.07 +* Removed Object.is and List.apply +* Renamed Object.plain.is to Object.plain.isPlainObject (keep naming convention + consistent) +* Improved documentation + +v0.4.0 -- 2011.07.05 +* Take most functions on Object to Object.plain to keep them away from object + descriptors +* Object functions with ES5 standard in mind (object descriptors) + +v0.3.0 -- 2011.06.24 +* New functions +* Consistent file naming (dash instead of camelCase) + +v0.2.1 -- 2011.05.28 +* Renamed Functions.K and Function.S to to lowercase versions (use consistent + naming) + +v0.2.0 -- 2011.05.28 +* Renamed Array folder to List (as its generic functions for array-like objects) +* Added Makefile +* Added various functions + +v0.1.0 -- 2011.05.24 +* Initial version diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/LICENSE new file mode 100644 index 00000000000000..de39071f1b8bbf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/README.md b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/README.md new file mode 100644 index 00000000000000..11d8a343d57f1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/README.md @@ -0,0 +1,993 @@ +# es5-ext +## ECMAScript 5 extensions +### (with respect to ECMAScript 6 standard) + +Shims for upcoming ES6 standard and other goodies implemented strictly with ECMAScript conventions in mind. + +It's designed to be used in compliant ECMAScript 5 or ECMAScript 6 environments. Older environments are not supported, although most of the features should work with correct ECMAScript 5 shim on board. + +When used in ECMAScript 6 environment, native implementation (if valid) takes precedence over shims. + +### Installation + + $ npm install es5-ext + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +### Usage + +#### ECMAScript 6 features + +You can force ES6 features to be implemented in your environment, e.g. following will assign `from` function to `Array` (only if it's not implemented already). + +```javascript +require('es5-ext/array/from/implement'); +Array.from('foo'); // ['f', 'o', 'o'] +``` + +You can also access shims directly, without fixing native objects. Following will return native `Array.from` if it's available and fallback to shim if it's not. + +```javascript +var aFrom = require('es5-ext/array/from'); +aFrom('foo'); // ['f', 'o', 'o'] +``` + +If you want to use shim unconditionally (even if native implementation exists) do: + +```javascript +var aFrom = require('es5-ext/array/from/shim'); +aFrom('foo'); // ['f', 'o', 'o'] +``` + +##### List of ES6 shims + +It's about properties introduced with ES6 and those that have been updated in new spec. + +- `Array.from` -> `require('es5-ext/array/from')` +- `Array.of` -> `require('es5-ext/array/of')` +- `Array.prototype.concat` -> `require('es5-ext/array/#/concat')` +- `Array.prototype.copyWithin` -> `require('es5-ext/array/#/copy-within')` +- `Array.prototype.entries` -> `require('es5-ext/array/#/entries')` +- `Array.prototype.fill` -> `require('es5-ext/array/#/fill')` +- `Array.prototype.filter` -> `require('es5-ext/array/#/filter')` +- `Array.prototype.find` -> `require('es5-ext/array/#/find')` +- `Array.prototype.findIndex` -> `require('es5-ext/array/#/find-index')` +- `Array.prototype.keys` -> `require('es5-ext/array/#/keys')` +- `Array.prototype.map` -> `require('es5-ext/array/#/map')` +- `Array.prototype.slice` -> `require('es5-ext/array/#/slice')` +- `Array.prototype.splice` -> `require('es5-ext/array/#/splice')` +- `Array.prototype.values` -> `require('es5-ext/array/#/values')` +- `Array.prototype[@@iterator]` -> `require('es5-ext/array/#/@@iterator')` +- `Math.acosh` -> `require('es5-ext/math/acosh')` +- `Math.asinh` -> `require('es5-ext/math/asinh')` +- `Math.atanh` -> `require('es5-ext/math/atanh')` +- `Math.cbrt` -> `require('es5-ext/math/cbrt')` +- `Math.clz32` -> `require('es5-ext/math/clz32')` +- `Math.cosh` -> `require('es5-ext/math/cosh')` +- `Math.exmp1` -> `require('es5-ext/math/expm1')` +- `Math.fround` -> `require('es5-ext/math/fround')` +- `Math.hypot` -> `require('es5-ext/math/hypot')` +- `Math.imul` -> `require('es5-ext/math/imul')` +- `Math.log1p` -> `require('es5-ext/math/log1p')` +- `Math.log2` -> `require('es5-ext/math/log2')` +- `Math.log10` -> `require('es5-ext/math/log10')` +- `Math.sign` -> `require('es5-ext/math/sign')` +- `Math.signh` -> `require('es5-ext/math/signh')` +- `Math.tanh` -> `require('es5-ext/math/tanh')` +- `Math.trunc` -> `require('es5-ext/math/trunc')` +- `Number.EPSILON` -> `require('es5-ext/number/epsilon')` +- `Number.MAX_SAFE_INTEGER` -> `require('es5-ext/number/max-safe-integer')` +- `Number.MIN_SAFE_INTEGER` -> `require('es5-ext/number/min-safe-integer')` +- `Number.isFinite` -> `require('es5-ext/number/is-finite')` +- `Number.isInteger` -> `require('es5-ext/number/is-integer')` +- `Number.isNaN` -> `require('es5-ext/number/is-nan')` +- `Number.isSafeInteger` -> `require('es5-ext/number/is-safe-integer')` +- `Object.assign` -> `require('es5-ext/object/assign')` +- `Object.keys` -> `require('es5-ext/object/keys')` +- `Object.setPrototypeOf` -> `require('es5-ext/object/set-prototype-of')` +- `RegExp.prototype.match` -> `require('es5-ext/reg-exp/#/match')` +- `RegExp.prototype.replace` -> `require('es5-ext/reg-exp/#/replace')` +- `RegExp.prototype.search` -> `require('es5-ext/reg-exp/#/search')` +- `RegExp.prototype.split` -> `require('es5-ext/reg-exp/#/split')` +- `RegExp.prototype.sticky` -> Implement with `require('es5-ext/reg-exp/#/sticky/implement')`, use as function with `require('es5-ext/reg-exp/#/is-sticky')` +- `RegExp.prototype.unicode` -> Implement with `require('es5-ext/reg-exp/#/unicode/implement')`, use as function with `require('es5-ext/reg-exp/#/is-unicode')` +- `String.fromCodePoint` -> `require('es5-ext/string/from-code-point')` +- `String.raw` -> `require('es5-ext/string/raw')` +- `String.prototype.codePointAt` -> `require('es5-ext/string/#/code-point-at')` +- `String.prototype.contains` -> `require('es5-ext/string/#/contains')` +- `String.prototype.endsWith` -> `require('es5-ext/string/#/ends-with')` +- `String.prototype.normalize` -> `require('es5-ext/string/#/normalize')` +- `String.prototype.repeat` -> `require('es5-ext/string/#/repeat')` +- `String.prototype.startsWith` -> `require('es5-ext/string/#/starts-with')` +- `String.prototype[@@iterator]` -> `require('es5-ext/string/#/@@iterator')` + +#### Non ECMAScript standard features + +__es5-ext__ provides also other utils, and implements them as if they were proposed for a standard. It mostly offers methods (not functions) which can directly be assigned to native prototypes: + +```javascript +Object.defineProperty(Function.prototype, 'partial', { value: require('es5-ext/function/#/partial'), + configurable: true, enumerable: false, writable: true }); +Object.defineProperty(Array.prototype, 'flatten', { value: require('es5-ext/array/#/flatten'), + configurable: true, enumerable: false, writable: true }); +Object.defineProperty(String.prototype, 'capitalize', { value: require('es5-ext/string/#/capitalize'), + configurable: true, enumerable: false, writable: true }); +``` + +See [es5-extend](https://github.com/wookieb/es5-extend#es5-extend), a great utility that automatically will extend natives for you. + +__Important:__ Remember to __not__ extend natives in scope of generic reusable packages (e.g. ones you intend to publish to npm). Extending natives is fine __only__ if you're the _owner_ of the global scope, so e.g. in final project you lead development of. + +When you're in situation when native extensions are not good idea, then you should use methods indirectly: + + +```javascript +var flatten = require('es5-ext/array/#/flatten'); + +flatten.call([1, [2, [3, 4]]]); // [1, 2, 3, 4] +``` + +for better convenience you can turn methods into functions: + + +```javascript +var call = Function.prototype.call +var flatten = call.bind(require('es5-ext/array/#/flatten')); + +flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4] +``` + +You can configure custom toolkit (like [underscorejs](http://underscorejs.org/)), and use it throughout your application + +```javascript +var util = {}; +util.partial = call.bind(require('es5-ext/function/#/partial')); +util.flatten = call.bind(require('es5-ext/array/#/flatten')); +util.startsWith = call.bind(require('es5-ext/string/#/starts-with')); + +util.flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4] +``` + +As with native ones most methods are generic and can be run on any type of object. + +## API + +### Global extensions + +#### global _(es5-ext/global)_ + +Object that represents global scope + +### Array Constructor extensions + +#### from(arrayLike[, mapFn[, thisArg]]) _(es5-ext/array/from)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from). +Returns array representation of _iterable_ or _arrayLike_. If _arrayLike_ is an instance of array, its copy is returned. + +#### generate([length[, …fill]]) _(es5-ext/array/generate)_ + +Generate an array of pre-given _length_ built of repeated arguments. + +#### isPlainArray(x) _(es5-ext/array/is-plain-array)_ + +Returns true if object is plain array (not instance of one of the Array's extensions). + +#### of([…items]) _(es5-ext/array/of)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.of). +Create an array from given arguments. + +#### toArray(obj) _(es5-ext/array/to-array)_ + +Returns array representation of `obj`. If `obj` is already an array, `obj` is returned back. + +#### validArray(obj) _(es5-ext/array/valid-array)_ + +Returns `obj` if it's an array, otherwise throws `TypeError` + +### Array Prototype extensions + +#### arr.binarySearch(compareFn) _(es5-ext/array/#/binary-search)_ + +In __sorted__ list search for index of item for which _compareFn_ returns value closest to _0_. +It's variant of binary search algorithm + +#### arr.clear() _(es5-ext/array/#/clear)_ + +Clears the array + +#### arr.compact() _(es5-ext/array/#/compact)_ + +Returns a copy of the context with all non-values (`null` or `undefined`) removed. + +#### arr.concat() _(es5-ext/array/#/concat)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.concat). +ES6's version of `concat`. Supports `isConcatSpreadable` symbol, and returns array of same type as the context. + +#### arr.contains(searchElement[, position]) _(es5-ext/array/#/contains)_ + +Whether list contains the given value. + +#### arr.copyWithin(target, start[, end]) _(es5-ext/array/#/copy-within)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.copywithin). + +#### arr.diff(other) _(es5-ext/array/#/diff)_ + +Returns the array of elements that are present in context list but not present in other list. + +#### arr.eIndexOf(searchElement[, fromIndex]) _(es5-ext/array/#/e-index-of)_ + +_egal_ version of `indexOf` method. [_SameValueZero_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) logic is used for comparision + +#### arr.eLastIndexOf(searchElement[, fromIndex]) _(es5-ext/array/#/e-last-index-of)_ + +_egal_ version of `lastIndexOf` method. [_SameValueZero_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) logic is used for comparision + +#### arr.entries() _(es5-ext/array/#/entries)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.entries). +Returns iterator object, which traverses the array. Each value is represented with an array, where first value is an index and second is corresponding to index value. + +#### arr.exclusion([…lists]]) _(es5-ext/array/#/exclusion)_ + +Returns the array of elements that are found only in one of the lists (either context list or list provided in arguments). + +#### arr.fill(value[, start, end]) _(es5-ext/array/#/fill)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.fill). + +#### arr.filter(callback[, thisArg]) _(es5-ext/array/#/filter)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.filter). +ES6's version of `filter`, returns array of same type as the context. + +#### arr.find(predicate[, thisArg]) _(es5-ext/array/#/find)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.find). +Return first element for which given function returns true + +#### arr.findIndex(predicate[, thisArg]) _(es5-ext/array/#/find-index)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.findindex). +Return first index for which given function returns true + +#### arr.first() _(es5-ext/array/#/first)_ + +Returns value for first defined index + +#### arr.firstIndex() _(es5-ext/array/#/first-index)_ + +Returns first declared index of the array + +#### arr.flatten() _(es5-ext/array/#/flatten)_ + +Returns flattened version of the array + +#### arr.forEachRight(cb[, thisArg]) _(es5-ext/array/#/for-each-right)_ + +`forEach` starting from last element + +#### arr.group(cb[, thisArg]) _(es5-ext/array/#/group)_ + +Group list elements by value returned by _cb_ function + +#### arr.indexesOf(searchElement[, fromIndex]) _(es5-ext/array/#/indexes-of)_ + +Returns array of all indexes of given value + +#### arr.intersection([…lists]) _(es5-ext/array/#/intersection)_ + +Computes the array of values that are the intersection of all lists (context list and lists given in arguments) + +#### arr.isCopy(other) _(es5-ext/array/#/is-copy)_ + +Returns true if both context and _other_ lists have same content + +#### arr.isUniq() _(es5-ext/array/#/is-uniq)_ + +Returns true if all values in array are unique + +#### arr.keys() _(es5-ext/array/#/keys)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.keys). +Returns iterator object, which traverses all array indexes. + +#### arr.last() _(es5-ext/array/#/last)_ + +Returns value of last defined index + +#### arr.lastIndex() _(es5-ext/array/#/last)_ + +Returns last defined index of the array + +#### arr.map(callback[, thisArg]) _(es5-ext/array/#/map)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.map). +ES6's version of `map`, returns array of same type as the context. + +#### arr.remove(value[, …valuen]) _(es5-ext/array/#/remove)_ + +Remove values from the array + +#### arr.separate(sep) _(es5-ext/array/#/separate)_ + +Returns array with items separated with `sep` value + +#### arr.slice(callback[, thisArg]) _(es5-ext/array/#/slice)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.slice). +ES6's version of `slice`, returns array of same type as the context. + +#### arr.someRight(cb[, thisArg]) _(es5-ext/array/#/someRight)_ + +`some` starting from last element + +#### arr.splice(callback[, thisArg]) _(es5-ext/array/#/splice)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.splice). +ES6's version of `splice`, returns array of same type as the context. + +#### arr.uniq() _(es5-ext/array/#/uniq)_ + +Returns duplicate-free version of the array + +#### arr.values() _(es5-ext/array/#/values)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype.values). +Returns iterator object which traverses all array values. + +#### arr[@@iterator] _(es5-ext/array/#/@@iterator)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.prototype-@@iterator). +Returns iterator object which traverses all array values. + +### Boolean Constructor extensions + +#### isBoolean(x) _(es5-ext/boolean/is-boolean)_ + +Whether value is boolean + +### Date Constructor extensions + +#### isDate(x) _(es5-ext/date/is-date)_ + +Whether value is date instance + +#### validDate(x) _(es5-ext/date/valid-date)_ + +If given object is not date throw TypeError in other case return it. + +### Date Prototype extensions + +#### date.copy(date) _(es5-ext/date/#/copy)_ + +Returns a copy of the date object + +#### date.daysInMonth() _(es5-ext/date/#/days-in-month)_ + +Returns number of days of date's month + +#### date.floorDay() _(es5-ext/date/#/floor-day)_ + +Sets the date time to 00:00:00.000 + +#### date.floorMonth() _(es5-ext/date/#/floor-month)_ + +Sets date day to 1 and date time to 00:00:00.000 + +#### date.floorYear() _(es5-ext/date/#/floor-year)_ + +Sets date month to 0, day to 1 and date time to 00:00:00.000 + +#### date.format(pattern) _(es5-ext/date/#/format)_ + +Formats date up to given string. Supported patterns: + +* `%Y` - Year with century, 1999, 2003 +* `%y` - Year without century, 99, 03 +* `%m` - Month, 01..12 +* `%d` - Day of the month 01..31 +* `%H` - Hour (24-hour clock), 00..23 +* `%M` - Minute, 00..59 +* `%S` - Second, 00..59 +* `%L` - Milliseconds, 000..999 + +### Error Constructor extensions + +#### custom(message/*, code, ext*/) _(es5-ext/error/custom)_ + +Creates custom error object, optinally extended with `code` and other extension properties (provided with `ext` object) + +#### isError(x) _(es5-ext/error/is-error)_ + +Whether value is an error (instance of `Error`). + +#### validError(x) _(es5-ext/error/valid-error)_ + +If given object is not error throw TypeError in other case return it. + +### Error Prototype extensions + +#### err.throw() _(es5-ext/error/#/throw)_ + +Throws error + +### Function Constructor extensions + +Some of the functions were inspired by [Functional JavaScript](http://osteele.com/sources/javascript/functional/) project by Olivier Steele + +#### constant(x) _(es5-ext/function/constant)_ + +Returns a constant function that returns pregiven argument + +_k(x)(y) =def x_ + +#### identity(x) _(es5-ext/function/identity)_ + +Identity function. Returns first argument + +_i(x) =def x_ + +#### invoke(name[, …args]) _(es5-ext/function/invoke)_ + +Returns a function that takes an object as an argument, and applies object's +_name_ method to arguments. +_name_ can be name of the method or method itself. + +_invoke(name, …args)(object, …args2) =def object\[name\]\(…args, …args2\)_ + +#### isArguments(x) _(es5-ext/function/is-arguments)_ + +Whether value is arguments object + +#### isFunction(arg) _(es5-ext/function/is-function)_ + +Wether value is instance of function + +#### noop() _(es5-ext/function/noop)_ + +No operation function + +#### pluck(name) _(es5-ext/function/pluck)_ + +Returns a function that takes an object, and returns the value of its _name_ +property + +_pluck(name)(obj) =def obj[name]_ + +#### validFunction(arg) _(es5-ext/function/valid-function)_ + +If given object is not function throw TypeError in other case return it. + +### Function Prototype extensions + +Some of the methods were inspired by [Functional JavaScript](http://osteele.com/sources/javascript/functional/) project by Olivier Steele + +#### fn.compose([…fns]) _(es5-ext/function/#/compose)_ + +Applies the functions in reverse argument-list order. + +_f1.compose(f2, f3, f4)(…args) =def f1(f2(f3(f4(…arg))))_ + +#### fn.copy() _(es5-ext/function/#/copy)_ + +Produces copy of given function + +#### fn.curry([n]) _(es5-ext/function/#/curry)_ + +Invoking the function returned by this function only _n_ arguments are passed to the underlying function. If the underlying function is not saturated, the result is a function that passes all its arguments to the underlying function. +If _n_ is not provided then it defaults to context function length + +_f.curry(4)(arg1, arg2)(arg3)(arg4) =def f(arg1, args2, arg3, arg4)_ + +#### fn.lock([…args]) _(es5-ext/function/#/lock)_ + +Returns a function that applies the underlying function to _args_, and ignores its own arguments. + +_f.lock(…args)(…args2) =def f(…args)_ + +_Named after it's counterpart in Google Closure_ + +#### fn.not() _(es5-ext/function/#/not)_ + +Returns a function that returns boolean negation of value returned by underlying function. + +_f.not()(…args) =def !f(…args)_ + +#### fn.partial([…args]) _(es5-ext/function/#/partial)_ + +Returns a function that when called will behave like context function called with initially passed arguments. If more arguments are suplilied, they are appended to initial args. + +_f.partial(…args1)(…args2) =def f(…args1, …args2)_ + +#### fn.spread() _(es5-ext/function/#/spread)_ + +Returns a function that applies underlying function with first list argument + +_f.match()(args) =def f.apply(null, args)_ + +#### fn.toStringTokens() _(es5-ext/function/#/to-string-tokens)_ + +Serializes function into two (arguments and body) string tokens. Result is plain object with `args` and `body` properties. + +### Math extensions + +#### acosh(x) _(es5-ext/math/acosh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.acosh). + +#### asinh(x) _(es5-ext/math/asinh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.asinh). + +#### atanh(x) _(es5-ext/math/atanh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.atanh). + +#### cbrt(x) _(es5-ext/math/cbrt)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.cbrt). + +#### clz32(x) _(es5-ext/math/clz32)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.clz32). + +#### cosh(x) _(es5-ext/math/cosh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.cosh). + +#### expm1(x) _(es5-ext/math/expm1)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.expm1). + +#### fround(x) _(es5-ext/math/fround)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.fround). + +#### hypot([…values]) _(es5-ext/math/hypot)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.hypot). + +#### imul(x, y) _(es5-ext/math/imul)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.imul). + +#### log1p(x) _(es5-ext/math/log1p)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.log1p). + +#### log2(x) _(es5-ext/math/log2)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.log2). + +#### log10(x) _(es5-ext/math/log10)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.log10). + +#### sign(x) _(es5-ext/math/sign)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.sign). + +#### sinh(x) _(es5-ext/math/sinh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.sinh). + +#### tanh(x) _(es5-ext/math/tanh)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.tanh). + +#### trunc(x) _(es5-ext/math/trunc)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-math.trunc). + +### Number Constructor extensions + +#### EPSILON _(es5-ext/number/epsilon)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.epsilon). + +The difference between 1 and the smallest value greater than 1 that is representable as a Number value, which is approximately 2.2204460492503130808472633361816 x 10-16. + +#### isFinite(x) _(es5-ext/number/is-finite)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite). +Whether value is finite. Differs from global isNaN that it doesn't do type coercion. + +#### isInteger(x) _(es5-ext/number/is-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isinteger). +Whether value is integer. + +#### isNaN(x) _(es5-ext/number/is-nan)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isnan). +Whether value is NaN. Differs from global isNaN that it doesn't do type coercion. + +#### isNumber(x) _(es5-ext/number/is-number)_ + +Whether given value is number + +#### isSafeInteger(x) _(es5-ext/number/is-safe-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.issafeinteger). + +#### MAX_SAFE_INTEGER _(es5-ext/number/max-safe-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.maxsafeinteger). +The value of Number.MAX_SAFE_INTEGER is 9007199254740991. + +#### MIN_SAFE_INTEGER _(es5-ext/number/min-safe-integer)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.minsafeinteger). +The value of Number.MIN_SAFE_INTEGER is -9007199254740991 (253-1). + +#### toInteger(x) _(es5-ext/number/to-integer)_ + +Converts value to integer + +#### toPosInteger(x) _(es5-ext/number/to-pos-integer)_ + +Converts value to positive integer. If provided value is less than 0, then 0 is returned + +#### toUint32(x) _(es5-ext/number/to-uint32)_ + +Converts value to unsigned 32 bit integer. This type is used for array lengths. +See: http://www.2ality.com/2012/02/js-integers.html + +### Number Prototype extensions + +#### num.pad(length[, precision]) _(es5-ext/number/#/pad)_ + +Pad given number with zeros. Returns string + +### Object Constructor extensions + +#### assign(target, source[, …sourcen]) _(es5-ext/object/assign)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). +Extend _target_ by enumerable own properties of other objects. If properties are already set on target object, they will be overwritten. + +#### clear(obj) _(es5-ext/object/clear)_ + +Remove all enumerable own properties of the object + +#### compact(obj) _(es5-ext/object/compact)_ + +Returns copy of the object with all enumerable properties that have no falsy values + +#### compare(obj1, obj2) _(es5-ext/object/compare)_ + +Universal cross-type compare function. To be used for e.g. array sort. + +#### copy(obj) _(es5-ext/object/copy)_ + +Returns copy of the object with all enumerable properties. + +#### copyDeep(obj) _(es5-ext/object/copy-deep)_ + +Returns deep copy of the object with all enumerable properties. + +#### count(obj) _(es5-ext/object/count)_ + +Counts number of enumerable own properties on object + +#### create(obj[, properties]) _(es5-ext/object/create)_ + +`Object.create` alternative that provides workaround for [V8 issue](http://code.google.com/p/v8/issues/detail?id=2804). + +When `null` is provided as a prototype, it's substituted with specially prepared object that derives from Object.prototype but has all Object.prototype properties shadowed with undefined. + +It's quirky solution that allows us to have plain objects with no truthy properties but with turnable prototype. + +Use only for objects that you plan to switch prototypes of and be aware of limitations of this workaround. + +#### eq(x, y) _(es5-ext/object/eq)_ + +Whether two values are equal, using [_SameValueZero_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) algorithm. + +#### every(obj, cb[, thisArg[, compareFn]]) _(es5-ext/object/every)_ + +Analogous to Array.prototype.every. Returns true if every key-value pair in this object satisfies the provided testing function. +Optionally _compareFn_ can be provided which assures that keys are tested in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### filter(obj, cb[, thisArg]) _(es5-ext/object/filter)_ + +Analogous to Array.prototype.filter. Returns new object with properites for which _cb_ function returned truthy value. + +#### firstKey(obj) _(es5-ext/object/first-key)_ + +Returns first enumerable key of the object, as keys are unordered by specification, it can be any key of an object. + +#### flatten(obj) _(es5-ext/object/flatten)_ + +Returns new object, with flatten properties of input object + +_flatten({ a: { b: 1 }, c: { d: 1 } }) =def { b: 1, d: 1 }_ + +#### forEach(obj, cb[, thisArg[, compareFn]]) _(es5-ext/object/for-each)_ + +Analogous to Array.prototype.forEach. Calls a function for each key-value pair found in object +Optionally _compareFn_ can be provided which assures that properties are iterated in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### getPropertyNames() _(es5-ext/object/get-property-names)_ + +Get all (not just own) property names of the object + +#### is(x, y) _(es5-ext/object/is)_ + +Whether two values are equal, using [_SameValue_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) algorithm. + +#### isArrayLike(x) _(es5-ext/object/is-array-like)_ + +Whether object is array-like object + +#### isCopy(x, y) _(es5-ext/object/is-copy)_ + +Two values are considered a copy of same value when all of their own enumerable properties have same values. + +#### isCopyDeep(x, y) _(es5-ext/object/is-copy-deep)_ + +Deep comparision of objects + +#### isEmpty(obj) _(es5-ext/object/is-empty)_ + +True if object doesn't have any own enumerable property + +#### isObject(arg) _(es5-ext/object/is-object)_ + +Whether value is not primitive + +#### isPlainObject(arg) _(es5-ext/object/is-plain-object)_ + +Whether object is plain object, its protototype should be Object.prototype and it cannot be host object. + +#### keyOf(obj, searchValue) _(es5-ext/object/key-of)_ + +Search object for value + +#### keys(obj) _(es5-ext/object/keys)_ + +[_Updated with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys). +ES6's version of `keys`, doesn't throw on primitive input + +#### map(obj, cb[, thisArg]) _(es5-ext/object/map)_ + +Analogous to Array.prototype.map. Creates a new object with properties which values are results of calling a provided function on every key-value pair in this object. + +#### mapKeys(obj, cb[, thisArg]) _(es5-ext/object/map-keys)_ + +Create new object with same values, but remapped keys + +#### mixin(target, source) _(es5-ext/object/mixin)_ + +Extend _target_ by all own properties of other objects. Properties found in both objects will be overwritten (unless they're not configurable and cannot be overwritten). +_It was for a moment part of ECMAScript 6 draft._ + +#### mixinPrototypes(target, …source]) _(es5-ext/object/mixin-prototypes)_ + +Extends _target_, with all source and source's prototype properties. +Useful as an alternative for `setPrototypeOf` in environments in which it cannot be shimmed (no `__proto__` support). + +#### normalizeOptions(options) _(es5-ext/object/normalize-options)_ + +Normalizes options object into flat plain object. + +Useful for functions in which we either need to keep options object for future reference or need to modify it for internal use. + +- It never returns input `options` object back (always a copy is created) +- `options` can be undefined in such case empty plain object is returned. +- Copies all enumerable properties found down prototype chain. + +#### primitiveSet([…names]) _(es5-ext/object/primitive-set)_ + +Creates `null` prototype based plain object, and sets on it all property names provided in arguments to true. + +#### safeTraverse(obj[, …names]) _(es5-ext/object/safe-traverse)_ + +Safe navigation of object properties. See http://wiki.ecmascript.org/doku.php?id=strawman:existential_operator + +#### serialize(value) _(es5-ext/object/serialize)_ + +Serialize value into string. Differs from [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that it serializes also dates, functions and regular expresssions. + +#### setPrototypeOf(object, proto) _(es5-ext/object/set-prototype-of)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.setprototypeof). +If native version is not provided, it depends on existence of `__proto__` functionality, if it's missing, `null` instead of function is exposed. + +#### some(obj, cb[, thisArg[, compareFn]]) _(es5-ext/object/some)_ + +Analogous to Array.prototype.some Returns true if any key-value pair satisfies the provided +testing function. +Optionally _compareFn_ can be provided which assures that keys are tested in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### toArray(obj[, cb[, thisArg[, compareFn]]]) _(es5-ext/object/to-array)_ + +Creates an array of results of calling a provided function on every key-value pair in this object. +Optionally _compareFn_ can be provided which assures that results are added in given order. If provided _compareFn_ is equal to `true`, then order is alphabetical (by key). + +#### unserialize(str) _(es5-ext/object/unserialize)_ + +Userializes value previously serialized with [serialize](#serializevalue-es5-extobjectserialize) + +#### validCallable(x) _(es5-ext/object/valid-callable)_ + +If given object is not callable throw TypeError in other case return it. + +#### validObject(x) _(es5-ext/object/valid-object)_ + +Throws error if given value is not an object, otherwise it is returned. + +#### validValue(x) _(es5-ext/object/valid-value)_ + +Throws error if given value is `null` or `undefined`, otherwise returns value. + +### RegExp Constructor extensions + +#### escape(str) _(es5-ext/reg-exp/escape)_ + +Escapes string to be used in regular expression + +#### isRegExp(x) _(es5-ext/reg-exp/is-reg-exp)_ + +Whether object is regular expression + +#### validRegExp(x) _(es5-ext/reg-exp/valid-reg-exp)_ + +If object is regular expression it is returned, otherwise TypeError is thrown. + +### RegExp Prototype extensions + +#### re.isSticky(x) _(es5-ext/reg-exp/#/is-sticky)_ + +Whether regular expression has `sticky` flag. + +It's to be used as counterpart to [regExp.sticky](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-get-regexp.prototype.sticky) if it's not implemented. + +#### re.isUnicode(x) _(es5-ext/reg-exp/#/is-unicode)_ + +Whether regular expression has `unicode` flag. + +It's to be used as counterpart to [regExp.unicode](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-get-regexp.prototype.unicode) if it's not implemented. + +#### re.match(string) _(es5-ext/reg-exp/#/match)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.match). + +#### re.replace(string, replaceValue) _(es5-ext/reg-exp/#/replace)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.replace). + +#### re.search(string) _(es5-ext/reg-exp/#/search)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.search). + +#### re.split(string) _(es5-ext/reg-exp/#/search)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.split). + +#### re.sticky _(es5-ext/reg-exp/#/sticky/implement)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.sticky). +It's a getter, so only `implement` and `is-implemented` modules are provided. + +#### re.unicode _(es5-ext/reg-exp/#/unicode/implement)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-regexp.prototype.unicode). +It's a getter, so only `implement` and `is-implemented` modules are provided. + +### String Constructor extensions + +#### formatMethod(fMap) _(es5-ext/string/format-method)_ + +Creates format method. It's used e.g. to create `Date.prototype.format` method + +#### fromCodePoint([…codePoints]) _(es5-ext/string/from-code-point)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.fromcodepoint) + +#### isString(x) _(es5-ext/string/is-string)_ + +Whether object is string + +#### randomUniq() _(es5-ext/string/random-uniq)_ + +Returns randomly generated id, with guarantee of local uniqueness (no same id will be returned twice) + +#### raw(callSite[, …substitutions]) _(es5-ext/string/raw)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.raw) + +### String Prototype extensions + +#### str.at(pos) _(es5-ext/string/#/at)_ + +_Proposed for ECMAScript 6/7 standard, but not (yet) in a draft_ + +Returns a string at given position in Unicode-safe manner. +Based on [implementation by Mathias Bynens](https://github.com/mathiasbynens/String.prototype.at). + +#### str.camelToHyphen() _(es5-ext/string/#/camel-to-hyphen)_ + +Convert camelCase string to hyphen separated, e.g. one-two-three -> oneTwoThree. +Useful when converting names from js property convention into filename convention. + +#### str.capitalize() _(es5-ext/string/#/capitalize)_ + +Capitalize first character of a string + +#### str.caseInsensitiveCompare(str) _(es5-ext/string/#/case-insensitive-compare)_ + +Case insensitive compare + +#### str.codePointAt(pos) _(es5-ext/string/#/code-point-at)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.codepointat) + +Based on [implementation by Mathias Bynens](https://github.com/mathiasbynens/String.prototype.codePointAt). + +#### str.contains(searchString[, position]) _(es5-ext/string/#/contains)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.contains) + +Whether string contains given string. + +#### str.endsWith(searchString[, endPosition]) _(es5-ext/string/#/ends-with)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.endswith). +Whether strings ends with given string + +#### str.hyphenToCamel() _(es5-ext/string/#/hyphen-to-camel)_ + +Convert hyphen separated string to camelCase, e.g. one-two-three -> oneTwoThree. +Useful when converting names from filename convention to js property name convention. + +#### str.indent(str[, count]) _(es5-ext/string/#/indent)_ + +Indents each line with provided _str_ (if _count_ given then _str_ is repeated _count_ times). + +#### str.last() _(es5-ext/string/#/last)_ + +Return last character + +#### str.normalize([form]) _(es5-ext/string/#/normalize)_ + +[_Introduced with ECMAScript 6_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize). +Returns the Unicode Normalization Form of a given string. +Based on Matsuza's version. Code used for integrated shim can be found at [github.com/walling/unorm](https://github.com/walling/unorm/blob/master/lib/unorm.js) + +#### str.pad(fill[, length]) _(es5-ext/string/#/pad)_ + +Pad string with _fill_. +If _length_ si given than _fill_ is reapated _length_ times. +If _length_ is negative then pad is applied from right. + +#### str.repeat(n) _(es5-ext/string/#/repeat)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.repeat). +Repeat given string _n_ times + +#### str.plainReplace(search, replace) _(es5-ext/string/#/plain-replace)_ + +Simple `replace` version. Doesn't support regular expressions. Replaces just first occurrence of search string. Doesn't support insert patterns, therefore it is safe to replace text with text obtained programmatically (there's no need for additional _$_ characters escape in such case). + +#### str.plainReplaceAll(search, replace) _(es5-ext/string/#/plain-replace-all)_ + +Simple `replace` version. Doesn't support regular expressions. Replaces all occurrences of search string. Doesn't support insert patterns, therefore it is safe to replace text with text obtained programmatically (there's no need for additional _$_ characters escape in such case). + +#### str.startsWith(searchString[, position]) _(es5-ext/string/#/starts-with)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.startswith). +Whether strings starts with given string + +#### str[@@iterator] _(es5-ext/string/#/@@iterator)_ + +[_Introduced with ECMAScript 6_](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator). +Returns iterator object which traverses all string characters (with respect to unicode symbols) + +### Tests [![Build Status](https://travis-ci.org/medikoo/es5-ext.png)](https://travis-ci.org/medikoo/es5-ext) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/implement.js new file mode 100644 index 00000000000000..0f714a1d2795e3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, require('es6-symbol').iterator, { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/index.js new file mode 100644 index 00000000000000..a69462650e7302 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.prototype[require('es6-symbol').iterator] : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..72eb1f8a27ff30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/is-implemented.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function () { + var arr = ['foo', 1], iterator, result; + if (typeof arr[iteratorSymbol] !== 'function') return false; + iterator = arr[iteratorSymbol](); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== 'foo') return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/shim.js new file mode 100644 index 00000000000000..ff295df9961e9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/@@iterator/shim.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('../values/shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/_compare-by-length.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/_compare-by-length.js new file mode 100644 index 00000000000000..d8343ce306d3ca --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/_compare-by-length.js @@ -0,0 +1,9 @@ +// Used internally to sort array of lists by length + +'use strict'; + +var toPosInt = require('../../number/to-pos-integer'); + +module.exports = function (a, b) { + return toPosInt(a.length) - toPosInt(b.length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/binary-search.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/binary-search.js new file mode 100644 index 00000000000000..8eb45675149256 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/binary-search.js @@ -0,0 +1,28 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , floor = Math.floor; + +module.exports = function (compareFn) { + var length, low, high, middle; + + value(this); + callable(compareFn); + + length = toPosInt(this.length); + low = 0; + high = length - 1; + + while (low <= high) { + middle = floor((low + high) / 2); + if (compareFn(this[middle]) < 0) high = middle - 1; + else low = middle + 1; + } + + if (high < 0) return 0; + if (high >= length) return length - 1; + return high; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/clear.js new file mode 100644 index 00000000000000..3587bdf972d458 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/clear.js @@ -0,0 +1,12 @@ +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear + +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + value(this).length = 0; + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/compact.js new file mode 100644 index 00000000000000..d529d5a2beab8f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/compact.js @@ -0,0 +1,9 @@ +// Inspired by: http://documentcloud.github.com/underscore/#compact + +'use strict'; + +var filter = Array.prototype.filter; + +module.exports = function () { + return filter.call(this, function (val) { return val != null; }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/implement.js new file mode 100644 index 00000000000000..80c67cb4faf764 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'concat', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/index.js new file mode 100644 index 00000000000000..db205ea54a41ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.concat : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/is-implemented.js new file mode 100644 index 00000000000000..cab8bc9e323bbd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).concat('foo') instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/shim.js new file mode 100644 index 00000000000000..8b28e4ae03b70f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/concat/shim.js @@ -0,0 +1,39 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + , toPosInt = require('../../../number/to-pos-integer') + , isObject = require('../../../object/is-object') + + , isArray = Array.isArray, concat = Array.prototype.concat + , forEach = Array.prototype.forEach + + , isSpreadable; + +isSpreadable = function (value) { + if (!value) return false; + if (!isObject(value)) return false; + if (value['@@isConcatSpreadable'] !== undefined) { + return Boolean(value['@@isConcatSpreadable']); + } + return isArray(value); +}; + +module.exports = function (item/*, …items*/) { + var result; + if (!this || !isArray(this) || isPlainArray(this)) { + return concat.apply(this, arguments); + } + result = new this.constructor(this.length); + forEach.call(this, function (val, i) { result[i] = val; }); + forEach.call(arguments, function (arg) { + var base; + if (isSpreadable(arg)) { + base = result.length; + result.length += toPosInt(arg.length); + forEach.call(arg, function (val, i) { result[base + i] = val; }); + return; + } + result.push(arg); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/contains.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/contains.js new file mode 100644 index 00000000000000..4a2f9f6731c8c6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/contains.js @@ -0,0 +1,7 @@ +'use strict'; + +var indexOf = require('./e-index-of'); + +module.exports = function (searchElement/*, position*/) { + return indexOf.call(this, searchElement, arguments[1]) > -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/implement.js new file mode 100644 index 00000000000000..eedbad77eebe09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'copyWithin', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/index.js new file mode 100644 index 00000000000000..bb89d0b87934d1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.copyWithin : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/is-implemented.js new file mode 100644 index 00000000000000..8f17e06d816d14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5]; + if (typeof arr.copyWithin !== 'function') return false; + return String(arr.copyWithin(1, 3)) === '1,4,5,4,5'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/shim.js new file mode 100644 index 00000000000000..c0bfb8b0609f4e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/copy-within/shim.js @@ -0,0 +1,39 @@ +// Taken from: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var toInteger = require('../../../number/to-integer') + , toPosInt = require('../../../number/to-pos-integer') + , validValue = require('../../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty + , max = Math.max, min = Math.min; + +module.exports = function (target, start/*, end*/) { + var o = validValue(this), end = arguments[2], l = toPosInt(o.length) + , to, from, fin, count, direction; + + target = toInteger(target); + start = toInteger(start); + end = (end === undefined) ? l : toInteger(end); + + to = target < 0 ? max(l + target, 0) : min(target, l); + from = start < 0 ? max(l + start, 0) : min(start, l); + fin = end < 0 ? max(l + end, 0) : min(end, l); + count = min(fin - from, l - to); + direction = 1; + + if ((from < to) && (to < (from + count))) { + direction = -1; + from += count - 1; + to += count - 1; + } + while (count > 0) { + if (hasOwnProperty.call(o, from)) o[to] = o[from]; + else delete o[from]; + from += direction; + to += direction; + count -= 1; + } + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/diff.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/diff.js new file mode 100644 index 00000000000000..a1f95419d4ed65 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/diff.js @@ -0,0 +1,13 @@ +'use strict'; + +var value = require('../../object/valid-value') + , contains = require('./contains') + + , filter = Array.prototype.filter; + +module.exports = function (other) { + (value(this) && value(other)); + return filter.call(this, function (item) { + return !contains.call(other, item); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/e-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/e-index-of.js new file mode 100644 index 00000000000000..80864d0666168a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/e-index-of.js @@ -0,0 +1,29 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , indexOf = Array.prototype.indexOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs, floor = Math.floor; + +module.exports = function (searchElement/*, fromIndex*/) { + var i, l, fromIndex, val; + if (searchElement === searchElement) { //jslint: ignore + return indexOf.apply(this, arguments); + } + + l = toPosInt(value(this).length); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = 0; + else if (fromIndex >= 0) fromIndex = floor(fromIndex); + else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + + for (i = fromIndex; i < l; ++i) { + if (hasOwnProperty.call(this, i)) { + val = this[i]; + if (val !== val) return i; //jslint: ignore + } + } + return -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/e-last-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/e-last-index-of.js new file mode 100644 index 00000000000000..4fc536bd68082d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/e-last-index-of.js @@ -0,0 +1,29 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , lastIndexOf = Array.prototype.lastIndexOf + , hasOwnProperty = Object.prototype.hasOwnProperty + , abs = Math.abs, floor = Math.floor; + +module.exports = function (searchElement/*, fromIndex*/) { + var i, fromIndex, val; + if (searchElement === searchElement) { //jslint: ignore + return lastIndexOf.apply(this, arguments); + } + + value(this); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = (toPosInt(this.length) - 1); + else if (fromIndex >= 0) fromIndex = floor(fromIndex); + else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); + + for (i = fromIndex; i >= 0; --i) { + if (hasOwnProperty.call(this, i)) { + val = this[i]; + if (val !== val) return i; //jslint: ignore + } + } + return -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/implement.js new file mode 100644 index 00000000000000..490de60e207ab4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'entries', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/index.js new file mode 100644 index 00000000000000..292792cf159da8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.entries : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/is-implemented.js new file mode 100644 index 00000000000000..e186c17237bd39 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/is-implemented.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 'foo'], iterator, result; + if (typeof arr.entries !== 'function') return false; + iterator = arr.entries(); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result || !result.value) return false; + if (result.value[0] !== 0) return false; + if (result.value[1] !== 1) return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/shim.js new file mode 100644 index 00000000000000..c052b53f01d89f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/entries/shim.js @@ -0,0 +1,4 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array'); +module.exports = function () { return new ArrayIterator(this, 'key+value'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/exclusion.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/exclusion.js new file mode 100644 index 00000000000000..f08adc81c9631e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/exclusion.js @@ -0,0 +1,27 @@ +'use strict'; + +var value = require('../../object/valid-value') + , aFrom = require('../from') + , toArray = require('../to-array') + , contains = require('./contains') + , byLength = require('./_compare-by-length') + + , filter = Array.prototype.filter, push = Array.prototype.push; + +module.exports = function (/*…lists*/) { + var lists, seen, result; + if (!arguments.length) return aFrom(this); + push.apply(lists = [this], arguments); + lists.forEach(value); + seen = []; + result = []; + lists.sort(byLength).forEach(function (list) { + result = result.filter(function (item) { + return !contains.call(list, item); + }).concat(filter.call(list, function (x) { + return !contains.call(seen, x); + })); + push.apply(seen, toArray(list)); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/implement.js new file mode 100644 index 00000000000000..22511919c516fe --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'fill', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/index.js new file mode 100644 index 00000000000000..36c1f66668b29d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.fill : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/is-implemented.js new file mode 100644 index 00000000000000..b8e546888af2b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5, 6]; + if (typeof arr.fill !== 'function') return false; + return String(arr.fill(-1, -3)) === '1,2,3,-1,-1,-1'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/shim.js new file mode 100644 index 00000000000000..45823be51fc193 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/fill/shim.js @@ -0,0 +1,21 @@ +// Taken from: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var toInteger = require('../../../number/to-integer') + , toPosInt = require('../../../number/to-pos-integer') + , validValue = require('../../../object/valid-value') + + , max = Math.max, min = Math.min; + +module.exports = function (value/*, start, end*/) { + var o = validValue(this), start = arguments[1], end = arguments[2] + , l = toPosInt(o.length), relativeStart, i; + + start = (start === undefined) ? 0 : toInteger(start); + end = (end === undefined) ? l : toInteger(end); + + relativeStart = start < 0 ? max(l + start, 0) : min(start, l); + for (i = relativeStart; i < l && i < end; ++i) o[i] = value; + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/implement.js new file mode 100644 index 00000000000000..090c5f109aee35 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'filter', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/index.js new file mode 100644 index 00000000000000..bcf0268dc2dcb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.filter : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/is-implemented.js new file mode 100644 index 00000000000000..5577273501531e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe') + + , pass = function () { return true; }; + +module.exports = function () { + return (new SubArray()).filter(pass) instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/shim.js new file mode 100644 index 00000000000000..b0116defce5021 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/filter/shim.js @@ -0,0 +1,22 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + , callable = require('../../../object/valid-callable') + + , isArray = Array.isArray, filter = Array.prototype.filter + , forEach = Array.prototype.forEach, call = Function.prototype.call; + +module.exports = function (callbackFn/*, thisArg*/) { + var result, thisArg, i; + if (!this || !isArray(this) || isPlainArray(this)) { + return filter.apply(this, arguments); + } + callable(callbackFn); + thisArg = arguments[1]; + result = new this.constructor(); + i = 0; + forEach.call(this, function (val, j, self) { + if (call.call(callbackFn, thisArg, val, j, self)) result[i++] = val; + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/implement.js new file mode 100644 index 00000000000000..556cb846002b0e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'findIndex', + { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/index.js new file mode 100644 index 00000000000000..03a987e22347bf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.findIndex : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/is-implemented.js new file mode 100644 index 00000000000000..dbd3c814b4650f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var fn = function (x) { return x > 3; }; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5, 6]; + if (typeof arr.findIndex !== 'function') return false; + return arr.findIndex(fn) === 3; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/shim.js new file mode 100644 index 00000000000000..957939f2ba224a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find-index/shim.js @@ -0,0 +1,20 @@ +'use strict'; + +var callable = require('../../../object/valid-callable') + , value = require('../../../object/valid-value') + + , some = Array.prototype.some, apply = Function.prototype.apply; + +module.exports = function (predicate/*, thisArg*/) { + var k, self; + self = Object(value(this)); + callable(predicate); + + return some.call(self, function (value, index) { + if (apply.call(predicate, this, arguments)) { + k = index; + return true; + } + return false; + }, arguments[1]) ? k : -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/implement.js new file mode 100644 index 00000000000000..0f37104ac8dbbf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'find', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/index.js new file mode 100644 index 00000000000000..96819d09f02198 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.find : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/is-implemented.js new file mode 100644 index 00000000000000..cc7ec774df0fa4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var fn = function (x) { return x > 3; }; + +module.exports = function () { + var arr = [1, 2, 3, 4, 5, 6]; + if (typeof arr.find !== 'function') return false; + return arr.find(fn) === 4; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/shim.js new file mode 100644 index 00000000000000..c7ee9069a9a308 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/find/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var findIndex = require('../find-index/shim'); + +module.exports = function (predicate/*, thisArg*/) { + var index = findIndex.apply(this, arguments); + return (index === -1) ? undefined : this[index]; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/first-index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/first-index.js new file mode 100644 index 00000000000000..7a9e4c34736ca3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/first-index.js @@ -0,0 +1,16 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function () { + var i, l; + if (!(l = toPosInt(value(this).length))) return null; + i = 0; + while (!hasOwnProperty.call(this, i)) { + if (++i === l) return null; + } + return i; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/first.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/first.js new file mode 100644 index 00000000000000..11df571754857f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/first.js @@ -0,0 +1,9 @@ +'use strict'; + +var firstIndex = require('./first-index'); + +module.exports = function () { + var i; + if ((i = firstIndex.call(this)) !== null) return this[i]; + return undefined; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/flatten.js new file mode 100644 index 00000000000000..c95407d317fd3b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/flatten.js @@ -0,0 +1,12 @@ +'use strict'; + +var isArray = Array.isArray, forEach = Array.prototype.forEach + , push = Array.prototype.push; + +module.exports = function flatten() { + var r = []; + forEach.call(this, function (x) { + push.apply(r, isArray(x) ? flatten.call(x) : [x]); + }); + return r; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/for-each-right.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/for-each-right.js new file mode 100644 index 00000000000000..2f0ffaea84cb38 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/for-each-right.js @@ -0,0 +1,20 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty + , call = Function.prototype.call; + +module.exports = function (cb/*, thisArg*/) { + var i, self, thisArg; + + self = Object(value(this)); + callable(cb); + thisArg = arguments[1]; + + for (i = toPosInt(self.length); i >= 0; --i) { + if (hasOwnProperty.call(self, i)) call.call(cb, thisArg, self[i], i, self); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/group.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/group.js new file mode 100644 index 00000000000000..fbb178c35c1730 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/group.js @@ -0,0 +1,23 @@ +// Inspired by Underscore's groupBy: +// http://documentcloud.github.com/underscore/#groupBy + +'use strict'; + +var callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , forEach = Array.prototype.forEach, apply = Function.prototype.apply; + +module.exports = function (cb/*, thisArg*/) { + var r; + + (value(this) && callable(cb)); + + r = {}; + forEach.call(this, function (v) { + var key = apply.call(cb, this, arguments); + if (!r.hasOwnProperty(key)) r[key] = []; + r[key].push(v); + }, arguments[1]); + return r; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/index.js new file mode 100644 index 00000000000000..97ef65cfd42cf1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/index.js @@ -0,0 +1,40 @@ +'use strict'; + +module.exports = { + '@@iterator': require('./@@iterator'), + binarySearch: require('./binary-search'), + clear: require('./clear'), + compact: require('./compact'), + concat: require('./concat'), + contains: require('./contains'), + copyWithin: require('./copy-within'), + diff: require('./diff'), + eIndexOf: require('./e-index-of'), + eLastIndexOf: require('./e-last-index-of'), + entries: require('./entries'), + exclusion: require('./exclusion'), + fill: require('./fill'), + filter: require('./filter'), + find: require('./find'), + findIndex: require('./find-index'), + first: require('./first'), + firstIndex: require('./first-index'), + flatten: require('./flatten'), + forEachRight: require('./for-each-right'), + keys: require('./keys'), + group: require('./group'), + indexesOf: require('./indexes-of'), + intersection: require('./intersection'), + isCopy: require('./is-copy'), + isUniq: require('./is-uniq'), + last: require('./last'), + lastIndex: require('./last-index'), + map: require('./map'), + remove: require('./remove'), + separate: require('./separate'), + slice: require('./slice'), + someRight: require('./some-right'), + splice: require('./splice'), + uniq: require('./uniq'), + values: require('./values') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/indexes-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/indexes-of.js new file mode 100644 index 00000000000000..6b89157a35b805 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/indexes-of.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexOf = require('./e-index-of'); + +module.exports = function (value/*, fromIndex*/) { + var r = [], i, fromIndex = arguments[1]; + while ((i = indexOf.call(this, value, fromIndex)) !== -1) { + r.push(i); + fromIndex = i + 1; + } + return r; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/intersection.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/intersection.js new file mode 100644 index 00000000000000..fadcb525308964 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/intersection.js @@ -0,0 +1,19 @@ +'use strict'; + +var value = require('../../object/valid-value') + , contains = require('./contains') + , byLength = require('./_compare-by-length') + + , filter = Array.prototype.filter, push = Array.prototype.push + , slice = Array.prototype.slice; + +module.exports = function (/*…list*/) { + var lists; + if (!arguments.length) slice.call(this); + push.apply(lists = [this], arguments); + lists.forEach(value); + lists.sort(byLength); + return lists.reduce(function (a, b) { + return filter.call(a, function (x) { return contains.call(b, x); }); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/is-copy.js new file mode 100644 index 00000000000000..ac7c79bc4521ce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/is-copy.js @@ -0,0 +1,21 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , eq = require('../../object/eq') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function (other) { + var i, l; + (value(this) && value(other)); + l = toPosInt(this.length); + if (l !== toPosInt(other.length)) return false; + for (i = 0; i < l; ++i) { + if (hasOwnProperty.call(this, i) !== hasOwnProperty.call(other, i)) { + return false; + } + if (!eq(this[i], other[i])) return false; + } + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/is-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/is-uniq.js new file mode 100644 index 00000000000000..b14f461d941ee5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/is-uniq.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexOf = require('./e-index-of') + + , every = Array.prototype.every + , isFirst; + +isFirst = function (value, index) { + return indexOf.call(this, value) === index; +}; + +module.exports = function () { return every.call(this, isFirst, this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/implement.js new file mode 100644 index 00000000000000..e18e61701fa028 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'keys', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/index.js new file mode 100644 index 00000000000000..2f89cffe101d61 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.keys : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/is-implemented.js new file mode 100644 index 00000000000000..06bd87bf296c15 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function () { + var arr = [1, 'foo'], iterator, result; + if (typeof arr.keys !== 'function') return false; + iterator = arr.keys(); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== 0) return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/shim.js new file mode 100644 index 00000000000000..83773f6ec955d2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/keys/shim.js @@ -0,0 +1,4 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array'); +module.exports = function () { return new ArrayIterator(this, 'key'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/last-index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/last-index.js new file mode 100644 index 00000000000000..a191d6e153d6ae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/last-index.js @@ -0,0 +1,16 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function () { + var i, l; + if (!(l = toPosInt(value(this).length))) return null; + i = l - 1; + while (!hasOwnProperty.call(this, i)) { + if (--i === -1) return null; + } + return i; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/last.js new file mode 100644 index 00000000000000..bf9d2f29249d09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/last.js @@ -0,0 +1,9 @@ +'use strict'; + +var lastIndex = require('./last-index'); + +module.exports = function () { + var i; + if ((i = lastIndex.call(this)) !== null) return this[i]; + return undefined; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/implement.js new file mode 100644 index 00000000000000..3aabb87440e099 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'map', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/index.js new file mode 100644 index 00000000000000..66f66607df4f14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? + Array.prototype.map : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/is-implemented.js new file mode 100644 index 00000000000000..c328b473302cea --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var identity = require('../../../function/identity') + , SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).map(identity) instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/shim.js new file mode 100644 index 00000000000000..2ee731347b1aee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/map/shim.js @@ -0,0 +1,21 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + , callable = require('../../../object/valid-callable') + + , isArray = Array.isArray, map = Array.prototype.map + , forEach = Array.prototype.forEach, call = Function.prototype.call; + +module.exports = function (callbackFn/*, thisArg*/) { + var result, thisArg; + if (!this || !isArray(this) || isPlainArray(this)) { + return map.apply(this, arguments); + } + callable(callbackFn); + thisArg = arguments[1]; + result = new this.constructor(this.length); + forEach.call(this, function (val, i, self) { + result[i] = call.call(callbackFn, thisArg, val, i, self); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/remove.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/remove.js new file mode 100644 index 00000000000000..dcf843313d5fcb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/remove.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexOf = require('./e-index-of') + + , forEach = Array.prototype.forEach, splice = Array.prototype.splice; + +module.exports = function (item/*, …item*/) { + forEach.call(arguments, function (item) { + var index = indexOf.call(this, item); + if (index !== -1) splice.call(this, index, 1); + }, this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/separate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/separate.js new file mode 100644 index 00000000000000..dc974b832e07d2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/separate.js @@ -0,0 +1,10 @@ +'use strict'; + +var forEach = Array.prototype.forEach; + +module.exports = function (sep) { + var result = []; + forEach.call(this, function (val, i) { result.push(val, sep); }); + result.pop(); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/implement.js new file mode 100644 index 00000000000000..cd488a063956e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'slice', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/index.js new file mode 100644 index 00000000000000..72200ca9e381b6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.prototype.slice : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/is-implemented.js new file mode 100644 index 00000000000000..ec1985e70ee034 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).slice() instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/shim.js new file mode 100644 index 00000000000000..2761a1aad8340d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/slice/shim.js @@ -0,0 +1,35 @@ +'use strict'; + +var toInteger = require('../../../number/to-integer') + , toPosInt = require('../../../number/to-pos-integer') + , isPlainArray = require('../../is-plain-array') + + , isArray = Array.isArray, slice = Array.prototype.slice + , hasOwnProperty = Object.prototype.hasOwnProperty, max = Math.max; + +module.exports = function (start, end) { + var length, result, i; + if (!this || !isArray(this) || isPlainArray(this)) { + return slice.apply(this, arguments); + } + length = toPosInt(this.length); + start = toInteger(start); + if (start < 0) start = max(length + start, 0); + else if (start > length) start = length; + if (end === undefined) { + end = length; + } else { + end = toInteger(end); + if (end < 0) end = max(length + end, 0); + else if (end > length) end = length; + } + if (start > end) start = end; + result = new this.constructor(end - start); + i = 0; + while (start !== end) { + if (hasOwnProperty.call(this, start)) result[i] = this[start]; + ++i; + ++start; + } + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/some-right.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/some-right.js new file mode 100644 index 00000000000000..de7460d62234cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/some-right.js @@ -0,0 +1,22 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , value = require('../../object/valid-value') + + , hasOwnProperty = Object.prototype.hasOwnProperty + , call = Function.prototype.call; + +module.exports = function (cb/*, thisArg*/) { + var i, self, thisArg; + self = Object(value(this)); + callable(cb); + thisArg = arguments[1]; + + for (i = self.length; i >= 0; --i) { + if (hasOwnProperty.call(self, i) && + call.call(cb, thisArg, self[i], i, self)) { + return true; + } + } + return false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/implement.js new file mode 100644 index 00000000000000..aab1f8eff677b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'splice', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/index.js new file mode 100644 index 00000000000000..e8ecf3cf856171 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.prototype.splice : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/is-implemented.js new file mode 100644 index 00000000000000..ffddaa81ef83dd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +var SubArray = require('../../_sub-array-dummy-safe'); + +module.exports = function () { + return (new SubArray()).splice(0) instanceof SubArray; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/shim.js new file mode 100644 index 00000000000000..a8505a2ce2a201 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/splice/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var isPlainArray = require('../../is-plain-array') + + , isArray = Array.isArray, splice = Array.prototype.splice + , forEach = Array.prototype.forEach; + +module.exports = function (start, deleteCount/*, …items*/) { + var arr = splice.apply(this, arguments), result; + if (!this || !isArray(this) || isPlainArray(this)) return arr; + result = new this.constructor(arr.length); + forEach.call(arr, function (val, i) { result[i] = val; }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/uniq.js new file mode 100644 index 00000000000000..db0146555733a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/uniq.js @@ -0,0 +1,13 @@ +'use strict'; + +var indexOf = require('./e-index-of') + + , filter = Array.prototype.filter + + , isFirst; + +isFirst = function (value, index) { + return indexOf.call(this, value) === index; +}; + +module.exports = function () { return filter.call(this, isFirst, this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/implement.js new file mode 100644 index 00000000000000..237281fd3beed0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array.prototype, 'values', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/index.js new file mode 100644 index 00000000000000..c0832c30ea4566 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Array.prototype.values : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/is-implemented.js new file mode 100644 index 00000000000000..cc0c6294e2af14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function () { + var arr = ['foo', 1], iterator, result; + if (typeof arr.values !== 'function') return false; + iterator = arr.values(); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== 'foo') return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/shim.js new file mode 100644 index 00000000000000..f6555fd858e99a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/#/values/shim.js @@ -0,0 +1,4 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array'); +module.exports = function () { return new ArrayIterator(this, 'value'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_is-extensible.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_is-extensible.js new file mode 100644 index 00000000000000..612320647b39f6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_is-extensible.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = (function () { + var SubArray = require('./_sub-array-dummy'), arr; + + if (!SubArray) return false; + arr = new SubArray(); + if (!Array.isArray(arr)) return false; + if (!(arr instanceof SubArray)) return false; + + arr[34] = 'foo'; + return (arr.length === 35); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_sub-array-dummy-safe.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_sub-array-dummy-safe.js new file mode 100644 index 00000000000000..5baf8a8d1127a4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_sub-array-dummy-safe.js @@ -0,0 +1,23 @@ +'use strict'; + +var setPrototypeOf = require('../object/set-prototype-of') + , isExtensible = require('./_is-extensible'); + +module.exports = (function () { + var SubArray; + + if (isExtensible) return require('./_sub-array-dummy'); + + if (!setPrototypeOf) return null; + SubArray = function () { + var arr = Array.apply(this, arguments); + setPrototypeOf(arr, SubArray.prototype); + return arr; + }; + setPrototypeOf(SubArray, Array); + SubArray.prototype = Object.create(Array.prototype, { + constructor: { value: SubArray, enumerable: false, writable: true, + configurable: true } + }); + return SubArray; +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_sub-array-dummy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_sub-array-dummy.js new file mode 100644 index 00000000000000..a926d1a32ddd7e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/_sub-array-dummy.js @@ -0,0 +1,16 @@ +'use strict'; + +var setPrototypeOf = require('../object/set-prototype-of'); + +module.exports = (function () { + var SubArray; + + if (!setPrototypeOf) return null; + SubArray = function () { Array.apply(this, arguments); }; + setPrototypeOf(SubArray, Array); + SubArray.prototype = Object.create(Array.prototype, { + constructor: { value: SubArray, enumerable: false, writable: true, + configurable: true } + }); + return SubArray; +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/implement.js new file mode 100644 index 00000000000000..f3411b13770743 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array, 'from', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/index.js new file mode 100644 index 00000000000000..3b99cda8ec3db6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.from + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/is-implemented.js new file mode 100644 index 00000000000000..63ff2a572a353b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function () { + var from = Array.from, arr, result; + if (typeof from !== 'function') return false; + arr = ['raz', 'dwa']; + result = from(arr); + return Boolean(result && (result !== arr) && (result[1] === 'dwa')); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/shim.js new file mode 100644 index 00000000000000..a90ba2f9730c54 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/from/shim.js @@ -0,0 +1,106 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , isArguments = require('../../function/is-arguments') + , isFunction = require('../../function/is-function') + , toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , validValue = require('../../object/valid-value') + , isString = require('../../string/is-string') + + , isArray = Array.isArray, call = Function.prototype.call + , desc = { configurable: true, enumerable: true, writable: true, value: null } + , defineProperty = Object.defineProperty; + +module.exports = function (arrayLike/*, mapFn, thisArg*/) { + var mapFn = arguments[1], thisArg = arguments[2], Constructor, i, j, arr, l, code, iterator + , result, getIterator, value; + + arrayLike = Object(validValue(arrayLike)); + + if (mapFn != null) callable(mapFn); + if (!this || (this === Array) || !isFunction(this)) { + // Result: Plain array + if (!mapFn) { + if (isArguments(arrayLike)) { + // Source: Arguments + l = arrayLike.length; + if (l !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (isArray(arrayLike)) { + // Source: Array + arr = new Array(l = arrayLike.length); + for (i = 0; i < l; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + // Result: Non plain array + Constructor = this; + } + + if (!isArray(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { + // Source: Iterator + iterator = callable(getIterator).call(arrayLike); + if (Constructor) arr = new Constructor(); + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (!Constructor) { + arr[i] = value; + } else { + desc.value = value; + defineProperty(arr, i, desc); + } + result = iterator.next(); + ++i; + } + l = i; + } else if (isString(arrayLike)) { + // Source: String + l = arrayLike.length; + if (Constructor) arr = new Constructor(); + for (i = 0, j = 0; i < l; ++i) { + value = arrayLike[i]; + if ((i + 1) < l) { + code = value.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) value += arrayLike[++i]; + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (!Constructor) { + arr[j] = value; + } else { + desc.value = value; + defineProperty(arr, j, desc); + } + ++j; + } + l = j; + } + } + if (l === undefined) { + // Source: array or array-like + l = toPosInt(arrayLike.length); + if (Constructor) arr = new Constructor(l); + for (i = 0; i < l; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (!Constructor) { + arr[i] = value; + } else { + desc.value = value; + defineProperty(arr, i, desc); + } + } + } + if (Constructor) { + desc.value = null; + arr.length = l; + } + return arr; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/generate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/generate.js new file mode 100644 index 00000000000000..5e066750b1d5ba --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/generate.js @@ -0,0 +1,20 @@ +'use strict'; + +var toPosInt = require('../number/to-pos-integer') + , value = require('../object/valid-value') + + , slice = Array.prototype.slice; + +module.exports = function (length/*, …fill*/) { + var arr, l; + length = toPosInt(value(length)); + if (length === 0) return []; + + arr = (arguments.length < 2) ? [undefined] : + slice.call(arguments, 1, 1 + length); + + while ((l = arr.length) < length) { + arr = arr.concat(arr.slice(0, length - l)); + } + return arr; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/index.js new file mode 100644 index 00000000000000..7a6867894b56dd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/index.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + from: require('./from'), + generate: require('./generate'), + isPlainArray: require('./is-plain-array'), + of: require('./of'), + toArray: require('./to-array'), + validArray: require('./valid-array') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/is-plain-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/is-plain-array.js new file mode 100644 index 00000000000000..6b37e4069738b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/is-plain-array.js @@ -0,0 +1,11 @@ +'use strict'; + +var isArray = Array.isArray, getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (obj) { + var proto; + if (!obj || !isArray(obj)) return false; + proto = getPrototypeOf(obj); + if (!isArray(proto)) return false; + return !isArray(getPrototypeOf(proto)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/implement.js new file mode 100644 index 00000000000000..bf2a5a54a740e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Array, 'of', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/index.js new file mode 100644 index 00000000000000..07ee54dbcd4283 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Array.of + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/is-implemented.js new file mode 100644 index 00000000000000..4390a10863326b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + var of = Array.of, result; + if (typeof of !== 'function') return false; + result = of('foo', 'bar'); + return Boolean(result && (result[1] === 'bar')); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/shim.js new file mode 100644 index 00000000000000..de72bc92291154 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/of/shim.js @@ -0,0 +1,19 @@ +'use strict'; + +var isFunction = require('../../function/is-function') + + , slice = Array.prototype.slice, defineProperty = Object.defineProperty + , desc = { configurable: true, enumerable: true, writable: true, value: null }; + +module.exports = function (/*…items*/) { + var result, i, l; + if (!this || (this === Array) || !isFunction(this)) return slice.call(arguments); + result = new this(l = arguments.length); + for (i = 0; i < l; ++i) { + desc.value = arguments[i]; + defineProperty(result, i, desc); + } + desc.value = null; + result.length = l; + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/to-array.js new file mode 100644 index 00000000000000..ce908dd912959b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/to-array.js @@ -0,0 +1,9 @@ +'use strict'; + +var from = require('./from') + + , isArray = Array.isArray; + +module.exports = function (arrayLike) { + return isArray(arrayLike) ? arrayLike : from(arrayLike); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/valid-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/valid-array.js new file mode 100644 index 00000000000000..d86a8f5f242b27 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/array/valid-array.js @@ -0,0 +1,8 @@ +'use strict'; + +var isArray = Array.isArray; + +module.exports = function (value) { + if (isArray(value)) return value; + throw new TypeError(value + " is not an array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/boolean/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/boolean/index.js new file mode 100644 index 00000000000000..c193b948eb9d01 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/boolean/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + isBoolean: require('./is-boolean') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/boolean/is-boolean.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/boolean/is-boolean.js new file mode 100644 index 00000000000000..5d1a802e11211c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/boolean/is-boolean.js @@ -0,0 +1,10 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(true); + +module.exports = function (x) { + return (typeof x === 'boolean') || ((typeof x === 'object') && + ((x instanceof Boolean) || (toString.call(x) === id))); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/copy.js new file mode 100644 index 00000000000000..69e2eb09fcbcf1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/copy.js @@ -0,0 +1,5 @@ +'use strict'; + +var getTime = Date.prototype.getTime; + +module.exports = function () { return new Date(getTime.call(this)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/days-in-month.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/days-in-month.js new file mode 100644 index 00000000000000..e780efe3c7f99e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/days-in-month.js @@ -0,0 +1,17 @@ +'use strict'; + +var getMonth = Date.prototype.getMonth; + +module.exports = function () { + switch (getMonth.call(this)) { + case 1: + return this.getFullYear() % 4 ? 28 : 29; + case 3: + case 5: + case 8: + case 10: + return 30; + default: + return 31; + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-day.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-day.js new file mode 100644 index 00000000000000..0c9eb8b62788cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-day.js @@ -0,0 +1,8 @@ +'use strict'; + +var setHours = Date.prototype.setHours; + +module.exports = function () { + setHours.call(this, 0, 0, 0, 0); + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-month.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-month.js new file mode 100644 index 00000000000000..7328c250b36506 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-month.js @@ -0,0 +1,8 @@ +'use strict'; + +var floorDay = require('./floor-day'); + +module.exports = function () { + floorDay.call(this).setDate(1); + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-year.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-year.js new file mode 100644 index 00000000000000..9c5085389fbf67 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/floor-year.js @@ -0,0 +1,8 @@ +'use strict'; + +var floorMonth = require('./floor-month'); + +module.exports = function () { + floorMonth.call(this).setMonth(0); + return this; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/format.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/format.js new file mode 100644 index 00000000000000..15bd95f7eddf21 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/format.js @@ -0,0 +1,21 @@ +'use strict'; + +var pad = require('../../number/#/pad') + , date = require('../valid-date') + + , format; + +format = require('../../string/format-method')({ + Y: function () { return String(this.getFullYear()); }, + y: function () { return String(this.getFullYear()).slice(-2); }, + m: function () { return pad.call(this.getMonth() + 1, 2); }, + d: function () { return pad.call(this.getDate(), 2); }, + H: function () { return pad.call(this.getHours(), 2); }, + M: function () { return pad.call(this.getMinutes(), 2); }, + S: function () { return pad.call(this.getSeconds(), 2); }, + L: function () { return pad.call(this.getMilliseconds(), 3); } +}); + +module.exports = function (pattern) { + return format.call(date(this), pattern); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/index.js new file mode 100644 index 00000000000000..f71b2950029e59 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/#/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + copy: require('./copy'), + daysInMonth: require('./days-in-month'), + floorDay: require('./floor-day'), + floorMonth: require('./floor-month'), + floorYear: require('./floor-year'), + format: require('./format') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/index.js new file mode 100644 index 00000000000000..eac33fbe6dddce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/index.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + isDate: require('./is-date'), + validDate: require('./valid-date') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/is-date.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/is-date.js new file mode 100644 index 00000000000000..6ba236ecbc0783 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/is-date.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(new Date()); + +module.exports = function (x) { + return (x && ((x instanceof Date) || (toString.call(x) === id))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/valid-date.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/valid-date.js new file mode 100644 index 00000000000000..7d1a9b60d4748a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/date/valid-date.js @@ -0,0 +1,8 @@ +'use strict'; + +var isDate = require('./is-date'); + +module.exports = function (x) { + if (!isDate(x)) throw new TypeError(x + " is not a Date object"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/#/index.js new file mode 100644 index 00000000000000..b984aa91fef8b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/#/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + throw: require('./throw') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/#/throw.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/#/throw.js new file mode 100644 index 00000000000000..7e15ebd1cf028b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/#/throw.js @@ -0,0 +1,5 @@ +'use strict'; + +var error = require('../valid-error'); + +module.exports = function () { throw error(this); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/custom.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/custom.js new file mode 100644 index 00000000000000..bbc2dc20b462b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/custom.js @@ -0,0 +1,20 @@ +'use strict'; + +var assign = require('../object/assign') + + , captureStackTrace = Error.captureStackTrace; + +exports = module.exports = function (message/*, code, ext*/) { + var err = new Error(), code = arguments[1], ext = arguments[2]; + if (ext == null) { + if (code && (typeof code === 'object')) { + ext = code; + code = null; + } + } + if (ext != null) assign(err, ext); + err.message = String(message); + if (code != null) err.code = String(code); + if (captureStackTrace) captureStackTrace(err, exports); + return err; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/index.js new file mode 100644 index 00000000000000..62984b52de0871 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + custom: require('./custom'), + isError: require('./is-error'), + validError: require('./valid-error') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/is-error.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/is-error.js new file mode 100644 index 00000000000000..422705faf71d2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/is-error.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(new Error()); + +module.exports = function (x) { + return (x && ((x instanceof Error) || (toString.call(x)) === id)) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/valid-error.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/valid-error.js new file mode 100644 index 00000000000000..0bef768a776d09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/error/valid-error.js @@ -0,0 +1,8 @@ +'use strict'; + +var isError = require('./is-error'); + +module.exports = function (x) { + if (!isError(x)) throw new TypeError(x + " is not an Error object"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/compose.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/compose.js new file mode 100644 index 00000000000000..1da5e01162dcf5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/compose.js @@ -0,0 +1,20 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , aFrom = require('../../array/from') + + , apply = Function.prototype.apply, call = Function.prototype.call + , callFn = function (arg, fn) { return call.call(fn, this, arg); }; + +module.exports = function (fn/*, …fnn*/) { + var fns, first; + if (!fn) callable(fn); + fns = [this].concat(aFrom(arguments)); + fns.forEach(callable); + fns = fns.reverse(); + first = fns[0]; + fns = fns.slice(1); + return function (arg) { + return fns.reduce(callFn, apply.call(first, this, arguments)); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/copy.js new file mode 100644 index 00000000000000..e1467f7671946c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/copy.js @@ -0,0 +1,15 @@ +'use strict'; + +var mixin = require('../../object/mixin') + , validFunction = require('../valid-function') + + , re = /^\s*function\s*([\0-'\)-\uffff]+)*\s*\(([\0-\(\*-\uffff]*)\)\s*\{/; + +module.exports = function () { + var match = String(validFunction(this)).match(re), fn; + + fn = new Function('fn', 'return function ' + match[1].trim() + '(' + + match[2] + ') { return fn.apply(this, arguments); };')(this); + try { mixin(fn, this); } catch (ignore) {} + return fn; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/curry.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/curry.js new file mode 100644 index 00000000000000..943d6faf860772 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/curry.js @@ -0,0 +1,24 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , callable = require('../../object/valid-callable') + , defineLength = require('../_define-length') + + , slice = Array.prototype.slice, apply = Function.prototype.apply + , curry; + +curry = function self(fn, length, preArgs) { + return defineLength(function () { + var args = preArgs ? + preArgs.concat(slice.call(arguments, 0, length - preArgs.length)) : + slice.call(arguments, 0, length); + return (args.length === length) ? apply.call(fn, this, args) : + self(fn, length, args); + }, preArgs ? (length - preArgs.length) : length); +}; + +module.exports = function (/*length*/) { + var length = arguments[0]; + return curry(callable(this), + isNaN(length) ? toPosInt(this.length) : toPosInt(length)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/index.js new file mode 100644 index 00000000000000..8d0da007fa182b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/index.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + compose: require('./compose'), + copy: require('./copy'), + curry: require('./curry'), + lock: require('./lock'), + not: require('./not'), + partial: require('./partial'), + spread: require('./spread'), + toStringTokens: require('./to-string-tokens') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/lock.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/lock.js new file mode 100644 index 00000000000000..91e1a65cd91887 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/lock.js @@ -0,0 +1,12 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + + , apply = Function.prototype.apply; + +module.exports = function (/*…args*/) { + var fn = callable(this) + , args = arguments; + + return function () { return apply.call(fn, this, args); }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/not.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/not.js new file mode 100644 index 00000000000000..c6dbe97fb6ecd9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/not.js @@ -0,0 +1,14 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , defineLength = require('../_define-length') + + , apply = Function.prototype.apply; + +module.exports = function () { + var fn = callable(this); + + return defineLength(function () { + return !apply.call(fn, this, arguments); + }, fn.length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/partial.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/partial.js new file mode 100644 index 00000000000000..bf31a3575a56df --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/partial.js @@ -0,0 +1,16 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + , aFrom = require('../../array/from') + , defineLength = require('../_define-length') + + , apply = Function.prototype.apply; + +module.exports = function (/*…args*/) { + var fn = callable(this) + , args = aFrom(arguments); + + return defineLength(function () { + return apply.call(fn, this, args.concat(aFrom(arguments))); + }, fn.length - args.length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/spread.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/spread.js new file mode 100644 index 00000000000000..d7c93b7e07ee15 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/spread.js @@ -0,0 +1,10 @@ +'use strict'; + +var callable = require('../../object/valid-callable') + + , apply = Function.prototype.apply; + +module.exports = function () { + var fn = callable(this); + return function (args) { return apply.call(fn, this, args); }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/to-string-tokens.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/to-string-tokens.js new file mode 100644 index 00000000000000..67afeae82def7e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/#/to-string-tokens.js @@ -0,0 +1,11 @@ +'use strict'; + +var validFunction = require('../valid-function') + + , re = new RegExp('^\\s*function[\\0-\'\\)-\\uffff]*' + + '\\(([\\0-\\(\\*-\\uffff]*)\\)\\s*\\{([\\0-\\uffff]*)\\}\\s*$'); + +module.exports = function () { + var data = String(validFunction(this)).match(re); + return { args: data[1], body: data[2] }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/_define-length.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/_define-length.js new file mode 100644 index 00000000000000..496ea62c52b612 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/_define-length.js @@ -0,0 +1,44 @@ +'use strict'; + +var toPosInt = require('../number/to-pos-integer') + + , test = function (a, b) {}, desc, defineProperty + , generate, mixin; + +try { + Object.defineProperty(test, 'length', { configurable: true, writable: false, + enumerable: false, value: 1 }); +} catch (ignore) {} + +if (test.length === 1) { + // ES6 + desc = { configurable: true, writable: false, enumerable: false }; + defineProperty = Object.defineProperty; + module.exports = function (fn, length) { + length = toPosInt(length); + if (fn.length === length) return fn; + desc.value = length; + return defineProperty(fn, 'length', desc); + }; +} else { + mixin = require('../object/mixin'); + generate = (function () { + var cache = []; + return function (l) { + var args, i = 0; + if (cache[l]) return cache[l]; + args = []; + while (l--) args.push('a' + (++i).toString(36)); + return new Function('fn', 'return function (' + args.join(', ') + + ') { return fn.apply(this, arguments); };'); + }; + }()); + module.exports = function (src, length) { + var target; + length = toPosInt(length); + if (src.length === length) return src; + target = generate(length)(src); + try { mixin(target, src); } catch (ignore) {} + return target; + }; +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/constant.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/constant.js new file mode 100644 index 00000000000000..10f1e203e2d023 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/constant.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x) { + return function () { return x; }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/identity.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/identity.js new file mode 100644 index 00000000000000..a9289f0b21dfac --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/identity.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (x) { return x; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/index.js new file mode 100644 index 00000000000000..cfad3f3ec25bf8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/index.js @@ -0,0 +1,15 @@ +// Export all modules. + +'use strict'; + +module.exports = { + '#': require('./#'), + constant: require('./constant'), + identity: require('./identity'), + invoke: require('./invoke'), + isArguments: require('./is-arguments'), + isFunction: require('./is-function'), + noop: require('./noop'), + pluck: require('./pluck'), + validFunction: require('./valid-function') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/invoke.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/invoke.js new file mode 100644 index 00000000000000..9195afddd8c1e8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/invoke.js @@ -0,0 +1,15 @@ +'use strict'; + +var isCallable = require('../object/is-callable') + , value = require('../object/valid-value') + + , slice = Array.prototype.slice, apply = Function.prototype.apply; + +module.exports = function (name/*, …args*/) { + var args = slice.call(arguments, 1), isFn = isCallable(name); + return function (obj) { + value(obj); + return apply.call(isFn ? name : obj[name], obj, + args.concat(slice.call(arguments, 1))); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/is-arguments.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/is-arguments.js new file mode 100644 index 00000000000000..9a29855f87dc6a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/is-arguments.js @@ -0,0 +1,7 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call((function () { return arguments; }())); + +module.exports = function (x) { return (toString.call(x) === id); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/is-function.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/is-function.js new file mode 100644 index 00000000000000..ab4399ce25e98b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/is-function.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(require('./noop')); + +module.exports = function (f) { + return (typeof f === "function") && (toString.call(f) === id); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/noop.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/noop.js new file mode 100644 index 00000000000000..aa43baedf1d5d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/noop.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function () {}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/pluck.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/pluck.js new file mode 100644 index 00000000000000..7f70a30cbd95ee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/pluck.js @@ -0,0 +1,7 @@ +'use strict'; + +var value = require('../object/valid-value'); + +module.exports = function (name) { + return function (o) { return value(o)[name]; }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/valid-function.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/valid-function.js new file mode 100644 index 00000000000000..05fdee2c3debda --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/function/valid-function.js @@ -0,0 +1,8 @@ +'use strict'; + +var isFunction = require('./is-function'); + +module.exports = function (x) { + if (!isFunction(x)) throw new TypeError(x + " is not a function"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/global.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/global.js new file mode 100644 index 00000000000000..872a40e814be44 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/global.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = new Function("return this")(); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/index.js new file mode 100644 index 00000000000000..db9a7600b47115 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/index.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + global: require('./global'), + + array: require('./array'), + boolean: require('./boolean'), + date: require('./date'), + error: require('./error'), + function: require('./function'), + iterable: require('./iterable'), + math: require('./math'), + number: require('./number'), + object: require('./object'), + regExp: require('./reg-exp'), + string: require('./string') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/for-each.js new file mode 100644 index 00000000000000..f1e20425b329a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/for-each.js @@ -0,0 +1,12 @@ +'use strict'; + +var forOf = require('es6-iterator/for-of') + , isIterable = require('es6-iterator/is-iterable') + , iterable = require('./validate') + + , forEach = Array.prototype.forEach; + +module.exports = function (target, cb/*, thisArg*/) { + if (isIterable(iterable(target))) forOf(target, cb, arguments[2]); + else forEach.call(target, cb, arguments[2]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/index.js new file mode 100644 index 00000000000000..a3e16a5e892c6c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + forEach: require('./for-each'), + is: require('./is'), + validate: require('./validate'), + validateObject: require('./validate-object') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/is.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/is.js new file mode 100644 index 00000000000000..bb8bf287276bee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/is.js @@ -0,0 +1,10 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , isArrayLike = require('../object/is-array-like'); + +module.exports = function (x) { + if (x == null) return false; + if (typeof x[iteratorSymbol] === 'function') return true; + return isArrayLike(x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/validate-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/validate-object.js new file mode 100644 index 00000000000000..988a6adb6249e7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/validate-object.js @@ -0,0 +1,9 @@ +'use strict'; + +var isObject = require('../object/is-object') + , is = require('./is'); + +module.exports = function (x) { + if (is(x) && isObject(x)) return x; + throw new TypeError(x + " is not an iterable or array-like object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/validate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/validate.js new file mode 100644 index 00000000000000..1be6d7fcd96e44 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/iterable/validate.js @@ -0,0 +1,8 @@ +'use strict'; + +var is = require('./is'); + +module.exports = function (x) { + if (is(x)) return x; + throw new TypeError(x + " is not an iterable or array-like"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/_pack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/_pack-ieee754.js new file mode 100644 index 00000000000000..eecda5654dad51 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/_pack-ieee754.js @@ -0,0 +1,82 @@ +// Credit: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min + , pow = Math.pow, LN2 = Math.LN2 + , roundToEven; + +roundToEven = function (n) { + var w = floor(n), f = n - w; + if (f < 0.5) return w; + if (f > 0.5) return w + 1; + return w % 2 ? w + 1 : w; +}; + +module.exports = function (v, ebits, fbits) { + var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes; + + // Compute sign, exponent, fraction + if (isNaN(v)) { + // NaN + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping + e = (1 << ebits) - 1; + f = pow(2, fbits - 1); + s = 0; + } else if (v === Infinity || v === -Infinity) { + e = (1 << ebits) - 1; + f = 0; + s = (v < 0) ? 1 : 0; + } else if (v === 0) { + e = 0; + f = 0; + s = (1 / v === -Infinity) ? 1 : 0; + } else { + s = v < 0; + v = abs(v); + + if (v >= pow(2, 1 - bias)) { + e = min(floor(log(v) / LN2), 1023); + f = roundToEven(v / pow(2, e) * pow(2, fbits)); + if (f / pow(2, fbits) >= 2) { + e = e + 1; + f = 1; + } + if (e > bias) { + // Overflow + e = (1 << ebits) - 1; + f = 0; + } else { + // Normal + e = e + bias; + f = f - pow(2, fbits); + } + } else { + // Subnormal + e = 0; + f = roundToEven(v / pow(2, 1 - bias - fbits)); + } + } + + // Pack sign, exponent, fraction + bits = []; + for (i = fbits; i; i -= 1) { + bits.push(f % 2 ? 1 : 0); + f = floor(f / 2); + } + for (i = ebits; i; i -= 1) { + bits.push(e % 2 ? 1 : 0); + e = floor(e / 2); + } + bits.push(s ? 1 : 0); + bits.reverse(); + str = bits.join(''); + + // Bits to bytes + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/_unpack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/_unpack-ieee754.js new file mode 100644 index 00000000000000..c9f26f2bb6f12e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/_unpack-ieee754.js @@ -0,0 +1,33 @@ +// Credit: https://github.com/paulmillr/es6-shim/ + +'use strict'; + +var pow = Math.pow; + +module.exports = function (bytes, ebits, fbits) { + // Bytes to bits + var bits = [], i, j, b, str, + bias, s, e, f; + + for (i = bytes.length; i; i -= 1) { + b = bytes[i - 1]; + for (j = 8; j; j -= 1) { + bits.push(b % 2 ? 1 : 0); + b = b >> 1; + } + } + bits.reverse(); + str = bits.join(''); + + // Unpack sign, exponent, fraction + bias = (1 << (ebits - 1)) - 1; + s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e = parseInt(str.substring(1, 1 + ebits), 2); + f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) return f !== 0 ? NaN : s * Infinity; + if (e > 0) return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); + if (f !== 0) return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); + return s < 0 ? -0 : 0; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/implement.js new file mode 100644 index 00000000000000..f48ad11de722a1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'acosh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/index.js new file mode 100644 index 00000000000000..00ddea69dd7a46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.acosh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/is-implemented.js new file mode 100644 index 00000000000000..363f0d8bcdd61b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var acosh = Math.acosh; + if (typeof acosh !== 'function') return false; + return acosh(2) === 1.3169578969248166; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/shim.js new file mode 100644 index 00000000000000..89a24b5d767e18 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/acosh/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var log = Math.log, sqrt = Math.sqrt; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < 1) return NaN; + if (x === 1) return 0; + if (x === Infinity) return x; + return log(x + sqrt(x * x - 1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/implement.js new file mode 100644 index 00000000000000..21f64d50491960 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'asinh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/index.js new file mode 100644 index 00000000000000..d415144eea7373 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.asinh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/is-implemented.js new file mode 100644 index 00000000000000..6c205f418cae9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var asinh = Math.asinh; + if (typeof asinh !== 'function') return false; + return asinh(2) === 1.4436354751788103; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/shim.js new file mode 100644 index 00000000000000..42fbf1457f7604 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/asinh/shim.js @@ -0,0 +1,15 @@ +'use strict'; + +var log = Math.log, sqrt = Math.sqrt; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + if (x < 0) { + x = -x; + return -log(x + sqrt(x * x + 1)); + } + return log(x + sqrt(x * x + 1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/implement.js new file mode 100644 index 00000000000000..1a4851343b3196 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'atanh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/index.js new file mode 100644 index 00000000000000..785b3deba5eb11 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.atanh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/is-implemented.js new file mode 100644 index 00000000000000..dbaf18ece2d2b0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var atanh = Math.atanh; + if (typeof atanh !== 'function') return false; + return atanh(0.5) === 0.5493061443340549; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/shim.js new file mode 100644 index 00000000000000..531e2891fe2f67 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/atanh/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var log = Math.log; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < -1) return NaN; + if (x > 1) return NaN; + if (x === -1) return -Infinity; + if (x === 1) return Infinity; + if (x === 0) return x; + return 0.5 * log((1 + x) / (1 - x)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/implement.js new file mode 100644 index 00000000000000..3a12dde487eba3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'cbrt', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/index.js new file mode 100644 index 00000000000000..89f966dfe4ed1a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.cbrt + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/is-implemented.js new file mode 100644 index 00000000000000..69809f3cf4956d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var cbrt = Math.cbrt; + if (typeof cbrt !== 'function') return false; + return cbrt(2) === 1.2599210498948732; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/shim.js new file mode 100644 index 00000000000000..bca196026c730a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cbrt/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var pow = Math.pow; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + if (x < 0) return -pow(-x, 1 / 3); + return pow(x, 1 / 3); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/implement.js new file mode 100644 index 00000000000000..339df33ea71822 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'clz32', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/index.js new file mode 100644 index 00000000000000..1687b337e3bdf9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.clz32 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/is-implemented.js new file mode 100644 index 00000000000000..ccc8f71337bf29 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var clz32 = Math.clz32; + if (typeof clz32 !== 'function') return false; + return clz32(1000) === 22; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/shim.js new file mode 100644 index 00000000000000..2a582da3bf0b31 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/clz32/shim.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (value) { + value = value >>> 0; + return value ? 32 - value.toString(2).length : 32; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/implement.js new file mode 100644 index 00000000000000..f90d83056c8b62 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'cosh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/index.js new file mode 100644 index 00000000000000..000636ab774ae5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.cosh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/is-implemented.js new file mode 100644 index 00000000000000..c796bcbf314f05 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var cosh = Math.cosh; + if (typeof cosh !== 'function') return false; + return cosh(1) === 1.5430806348152437; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/shim.js new file mode 100644 index 00000000000000..f9062bd976c693 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/cosh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +var exp = Math.exp; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return 1; + if (!isFinite(x)) return Infinity; + return (exp(x) + exp(-x)) / 2; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/implement.js new file mode 100644 index 00000000000000..fc20c8cfa068c4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'expm1', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/index.js new file mode 100644 index 00000000000000..4c1bc77a222f78 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.expm1 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/is-implemented.js new file mode 100644 index 00000000000000..3b106d5d535858 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var expm1 = Math.expm1; + if (typeof expm1 !== 'function') return false; + return expm1(1).toFixed(15) === '1.718281828459045'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/shim.js new file mode 100644 index 00000000000000..9c8c2360857e59 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/expm1/shim.js @@ -0,0 +1,16 @@ +// Thanks: https://github.com/monolithed/ECMAScript-6 + +'use strict'; + +var exp = Math.exp; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (x === Infinity) return Infinity; + if (x === -Infinity) return -1; + + if ((x > -1.0e-6) && (x < 1.0e-6)) return x + x * x / 2; + return exp(x) - 1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/implement.js new file mode 100644 index 00000000000000..c55b26c464bce5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'fround', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/index.js new file mode 100644 index 00000000000000..a077ed0ba33aa7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.fround + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/is-implemented.js new file mode 100644 index 00000000000000..ffbf094e6b3447 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var fround = Math.fround; + if (typeof fround !== 'function') return false; + return fround(1.337) === 1.3370000123977661; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/shim.js new file mode 100644 index 00000000000000..f2c86e46a41c7a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/fround/shim.js @@ -0,0 +1,33 @@ +// Credit: https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js + +'use strict'; + +var toFloat32; + +if (typeof Float32Array !== 'undefined') { + toFloat32 = (function () { + var float32Array = new Float32Array(1); + return function (x) { + float32Array[0] = x; + return float32Array[0]; + }; + }()); +} else { + toFloat32 = (function () { + var pack = require('../_pack-ieee754') + , unpack = require('../_unpack-ieee754'); + + return function (x) { + return unpack(pack(x, 8, 23), 8, 23); + }; + }()); +} + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + + return toFloat32(x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/implement.js new file mode 100644 index 00000000000000..b27fda7a0961b9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'hypot', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/index.js new file mode 100644 index 00000000000000..334bc584cf7778 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.hypot + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/is-implemented.js new file mode 100644 index 00000000000000..e75c5d36be34c8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var hypot = Math.hypot; + if (typeof hypot !== 'function') return false; + return hypot(3, 4) === 5; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/shim.js new file mode 100644 index 00000000000000..3d0988bc13dd4e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/hypot/shim.js @@ -0,0 +1,34 @@ +// Thanks for hints: https://github.com/paulmillr/es6-shim + +'use strict'; + +var some = Array.prototype.some, abs = Math.abs, sqrt = Math.sqrt + + , compare = function (a, b) { return b - a; } + , divide = function (x) { return x / this; } + , add = function (sum, number) { return sum + number * number; }; + +module.exports = function (val1, val2/*, …valn*/) { + var result, numbers; + if (!arguments.length) return 0; + some.call(arguments, function (val) { + if (isNaN(val)) { + result = NaN; + return; + } + if (!isFinite(val)) { + result = Infinity; + return true; + } + if (result !== undefined) return; + val = Number(val); + if (val === 0) return; + if (!numbers) numbers = [abs(val)]; + else numbers.push(abs(val)); + }); + if (result !== undefined) return result; + if (!numbers) return 0; + + numbers.sort(compare); + return numbers[0] * sqrt(numbers.map(divide, numbers[0]).reduce(add, 0)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/implement.js new file mode 100644 index 00000000000000..ed207bd271f7f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'imul', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/index.js new file mode 100644 index 00000000000000..41e5d5f010383f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.imul + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/is-implemented.js new file mode 100644 index 00000000000000..d8495dea2a8ec9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var imul = Math.imul; + if (typeof imul !== 'function') return false; + return imul(-1, 8) === -8; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/shim.js new file mode 100644 index 00000000000000..8fd8a8d7a79111 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/imul/shim.js @@ -0,0 +1,13 @@ +// Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference +// /Global_Objects/Math/imul + +'use strict'; + +module.exports = function (x, y) { + var xh = (x >>> 16) & 0xffff, xl = x & 0xffff + , yh = (y >>> 16) & 0xffff, yl = y & 0xffff; + + // the shift by 0 fixes the sign on the high part + // the final |0 converts the unsigned value into a signed value + return ((xl * yl) + (((xh * yl + xl * yh) << 16) >>> 0) | 0); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/index.js new file mode 100644 index 00000000000000..d112d0bfe0d04d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/index.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = { + acosh: require('./acosh'), + asinh: require('./asinh'), + atanh: require('./atanh'), + cbrt: require('./cbrt'), + clz32: require('./clz32'), + cosh: require('./cosh'), + expm1: require('./expm1'), + fround: require('./fround'), + hypot: require('./hypot'), + imul: require('./imul'), + log10: require('./log10'), + log2: require('./log2'), + log1p: require('./log1p'), + sign: require('./sign'), + sinh: require('./sinh'), + tanh: require('./tanh'), + trunc: require('./trunc') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/implement.js new file mode 100644 index 00000000000000..dd96edd80e0f20 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'log10', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/index.js new file mode 100644 index 00000000000000..a9eee513130691 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.log10 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/is-implemented.js new file mode 100644 index 00000000000000..c7f40ee7753bef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var log10 = Math.log10; + if (typeof log10 !== 'function') return false; + return log10(2) === 0.3010299956639812; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/shim.js new file mode 100644 index 00000000000000..fc77287f6176ff --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log10/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var log = Math.log, LOG10E = Math.LOG10E; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < 0) return NaN; + if (x === 0) return -Infinity; + if (x === 1) return 0; + if (x === Infinity) return Infinity; + + return log(x) * LOG10E; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/implement.js new file mode 100644 index 00000000000000..f62f91f6877d5b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'log1p', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/index.js new file mode 100644 index 00000000000000..107b114713cb57 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.log1p + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/is-implemented.js new file mode 100644 index 00000000000000..61e90974c5f5e0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var log1p = Math.log1p; + if (typeof log1p !== 'function') return false; + return log1p(1) === 0.6931471805599453; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/shim.js new file mode 100644 index 00000000000000..10acebca4ab9af --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log1p/shim.js @@ -0,0 +1,17 @@ +// Thanks: https://github.com/monolithed/ECMAScript-6/blob/master/ES6.js + +'use strict'; + +var log = Math.log; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < -1) return NaN; + if (x === -1) return -Infinity; + if (x === 0) return x; + if (x === Infinity) return Infinity; + + if (x > -1.0e-8 && x < 1.0e-8) return (x - x * x / 2); + return log(1 + x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/implement.js new file mode 100644 index 00000000000000..8483f0950aa965 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'log2', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/index.js new file mode 100644 index 00000000000000..87e9050abe0895 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.log2 + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/is-implemented.js new file mode 100644 index 00000000000000..802322faf38e32 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var log2 = Math.log2; + if (typeof log2 !== 'function') return false; + return log2(3).toFixed(15) === '1.584962500721156'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/shim.js new file mode 100644 index 00000000000000..cd80994a72b7d5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/log2/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var log = Math.log, LOG2E = Math.LOG2E; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x < 0) return NaN; + if (x === 0) return -Infinity; + if (x === 1) return 0; + if (x === Infinity) return Infinity; + + return log(x) * LOG2E; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/implement.js new file mode 100644 index 00000000000000..b0db2f413fa598 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'sign', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/index.js new file mode 100644 index 00000000000000..b2326333432fcb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sign + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/is-implemented.js new file mode 100644 index 00000000000000..6d0de475aba61e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var sign = Math.sign; + if (typeof sign !== 'function') return false; + return ((sign(10) === 1) && (sign(-20) === -1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/shim.js new file mode 100644 index 00000000000000..4df9c95aa5d64f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sign/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return (value > 0) ? 1 : -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/implement.js new file mode 100644 index 00000000000000..f259a631b5718a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'sinh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/index.js new file mode 100644 index 00000000000000..e5bea572f838d6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.sinh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/is-implemented.js new file mode 100644 index 00000000000000..888ec67a9c8cd8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var sinh = Math.sinh; + if (typeof sinh !== 'function') return false; + return ((sinh(1) === 1.1752011936438014) && (sinh(Number.MIN_VALUE) === 5e-324)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/shim.js new file mode 100644 index 00000000000000..5b725bed656d95 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/sinh/shim.js @@ -0,0 +1,17 @@ +// Parts of implementation taken from es6-shim project +// See: https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js + +'use strict'; + +var expm1 = require('../expm1') + + , abs = Math.abs, exp = Math.exp, e = Math.E; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (!isFinite(x)) return x; + if (abs(x) < 1) return (expm1(x) - expm1(-x)) / 2; + return (exp(x - 1) - exp(-x - 1)) * e / 2; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/implement.js new file mode 100644 index 00000000000000..5199a029c88b7e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'tanh', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/index.js new file mode 100644 index 00000000000000..6099c408a82be9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.tanh + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/is-implemented.js new file mode 100644 index 00000000000000..a7d22237136416 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var tanh = Math.tanh; + if (typeof tanh !== 'function') return false; + return ((tanh(1) === 0.7615941559557649) && (tanh(Number.MAX_VALUE) === 1)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/shim.js new file mode 100644 index 00000000000000..f6e948f2c53797 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/tanh/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +var exp = Math.exp; + +module.exports = function (x) { + var a, b; + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (x === Infinity) return 1; + if (x === -Infinity) return -1; + a = exp(x); + if (a === Infinity) return 1; + b = exp(-x); + if (b === Infinity) return -1; + return (a - b) / (a + b); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/implement.js new file mode 100644 index 00000000000000..3ee80ab2a0a0b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Math, 'trunc', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/index.js new file mode 100644 index 00000000000000..0b0f9b2ac93882 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Math.trunc + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/is-implemented.js new file mode 100644 index 00000000000000..3e8cde1f0053dd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var trunc = Math.trunc; + if (typeof trunc !== 'function') return false; + return (trunc(13.67) === 13) && (trunc(-13.67) === -13); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/shim.js new file mode 100644 index 00000000000000..02e2c2ad3bfcf4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/math/trunc/shim.js @@ -0,0 +1,13 @@ +'use strict'; + +var floor = Math.floor; + +module.exports = function (x) { + if (isNaN(x)) return NaN; + x = Number(x); + if (x === 0) return x; + if (x === Infinity) return Infinity; + if (x === -Infinity) return -Infinity; + if (x > 0) return floor(x); + return -floor(-x); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/#/index.js new file mode 100644 index 00000000000000..324811704b80a0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/#/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + pad: require('./pad') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/#/pad.js new file mode 100644 index 00000000000000..4478f6a11e0c9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/#/pad.js @@ -0,0 +1,15 @@ +'use strict'; + +var pad = require('../../string/#/pad') + , toPosInt = require('../to-pos-integer') + + , toFixed = Number.prototype.toFixed; + +module.exports = function (length/*, precision*/) { + var precision; + length = toPosInt(length); + precision = toPosInt(arguments[1]); + + return pad.call(precision ? toFixed.call(this, precision) : this, + '0', length + (precision ? (1 + precision) : 0)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/implement.js new file mode 100644 index 00000000000000..f0a670ae33824b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'EPSILON', { value: require('./'), + configurable: false, enumerable: false, writable: false }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/index.js new file mode 100644 index 00000000000000..4e4b621b7bc6f5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = 2.220446049250313e-16; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/is-implemented.js new file mode 100644 index 00000000000000..141f5d2f24a512 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/epsilon/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return (typeof Number.EPSILON === 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/index.js new file mode 100644 index 00000000000000..35daf78eea88c2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/index.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + EPSILON: require('./epsilon'), + isFinite: require('./is-finite'), + isInteger: require('./is-integer'), + isNaN: require('./is-nan'), + isNumber: require('./is-number'), + isSafeInteger: require('./is-safe-integer'), + MAX_SAFE_INTEGER: require('./max-safe-integer'), + MIN_SAFE_INTEGER: require('./min-safe-integer'), + toInteger: require('./to-integer'), + toPosInteger: require('./to-pos-integer'), + toUint32: require('./to-uint32') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/implement.js new file mode 100644 index 00000000000000..51d7cac07adb71 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isFinite', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/index.js new file mode 100644 index 00000000000000..15d5f40588134c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isFinite + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/is-implemented.js new file mode 100644 index 00000000000000..556e396bb0b0fd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var isFinite = Number.isFinite; + if (typeof isFinite !== 'function') return false; + return !isFinite('23') && isFinite(34) && !isFinite(Infinity); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/shim.js new file mode 100644 index 00000000000000..e3aee551a7053a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-finite/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (value) { + return (typeof value === 'number') && isFinite(value); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/implement.js new file mode 100644 index 00000000000000..fe53f28143ad0c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isInteger', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/index.js new file mode 100644 index 00000000000000..55e039a99d6d97 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isInteger + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/is-implemented.js new file mode 100644 index 00000000000000..a0e573be7c299d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var isInteger = Number.isInteger; + if (typeof isInteger !== 'function') return false; + return !isInteger('23') && isInteger(34) && !isInteger(32.34); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/shim.js new file mode 100644 index 00000000000000..5402939806da40 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-integer/shim.js @@ -0,0 +1,8 @@ +// Credit: http://www.2ality.com/2014/05/is-integer.html + +'use strict'; + +module.exports = function (value) { + if (typeof value !== 'number') return false; + return (value % 1 === 0); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/implement.js new file mode 100644 index 00000000000000..e1c5deea36a653 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isNaN', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/index.js new file mode 100644 index 00000000000000..3b2c4ca6bd902a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isNaN + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/is-implemented.js new file mode 100644 index 00000000000000..4cf276656365ca --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var isNaN = Number.isNaN; + if (typeof isNaN !== 'function') return false; + return !isNaN({}) && isNaN(NaN) && !isNaN(34); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/shim.js new file mode 100644 index 00000000000000..070d96cd460d3a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-nan/shim.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (value) { return (value !== value); } //jslint: ignore diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-number.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-number.js new file mode 100644 index 00000000000000..19a99e4f194c2e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-number.js @@ -0,0 +1,11 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(1); + +module.exports = function (x) { + return ((typeof x === 'number') || + ((x instanceof Number) || + ((typeof x === 'object') && (toString.call(x) === id)))); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/implement.js new file mode 100644 index 00000000000000..51cef960212134 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'isSafeInteger', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/index.js new file mode 100644 index 00000000000000..49adeaaf784e23 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Number.isSafeInteger + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..510b60e4e4bd43 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + var isSafeInteger = Number.isSafeInteger; + if (typeof isSafeInteger !== 'function') return false; + return !isSafeInteger('23') && isSafeInteger(34232322323) && + !isSafeInteger(9007199254740992); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/shim.js new file mode 100644 index 00000000000000..692acdd6ca7799 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/is-safe-integer/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +var isInteger = require('../is-integer/shim') + , maxValue = require('../max-safe-integer') + + , abs = Math.abs; + +module.exports = function (value) { + if (!isInteger(value)) return false; + return abs(value) <= maxValue; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/implement.js new file mode 100644 index 00000000000000..4e0bb5741d926d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'MAX_SAFE_INTEGER', { value: require('./'), + configurable: false, enumerable: false, writable: false }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/index.js new file mode 100644 index 00000000000000..ed5d6a5379fe15 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = Math.pow(2, 53) - 1; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..7bd08a9da4edc5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/max-safe-integer/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return (typeof Number.MAX_SAFE_INTEGER === 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/implement.js new file mode 100644 index 00000000000000..e3f110e419162f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Number, 'MIN_SAFE_INTEGER', { value: require('./'), + configurable: false, enumerable: false, writable: false }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/index.js new file mode 100644 index 00000000000000..1c6cc2744efe14 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = -(Math.pow(2, 53) - 1); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..efc9875f486d4a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/min-safe-integer/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return (typeof Number.MIN_SAFE_INTEGER === 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-integer.js new file mode 100644 index 00000000000000..60e798c5fda58d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-integer.js @@ -0,0 +1,12 @@ +'use strict'; + +var sign = require('../math/sign') + + , abs = Math.abs, floor = Math.floor; + +module.exports = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if ((value === 0) || !isFinite(value)) return value; + return sign(value) * floor(abs(value)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-pos-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-pos-integer.js new file mode 100644 index 00000000000000..605a302c7106f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-pos-integer.js @@ -0,0 +1,7 @@ +'use strict'; + +var toInteger = require('./to-integer') + + , max = Math.max; + +module.exports = function (value) { return max(0, toInteger(value)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-uint32.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-uint32.js new file mode 100644 index 00000000000000..6263e85ed6de95 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/number/to-uint32.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (value) { return value >>> 0; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/_iterate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/_iterate.js new file mode 100644 index 00000000000000..bf2c55d08601d3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/_iterate.js @@ -0,0 +1,29 @@ +// Internal method, used by iteration functions. +// Calls a function for each key-value pair found in object +// Optionally takes compareFn to iterate object in specific order + +'use strict'; + +var isCallable = require('./is-callable') + , callable = require('./valid-callable') + , value = require('./valid-value') + + , call = Function.prototype.call, keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (method, defVal) { + return function (obj, cb/*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(value(obj)); + callable(cb); + + list = keys(obj); + if (compareFn) { + list.sort(isCallable(compareFn) ? compareFn.bind(obj) : undefined); + } + return list[method](function (key, index) { + if (!propertyIsEnumerable.call(obj, key)) return defVal; + return call.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/implement.js new file mode 100644 index 00000000000000..3bcc68e31e1a44 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Object, 'assign', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/index.js new file mode 100644 index 00000000000000..ab0f9f249e81a8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.assign + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/is-implemented.js new file mode 100644 index 00000000000000..579ad2ddc433b9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function () { + var assign = Object.assign, obj; + if (typeof assign !== 'function') return false; + obj = { foo: 'raz' }; + assign(obj, { bar: 'dwa' }, { trzy: 'trzy' }); + return (obj.foo + obj.bar + obj.trzy) === 'razdwatrzy'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/shim.js new file mode 100644 index 00000000000000..74da11a86a8556 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/assign/shim.js @@ -0,0 +1,22 @@ +'use strict'; + +var keys = require('../keys') + , value = require('../valid-value') + + , max = Math.max; + +module.exports = function (dest, src/*, …srcn*/) { + var error, i, l = max(arguments.length, 2), assign; + dest = Object(value(dest)); + assign = function (key) { + try { dest[key] = src[key]; } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < l; ++i) { + src = arguments[i]; + keys(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/clear.js new file mode 100644 index 00000000000000..85e463728550d0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/clear.js @@ -0,0 +1,16 @@ +'use strict'; + +var keys = require('./keys'); + +module.exports = function (obj) { + var error; + keys(obj).forEach(function (key) { + try { + delete this[key]; + } catch (e) { + if (!error) error = e; + } + }, obj); + if (error !== undefined) throw error; + return obj; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/compact.js new file mode 100644 index 00000000000000..d021da457e3914 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/compact.js @@ -0,0 +1,7 @@ +'use strict'; + +var filter = require('./filter'); + +module.exports = function (obj) { + return filter(obj, function (val) { return val != null; }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/compare.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/compare.js new file mode 100644 index 00000000000000..2ab11f1a396350 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/compare.js @@ -0,0 +1,42 @@ +'use strict'; + +var strCompare = require('../string/#/case-insensitive-compare') + , isObject = require('./is-object') + + , resolve, typeMap; + +typeMap = { + undefined: 0, + object: 1, + boolean: 2, + string: 3, + number: 4 +}; + +resolve = function (a) { + if (isObject(a)) { + if (typeof a.valueOf !== 'function') return NaN; + a = a.valueOf(); + if (isObject(a)) { + if (typeof a.toString !== 'function') return NaN; + a = a.toString(); + if (typeof a !== 'string') return NaN; + } + } + return a; +}; + +module.exports = function (a, b) { + if (a === b) return 0; // Same + + a = resolve(a); + b = resolve(b); + if (a == b) return typeMap[typeof a] - typeMap[typeof b]; //jslint: ignore + if (a == null) return -1; + if (b == null) return 1; + if ((typeof a === 'string') || (typeof b === 'string')) { + return strCompare.call(a, b); + } + if ((a !== a) && (b !== b)) return 0; //jslint: ignore + return Number(a) - Number(b); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/copy-deep.js new file mode 100644 index 00000000000000..548e3ee4b66bac --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/copy-deep.js @@ -0,0 +1,30 @@ +'use strict'; + +var isPlainObject = require('./is-plain-object') + , value = require('./valid-value') + + , keys = Object.keys + , copy; + +copy = function (source) { + var target = {}; + this[0].push(source); + this[1].push(target); + keys(source).forEach(function (key) { + var index; + if (!isPlainObject(source[key])) { + target[key] = source[key]; + return; + } + index = this[0].indexOf(source[key]); + if (index === -1) target[key] = copy.call(this, source[key]); + else target[key] = this[1][index]; + }, this); + return target; +}; + +module.exports = function (source) { + var obj = Object(value(source)); + if (obj !== source) return obj; + return copy.call([[], []], obj); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/copy.js new file mode 100644 index 00000000000000..4d7177285fe5b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/copy.js @@ -0,0 +1,10 @@ +'use strict'; + +var assign = require('./assign') + , value = require('./valid-value'); + +module.exports = function (obj) { + var copy = Object(value(obj)); + if (copy !== obj) return copy; + return assign({}, obj); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/count.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/count.js new file mode 100644 index 00000000000000..29cfbb53fb40ae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/count.js @@ -0,0 +1,5 @@ +'use strict'; + +var keys = require('./keys'); + +module.exports = function (obj) { return keys(obj).length; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/create.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/create.js new file mode 100644 index 00000000000000..f813b4661c4498 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/create.js @@ -0,0 +1,36 @@ +// Workaround for http://code.google.com/p/v8/issues/detail?id=2804 + +'use strict'; + +var create = Object.create, shim; + +if (!require('./set-prototype-of/is-implemented')()) { + shim = require('./set-prototype-of/shim'); +} + +module.exports = (function () { + var nullObject, props, desc; + if (!shim) return create; + if (shim.level !== 1) return create; + + nullObject = {}; + props = {}; + desc = { configurable: false, enumerable: false, writable: true, + value: undefined }; + Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { + if (name === '__proto__') { + props[name] = { configurable: true, enumerable: false, writable: true, + value: undefined }; + return; + } + props[name] = desc; + }); + Object.defineProperties(nullObject, props); + + Object.defineProperty(shim, 'nullPolyfill', { configurable: false, + enumerable: false, writable: false, value: nullObject }); + + return function (prototype, props) { + return create((prototype === null) ? nullObject : prototype, props); + }; +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/eq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/eq.js new file mode 100644 index 00000000000000..037937ea6e9749 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/eq.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x, y) { + return ((x === y) || ((x !== x) && (y !== y))); //jslint: ignore +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/every.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/every.js new file mode 100644 index 00000000000000..1303db20958f8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/every.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_iterate')('every', true); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/filter.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/filter.js new file mode 100644 index 00000000000000..e5edb49b1b1610 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/filter.js @@ -0,0 +1,15 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + if (call.call(cb, thisArg, value, key, obj, index)) o[key] = obj[key]; + }); + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/first-key.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/first-key.js new file mode 100644 index 00000000000000..7df10b2f7f948d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/first-key.js @@ -0,0 +1,14 @@ +'use strict'; + +var value = require('./valid-value') + + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (obj) { + var i; + value(obj); + for (i in obj) { + if (propertyIsEnumerable.call(obj, i)) return i; + } + return null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/flatten.js new file mode 100644 index 00000000000000..e8b40444a94692 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/flatten.js @@ -0,0 +1,17 @@ +'use strict'; + +var isPlainObject = require('./is-plain-object') + , forEach = require('./for-each') + + , process; + +process = function self(value, key) { + if (isPlainObject(value)) forEach(value, self, this); + else this[key] = value; +}; + +module.exports = function (obj) { + var flattened = {}; + forEach(obj, process, flattened); + return flattened; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/for-each.js new file mode 100644 index 00000000000000..6674f8a614795b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/for-each.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_iterate')('forEach'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/get-property-names.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/get-property-names.js new file mode 100644 index 00000000000000..54a01e5047a392 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/get-property-names.js @@ -0,0 +1,18 @@ +'use strict'; + +var uniq = require('../array/#/uniq') + , value = require('./valid-value') + + , push = Array.prototype.push + , getOwnPropertyNames = Object.getOwnPropertyNames + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (obj) { + var keys; + obj = Object(value(obj)); + keys = getOwnPropertyNames(obj); + while ((obj = getPrototypeOf(obj))) { + push.apply(keys, getOwnPropertyNames(obj)); + } + return uniq.call(keys); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/index.js new file mode 100644 index 00000000000000..4bdf403583ace9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/index.js @@ -0,0 +1,48 @@ +'use strict'; + +module.exports = { + assign: require('./assign'), + clear: require('./clear'), + compact: require('./compact'), + compare: require('./compare'), + copy: require('./copy'), + copyDeep: require('./copy-deep'), + count: require('./count'), + create: require('./create'), + eq: require('./eq'), + every: require('./every'), + filter: require('./filter'), + firstKey: require('./first-key'), + flatten: require('./flatten'), + forEach: require('./for-each'), + getPropertyNames: require('./get-property-names'), + is: require('./is'), + isArrayLike: require('./is-array-like'), + isCallable: require('./is-callable'), + isCopy: require('./is-copy'), + isCopyDeep: require('./is-copy-deep'), + isEmpty: require('./is-empty'), + isObject: require('./is-object'), + isPlainObject: require('./is-plain-object'), + keyOf: require('./key-of'), + keys: require('./keys'), + map: require('./map'), + mapKeys: require('./map-keys'), + normalizeOptions: require('./normalize-options'), + mixin: require('./mixin'), + mixinPrototypes: require('./mixin-prototypes'), + primitiveSet: require('./primitive-set'), + safeTraverse: require('./safe-traverse'), + serialize: require('./serialize'), + setPrototypeOf: require('./set-prototype-of'), + some: require('./some'), + toArray: require('./to-array'), + unserialize: require('./unserialize'), + validateArrayLike: require('./validate-array-like'), + validateArrayLikeObject: require('./validate-array-like-object'), + validCallable: require('./valid-callable'), + validObject: require('./valid-object'), + validateStringifiable: require('./validate-stringifiable'), + validateStringifiableValue: require('./validate-stringifiable-value'), + validValue: require('./valid-value') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-array-like.js new file mode 100644 index 00000000000000..b8beed225b05ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-array-like.js @@ -0,0 +1,14 @@ +'use strict'; + +var isFunction = require('../function/is-function') + , isObject = require('./is-object'); + +module.exports = function (x) { + return ((x != null) && (typeof x.length === 'number') && + + // Just checking ((typeof x === 'object') && (typeof x !== 'function')) + // won't work right for some cases, e.g.: + // type of instance of NodeList in Safari is a 'function' + + ((isObject(x) && !isFunction(x)) || (typeof x === "string"))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-callable.js new file mode 100644 index 00000000000000..5d5d4b316b2a1c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-callable.js @@ -0,0 +1,5 @@ +// Deprecated + +'use strict'; + +module.exports = function (obj) { return typeof obj === 'function'; }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-copy-deep.js new file mode 100644 index 00000000000000..c4b2b42b100836 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-copy-deep.js @@ -0,0 +1,58 @@ +'use strict'; + +var eq = require('./eq') + , isPlainObject = require('./is-plain-object') + , value = require('./valid-value') + + , isArray = Array.isArray, keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable + + , eqArr, eqVal, eqObj; + +eqArr = function (a, b, recMap) { + var i, l = a.length; + if (l !== b.length) return false; + for (i = 0; i < l; ++i) { + if (a.hasOwnProperty(i) !== b.hasOwnProperty(i)) return false; + if (!eqVal(a[i], b[i], recMap)) return false; + } + return true; +}; + +eqObj = function (a, b, recMap) { + var k1 = keys(a), k2 = keys(b); + if (k1.length !== k2.length) return false; + return k1.every(function (key) { + if (!propertyIsEnumerable.call(b, key)) return false; + return eqVal(a[key], b[key], recMap); + }); +}; + +eqVal = function (a, b, recMap) { + var i, eqX, c1, c2; + if (eq(a, b)) return true; + if (isPlainObject(a)) { + if (!isPlainObject(b)) return false; + eqX = eqObj; + } else if (isArray(a) && isArray(b)) { + eqX = eqArr; + } else { + return false; + } + c1 = recMap[0]; + c2 = recMap[1]; + i = c1.indexOf(a); + if (i !== -1) { + if (c2[i].indexOf(b) !== -1) return true; + } else { + i = c1.push(a) - 1; + c2[i] = []; + } + c2[i].push(b); + return eqX(a, b, recMap); +}; + +module.exports = function (a, b) { + if (eq(value(a), value(b))) return true; + return eqVal(Object(a), Object(b), [[], []]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-copy.js new file mode 100644 index 00000000000000..4fe639d4efcd2d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-copy.js @@ -0,0 +1,24 @@ +'use strict'; + +var eq = require('./eq') + , value = require('./valid-value') + + , keys = Object.keys + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (a, b) { + var k1, k2; + + if (eq(value(a), value(b))) return true; + + a = Object(a); + b = Object(b); + + k1 = keys(a); + k2 = keys(b); + if (k1.length !== k2.length) return false; + return k1.every(function (key) { + if (!propertyIsEnumerable.call(b, key)) return false; + return eq(a[key], b[key]); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-empty.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-empty.js new file mode 100644 index 00000000000000..7b51a87cf57e70 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-empty.js @@ -0,0 +1,14 @@ +'use strict'; + +var value = require('./valid-value') + + , propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +module.exports = function (obj) { + var i; + value(obj); + for (i in obj) { //jslint: ignore + if (propertyIsEnumerable.call(obj, i)) return false; + } + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-object.js new file mode 100644 index 00000000000000..a86facf187a86f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-object.js @@ -0,0 +1,7 @@ +'use strict'; + +var map = { function: true, object: true }; + +module.exports = function (x) { + return ((x != null) && map[typeof x]) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-plain-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-plain-object.js new file mode 100644 index 00000000000000..9a2823198e746f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is-plain-object.js @@ -0,0 +1,20 @@ +'use strict'; + +var getPrototypeOf = Object.getPrototypeOf, prototype = Object.prototype + , toString = prototype.toString + + , id = Object().toString(); + +module.exports = function (value) { + var proto, constructor; + if (!value || (typeof value !== 'object') || (toString.call(value) !== id)) { + return false; + } + proto = getPrototypeOf(value); + if (proto === null) { + constructor = value.constructor; + if (typeof constructor !== 'function') return true; + return (constructor.prototype !== value); + } + return (proto === prototype) || (getPrototypeOf(proto) === null); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is.js new file mode 100644 index 00000000000000..5778b502d924cd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/is.js @@ -0,0 +1,10 @@ +// Implementation credits go to: +// http://wiki.ecmascript.org/doku.php?id=harmony:egal + +'use strict'; + +module.exports = function (x, y) { + return (x === y) ? + ((x !== 0) || ((1 / x) === (1 / y))) : + ((x !== x) && (y !== y)); //jslint: ignore +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/key-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/key-of.js new file mode 100644 index 00000000000000..8c44c8d8027f8b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/key-of.js @@ -0,0 +1,15 @@ +'use strict'; + +var eq = require('./eq') + , some = require('./some'); + +module.exports = function (obj, searchValue) { + var r; + return some(obj, function (value, name) { + if (eq(value, searchValue)) { + r = name; + return true; + } + return false; + }) ? r : null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/implement.js new file mode 100644 index 00000000000000..c6872bd02af0b2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(Object, 'keys', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/index.js new file mode 100644 index 00000000000000..5ef052233a76e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.keys + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/is-implemented.js new file mode 100644 index 00000000000000..40c32c33940c7c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + try { + Object.keys('primitive'); + return true; + } catch (e) { return false; } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/shim.js new file mode 100644 index 00000000000000..034b6b2981185a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/keys/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +var keys = Object.keys; + +module.exports = function (object) { + return keys(object == null ? object : Object(object)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/map-keys.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/map-keys.js new file mode 100644 index 00000000000000..26f0ecacb8aef3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/map-keys.js @@ -0,0 +1,15 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + o[call.call(cb, thisArg, key, value, this, index)] = value; + }, obj); + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/map.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/map.js new file mode 100644 index 00000000000000..6b39d3c94b7421 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/map.js @@ -0,0 +1,15 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call; + +module.exports = function (obj, cb/*, thisArg*/) { + var o = {}, thisArg = arguments[2]; + callable(cb); + forEach(obj, function (value, key, obj, index) { + o[key] = call.call(cb, thisArg, value, key, obj, index); + }); + return o; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/mixin-prototypes.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/mixin-prototypes.js new file mode 100644 index 00000000000000..1ef5756423cd36 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/mixin-prototypes.js @@ -0,0 +1,34 @@ +'use strict'; + +var value = require('./valid-value') + , mixin = require('./mixin') + + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getOwnPropertyNames = Object.getOwnPropertyNames + , getPrototypeOf = Object.getPrototypeOf + , hasOwnProperty = Object.prototype.hasOwnProperty; + +module.exports = function (target, source) { + var error, end, define; + target = Object(value(target)); + source = Object(value(source)); + end = getPrototypeOf(target); + if (source === end) return target; + try { + mixin(target, source); + } catch (e) { error = e; } + source = getPrototypeOf(source); + define = function (name) { + if (hasOwnProperty.call(target, name)) return; + try { + defineProperty(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { error = e; } + }; + while (source && (source !== end)) { + getOwnPropertyNames(source).forEach(define); + source = getPrototypeOf(source); + } + if (error) throw error; + return target; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/mixin.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/mixin.js new file mode 100644 index 00000000000000..80b5df5e04b9b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/mixin.js @@ -0,0 +1,19 @@ +'use strict'; + +var value = require('./valid-value') + + , defineProperty = Object.defineProperty + , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor + , getOwnPropertyNames = Object.getOwnPropertyNames; + +module.exports = function (target, source) { + var error; + target = Object(value(target)); + getOwnPropertyNames(Object(value(source))).forEach(function (name) { + try { + defineProperty(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { error = e; } + }); + if (error !== undefined) throw error; + return target; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/normalize-options.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/normalize-options.js new file mode 100644 index 00000000000000..cf8ed8d38cabd1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/normalize-options.js @@ -0,0 +1,17 @@ +'use strict'; + +var forEach = Array.prototype.forEach, create = Object.create; + +var process = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +module.exports = function (options/*, …options*/) { + var result = create(null); + forEach.call(arguments, function (options) { + if (options == null) return; + process(Object(options), result); + }); + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/primitive-set.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/primitive-set.js new file mode 100644 index 00000000000000..ada109510d4bd9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/primitive-set.js @@ -0,0 +1,9 @@ +'use strict'; + +var forEach = Array.prototype.forEach, create = Object.create; + +module.exports = function (arg/*, …args*/) { + var set = create(null); + forEach.call(arguments, function (name) { set[name] = true; }); + return set; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/safe-traverse.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/safe-traverse.js new file mode 100644 index 00000000000000..7e1b5f41edf162 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/safe-traverse.js @@ -0,0 +1,15 @@ +'use strict'; + +var value = require('./valid-value'); + +module.exports = function (obj/*, …names*/) { + var length, current = 1; + value(obj); + length = arguments.length - 1; + if (!length) return obj; + while (current < length) { + obj = obj[arguments[current++]]; + if (obj == null) return undefined; + } + return obj[arguments[current]]; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/serialize.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/serialize.js new file mode 100644 index 00000000000000..8113b6801dd395 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/serialize.js @@ -0,0 +1,36 @@ +'use strict'; + +var toArray = require('./to-array') + , isDate = require('../date/is-date') + , isRegExp = require('../reg-exp/is-reg-exp') + + , isArray = Array.isArray, stringify = JSON.stringify + , keyValueToString = function (value, key) { return stringify(key) + ':' + exports(value); }; + +var sparseMap = function (arr) { + var i, l = arr.length, result = new Array(l); + for (i = 0; i < l; ++i) { + if (!arr.hasOwnProperty(i)) continue; + result[i] = exports(arr[i]); + } + return result; +}; + +module.exports = exports = function (obj) { + if (obj == null) return String(obj); + switch (typeof obj) { + case 'string': + return stringify(obj); + case 'number': + case 'boolean': + case 'function': + return String(obj); + case 'object': + if (isArray(obj)) return '[' + sparseMap(obj) + ']'; + if (isRegExp(obj)) return String(obj); + if (isDate(obj)) return 'new Date(' + obj.valueOf() + ')'; + return '{' + toArray(obj, keyValueToString) + '}'; + default: + throw new TypeError("Serialization of " + String(obj) + "is unsupported"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/implement.js new file mode 100644 index 00000000000000..000e6bdbbebcb7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/implement.js @@ -0,0 +1,8 @@ +'use strict'; + +var shim; + +if (!require('./is-implemented')() && (shim = require('./shim'))) { + Object.defineProperty(Object, 'setPrototypeOf', + { value: shim, configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/index.js new file mode 100644 index 00000000000000..ccc40995b1e6b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? Object.setPrototypeOf + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/is-implemented.js new file mode 100644 index 00000000000000..98d0c8436a8d46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/is-implemented.js @@ -0,0 +1,11 @@ +'use strict'; + +var create = Object.create, getPrototypeOf = Object.getPrototypeOf + , x = {}; + +module.exports = function (/*customCreate*/) { + var setPrototypeOf = Object.setPrototypeOf + , customCreate = arguments[0] || create; + if (typeof setPrototypeOf !== 'function') return false; + return getPrototypeOf(setPrototypeOf(customCreate(null), x)) === x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/shim.js new file mode 100644 index 00000000000000..4ec944675e5685 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/set-prototype-of/shim.js @@ -0,0 +1,73 @@ +// Big thanks to @WebReflection for sorting this out +// https://gist.github.com/WebReflection/5593554 + +'use strict'; + +var isObject = require('../is-object') + , value = require('../valid-value') + + , isPrototypeOf = Object.prototype.isPrototypeOf + , defineProperty = Object.defineProperty + , nullDesc = { configurable: true, enumerable: false, writable: true, + value: undefined } + , validate; + +validate = function (obj, prototype) { + value(obj); + if ((prototype === null) || isObject(prototype)) return obj; + throw new TypeError('Prototype must be null or an object'); +}; + +module.exports = (function (status) { + var fn, set; + if (!status) return null; + if (status.level === 2) { + if (status.set) { + set = status.set; + fn = function (obj, prototype) { + set.call(validate(obj, prototype), prototype); + return obj; + }; + } else { + fn = function (obj, prototype) { + validate(obj, prototype).__proto__ = prototype; + return obj; + }; + } + } else { + fn = function self(obj, prototype) { + var isNullBase; + validate(obj, prototype); + isNullBase = isPrototypeOf.call(self.nullPolyfill, obj); + if (isNullBase) delete self.nullPolyfill.__proto__; + if (prototype === null) prototype = self.nullPolyfill; + obj.__proto__ = prototype; + if (isNullBase) defineProperty(self.nullPolyfill, '__proto__', nullDesc); + return obj; + }; + } + return Object.defineProperty(fn, 'level', { configurable: false, + enumerable: false, writable: false, value: status.level }); +}((function () { + var x = Object.create(null), y = {}, set + , desc = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'); + + if (desc) { + try { + set = desc.set; // Opera crashes at this point + set.call(x, y); + } catch (ignore) { } + if (Object.getPrototypeOf(x) === y) return { set: set, level: 2 }; + } + + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 2 }; + + x = {}; + x.__proto__ = y; + if (Object.getPrototypeOf(x) === y) return { level: 1 }; + + return false; +}()))); + +require('../create'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/some.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/some.js new file mode 100644 index 00000000000000..cde5ddeecdf749 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/some.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./_iterate')('some', false); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/to-array.js new file mode 100644 index 00000000000000..a954abb26fdffd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/to-array.js @@ -0,0 +1,18 @@ +'use strict'; + +var callable = require('./valid-callable') + , forEach = require('./for-each') + + , call = Function.prototype.call + + , defaultCb = function (value, key) { return [key, value]; }; + +module.exports = function (obj/*, cb, thisArg, compareFn*/) { + var a = [], cb = arguments[1], thisArg = arguments[2]; + cb = (cb == null) ? defaultCb : callable(cb); + + forEach(obj, function (value, key, obj, index) { + a.push(call.call(cb, thisArg, value, key, this, index)); + }, obj, arguments[3]); + return a; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/unserialize.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/unserialize.js new file mode 100644 index 00000000000000..ce68e403ae1b6e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/unserialize.js @@ -0,0 +1,7 @@ +'use strict'; + +var value = require('./valid-value'); + +module.exports = exports = function (code) { + return (new Function('return ' + value(code)))(); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-callable.js new file mode 100644 index 00000000000000..c977527a4fd660 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-callable.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (fn) { + if (typeof fn !== 'function') throw new TypeError(fn + " is not a function"); + return fn; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-object.js new file mode 100644 index 00000000000000..f82bd51ed106f2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-object.js @@ -0,0 +1,8 @@ +'use strict'; + +var isObject = require('./is-object'); + +module.exports = function (value) { + if (!isObject(value)) throw new TypeError(value + " is not an Object"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-value.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-value.js new file mode 100644 index 00000000000000..36c8ec31e84731 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/valid-value.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (value) { + if (value == null) throw new TypeError("Cannot use null or undefined"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-array-like-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-array-like-object.js new file mode 100644 index 00000000000000..89e12c51c5dfcf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-array-like-object.js @@ -0,0 +1,9 @@ +'use strict'; + +var isArrayLike = require('./is-array-like') + , isObject = require('./is-object'); + +module.exports = function (obj) { + if (isObject(obj) && isArrayLike(obj)) return obj; + throw new TypeError(obj + " is not array-like object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-array-like.js new file mode 100644 index 00000000000000..6a35b54a14f677 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-array-like.js @@ -0,0 +1,8 @@ +'use strict'; + +var isArrayLike = require('./is-array-like'); + +module.exports = function (obj) { + if (isArrayLike(obj)) return obj; + throw new TypeError(obj + " is not array-like value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-stringifiable-value.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-stringifiable-value.js new file mode 100644 index 00000000000000..9df3b668fb06c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-stringifiable-value.js @@ -0,0 +1,6 @@ +'use strict'; + +var value = require('./valid-value') + , stringifiable = require('./validate-stringifiable'); + +module.exports = function (x) { return stringifiable(value(x)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-stringifiable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-stringifiable.js new file mode 100644 index 00000000000000..eba7ce787cdfad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/object/validate-stringifiable.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (stringifiable) { + try { + return String(stringifiable); + } catch (e) { + throw new TypeError("Passed argument cannot be stringifed"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/package.json b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/package.json new file mode 100644 index 00000000000000..01d6532749e89c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/package.json @@ -0,0 +1,74 @@ +{ + "name": "es5-ext", + "version": "0.10.7", + "description": "ECMAScript 5 extensions and ES6 shims", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "ecmascript", + "ecmascript5", + "ecmascript6", + "es5", + "es6", + "extensions", + "ext", + "addons", + "extras", + "harmony", + "javascript", + "polyfill", + "shim", + "util", + "utils", + "utilities" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es5-ext.git" + }, + "dependencies": { + "es6-iterator": "~0.1.3", + "es6-symbol": "~2.0.1" + }, + "devDependencies": { + "tad": "~0.2.2", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "5b63ee02f50dfbc70dc1f62bc66b8718af443f83", + "bugs": { + "url": "https://github.com/medikoo/es5-ext/issues" + }, + "homepage": "https://github.com/medikoo/es5-ext", + "_id": "es5-ext@0.10.7", + "_shasum": "dfaea50721301042e2d89c1719d43493fa821656", + "_from": "es5-ext@>=0.10.6 <0.11.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "dfaea50721301042e2d89c1719d43493fa821656", + "tarball": "http://registry.npmjs.org/es5-ext/-/es5-ext-0.10.7.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/index.js new file mode 100644 index 00000000000000..f7e7a58ebd780a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + isSticky: require('./is-sticky'), + isUnicode: require('./is-unicode'), + match: require('./match'), + replace: require('./replace'), + search: require('./search'), + split: require('./split') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/is-sticky.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/is-sticky.js new file mode 100644 index 00000000000000..830a481f7e9213 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/is-sticky.js @@ -0,0 +1,9 @@ +'use strict'; + +var validRegExp = require('../valid-reg-exp') + + , re = /\/[a-xz]*y[a-xz]*$/; + +module.exports = function () { + return Boolean(String(validRegExp(this)).match(re)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/is-unicode.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/is-unicode.js new file mode 100644 index 00000000000000..b005f6d9194f1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/is-unicode.js @@ -0,0 +1,9 @@ +'use strict'; + +var validRegExp = require('../valid-reg-exp') + + , re = /\/[a-xz]*u[a-xz]*$/; + +module.exports = function () { + return Boolean(String(validRegExp(this)).match(re)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/implement.js new file mode 100644 index 00000000000000..921c9368e780b6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'match', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/index.js new file mode 100644 index 00000000000000..0534ac3bc352b3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.match + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/is-implemented.js new file mode 100644 index 00000000000000..b7e99643148089 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /foo/; + +module.exports = function () { + if (typeof re.match !== 'function') return false; + return re.match('barfoobar') && !re.match('elo'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/shim.js new file mode 100644 index 00000000000000..4f99cf4d1c02c5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/match/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string) { + validRegExp(this); + return String(string).match(this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/implement.js new file mode 100644 index 00000000000000..ad580de890618e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'replace', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/index.js new file mode 100644 index 00000000000000..5658177d804881 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.replace + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/is-implemented.js new file mode 100644 index 00000000000000..1b42d252430bd5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /foo/; + +module.exports = function () { + if (typeof re.replace !== 'function') return false; + return re.replace('foobar', 'mar') === 'marbar'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/shim.js new file mode 100644 index 00000000000000..c3e6aebab04cf3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/replace/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string, replaceValue) { + validRegExp(this); + return String(string).replace(this, replaceValue); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/implement.js new file mode 100644 index 00000000000000..3804f4eb1c3bb5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'search', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/index.js new file mode 100644 index 00000000000000..67995d4ac7b9f3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.search + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/is-implemented.js new file mode 100644 index 00000000000000..efba889f81724d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /foo/; + +module.exports = function () { + if (typeof re.search !== 'function') return false; + return re.search('barfoo') === 3; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/shim.js new file mode 100644 index 00000000000000..6d9dcaed8ab26f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/search/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string) { + validRegExp(this); + return String(string).search(this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/implement.js new file mode 100644 index 00000000000000..50facb6834d7c1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'split', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/index.js new file mode 100644 index 00000000000000..f101f5af7503cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? RegExp.prototype.split + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/is-implemented.js new file mode 100644 index 00000000000000..7244c998bf45fd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var re = /\|/; + +module.exports = function () { + if (typeof re.split !== 'function') return false; + return re.split('bar|foo')[1] === 'foo'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/shim.js new file mode 100644 index 00000000000000..76154e7e3c0069 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/split/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +var validRegExp = require('../../valid-reg-exp'); + +module.exports = function (string) { + validRegExp(this); + return String(string).split(this); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/sticky/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/sticky/implement.js new file mode 100644 index 00000000000000..7e8af1db31641b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/sticky/implement.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSticky = require('../is-sticky'); + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'sticky', { configurable: true, + enumerable: false, get: isSticky }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/sticky/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/sticky/is-implemented.js new file mode 100644 index 00000000000000..379c4a5a8fb1b8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/sticky/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return RegExp.prototype.sticky === false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/unicode/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/unicode/implement.js new file mode 100644 index 00000000000000..5a82a4d1d23386 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/unicode/implement.js @@ -0,0 +1,8 @@ +'use strict'; + +var isUnicode = require('../is-unicode'); + +if (!require('./is-implemented')()) { + Object.defineProperty(RegExp.prototype, 'unicode', { configurable: true, + enumerable: false, get: isUnicode }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/unicode/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/unicode/is-implemented.js new file mode 100644 index 00000000000000..a8b15b3b38defb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/#/unicode/is-implemented.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function () { + return RegExp.prototype.unicode === false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/escape.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/escape.js new file mode 100644 index 00000000000000..a2363fcfc68a03 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/escape.js @@ -0,0 +1,9 @@ +// Thanks to Andrew Clover: +// http://stackoverflow.com/questions/3561493 +// /is-there-a-regexp-escape-function-in-javascript + +'use strict'; + +var re = /[\-\/\\\^$*+?.()|\[\]{}]/g; + +module.exports = function (str) { return String(str).replace(re, '\\$&'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/index.js new file mode 100644 index 00000000000000..75ea3135a89afe --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + escape: require('./escape'), + isRegExp: require('./is-reg-exp'), + validRegExp: require('./valid-reg-exp') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/is-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/is-reg-exp.js new file mode 100644 index 00000000000000..6eb12977c031d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/is-reg-exp.js @@ -0,0 +1,9 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(/a/); + +module.exports = function (x) { + return (x && (x instanceof RegExp || (toString.call(x) === id))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/valid-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/valid-reg-exp.js new file mode 100644 index 00000000000000..d3a77641da0f86 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/reg-exp/valid-reg-exp.js @@ -0,0 +1,8 @@ +'use strict'; + +var isRegExp = require('./is-reg-exp'); + +module.exports = function (x) { + if (!isRegExp(x)) throw new TypeError(x + " is not a RegExp object"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/implement.js new file mode 100644 index 00000000000000..4494d7b6af3d93 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, require('es6-symbol').iterator, + { value: require('./shim'), configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/index.js new file mode 100644 index 00000000000000..22f15e69600bc0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/index.js @@ -0,0 +1,4 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype[require('es6-symbol').iterator] : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..f5c462deb91064 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/is-implemented.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function () { + var str = '🙈f', iterator, result; + if (typeof str[iteratorSymbol] !== 'function') return false; + iterator = str[iteratorSymbol](); + if (!iterator) return false; + if (typeof iterator.next !== 'function') return false; + result = iterator.next(); + if (!result) return false; + if (result.value !== '🙈') return false; + if (result.done !== false) return false; + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/shim.js new file mode 100644 index 00000000000000..0be30292f6e98d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/@@iterator/shim.js @@ -0,0 +1,6 @@ +'use strict'; + +var StringIterator = require('es6-iterator/string') + , value = require('../../../object/valid-value'); + +module.exports = function () { return new StringIterator(value(this)); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/at.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/at.js new file mode 100644 index 00000000000000..77bd251ac4f1ae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/at.js @@ -0,0 +1,33 @@ +// Based on: https://github.com/mathiasbynens/String.prototype.at +// Thanks @mathiasbynens ! + +'use strict'; + +var toInteger = require('../../number/to-integer') + , validValue = require('../../object/valid-value'); + +module.exports = function (pos) { + var str = String(validValue(this)), size = str.length + , cuFirst, cuSecond, nextPos, len; + pos = toInteger(pos); + + // Account for out-of-bounds indices + // The odd lower bound is because the ToInteger operation is + // going to round `n` to `0` for `-1 < n <= 0`. + if (pos <= -1 || pos >= size) return ''; + + // Second half of `ToInteger` + pos = pos | 0; + // Get the first code unit and code unit value + cuFirst = str.charCodeAt(pos); + nextPos = pos + 1; + len = 1; + if ( // check if it’s the start of a surrogate pair + (cuFirst >= 0xD800) && (cuFirst <= 0xDBFF) && // high surrogate + (size > nextPos) // there is a next code unit + ) { + cuSecond = str.charCodeAt(nextPos); + if (cuSecond >= 0xDC00 && cuSecond <= 0xDFFF) len = 2; // low surrogate + } + return str.slice(pos, pos + len); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/camel-to-hyphen.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/camel-to-hyphen.js new file mode 100644 index 00000000000000..1cb8d127796d8b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/camel-to-hyphen.js @@ -0,0 +1,10 @@ +'use strict'; + +var replace = String.prototype.replace + , re = /([A-Z])/g; + +module.exports = function () { + var str = replace.call(this, re, "-$1").toLowerCase(); + if (str[0] === '-') str = str.slice(1); + return str; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/capitalize.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/capitalize.js new file mode 100644 index 00000000000000..ed768273651c9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/capitalize.js @@ -0,0 +1,8 @@ +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + var str = String(value(this)); + return str.charAt(0).toUpperCase() + str.slice(1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/case-insensitive-compare.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/case-insensitive-compare.js new file mode 100644 index 00000000000000..599cb83469c149 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/case-insensitive-compare.js @@ -0,0 +1,7 @@ +'use strict'; + +var toLowerCase = String.prototype.toLowerCase; + +module.exports = function (other) { + return toLowerCase.call(this).localeCompare(toLowerCase.call(String(other))); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/implement.js new file mode 100644 index 00000000000000..1e7a37bd4d34ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'codePointAt', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/index.js new file mode 100644 index 00000000000000..7e91d833a867e4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.codePointAt + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/is-implemented.js new file mode 100644 index 00000000000000..b27158913a91d1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'abc\uD834\uDF06def'; + +module.exports = function () { + if (typeof str.codePointAt !== 'function') return false; + return str.codePointAt(3) === 0x1D306; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/shim.js new file mode 100644 index 00000000000000..1c9038b3cb0a79 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/code-point-at/shim.js @@ -0,0 +1,26 @@ +// Based on: https://github.com/mathiasbynens/String.prototype.codePointAt +// Thanks @mathiasbynens ! + +'use strict'; + +var toInteger = require('../../../number/to-integer') + , validValue = require('../../../object/valid-value'); + +module.exports = function (pos) { + var str = String(validValue(this)), l = str.length, first, second; + pos = toInteger(pos); + + // Account for out-of-bounds indices: + if (pos < 0 || pos >= l) return undefined; + + // Get the first code unit + first = str.charCodeAt(pos); + if ((first >= 0xD800) && (first <= 0xDBFF) && (l > pos + 1)) { + second = str.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/implement.js new file mode 100644 index 00000000000000..6b7a3c08164c4e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'contains', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/index.js new file mode 100644 index 00000000000000..abb3e3730bf103 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.contains + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/is-implemented.js new file mode 100644 index 00000000000000..6f7d4b719e218e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.contains !== 'function') return false; + return ((str.contains('dwa') === true) && (str.contains('foo') === false)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/shim.js new file mode 100644 index 00000000000000..89e39e793324b7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/contains/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +var indexOf = String.prototype.indexOf; + +module.exports = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/implement.js new file mode 100644 index 00000000000000..0b09025b0cde8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'endsWith', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/index.js new file mode 100644 index 00000000000000..d2d9484827957e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.endsWith + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/is-implemented.js new file mode 100644 index 00000000000000..f3bb00883bb978 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.endsWith !== 'function') return false; + return ((str.endsWith('trzy') === true) && (str.endsWith('raz') === false)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/shim.js new file mode 100644 index 00000000000000..26cbdb1366be10 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/ends-with/shim.js @@ -0,0 +1,16 @@ +'use strict'; + +var toInteger = require('../../../number/to-integer') + , value = require('../../../object/valid-value') + + , min = Math.min, max = Math.max; + +module.exports = function (searchString/*, endPosition*/) { + var self, start, endPos; + self = String(value(this)); + searchString = String(searchString); + endPos = arguments[1]; + start = ((endPos == null) ? self.length : + min(max(toInteger(endPos), 0), self.length)) - searchString.length; + return (start < 0) ? false : (self.indexOf(searchString, start) === start); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/hyphen-to-camel.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/hyphen-to-camel.js new file mode 100644 index 00000000000000..8928b02497f1a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/hyphen-to-camel.js @@ -0,0 +1,8 @@ +'use strict'; + +var replace = String.prototype.replace + + , re = /-([a-z0-9])/g + , toUpperCase = function (m, a) { return a.toUpperCase(); }; + +module.exports = function () { return replace.call(this, re, toUpperCase); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/indent.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/indent.js new file mode 100644 index 00000000000000..223bd82b0f1a97 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/indent.js @@ -0,0 +1,12 @@ +'use strict'; + +var repeat = require('./repeat') + + , replace = String.prototype.replace + , re = /(\r\n|[\n\r\u2028\u2029])([\u0000-\u0009\u000b-\uffff]+)/g; + +module.exports = function (indent/*, count*/) { + var count = arguments[1]; + indent = repeat.call(String(indent), (count == null) ? 1 : count); + return indent + replace.call(this, re, '$1' + indent + '$2'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/index.js new file mode 100644 index 00000000000000..d45d747cbe0954 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/index.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = { + '@@iterator': require('./@@iterator'), + at: require('./at'), + camelToHyphen: require('./camel-to-hyphen'), + capitalize: require('./capitalize'), + caseInsensitiveCompare: require('./case-insensitive-compare'), + codePointAt: require('./code-point-at'), + contains: require('./contains'), + hyphenToCamel: require('./hyphen-to-camel'), + endsWith: require('./ends-with'), + indent: require('./indent'), + last: require('./last'), + normalize: require('./normalize'), + pad: require('./pad'), + plainReplace: require('./plain-replace'), + plainReplaceAll: require('./plain-replace-all'), + repeat: require('./repeat'), + startsWith: require('./starts-with') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/last.js new file mode 100644 index 00000000000000..d5cf46ee5fb863 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/last.js @@ -0,0 +1,8 @@ +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function () { + var self = String(value(this)), l = self.length; + return l ? self[l - 1] : null; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/_data.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/_data.js new file mode 100644 index 00000000000000..e4e00a3298120f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/_data.js @@ -0,0 +1,69 @@ +'use strict'; + +module.exports = { 0:{60:[,,{824:8814}],61:[,,{824:8800}],62:[,,{824:8815}],65:[,,{768:192,769:193,770:194,771:195,772:256,774:258,775:550,776:196,777:7842,778:197,780:461,783:512,785:514,803:7840,805:7680,808:260}],66:[,,{775:7682,803:7684,817:7686}],67:[,,{769:262,770:264,775:266,780:268,807:199}],68:[,,{775:7690,780:270,803:7692,807:7696,813:7698,817:7694}],69:[,,{768:200,769:201,770:202,771:7868,772:274,774:276,775:278,776:203,777:7866,780:282,783:516,785:518,803:7864,807:552,808:280,813:7704,816:7706}],70:[,,{775:7710}],71:[,,{769:500,770:284,772:7712,774:286,775:288,780:486,807:290}],72:[,,{770:292,775:7714,776:7718,780:542,803:7716,807:7720,814:7722}],73:[,,{768:204,769:205,770:206,771:296,772:298,774:300,775:304,776:207,777:7880,780:463,783:520,785:522,803:7882,808:302,816:7724}],74:[,,{770:308}],75:[,,{769:7728,780:488,803:7730,807:310,817:7732}],76:[,,{769:313,780:317,803:7734,807:315,813:7740,817:7738}],77:[,,{769:7742,775:7744,803:7746}],78:[,,{768:504,769:323,771:209,775:7748,780:327,803:7750,807:325,813:7754,817:7752}],79:[,,{768:210,769:211,770:212,771:213,772:332,774:334,775:558,776:214,777:7886,779:336,780:465,783:524,785:526,795:416,803:7884,808:490}],80:[,,{769:7764,775:7766}],82:[,,{769:340,775:7768,780:344,783:528,785:530,803:7770,807:342,817:7774}],83:[,,{769:346,770:348,775:7776,780:352,803:7778,806:536,807:350}],84:[,,{775:7786,780:356,803:7788,806:538,807:354,813:7792,817:7790}],85:[,,{768:217,769:218,770:219,771:360,772:362,774:364,776:220,777:7910,778:366,779:368,780:467,783:532,785:534,795:431,803:7908,804:7794,808:370,813:7798,816:7796}],86:[,,{771:7804,803:7806}],87:[,,{768:7808,769:7810,770:372,775:7814,776:7812,803:7816}],88:[,,{775:7818,776:7820}],89:[,,{768:7922,769:221,770:374,771:7928,772:562,775:7822,776:376,777:7926,803:7924}],90:[,,{769:377,770:7824,775:379,780:381,803:7826,817:7828}],97:[,,{768:224,769:225,770:226,771:227,772:257,774:259,775:551,776:228,777:7843,778:229,780:462,783:513,785:515,803:7841,805:7681,808:261}],98:[,,{775:7683,803:7685,817:7687}],99:[,,{769:263,770:265,775:267,780:269,807:231}],100:[,,{775:7691,780:271,803:7693,807:7697,813:7699,817:7695}],101:[,,{768:232,769:233,770:234,771:7869,772:275,774:277,775:279,776:235,777:7867,780:283,783:517,785:519,803:7865,807:553,808:281,813:7705,816:7707}],102:[,,{775:7711}],103:[,,{769:501,770:285,772:7713,774:287,775:289,780:487,807:291}],104:[,,{770:293,775:7715,776:7719,780:543,803:7717,807:7721,814:7723,817:7830}],105:[,,{768:236,769:237,770:238,771:297,772:299,774:301,776:239,777:7881,780:464,783:521,785:523,803:7883,808:303,816:7725}],106:[,,{770:309,780:496}],107:[,,{769:7729,780:489,803:7731,807:311,817:7733}],108:[,,{769:314,780:318,803:7735,807:316,813:7741,817:7739}],109:[,,{769:7743,775:7745,803:7747}],110:[,,{768:505,769:324,771:241,775:7749,780:328,803:7751,807:326,813:7755,817:7753}],111:[,,{768:242,769:243,770:244,771:245,772:333,774:335,775:559,776:246,777:7887,779:337,780:466,783:525,785:527,795:417,803:7885,808:491}],112:[,,{769:7765,775:7767}],114:[,,{769:341,775:7769,780:345,783:529,785:531,803:7771,807:343,817:7775}],115:[,,{769:347,770:349,775:7777,780:353,803:7779,806:537,807:351}],116:[,,{775:7787,776:7831,780:357,803:7789,806:539,807:355,813:7793,817:7791}],117:[,,{768:249,769:250,770:251,771:361,772:363,774:365,776:252,777:7911,778:367,779:369,780:468,783:533,785:535,795:432,803:7909,804:7795,808:371,813:7799,816:7797}],118:[,,{771:7805,803:7807}],119:[,,{768:7809,769:7811,770:373,775:7815,776:7813,778:7832,803:7817}],120:[,,{775:7819,776:7821}],121:[,,{768:7923,769:253,770:375,771:7929,772:563,775:7823,776:255,777:7927,778:7833,803:7925}],122:[,,{769:378,770:7825,775:380,780:382,803:7827,817:7829}],160:[[32],256],168:[[32,776],256,{768:8173,769:901,834:8129}],170:[[97],256],175:[[32,772],256],178:[[50],256],179:[[51],256],180:[[32,769],256],181:[[956],256],184:[[32,807],256],185:[[49],256],186:[[111],256],188:[[49,8260,52],256],189:[[49,8260,50],256],190:[[51,8260,52],256],192:[[65,768]],193:[[65,769]],194:[[65,770],,{768:7846,769:7844,771:7850,777:7848}],195:[[65,771]],196:[[65,776],,{772:478}],197:[[65,778],,{769:506}],198:[,,{769:508,772:482}],199:[[67,807],,{769:7688}],200:[[69,768]],201:[[69,769]],202:[[69,770],,{768:7872,769:7870,771:7876,777:7874}],203:[[69,776]],204:[[73,768]],205:[[73,769]],206:[[73,770]],207:[[73,776],,{769:7726}],209:[[78,771]],210:[[79,768]],211:[[79,769]],212:[[79,770],,{768:7890,769:7888,771:7894,777:7892}],213:[[79,771],,{769:7756,772:556,776:7758}],214:[[79,776],,{772:554}],216:[,,{769:510}],217:[[85,768]],218:[[85,769]],219:[[85,770]],220:[[85,776],,{768:475,769:471,772:469,780:473}],221:[[89,769]],224:[[97,768]],225:[[97,769]],226:[[97,770],,{768:7847,769:7845,771:7851,777:7849}],227:[[97,771]],228:[[97,776],,{772:479}],229:[[97,778],,{769:507}],230:[,,{769:509,772:483}],231:[[99,807],,{769:7689}],232:[[101,768]],233:[[101,769]],234:[[101,770],,{768:7873,769:7871,771:7877,777:7875}],235:[[101,776]],236:[[105,768]],237:[[105,769]],238:[[105,770]],239:[[105,776],,{769:7727}],241:[[110,771]],242:[[111,768]],243:[[111,769]],244:[[111,770],,{768:7891,769:7889,771:7895,777:7893}],245:[[111,771],,{769:7757,772:557,776:7759}],246:[[111,776],,{772:555}],248:[,,{769:511}],249:[[117,768]],250:[[117,769]],251:[[117,770]],252:[[117,776],,{768:476,769:472,772:470,780:474}],253:[[121,769]],255:[[121,776]]}, + 256:{256:[[65,772]],257:[[97,772]],258:[[65,774],,{768:7856,769:7854,771:7860,777:7858}],259:[[97,774],,{768:7857,769:7855,771:7861,777:7859}],260:[[65,808]],261:[[97,808]],262:[[67,769]],263:[[99,769]],264:[[67,770]],265:[[99,770]],266:[[67,775]],267:[[99,775]],268:[[67,780]],269:[[99,780]],270:[[68,780]],271:[[100,780]],274:[[69,772],,{768:7700,769:7702}],275:[[101,772],,{768:7701,769:7703}],276:[[69,774]],277:[[101,774]],278:[[69,775]],279:[[101,775]],280:[[69,808]],281:[[101,808]],282:[[69,780]],283:[[101,780]],284:[[71,770]],285:[[103,770]],286:[[71,774]],287:[[103,774]],288:[[71,775]],289:[[103,775]],290:[[71,807]],291:[[103,807]],292:[[72,770]],293:[[104,770]],296:[[73,771]],297:[[105,771]],298:[[73,772]],299:[[105,772]],300:[[73,774]],301:[[105,774]],302:[[73,808]],303:[[105,808]],304:[[73,775]],306:[[73,74],256],307:[[105,106],256],308:[[74,770]],309:[[106,770]],310:[[75,807]],311:[[107,807]],313:[[76,769]],314:[[108,769]],315:[[76,807]],316:[[108,807]],317:[[76,780]],318:[[108,780]],319:[[76,183],256],320:[[108,183],256],323:[[78,769]],324:[[110,769]],325:[[78,807]],326:[[110,807]],327:[[78,780]],328:[[110,780]],329:[[700,110],256],332:[[79,772],,{768:7760,769:7762}],333:[[111,772],,{768:7761,769:7763}],334:[[79,774]],335:[[111,774]],336:[[79,779]],337:[[111,779]],340:[[82,769]],341:[[114,769]],342:[[82,807]],343:[[114,807]],344:[[82,780]],345:[[114,780]],346:[[83,769],,{775:7780}],347:[[115,769],,{775:7781}],348:[[83,770]],349:[[115,770]],350:[[83,807]],351:[[115,807]],352:[[83,780],,{775:7782}],353:[[115,780],,{775:7783}],354:[[84,807]],355:[[116,807]],356:[[84,780]],357:[[116,780]],360:[[85,771],,{769:7800}],361:[[117,771],,{769:7801}],362:[[85,772],,{776:7802}],363:[[117,772],,{776:7803}],364:[[85,774]],365:[[117,774]],366:[[85,778]],367:[[117,778]],368:[[85,779]],369:[[117,779]],370:[[85,808]],371:[[117,808]],372:[[87,770]],373:[[119,770]],374:[[89,770]],375:[[121,770]],376:[[89,776]],377:[[90,769]],378:[[122,769]],379:[[90,775]],380:[[122,775]],381:[[90,780]],382:[[122,780]],383:[[115],256,{775:7835}],416:[[79,795],,{768:7900,769:7898,771:7904,777:7902,803:7906}],417:[[111,795],,{768:7901,769:7899,771:7905,777:7903,803:7907}],431:[[85,795],,{768:7914,769:7912,771:7918,777:7916,803:7920}],432:[[117,795],,{768:7915,769:7913,771:7919,777:7917,803:7921}],439:[,,{780:494}],452:[[68,381],256],453:[[68,382],256],454:[[100,382],256],455:[[76,74],256],456:[[76,106],256],457:[[108,106],256],458:[[78,74],256],459:[[78,106],256],460:[[110,106],256],461:[[65,780]],462:[[97,780]],463:[[73,780]],464:[[105,780]],465:[[79,780]],466:[[111,780]],467:[[85,780]],468:[[117,780]],469:[[220,772]],470:[[252,772]],471:[[220,769]],472:[[252,769]],473:[[220,780]],474:[[252,780]],475:[[220,768]],476:[[252,768]],478:[[196,772]],479:[[228,772]],480:[[550,772]],481:[[551,772]],482:[[198,772]],483:[[230,772]],486:[[71,780]],487:[[103,780]],488:[[75,780]],489:[[107,780]],490:[[79,808],,{772:492}],491:[[111,808],,{772:493}],492:[[490,772]],493:[[491,772]],494:[[439,780]],495:[[658,780]],496:[[106,780]],497:[[68,90],256],498:[[68,122],256],499:[[100,122],256],500:[[71,769]],501:[[103,769]],504:[[78,768]],505:[[110,768]],506:[[197,769]],507:[[229,769]],508:[[198,769]],509:[[230,769]],510:[[216,769]],511:[[248,769]],66045:[,220]}, + 512:{512:[[65,783]],513:[[97,783]],514:[[65,785]],515:[[97,785]],516:[[69,783]],517:[[101,783]],518:[[69,785]],519:[[101,785]],520:[[73,783]],521:[[105,783]],522:[[73,785]],523:[[105,785]],524:[[79,783]],525:[[111,783]],526:[[79,785]],527:[[111,785]],528:[[82,783]],529:[[114,783]],530:[[82,785]],531:[[114,785]],532:[[85,783]],533:[[117,783]],534:[[85,785]],535:[[117,785]],536:[[83,806]],537:[[115,806]],538:[[84,806]],539:[[116,806]],542:[[72,780]],543:[[104,780]],550:[[65,775],,{772:480}],551:[[97,775],,{772:481}],552:[[69,807],,{774:7708}],553:[[101,807],,{774:7709}],554:[[214,772]],555:[[246,772]],556:[[213,772]],557:[[245,772]],558:[[79,775],,{772:560}],559:[[111,775],,{772:561}],560:[[558,772]],561:[[559,772]],562:[[89,772]],563:[[121,772]],658:[,,{780:495}],688:[[104],256],689:[[614],256],690:[[106],256],691:[[114],256],692:[[633],256],693:[[635],256],694:[[641],256],695:[[119],256],696:[[121],256],728:[[32,774],256],729:[[32,775],256],730:[[32,778],256],731:[[32,808],256],732:[[32,771],256],733:[[32,779],256],736:[[611],256],737:[[108],256],738:[[115],256],739:[[120],256],740:[[661],256]}, + 768:{768:[,230],769:[,230],770:[,230],771:[,230],772:[,230],773:[,230],774:[,230],775:[,230],776:[,230,{769:836}],777:[,230],778:[,230],779:[,230],780:[,230],781:[,230],782:[,230],783:[,230],784:[,230],785:[,230],786:[,230],787:[,230],788:[,230],789:[,232],790:[,220],791:[,220],792:[,220],793:[,220],794:[,232],795:[,216],796:[,220],797:[,220],798:[,220],799:[,220],800:[,220],801:[,202],802:[,202],803:[,220],804:[,220],805:[,220],806:[,220],807:[,202],808:[,202],809:[,220],810:[,220],811:[,220],812:[,220],813:[,220],814:[,220],815:[,220],816:[,220],817:[,220],818:[,220],819:[,220],820:[,1],821:[,1],822:[,1],823:[,1],824:[,1],825:[,220],826:[,220],827:[,220],828:[,220],829:[,230],830:[,230],831:[,230],832:[[768],230],833:[[769],230],834:[,230],835:[[787],230],836:[[776,769],230],837:[,240],838:[,230],839:[,220],840:[,220],841:[,220],842:[,230],843:[,230],844:[,230],845:[,220],846:[,220],848:[,230],849:[,230],850:[,230],851:[,220],852:[,220],853:[,220],854:[,220],855:[,230],856:[,232],857:[,220],858:[,220],859:[,230],860:[,233],861:[,234],862:[,234],863:[,233],864:[,234],865:[,234],866:[,233],867:[,230],868:[,230],869:[,230],870:[,230],871:[,230],872:[,230],873:[,230],874:[,230],875:[,230],876:[,230],877:[,230],878:[,230],879:[,230],884:[[697]],890:[[32,837],256],894:[[59]],900:[[32,769],256],901:[[168,769]],902:[[913,769]],903:[[183]],904:[[917,769]],905:[[919,769]],906:[[921,769]],908:[[927,769]],910:[[933,769]],911:[[937,769]],912:[[970,769]],913:[,,{768:8122,769:902,772:8121,774:8120,787:7944,788:7945,837:8124}],917:[,,{768:8136,769:904,787:7960,788:7961}],919:[,,{768:8138,769:905,787:7976,788:7977,837:8140}],921:[,,{768:8154,769:906,772:8153,774:8152,776:938,787:7992,788:7993}],927:[,,{768:8184,769:908,787:8008,788:8009}],929:[,,{788:8172}],933:[,,{768:8170,769:910,772:8169,774:8168,776:939,788:8025}],937:[,,{768:8186,769:911,787:8040,788:8041,837:8188}],938:[[921,776]],939:[[933,776]],940:[[945,769],,{837:8116}],941:[[949,769]],942:[[951,769],,{837:8132}],943:[[953,769]],944:[[971,769]],945:[,,{768:8048,769:940,772:8113,774:8112,787:7936,788:7937,834:8118,837:8115}],949:[,,{768:8050,769:941,787:7952,788:7953}],951:[,,{768:8052,769:942,787:7968,788:7969,834:8134,837:8131}],953:[,,{768:8054,769:943,772:8145,774:8144,776:970,787:7984,788:7985,834:8150}],959:[,,{768:8056,769:972,787:8000,788:8001}],961:[,,{787:8164,788:8165}],965:[,,{768:8058,769:973,772:8161,774:8160,776:971,787:8016,788:8017,834:8166}],969:[,,{768:8060,769:974,787:8032,788:8033,834:8182,837:8179}],970:[[953,776],,{768:8146,769:912,834:8151}],971:[[965,776],,{768:8162,769:944,834:8167}],972:[[959,769]],973:[[965,769]],974:[[969,769],,{837:8180}],976:[[946],256],977:[[952],256],978:[[933],256,{769:979,776:980}],979:[[978,769]],980:[[978,776]],981:[[966],256],982:[[960],256],1008:[[954],256],1009:[[961],256],1010:[[962],256],1012:[[920],256],1013:[[949],256],1017:[[931],256]}, + 1024:{1024:[[1045,768]],1025:[[1045,776]],1027:[[1043,769]],1030:[,,{776:1031}],1031:[[1030,776]],1036:[[1050,769]],1037:[[1048,768]],1038:[[1059,774]],1040:[,,{774:1232,776:1234}],1043:[,,{769:1027}],1045:[,,{768:1024,774:1238,776:1025}],1046:[,,{774:1217,776:1244}],1047:[,,{776:1246}],1048:[,,{768:1037,772:1250,774:1049,776:1252}],1049:[[1048,774]],1050:[,,{769:1036}],1054:[,,{776:1254}],1059:[,,{772:1262,774:1038,776:1264,779:1266}],1063:[,,{776:1268}],1067:[,,{776:1272}],1069:[,,{776:1260}],1072:[,,{774:1233,776:1235}],1075:[,,{769:1107}],1077:[,,{768:1104,774:1239,776:1105}],1078:[,,{774:1218,776:1245}],1079:[,,{776:1247}],1080:[,,{768:1117,772:1251,774:1081,776:1253}],1081:[[1080,774]],1082:[,,{769:1116}],1086:[,,{776:1255}],1091:[,,{772:1263,774:1118,776:1265,779:1267}],1095:[,,{776:1269}],1099:[,,{776:1273}],1101:[,,{776:1261}],1104:[[1077,768]],1105:[[1077,776]],1107:[[1075,769]],1110:[,,{776:1111}],1111:[[1110,776]],1116:[[1082,769]],1117:[[1080,768]],1118:[[1091,774]],1140:[,,{783:1142}],1141:[,,{783:1143}],1142:[[1140,783]],1143:[[1141,783]],1155:[,230],1156:[,230],1157:[,230],1158:[,230],1159:[,230],1217:[[1046,774]],1218:[[1078,774]],1232:[[1040,774]],1233:[[1072,774]],1234:[[1040,776]],1235:[[1072,776]],1238:[[1045,774]],1239:[[1077,774]],1240:[,,{776:1242}],1241:[,,{776:1243}],1242:[[1240,776]],1243:[[1241,776]],1244:[[1046,776]],1245:[[1078,776]],1246:[[1047,776]],1247:[[1079,776]],1250:[[1048,772]],1251:[[1080,772]],1252:[[1048,776]],1253:[[1080,776]],1254:[[1054,776]],1255:[[1086,776]],1256:[,,{776:1258}],1257:[,,{776:1259}],1258:[[1256,776]],1259:[[1257,776]],1260:[[1069,776]],1261:[[1101,776]],1262:[[1059,772]],1263:[[1091,772]],1264:[[1059,776]],1265:[[1091,776]],1266:[[1059,779]],1267:[[1091,779]],1268:[[1063,776]],1269:[[1095,776]],1272:[[1067,776]],1273:[[1099,776]]}, + 1280:{1415:[[1381,1410],256],1425:[,220],1426:[,230],1427:[,230],1428:[,230],1429:[,230],1430:[,220],1431:[,230],1432:[,230],1433:[,230],1434:[,222],1435:[,220],1436:[,230],1437:[,230],1438:[,230],1439:[,230],1440:[,230],1441:[,230],1442:[,220],1443:[,220],1444:[,220],1445:[,220],1446:[,220],1447:[,220],1448:[,230],1449:[,230],1450:[,220],1451:[,230],1452:[,230],1453:[,222],1454:[,228],1455:[,230],1456:[,10],1457:[,11],1458:[,12],1459:[,13],1460:[,14],1461:[,15],1462:[,16],1463:[,17],1464:[,18],1465:[,19],1466:[,19],1467:[,20],1468:[,21],1469:[,22],1471:[,23],1473:[,24],1474:[,25],1476:[,230],1477:[,220],1479:[,18]}, + 1536:{1552:[,230],1553:[,230],1554:[,230],1555:[,230],1556:[,230],1557:[,230],1558:[,230],1559:[,230],1560:[,30],1561:[,31],1562:[,32],1570:[[1575,1619]],1571:[[1575,1620]],1572:[[1608,1620]],1573:[[1575,1621]],1574:[[1610,1620]],1575:[,,{1619:1570,1620:1571,1621:1573}],1608:[,,{1620:1572}],1610:[,,{1620:1574}],1611:[,27],1612:[,28],1613:[,29],1614:[,30],1615:[,31],1616:[,32],1617:[,33],1618:[,34],1619:[,230],1620:[,230],1621:[,220],1622:[,220],1623:[,230],1624:[,230],1625:[,230],1626:[,230],1627:[,230],1628:[,220],1629:[,230],1630:[,230],1631:[,220],1648:[,35],1653:[[1575,1652],256],1654:[[1608,1652],256],1655:[[1735,1652],256],1656:[[1610,1652],256],1728:[[1749,1620]],1729:[,,{1620:1730}],1730:[[1729,1620]],1746:[,,{1620:1747}],1747:[[1746,1620]],1749:[,,{1620:1728}],1750:[,230],1751:[,230],1752:[,230],1753:[,230],1754:[,230],1755:[,230],1756:[,230],1759:[,230],1760:[,230],1761:[,230],1762:[,230],1763:[,220],1764:[,230],1767:[,230],1768:[,230],1770:[,220],1771:[,230],1772:[,230],1773:[,220]}, + 1792:{1809:[,36],1840:[,230],1841:[,220],1842:[,230],1843:[,230],1844:[,220],1845:[,230],1846:[,230],1847:[,220],1848:[,220],1849:[,220],1850:[,230],1851:[,220],1852:[,220],1853:[,230],1854:[,220],1855:[,230],1856:[,230],1857:[,230],1858:[,220],1859:[,230],1860:[,220],1861:[,230],1862:[,220],1863:[,230],1864:[,220],1865:[,230],1866:[,230],2027:[,230],2028:[,230],2029:[,230],2030:[,230],2031:[,230],2032:[,230],2033:[,230],2034:[,220],2035:[,230]}, + 2048:{2070:[,230],2071:[,230],2072:[,230],2073:[,230],2075:[,230],2076:[,230],2077:[,230],2078:[,230],2079:[,230],2080:[,230],2081:[,230],2082:[,230],2083:[,230],2085:[,230],2086:[,230],2087:[,230],2089:[,230],2090:[,230],2091:[,230],2092:[,230],2093:[,230],2137:[,220],2138:[,220],2139:[,220],2276:[,230],2277:[,230],2278:[,220],2279:[,230],2280:[,230],2281:[,220],2282:[,230],2283:[,230],2284:[,230],2285:[,220],2286:[,220],2287:[,220],2288:[,27],2289:[,28],2290:[,29],2291:[,230],2292:[,230],2293:[,230],2294:[,220],2295:[,230],2296:[,230],2297:[,220],2298:[,220],2299:[,230],2300:[,230],2301:[,230],2302:[,230]}, + 2304:{2344:[,,{2364:2345}],2345:[[2344,2364]],2352:[,,{2364:2353}],2353:[[2352,2364]],2355:[,,{2364:2356}],2356:[[2355,2364]],2364:[,7],2381:[,9],2385:[,230],2386:[,220],2387:[,230],2388:[,230],2392:[[2325,2364],512],2393:[[2326,2364],512],2394:[[2327,2364],512],2395:[[2332,2364],512],2396:[[2337,2364],512],2397:[[2338,2364],512],2398:[[2347,2364],512],2399:[[2351,2364],512],2492:[,7],2503:[,,{2494:2507,2519:2508}],2507:[[2503,2494]],2508:[[2503,2519]],2509:[,9],2524:[[2465,2492],512],2525:[[2466,2492],512],2527:[[2479,2492],512]}, + 2560:{2611:[[2610,2620],512],2614:[[2616,2620],512],2620:[,7],2637:[,9],2649:[[2582,2620],512],2650:[[2583,2620],512],2651:[[2588,2620],512],2654:[[2603,2620],512],2748:[,7],2765:[,9],68109:[,220],68111:[,230],68152:[,230],68153:[,1],68154:[,220],68159:[,9]}, + 2816:{2876:[,7],2887:[,,{2878:2891,2902:2888,2903:2892}],2888:[[2887,2902]],2891:[[2887,2878]],2892:[[2887,2903]],2893:[,9],2908:[[2849,2876],512],2909:[[2850,2876],512],2962:[,,{3031:2964}],2964:[[2962,3031]],3014:[,,{3006:3018,3031:3020}],3015:[,,{3006:3019}],3018:[[3014,3006]],3019:[[3015,3006]],3020:[[3014,3031]],3021:[,9]}, + 3072:{3142:[,,{3158:3144}],3144:[[3142,3158]],3149:[,9],3157:[,84],3158:[,91],3260:[,7],3263:[,,{3285:3264}],3264:[[3263,3285]],3270:[,,{3266:3274,3285:3271,3286:3272}],3271:[[3270,3285]],3272:[[3270,3286]],3274:[[3270,3266],,{3285:3275}],3275:[[3274,3285]],3277:[,9]}, + 3328:{3398:[,,{3390:3402,3415:3404}],3399:[,,{3390:3403}],3402:[[3398,3390]],3403:[[3399,3390]],3404:[[3398,3415]],3405:[,9],3530:[,9],3545:[,,{3530:3546,3535:3548,3551:3550}],3546:[[3545,3530]],3548:[[3545,3535],,{3530:3549}],3549:[[3548,3530]],3550:[[3545,3551]]}, + 3584:{3635:[[3661,3634],256],3640:[,103],3641:[,103],3642:[,9],3656:[,107],3657:[,107],3658:[,107],3659:[,107],3763:[[3789,3762],256],3768:[,118],3769:[,118],3784:[,122],3785:[,122],3786:[,122],3787:[,122],3804:[[3755,3737],256],3805:[[3755,3745],256]}, + 3840:{3852:[[3851],256],3864:[,220],3865:[,220],3893:[,220],3895:[,220],3897:[,216],3907:[[3906,4023],512],3917:[[3916,4023],512],3922:[[3921,4023],512],3927:[[3926,4023],512],3932:[[3931,4023],512],3945:[[3904,4021],512],3953:[,129],3954:[,130],3955:[[3953,3954],512],3956:[,132],3957:[[3953,3956],512],3958:[[4018,3968],512],3959:[[4018,3969],256],3960:[[4019,3968],512],3961:[[4019,3969],256],3962:[,130],3963:[,130],3964:[,130],3965:[,130],3968:[,130],3969:[[3953,3968],512],3970:[,230],3971:[,230],3972:[,9],3974:[,230],3975:[,230],3987:[[3986,4023],512],3997:[[3996,4023],512],4002:[[4001,4023],512],4007:[[4006,4023],512],4012:[[4011,4023],512],4025:[[3984,4021],512],4038:[,220]}, + 4096:{4133:[,,{4142:4134}],4134:[[4133,4142]],4151:[,7],4153:[,9],4154:[,9],4237:[,220],4348:[[4316],256],69702:[,9],69785:[,,{69818:69786}],69786:[[69785,69818]],69787:[,,{69818:69788}],69788:[[69787,69818]],69797:[,,{69818:69803}],69803:[[69797,69818]],69817:[,9],69818:[,7]}, + 4352:{69888:[,230],69889:[,230],69890:[,230],69934:[[69937,69927]],69935:[[69938,69927]],69937:[,,{69927:69934}],69938:[,,{69927:69935}],69939:[,9],69940:[,9],70080:[,9]}, + 4864:{4957:[,230],4958:[,230],4959:[,230]}, + 5632:{71350:[,9],71351:[,7]}, + 5888:{5908:[,9],5940:[,9],6098:[,9],6109:[,230]}, + 6144:{6313:[,228]}, + 6400:{6457:[,222],6458:[,230],6459:[,220]}, + 6656:{6679:[,230],6680:[,220],6752:[,9],6773:[,230],6774:[,230],6775:[,230],6776:[,230],6777:[,230],6778:[,230],6779:[,230],6780:[,230],6783:[,220]}, + 6912:{6917:[,,{6965:6918}],6918:[[6917,6965]],6919:[,,{6965:6920}],6920:[[6919,6965]],6921:[,,{6965:6922}],6922:[[6921,6965]],6923:[,,{6965:6924}],6924:[[6923,6965]],6925:[,,{6965:6926}],6926:[[6925,6965]],6929:[,,{6965:6930}],6930:[[6929,6965]],6964:[,7],6970:[,,{6965:6971}],6971:[[6970,6965]],6972:[,,{6965:6973}],6973:[[6972,6965]],6974:[,,{6965:6976}],6975:[,,{6965:6977}],6976:[[6974,6965]],6977:[[6975,6965]],6978:[,,{6965:6979}],6979:[[6978,6965]],6980:[,9],7019:[,230],7020:[,220],7021:[,230],7022:[,230],7023:[,230],7024:[,230],7025:[,230],7026:[,230],7027:[,230],7082:[,9],7083:[,9],7142:[,7],7154:[,9],7155:[,9]}, + 7168:{7223:[,7],7376:[,230],7377:[,230],7378:[,230],7380:[,1],7381:[,220],7382:[,220],7383:[,220],7384:[,220],7385:[,220],7386:[,230],7387:[,230],7388:[,220],7389:[,220],7390:[,220],7391:[,220],7392:[,230],7394:[,1],7395:[,1],7396:[,1],7397:[,1],7398:[,1],7399:[,1],7400:[,1],7405:[,220],7412:[,230]}, + 7424:{7468:[[65],256],7469:[[198],256],7470:[[66],256],7472:[[68],256],7473:[[69],256],7474:[[398],256],7475:[[71],256],7476:[[72],256],7477:[[73],256],7478:[[74],256],7479:[[75],256],7480:[[76],256],7481:[[77],256],7482:[[78],256],7484:[[79],256],7485:[[546],256],7486:[[80],256],7487:[[82],256],7488:[[84],256],7489:[[85],256],7490:[[87],256],7491:[[97],256],7492:[[592],256],7493:[[593],256],7494:[[7426],256],7495:[[98],256],7496:[[100],256],7497:[[101],256],7498:[[601],256],7499:[[603],256],7500:[[604],256],7501:[[103],256],7503:[[107],256],7504:[[109],256],7505:[[331],256],7506:[[111],256],7507:[[596],256],7508:[[7446],256],7509:[[7447],256],7510:[[112],256],7511:[[116],256],7512:[[117],256],7513:[[7453],256],7514:[[623],256],7515:[[118],256],7516:[[7461],256],7517:[[946],256],7518:[[947],256],7519:[[948],256],7520:[[966],256],7521:[[967],256],7522:[[105],256],7523:[[114],256],7524:[[117],256],7525:[[118],256],7526:[[946],256],7527:[[947],256],7528:[[961],256],7529:[[966],256],7530:[[967],256],7544:[[1085],256],7579:[[594],256],7580:[[99],256],7581:[[597],256],7582:[[240],256],7583:[[604],256],7584:[[102],256],7585:[[607],256],7586:[[609],256],7587:[[613],256],7588:[[616],256],7589:[[617],256],7590:[[618],256],7591:[[7547],256],7592:[[669],256],7593:[[621],256],7594:[[7557],256],7595:[[671],256],7596:[[625],256],7597:[[624],256],7598:[[626],256],7599:[[627],256],7600:[[628],256],7601:[[629],256],7602:[[632],256],7603:[[642],256],7604:[[643],256],7605:[[427],256],7606:[[649],256],7607:[[650],256],7608:[[7452],256],7609:[[651],256],7610:[[652],256],7611:[[122],256],7612:[[656],256],7613:[[657],256],7614:[[658],256],7615:[[952],256],7616:[,230],7617:[,230],7618:[,220],7619:[,230],7620:[,230],7621:[,230],7622:[,230],7623:[,230],7624:[,230],7625:[,230],7626:[,220],7627:[,230],7628:[,230],7629:[,234],7630:[,214],7631:[,220],7632:[,202],7633:[,230],7634:[,230],7635:[,230],7636:[,230],7637:[,230],7638:[,230],7639:[,230],7640:[,230],7641:[,230],7642:[,230],7643:[,230],7644:[,230],7645:[,230],7646:[,230],7647:[,230],7648:[,230],7649:[,230],7650:[,230],7651:[,230],7652:[,230],7653:[,230],7654:[,230],7676:[,233],7677:[,220],7678:[,230],7679:[,220]}, + 7680:{7680:[[65,805]],7681:[[97,805]],7682:[[66,775]],7683:[[98,775]],7684:[[66,803]],7685:[[98,803]],7686:[[66,817]],7687:[[98,817]],7688:[[199,769]],7689:[[231,769]],7690:[[68,775]],7691:[[100,775]],7692:[[68,803]],7693:[[100,803]],7694:[[68,817]],7695:[[100,817]],7696:[[68,807]],7697:[[100,807]],7698:[[68,813]],7699:[[100,813]],7700:[[274,768]],7701:[[275,768]],7702:[[274,769]],7703:[[275,769]],7704:[[69,813]],7705:[[101,813]],7706:[[69,816]],7707:[[101,816]],7708:[[552,774]],7709:[[553,774]],7710:[[70,775]],7711:[[102,775]],7712:[[71,772]],7713:[[103,772]],7714:[[72,775]],7715:[[104,775]],7716:[[72,803]],7717:[[104,803]],7718:[[72,776]],7719:[[104,776]],7720:[[72,807]],7721:[[104,807]],7722:[[72,814]],7723:[[104,814]],7724:[[73,816]],7725:[[105,816]],7726:[[207,769]],7727:[[239,769]],7728:[[75,769]],7729:[[107,769]],7730:[[75,803]],7731:[[107,803]],7732:[[75,817]],7733:[[107,817]],7734:[[76,803],,{772:7736}],7735:[[108,803],,{772:7737}],7736:[[7734,772]],7737:[[7735,772]],7738:[[76,817]],7739:[[108,817]],7740:[[76,813]],7741:[[108,813]],7742:[[77,769]],7743:[[109,769]],7744:[[77,775]],7745:[[109,775]],7746:[[77,803]],7747:[[109,803]],7748:[[78,775]],7749:[[110,775]],7750:[[78,803]],7751:[[110,803]],7752:[[78,817]],7753:[[110,817]],7754:[[78,813]],7755:[[110,813]],7756:[[213,769]],7757:[[245,769]],7758:[[213,776]],7759:[[245,776]],7760:[[332,768]],7761:[[333,768]],7762:[[332,769]],7763:[[333,769]],7764:[[80,769]],7765:[[112,769]],7766:[[80,775]],7767:[[112,775]],7768:[[82,775]],7769:[[114,775]],7770:[[82,803],,{772:7772}],7771:[[114,803],,{772:7773}],7772:[[7770,772]],7773:[[7771,772]],7774:[[82,817]],7775:[[114,817]],7776:[[83,775]],7777:[[115,775]],7778:[[83,803],,{775:7784}],7779:[[115,803],,{775:7785}],7780:[[346,775]],7781:[[347,775]],7782:[[352,775]],7783:[[353,775]],7784:[[7778,775]],7785:[[7779,775]],7786:[[84,775]],7787:[[116,775]],7788:[[84,803]],7789:[[116,803]],7790:[[84,817]],7791:[[116,817]],7792:[[84,813]],7793:[[116,813]],7794:[[85,804]],7795:[[117,804]],7796:[[85,816]],7797:[[117,816]],7798:[[85,813]],7799:[[117,813]],7800:[[360,769]],7801:[[361,769]],7802:[[362,776]],7803:[[363,776]],7804:[[86,771]],7805:[[118,771]],7806:[[86,803]],7807:[[118,803]],7808:[[87,768]],7809:[[119,768]],7810:[[87,769]],7811:[[119,769]],7812:[[87,776]],7813:[[119,776]],7814:[[87,775]],7815:[[119,775]],7816:[[87,803]],7817:[[119,803]],7818:[[88,775]],7819:[[120,775]],7820:[[88,776]],7821:[[120,776]],7822:[[89,775]],7823:[[121,775]],7824:[[90,770]],7825:[[122,770]],7826:[[90,803]],7827:[[122,803]],7828:[[90,817]],7829:[[122,817]],7830:[[104,817]],7831:[[116,776]],7832:[[119,778]],7833:[[121,778]],7834:[[97,702],256],7835:[[383,775]],7840:[[65,803],,{770:7852,774:7862}],7841:[[97,803],,{770:7853,774:7863}],7842:[[65,777]],7843:[[97,777]],7844:[[194,769]],7845:[[226,769]],7846:[[194,768]],7847:[[226,768]],7848:[[194,777]],7849:[[226,777]],7850:[[194,771]],7851:[[226,771]],7852:[[7840,770]],7853:[[7841,770]],7854:[[258,769]],7855:[[259,769]],7856:[[258,768]],7857:[[259,768]],7858:[[258,777]],7859:[[259,777]],7860:[[258,771]],7861:[[259,771]],7862:[[7840,774]],7863:[[7841,774]],7864:[[69,803],,{770:7878}],7865:[[101,803],,{770:7879}],7866:[[69,777]],7867:[[101,777]],7868:[[69,771]],7869:[[101,771]],7870:[[202,769]],7871:[[234,769]],7872:[[202,768]],7873:[[234,768]],7874:[[202,777]],7875:[[234,777]],7876:[[202,771]],7877:[[234,771]],7878:[[7864,770]],7879:[[7865,770]],7880:[[73,777]],7881:[[105,777]],7882:[[73,803]],7883:[[105,803]],7884:[[79,803],,{770:7896}],7885:[[111,803],,{770:7897}],7886:[[79,777]],7887:[[111,777]],7888:[[212,769]],7889:[[244,769]],7890:[[212,768]],7891:[[244,768]],7892:[[212,777]],7893:[[244,777]],7894:[[212,771]],7895:[[244,771]],7896:[[7884,770]],7897:[[7885,770]],7898:[[416,769]],7899:[[417,769]],7900:[[416,768]],7901:[[417,768]],7902:[[416,777]],7903:[[417,777]],7904:[[416,771]],7905:[[417,771]],7906:[[416,803]],7907:[[417,803]],7908:[[85,803]],7909:[[117,803]],7910:[[85,777]],7911:[[117,777]],7912:[[431,769]],7913:[[432,769]],7914:[[431,768]],7915:[[432,768]],7916:[[431,777]],7917:[[432,777]],7918:[[431,771]],7919:[[432,771]],7920:[[431,803]],7921:[[432,803]],7922:[[89,768]],7923:[[121,768]],7924:[[89,803]],7925:[[121,803]],7926:[[89,777]],7927:[[121,777]],7928:[[89,771]],7929:[[121,771]]}, + 7936:{7936:[[945,787],,{768:7938,769:7940,834:7942,837:8064}],7937:[[945,788],,{768:7939,769:7941,834:7943,837:8065}],7938:[[7936,768],,{837:8066}],7939:[[7937,768],,{837:8067}],7940:[[7936,769],,{837:8068}],7941:[[7937,769],,{837:8069}],7942:[[7936,834],,{837:8070}],7943:[[7937,834],,{837:8071}],7944:[[913,787],,{768:7946,769:7948,834:7950,837:8072}],7945:[[913,788],,{768:7947,769:7949,834:7951,837:8073}],7946:[[7944,768],,{837:8074}],7947:[[7945,768],,{837:8075}],7948:[[7944,769],,{837:8076}],7949:[[7945,769],,{837:8077}],7950:[[7944,834],,{837:8078}],7951:[[7945,834],,{837:8079}],7952:[[949,787],,{768:7954,769:7956}],7953:[[949,788],,{768:7955,769:7957}],7954:[[7952,768]],7955:[[7953,768]],7956:[[7952,769]],7957:[[7953,769]],7960:[[917,787],,{768:7962,769:7964}],7961:[[917,788],,{768:7963,769:7965}],7962:[[7960,768]],7963:[[7961,768]],7964:[[7960,769]],7965:[[7961,769]],7968:[[951,787],,{768:7970,769:7972,834:7974,837:8080}],7969:[[951,788],,{768:7971,769:7973,834:7975,837:8081}],7970:[[7968,768],,{837:8082}],7971:[[7969,768],,{837:8083}],7972:[[7968,769],,{837:8084}],7973:[[7969,769],,{837:8085}],7974:[[7968,834],,{837:8086}],7975:[[7969,834],,{837:8087}],7976:[[919,787],,{768:7978,769:7980,834:7982,837:8088}],7977:[[919,788],,{768:7979,769:7981,834:7983,837:8089}],7978:[[7976,768],,{837:8090}],7979:[[7977,768],,{837:8091}],7980:[[7976,769],,{837:8092}],7981:[[7977,769],,{837:8093}],7982:[[7976,834],,{837:8094}],7983:[[7977,834],,{837:8095}],7984:[[953,787],,{768:7986,769:7988,834:7990}],7985:[[953,788],,{768:7987,769:7989,834:7991}],7986:[[7984,768]],7987:[[7985,768]],7988:[[7984,769]],7989:[[7985,769]],7990:[[7984,834]],7991:[[7985,834]],7992:[[921,787],,{768:7994,769:7996,834:7998}],7993:[[921,788],,{768:7995,769:7997,834:7999}],7994:[[7992,768]],7995:[[7993,768]],7996:[[7992,769]],7997:[[7993,769]],7998:[[7992,834]],7999:[[7993,834]],8000:[[959,787],,{768:8002,769:8004}],8001:[[959,788],,{768:8003,769:8005}],8002:[[8000,768]],8003:[[8001,768]],8004:[[8000,769]],8005:[[8001,769]],8008:[[927,787],,{768:8010,769:8012}],8009:[[927,788],,{768:8011,769:8013}],8010:[[8008,768]],8011:[[8009,768]],8012:[[8008,769]],8013:[[8009,769]],8016:[[965,787],,{768:8018,769:8020,834:8022}],8017:[[965,788],,{768:8019,769:8021,834:8023}],8018:[[8016,768]],8019:[[8017,768]],8020:[[8016,769]],8021:[[8017,769]],8022:[[8016,834]],8023:[[8017,834]],8025:[[933,788],,{768:8027,769:8029,834:8031}],8027:[[8025,768]],8029:[[8025,769]],8031:[[8025,834]],8032:[[969,787],,{768:8034,769:8036,834:8038,837:8096}],8033:[[969,788],,{768:8035,769:8037,834:8039,837:8097}],8034:[[8032,768],,{837:8098}],8035:[[8033,768],,{837:8099}],8036:[[8032,769],,{837:8100}],8037:[[8033,769],,{837:8101}],8038:[[8032,834],,{837:8102}],8039:[[8033,834],,{837:8103}],8040:[[937,787],,{768:8042,769:8044,834:8046,837:8104}],8041:[[937,788],,{768:8043,769:8045,834:8047,837:8105}],8042:[[8040,768],,{837:8106}],8043:[[8041,768],,{837:8107}],8044:[[8040,769],,{837:8108}],8045:[[8041,769],,{837:8109}],8046:[[8040,834],,{837:8110}],8047:[[8041,834],,{837:8111}],8048:[[945,768],,{837:8114}],8049:[[940]],8050:[[949,768]],8051:[[941]],8052:[[951,768],,{837:8130}],8053:[[942]],8054:[[953,768]],8055:[[943]],8056:[[959,768]],8057:[[972]],8058:[[965,768]],8059:[[973]],8060:[[969,768],,{837:8178}],8061:[[974]],8064:[[7936,837]],8065:[[7937,837]],8066:[[7938,837]],8067:[[7939,837]],8068:[[7940,837]],8069:[[7941,837]],8070:[[7942,837]],8071:[[7943,837]],8072:[[7944,837]],8073:[[7945,837]],8074:[[7946,837]],8075:[[7947,837]],8076:[[7948,837]],8077:[[7949,837]],8078:[[7950,837]],8079:[[7951,837]],8080:[[7968,837]],8081:[[7969,837]],8082:[[7970,837]],8083:[[7971,837]],8084:[[7972,837]],8085:[[7973,837]],8086:[[7974,837]],8087:[[7975,837]],8088:[[7976,837]],8089:[[7977,837]],8090:[[7978,837]],8091:[[7979,837]],8092:[[7980,837]],8093:[[7981,837]],8094:[[7982,837]],8095:[[7983,837]],8096:[[8032,837]],8097:[[8033,837]],8098:[[8034,837]],8099:[[8035,837]],8100:[[8036,837]],8101:[[8037,837]],8102:[[8038,837]],8103:[[8039,837]],8104:[[8040,837]],8105:[[8041,837]],8106:[[8042,837]],8107:[[8043,837]],8108:[[8044,837]],8109:[[8045,837]],8110:[[8046,837]],8111:[[8047,837]],8112:[[945,774]],8113:[[945,772]],8114:[[8048,837]],8115:[[945,837]],8116:[[940,837]],8118:[[945,834],,{837:8119}],8119:[[8118,837]],8120:[[913,774]],8121:[[913,772]],8122:[[913,768]],8123:[[902]],8124:[[913,837]],8125:[[32,787],256],8126:[[953]],8127:[[32,787],256,{768:8141,769:8142,834:8143}],8128:[[32,834],256],8129:[[168,834]],8130:[[8052,837]],8131:[[951,837]],8132:[[942,837]],8134:[[951,834],,{837:8135}],8135:[[8134,837]],8136:[[917,768]],8137:[[904]],8138:[[919,768]],8139:[[905]],8140:[[919,837]],8141:[[8127,768]],8142:[[8127,769]],8143:[[8127,834]],8144:[[953,774]],8145:[[953,772]],8146:[[970,768]],8147:[[912]],8150:[[953,834]],8151:[[970,834]],8152:[[921,774]],8153:[[921,772]],8154:[[921,768]],8155:[[906]],8157:[[8190,768]],8158:[[8190,769]],8159:[[8190,834]],8160:[[965,774]],8161:[[965,772]],8162:[[971,768]],8163:[[944]],8164:[[961,787]],8165:[[961,788]],8166:[[965,834]],8167:[[971,834]],8168:[[933,774]],8169:[[933,772]],8170:[[933,768]],8171:[[910]],8172:[[929,788]],8173:[[168,768]],8174:[[901]],8175:[[96]],8178:[[8060,837]],8179:[[969,837]],8180:[[974,837]],8182:[[969,834],,{837:8183}],8183:[[8182,837]],8184:[[927,768]],8185:[[908]],8186:[[937,768]],8187:[[911]],8188:[[937,837]],8189:[[180]],8190:[[32,788],256,{768:8157,769:8158,834:8159}]}, + 8192:{8192:[[8194]],8193:[[8195]],8194:[[32],256],8195:[[32],256],8196:[[32],256],8197:[[32],256],8198:[[32],256],8199:[[32],256],8200:[[32],256],8201:[[32],256],8202:[[32],256],8209:[[8208],256],8215:[[32,819],256],8228:[[46],256],8229:[[46,46],256],8230:[[46,46,46],256],8239:[[32],256],8243:[[8242,8242],256],8244:[[8242,8242,8242],256],8246:[[8245,8245],256],8247:[[8245,8245,8245],256],8252:[[33,33],256],8254:[[32,773],256],8263:[[63,63],256],8264:[[63,33],256],8265:[[33,63],256],8279:[[8242,8242,8242,8242],256],8287:[[32],256],8304:[[48],256],8305:[[105],256],8308:[[52],256],8309:[[53],256],8310:[[54],256],8311:[[55],256],8312:[[56],256],8313:[[57],256],8314:[[43],256],8315:[[8722],256],8316:[[61],256],8317:[[40],256],8318:[[41],256],8319:[[110],256],8320:[[48],256],8321:[[49],256],8322:[[50],256],8323:[[51],256],8324:[[52],256],8325:[[53],256],8326:[[54],256],8327:[[55],256],8328:[[56],256],8329:[[57],256],8330:[[43],256],8331:[[8722],256],8332:[[61],256],8333:[[40],256],8334:[[41],256],8336:[[97],256],8337:[[101],256],8338:[[111],256],8339:[[120],256],8340:[[601],256],8341:[[104],256],8342:[[107],256],8343:[[108],256],8344:[[109],256],8345:[[110],256],8346:[[112],256],8347:[[115],256],8348:[[116],256],8360:[[82,115],256],8400:[,230],8401:[,230],8402:[,1],8403:[,1],8404:[,230],8405:[,230],8406:[,230],8407:[,230],8408:[,1],8409:[,1],8410:[,1],8411:[,230],8412:[,230],8417:[,230],8421:[,1],8422:[,1],8423:[,230],8424:[,220],8425:[,230],8426:[,1],8427:[,1],8428:[,220],8429:[,220],8430:[,220],8431:[,220],8432:[,230]}, + 8448:{8448:[[97,47,99],256],8449:[[97,47,115],256],8450:[[67],256],8451:[[176,67],256],8453:[[99,47,111],256],8454:[[99,47,117],256],8455:[[400],256],8457:[[176,70],256],8458:[[103],256],8459:[[72],256],8460:[[72],256],8461:[[72],256],8462:[[104],256],8463:[[295],256],8464:[[73],256],8465:[[73],256],8466:[[76],256],8467:[[108],256],8469:[[78],256],8470:[[78,111],256],8473:[[80],256],8474:[[81],256],8475:[[82],256],8476:[[82],256],8477:[[82],256],8480:[[83,77],256],8481:[[84,69,76],256],8482:[[84,77],256],8484:[[90],256],8486:[[937]],8488:[[90],256],8490:[[75]],8491:[[197]],8492:[[66],256],8493:[[67],256],8495:[[101],256],8496:[[69],256],8497:[[70],256],8499:[[77],256],8500:[[111],256],8501:[[1488],256],8502:[[1489],256],8503:[[1490],256],8504:[[1491],256],8505:[[105],256],8507:[[70,65,88],256],8508:[[960],256],8509:[[947],256],8510:[[915],256],8511:[[928],256],8512:[[8721],256],8517:[[68],256],8518:[[100],256],8519:[[101],256],8520:[[105],256],8521:[[106],256],8528:[[49,8260,55],256],8529:[[49,8260,57],256],8530:[[49,8260,49,48],256],8531:[[49,8260,51],256],8532:[[50,8260,51],256],8533:[[49,8260,53],256],8534:[[50,8260,53],256],8535:[[51,8260,53],256],8536:[[52,8260,53],256],8537:[[49,8260,54],256],8538:[[53,8260,54],256],8539:[[49,8260,56],256],8540:[[51,8260,56],256],8541:[[53,8260,56],256],8542:[[55,8260,56],256],8543:[[49,8260],256],8544:[[73],256],8545:[[73,73],256],8546:[[73,73,73],256],8547:[[73,86],256],8548:[[86],256],8549:[[86,73],256],8550:[[86,73,73],256],8551:[[86,73,73,73],256],8552:[[73,88],256],8553:[[88],256],8554:[[88,73],256],8555:[[88,73,73],256],8556:[[76],256],8557:[[67],256],8558:[[68],256],8559:[[77],256],8560:[[105],256],8561:[[105,105],256],8562:[[105,105,105],256],8563:[[105,118],256],8564:[[118],256],8565:[[118,105],256],8566:[[118,105,105],256],8567:[[118,105,105,105],256],8568:[[105,120],256],8569:[[120],256],8570:[[120,105],256],8571:[[120,105,105],256],8572:[[108],256],8573:[[99],256],8574:[[100],256],8575:[[109],256],8585:[[48,8260,51],256],8592:[,,{824:8602}],8594:[,,{824:8603}],8596:[,,{824:8622}],8602:[[8592,824]],8603:[[8594,824]],8622:[[8596,824]],8653:[[8656,824]],8654:[[8660,824]],8655:[[8658,824]],8656:[,,{824:8653}],8658:[,,{824:8655}],8660:[,,{824:8654}]}, + 8704:{8707:[,,{824:8708}],8708:[[8707,824]],8712:[,,{824:8713}],8713:[[8712,824]],8715:[,,{824:8716}],8716:[[8715,824]],8739:[,,{824:8740}],8740:[[8739,824]],8741:[,,{824:8742}],8742:[[8741,824]],8748:[[8747,8747],256],8749:[[8747,8747,8747],256],8751:[[8750,8750],256],8752:[[8750,8750,8750],256],8764:[,,{824:8769}],8769:[[8764,824]],8771:[,,{824:8772}],8772:[[8771,824]],8773:[,,{824:8775}],8775:[[8773,824]],8776:[,,{824:8777}],8777:[[8776,824]],8781:[,,{824:8813}],8800:[[61,824]],8801:[,,{824:8802}],8802:[[8801,824]],8804:[,,{824:8816}],8805:[,,{824:8817}],8813:[[8781,824]],8814:[[60,824]],8815:[[62,824]],8816:[[8804,824]],8817:[[8805,824]],8818:[,,{824:8820}],8819:[,,{824:8821}],8820:[[8818,824]],8821:[[8819,824]],8822:[,,{824:8824}],8823:[,,{824:8825}],8824:[[8822,824]],8825:[[8823,824]],8826:[,,{824:8832}],8827:[,,{824:8833}],8828:[,,{824:8928}],8829:[,,{824:8929}],8832:[[8826,824]],8833:[[8827,824]],8834:[,,{824:8836}],8835:[,,{824:8837}],8836:[[8834,824]],8837:[[8835,824]],8838:[,,{824:8840}],8839:[,,{824:8841}],8840:[[8838,824]],8841:[[8839,824]],8849:[,,{824:8930}],8850:[,,{824:8931}],8866:[,,{824:8876}],8872:[,,{824:8877}],8873:[,,{824:8878}],8875:[,,{824:8879}],8876:[[8866,824]],8877:[[8872,824]],8878:[[8873,824]],8879:[[8875,824]],8882:[,,{824:8938}],8883:[,,{824:8939}],8884:[,,{824:8940}],8885:[,,{824:8941}],8928:[[8828,824]],8929:[[8829,824]],8930:[[8849,824]],8931:[[8850,824]],8938:[[8882,824]],8939:[[8883,824]],8940:[[8884,824]],8941:[[8885,824]]}, + 8960:{9001:[[12296]],9002:[[12297]]}, + 9216:{9312:[[49],256],9313:[[50],256],9314:[[51],256],9315:[[52],256],9316:[[53],256],9317:[[54],256],9318:[[55],256],9319:[[56],256],9320:[[57],256],9321:[[49,48],256],9322:[[49,49],256],9323:[[49,50],256],9324:[[49,51],256],9325:[[49,52],256],9326:[[49,53],256],9327:[[49,54],256],9328:[[49,55],256],9329:[[49,56],256],9330:[[49,57],256],9331:[[50,48],256],9332:[[40,49,41],256],9333:[[40,50,41],256],9334:[[40,51,41],256],9335:[[40,52,41],256],9336:[[40,53,41],256],9337:[[40,54,41],256],9338:[[40,55,41],256],9339:[[40,56,41],256],9340:[[40,57,41],256],9341:[[40,49,48,41],256],9342:[[40,49,49,41],256],9343:[[40,49,50,41],256],9344:[[40,49,51,41],256],9345:[[40,49,52,41],256],9346:[[40,49,53,41],256],9347:[[40,49,54,41],256],9348:[[40,49,55,41],256],9349:[[40,49,56,41],256],9350:[[40,49,57,41],256],9351:[[40,50,48,41],256],9352:[[49,46],256],9353:[[50,46],256],9354:[[51,46],256],9355:[[52,46],256],9356:[[53,46],256],9357:[[54,46],256],9358:[[55,46],256],9359:[[56,46],256],9360:[[57,46],256],9361:[[49,48,46],256],9362:[[49,49,46],256],9363:[[49,50,46],256],9364:[[49,51,46],256],9365:[[49,52,46],256],9366:[[49,53,46],256],9367:[[49,54,46],256],9368:[[49,55,46],256],9369:[[49,56,46],256],9370:[[49,57,46],256],9371:[[50,48,46],256],9372:[[40,97,41],256],9373:[[40,98,41],256],9374:[[40,99,41],256],9375:[[40,100,41],256],9376:[[40,101,41],256],9377:[[40,102,41],256],9378:[[40,103,41],256],9379:[[40,104,41],256],9380:[[40,105,41],256],9381:[[40,106,41],256],9382:[[40,107,41],256],9383:[[40,108,41],256],9384:[[40,109,41],256],9385:[[40,110,41],256],9386:[[40,111,41],256],9387:[[40,112,41],256],9388:[[40,113,41],256],9389:[[40,114,41],256],9390:[[40,115,41],256],9391:[[40,116,41],256],9392:[[40,117,41],256],9393:[[40,118,41],256],9394:[[40,119,41],256],9395:[[40,120,41],256],9396:[[40,121,41],256],9397:[[40,122,41],256],9398:[[65],256],9399:[[66],256],9400:[[67],256],9401:[[68],256],9402:[[69],256],9403:[[70],256],9404:[[71],256],9405:[[72],256],9406:[[73],256],9407:[[74],256],9408:[[75],256],9409:[[76],256],9410:[[77],256],9411:[[78],256],9412:[[79],256],9413:[[80],256],9414:[[81],256],9415:[[82],256],9416:[[83],256],9417:[[84],256],9418:[[85],256],9419:[[86],256],9420:[[87],256],9421:[[88],256],9422:[[89],256],9423:[[90],256],9424:[[97],256],9425:[[98],256],9426:[[99],256],9427:[[100],256],9428:[[101],256],9429:[[102],256],9430:[[103],256],9431:[[104],256],9432:[[105],256],9433:[[106],256],9434:[[107],256],9435:[[108],256],9436:[[109],256],9437:[[110],256],9438:[[111],256],9439:[[112],256],9440:[[113],256],9441:[[114],256],9442:[[115],256],9443:[[116],256],9444:[[117],256],9445:[[118],256],9446:[[119],256],9447:[[120],256],9448:[[121],256],9449:[[122],256],9450:[[48],256]}, + 10752:{10764:[[8747,8747,8747,8747],256],10868:[[58,58,61],256],10869:[[61,61],256],10870:[[61,61,61],256],10972:[[10973,824],512]}, + 11264:{11388:[[106],256],11389:[[86],256],11503:[,230],11504:[,230],11505:[,230]}, + 11520:{11631:[[11617],256],11647:[,9],11744:[,230],11745:[,230],11746:[,230],11747:[,230],11748:[,230],11749:[,230],11750:[,230],11751:[,230],11752:[,230],11753:[,230],11754:[,230],11755:[,230],11756:[,230],11757:[,230],11758:[,230],11759:[,230],11760:[,230],11761:[,230],11762:[,230],11763:[,230],11764:[,230],11765:[,230],11766:[,230],11767:[,230],11768:[,230],11769:[,230],11770:[,230],11771:[,230],11772:[,230],11773:[,230],11774:[,230],11775:[,230]}, + 11776:{11935:[[27597],256],12019:[[40863],256]}, + 12032:{12032:[[19968],256],12033:[[20008],256],12034:[[20022],256],12035:[[20031],256],12036:[[20057],256],12037:[[20101],256],12038:[[20108],256],12039:[[20128],256],12040:[[20154],256],12041:[[20799],256],12042:[[20837],256],12043:[[20843],256],12044:[[20866],256],12045:[[20886],256],12046:[[20907],256],12047:[[20960],256],12048:[[20981],256],12049:[[20992],256],12050:[[21147],256],12051:[[21241],256],12052:[[21269],256],12053:[[21274],256],12054:[[21304],256],12055:[[21313],256],12056:[[21340],256],12057:[[21353],256],12058:[[21378],256],12059:[[21430],256],12060:[[21448],256],12061:[[21475],256],12062:[[22231],256],12063:[[22303],256],12064:[[22763],256],12065:[[22786],256],12066:[[22794],256],12067:[[22805],256],12068:[[22823],256],12069:[[22899],256],12070:[[23376],256],12071:[[23424],256],12072:[[23544],256],12073:[[23567],256],12074:[[23586],256],12075:[[23608],256],12076:[[23662],256],12077:[[23665],256],12078:[[24027],256],12079:[[24037],256],12080:[[24049],256],12081:[[24062],256],12082:[[24178],256],12083:[[24186],256],12084:[[24191],256],12085:[[24308],256],12086:[[24318],256],12087:[[24331],256],12088:[[24339],256],12089:[[24400],256],12090:[[24417],256],12091:[[24435],256],12092:[[24515],256],12093:[[25096],256],12094:[[25142],256],12095:[[25163],256],12096:[[25903],256],12097:[[25908],256],12098:[[25991],256],12099:[[26007],256],12100:[[26020],256],12101:[[26041],256],12102:[[26080],256],12103:[[26085],256],12104:[[26352],256],12105:[[26376],256],12106:[[26408],256],12107:[[27424],256],12108:[[27490],256],12109:[[27513],256],12110:[[27571],256],12111:[[27595],256],12112:[[27604],256],12113:[[27611],256],12114:[[27663],256],12115:[[27668],256],12116:[[27700],256],12117:[[28779],256],12118:[[29226],256],12119:[[29238],256],12120:[[29243],256],12121:[[29247],256],12122:[[29255],256],12123:[[29273],256],12124:[[29275],256],12125:[[29356],256],12126:[[29572],256],12127:[[29577],256],12128:[[29916],256],12129:[[29926],256],12130:[[29976],256],12131:[[29983],256],12132:[[29992],256],12133:[[30000],256],12134:[[30091],256],12135:[[30098],256],12136:[[30326],256],12137:[[30333],256],12138:[[30382],256],12139:[[30399],256],12140:[[30446],256],12141:[[30683],256],12142:[[30690],256],12143:[[30707],256],12144:[[31034],256],12145:[[31160],256],12146:[[31166],256],12147:[[31348],256],12148:[[31435],256],12149:[[31481],256],12150:[[31859],256],12151:[[31992],256],12152:[[32566],256],12153:[[32593],256],12154:[[32650],256],12155:[[32701],256],12156:[[32769],256],12157:[[32780],256],12158:[[32786],256],12159:[[32819],256],12160:[[32895],256],12161:[[32905],256],12162:[[33251],256],12163:[[33258],256],12164:[[33267],256],12165:[[33276],256],12166:[[33292],256],12167:[[33307],256],12168:[[33311],256],12169:[[33390],256],12170:[[33394],256],12171:[[33400],256],12172:[[34381],256],12173:[[34411],256],12174:[[34880],256],12175:[[34892],256],12176:[[34915],256],12177:[[35198],256],12178:[[35211],256],12179:[[35282],256],12180:[[35328],256],12181:[[35895],256],12182:[[35910],256],12183:[[35925],256],12184:[[35960],256],12185:[[35997],256],12186:[[36196],256],12187:[[36208],256],12188:[[36275],256],12189:[[36523],256],12190:[[36554],256],12191:[[36763],256],12192:[[36784],256],12193:[[36789],256],12194:[[37009],256],12195:[[37193],256],12196:[[37318],256],12197:[[37324],256],12198:[[37329],256],12199:[[38263],256],12200:[[38272],256],12201:[[38428],256],12202:[[38582],256],12203:[[38585],256],12204:[[38632],256],12205:[[38737],256],12206:[[38750],256],12207:[[38754],256],12208:[[38761],256],12209:[[38859],256],12210:[[38893],256],12211:[[38899],256],12212:[[38913],256],12213:[[39080],256],12214:[[39131],256],12215:[[39135],256],12216:[[39318],256],12217:[[39321],256],12218:[[39340],256],12219:[[39592],256],12220:[[39640],256],12221:[[39647],256],12222:[[39717],256],12223:[[39727],256],12224:[[39730],256],12225:[[39740],256],12226:[[39770],256],12227:[[40165],256],12228:[[40565],256],12229:[[40575],256],12230:[[40613],256],12231:[[40635],256],12232:[[40643],256],12233:[[40653],256],12234:[[40657],256],12235:[[40697],256],12236:[[40701],256],12237:[[40718],256],12238:[[40723],256],12239:[[40736],256],12240:[[40763],256],12241:[[40778],256],12242:[[40786],256],12243:[[40845],256],12244:[[40860],256],12245:[[40864],256]}, + 12288:{12288:[[32],256],12330:[,218],12331:[,228],12332:[,232],12333:[,222],12334:[,224],12335:[,224],12342:[[12306],256],12344:[[21313],256],12345:[[21316],256],12346:[[21317],256],12358:[,,{12441:12436}],12363:[,,{12441:12364}],12364:[[12363,12441]],12365:[,,{12441:12366}],12366:[[12365,12441]],12367:[,,{12441:12368}],12368:[[12367,12441]],12369:[,,{12441:12370}],12370:[[12369,12441]],12371:[,,{12441:12372}],12372:[[12371,12441]],12373:[,,{12441:12374}],12374:[[12373,12441]],12375:[,,{12441:12376}],12376:[[12375,12441]],12377:[,,{12441:12378}],12378:[[12377,12441]],12379:[,,{12441:12380}],12380:[[12379,12441]],12381:[,,{12441:12382}],12382:[[12381,12441]],12383:[,,{12441:12384}],12384:[[12383,12441]],12385:[,,{12441:12386}],12386:[[12385,12441]],12388:[,,{12441:12389}],12389:[[12388,12441]],12390:[,,{12441:12391}],12391:[[12390,12441]],12392:[,,{12441:12393}],12393:[[12392,12441]],12399:[,,{12441:12400,12442:12401}],12400:[[12399,12441]],12401:[[12399,12442]],12402:[,,{12441:12403,12442:12404}],12403:[[12402,12441]],12404:[[12402,12442]],12405:[,,{12441:12406,12442:12407}],12406:[[12405,12441]],12407:[[12405,12442]],12408:[,,{12441:12409,12442:12410}],12409:[[12408,12441]],12410:[[12408,12442]],12411:[,,{12441:12412,12442:12413}],12412:[[12411,12441]],12413:[[12411,12442]],12436:[[12358,12441]],12441:[,8],12442:[,8],12443:[[32,12441],256],12444:[[32,12442],256],12445:[,,{12441:12446}],12446:[[12445,12441]],12447:[[12424,12426],256],12454:[,,{12441:12532}],12459:[,,{12441:12460}],12460:[[12459,12441]],12461:[,,{12441:12462}],12462:[[12461,12441]],12463:[,,{12441:12464}],12464:[[12463,12441]],12465:[,,{12441:12466}],12466:[[12465,12441]],12467:[,,{12441:12468}],12468:[[12467,12441]],12469:[,,{12441:12470}],12470:[[12469,12441]],12471:[,,{12441:12472}],12472:[[12471,12441]],12473:[,,{12441:12474}],12474:[[12473,12441]],12475:[,,{12441:12476}],12476:[[12475,12441]],12477:[,,{12441:12478}],12478:[[12477,12441]],12479:[,,{12441:12480}],12480:[[12479,12441]],12481:[,,{12441:12482}],12482:[[12481,12441]],12484:[,,{12441:12485}],12485:[[12484,12441]],12486:[,,{12441:12487}],12487:[[12486,12441]],12488:[,,{12441:12489}],12489:[[12488,12441]],12495:[,,{12441:12496,12442:12497}],12496:[[12495,12441]],12497:[[12495,12442]],12498:[,,{12441:12499,12442:12500}],12499:[[12498,12441]],12500:[[12498,12442]],12501:[,,{12441:12502,12442:12503}],12502:[[12501,12441]],12503:[[12501,12442]],12504:[,,{12441:12505,12442:12506}],12505:[[12504,12441]],12506:[[12504,12442]],12507:[,,{12441:12508,12442:12509}],12508:[[12507,12441]],12509:[[12507,12442]],12527:[,,{12441:12535}],12528:[,,{12441:12536}],12529:[,,{12441:12537}],12530:[,,{12441:12538}],12532:[[12454,12441]],12535:[[12527,12441]],12536:[[12528,12441]],12537:[[12529,12441]],12538:[[12530,12441]],12541:[,,{12441:12542}],12542:[[12541,12441]],12543:[[12467,12488],256]}, + 12544:{12593:[[4352],256],12594:[[4353],256],12595:[[4522],256],12596:[[4354],256],12597:[[4524],256],12598:[[4525],256],12599:[[4355],256],12600:[[4356],256],12601:[[4357],256],12602:[[4528],256],12603:[[4529],256],12604:[[4530],256],12605:[[4531],256],12606:[[4532],256],12607:[[4533],256],12608:[[4378],256],12609:[[4358],256],12610:[[4359],256],12611:[[4360],256],12612:[[4385],256],12613:[[4361],256],12614:[[4362],256],12615:[[4363],256],12616:[[4364],256],12617:[[4365],256],12618:[[4366],256],12619:[[4367],256],12620:[[4368],256],12621:[[4369],256],12622:[[4370],256],12623:[[4449],256],12624:[[4450],256],12625:[[4451],256],12626:[[4452],256],12627:[[4453],256],12628:[[4454],256],12629:[[4455],256],12630:[[4456],256],12631:[[4457],256],12632:[[4458],256],12633:[[4459],256],12634:[[4460],256],12635:[[4461],256],12636:[[4462],256],12637:[[4463],256],12638:[[4464],256],12639:[[4465],256],12640:[[4466],256],12641:[[4467],256],12642:[[4468],256],12643:[[4469],256],12644:[[4448],256],12645:[[4372],256],12646:[[4373],256],12647:[[4551],256],12648:[[4552],256],12649:[[4556],256],12650:[[4558],256],12651:[[4563],256],12652:[[4567],256],12653:[[4569],256],12654:[[4380],256],12655:[[4573],256],12656:[[4575],256],12657:[[4381],256],12658:[[4382],256],12659:[[4384],256],12660:[[4386],256],12661:[[4387],256],12662:[[4391],256],12663:[[4393],256],12664:[[4395],256],12665:[[4396],256],12666:[[4397],256],12667:[[4398],256],12668:[[4399],256],12669:[[4402],256],12670:[[4406],256],12671:[[4416],256],12672:[[4423],256],12673:[[4428],256],12674:[[4593],256],12675:[[4594],256],12676:[[4439],256],12677:[[4440],256],12678:[[4441],256],12679:[[4484],256],12680:[[4485],256],12681:[[4488],256],12682:[[4497],256],12683:[[4498],256],12684:[[4500],256],12685:[[4510],256],12686:[[4513],256],12690:[[19968],256],12691:[[20108],256],12692:[[19977],256],12693:[[22235],256],12694:[[19978],256],12695:[[20013],256],12696:[[19979],256],12697:[[30002],256],12698:[[20057],256],12699:[[19993],256],12700:[[19969],256],12701:[[22825],256],12702:[[22320],256],12703:[[20154],256]}, + 12800:{12800:[[40,4352,41],256],12801:[[40,4354,41],256],12802:[[40,4355,41],256],12803:[[40,4357,41],256],12804:[[40,4358,41],256],12805:[[40,4359,41],256],12806:[[40,4361,41],256],12807:[[40,4363,41],256],12808:[[40,4364,41],256],12809:[[40,4366,41],256],12810:[[40,4367,41],256],12811:[[40,4368,41],256],12812:[[40,4369,41],256],12813:[[40,4370,41],256],12814:[[40,4352,4449,41],256],12815:[[40,4354,4449,41],256],12816:[[40,4355,4449,41],256],12817:[[40,4357,4449,41],256],12818:[[40,4358,4449,41],256],12819:[[40,4359,4449,41],256],12820:[[40,4361,4449,41],256],12821:[[40,4363,4449,41],256],12822:[[40,4364,4449,41],256],12823:[[40,4366,4449,41],256],12824:[[40,4367,4449,41],256],12825:[[40,4368,4449,41],256],12826:[[40,4369,4449,41],256],12827:[[40,4370,4449,41],256],12828:[[40,4364,4462,41],256],12829:[[40,4363,4457,4364,4453,4523,41],256],12830:[[40,4363,4457,4370,4462,41],256],12832:[[40,19968,41],256],12833:[[40,20108,41],256],12834:[[40,19977,41],256],12835:[[40,22235,41],256],12836:[[40,20116,41],256],12837:[[40,20845,41],256],12838:[[40,19971,41],256],12839:[[40,20843,41],256],12840:[[40,20061,41],256],12841:[[40,21313,41],256],12842:[[40,26376,41],256],12843:[[40,28779,41],256],12844:[[40,27700,41],256],12845:[[40,26408,41],256],12846:[[40,37329,41],256],12847:[[40,22303,41],256],12848:[[40,26085,41],256],12849:[[40,26666,41],256],12850:[[40,26377,41],256],12851:[[40,31038,41],256],12852:[[40,21517,41],256],12853:[[40,29305,41],256],12854:[[40,36001,41],256],12855:[[40,31069,41],256],12856:[[40,21172,41],256],12857:[[40,20195,41],256],12858:[[40,21628,41],256],12859:[[40,23398,41],256],12860:[[40,30435,41],256],12861:[[40,20225,41],256],12862:[[40,36039,41],256],12863:[[40,21332,41],256],12864:[[40,31085,41],256],12865:[[40,20241,41],256],12866:[[40,33258,41],256],12867:[[40,33267,41],256],12868:[[21839],256],12869:[[24188],256],12870:[[25991],256],12871:[[31631],256],12880:[[80,84,69],256],12881:[[50,49],256],12882:[[50,50],256],12883:[[50,51],256],12884:[[50,52],256],12885:[[50,53],256],12886:[[50,54],256],12887:[[50,55],256],12888:[[50,56],256],12889:[[50,57],256],12890:[[51,48],256],12891:[[51,49],256],12892:[[51,50],256],12893:[[51,51],256],12894:[[51,52],256],12895:[[51,53],256],12896:[[4352],256],12897:[[4354],256],12898:[[4355],256],12899:[[4357],256],12900:[[4358],256],12901:[[4359],256],12902:[[4361],256],12903:[[4363],256],12904:[[4364],256],12905:[[4366],256],12906:[[4367],256],12907:[[4368],256],12908:[[4369],256],12909:[[4370],256],12910:[[4352,4449],256],12911:[[4354,4449],256],12912:[[4355,4449],256],12913:[[4357,4449],256],12914:[[4358,4449],256],12915:[[4359,4449],256],12916:[[4361,4449],256],12917:[[4363,4449],256],12918:[[4364,4449],256],12919:[[4366,4449],256],12920:[[4367,4449],256],12921:[[4368,4449],256],12922:[[4369,4449],256],12923:[[4370,4449],256],12924:[[4366,4449,4535,4352,4457],256],12925:[[4364,4462,4363,4468],256],12926:[[4363,4462],256],12928:[[19968],256],12929:[[20108],256],12930:[[19977],256],12931:[[22235],256],12932:[[20116],256],12933:[[20845],256],12934:[[19971],256],12935:[[20843],256],12936:[[20061],256],12937:[[21313],256],12938:[[26376],256],12939:[[28779],256],12940:[[27700],256],12941:[[26408],256],12942:[[37329],256],12943:[[22303],256],12944:[[26085],256],12945:[[26666],256],12946:[[26377],256],12947:[[31038],256],12948:[[21517],256],12949:[[29305],256],12950:[[36001],256],12951:[[31069],256],12952:[[21172],256],12953:[[31192],256],12954:[[30007],256],12955:[[22899],256],12956:[[36969],256],12957:[[20778],256],12958:[[21360],256],12959:[[27880],256],12960:[[38917],256],12961:[[20241],256],12962:[[20889],256],12963:[[27491],256],12964:[[19978],256],12965:[[20013],256],12966:[[19979],256],12967:[[24038],256],12968:[[21491],256],12969:[[21307],256],12970:[[23447],256],12971:[[23398],256],12972:[[30435],256],12973:[[20225],256],12974:[[36039],256],12975:[[21332],256],12976:[[22812],256],12977:[[51,54],256],12978:[[51,55],256],12979:[[51,56],256],12980:[[51,57],256],12981:[[52,48],256],12982:[[52,49],256],12983:[[52,50],256],12984:[[52,51],256],12985:[[52,52],256],12986:[[52,53],256],12987:[[52,54],256],12988:[[52,55],256],12989:[[52,56],256],12990:[[52,57],256],12991:[[53,48],256],12992:[[49,26376],256],12993:[[50,26376],256],12994:[[51,26376],256],12995:[[52,26376],256],12996:[[53,26376],256],12997:[[54,26376],256],12998:[[55,26376],256],12999:[[56,26376],256],13000:[[57,26376],256],13001:[[49,48,26376],256],13002:[[49,49,26376],256],13003:[[49,50,26376],256],13004:[[72,103],256],13005:[[101,114,103],256],13006:[[101,86],256],13007:[[76,84,68],256],13008:[[12450],256],13009:[[12452],256],13010:[[12454],256],13011:[[12456],256],13012:[[12458],256],13013:[[12459],256],13014:[[12461],256],13015:[[12463],256],13016:[[12465],256],13017:[[12467],256],13018:[[12469],256],13019:[[12471],256],13020:[[12473],256],13021:[[12475],256],13022:[[12477],256],13023:[[12479],256],13024:[[12481],256],13025:[[12484],256],13026:[[12486],256],13027:[[12488],256],13028:[[12490],256],13029:[[12491],256],13030:[[12492],256],13031:[[12493],256],13032:[[12494],256],13033:[[12495],256],13034:[[12498],256],13035:[[12501],256],13036:[[12504],256],13037:[[12507],256],13038:[[12510],256],13039:[[12511],256],13040:[[12512],256],13041:[[12513],256],13042:[[12514],256],13043:[[12516],256],13044:[[12518],256],13045:[[12520],256],13046:[[12521],256],13047:[[12522],256],13048:[[12523],256],13049:[[12524],256],13050:[[12525],256],13051:[[12527],256],13052:[[12528],256],13053:[[12529],256],13054:[[12530],256]}, + 13056:{13056:[[12450,12497,12540,12488],256],13057:[[12450,12523,12501,12449],256],13058:[[12450,12531,12506,12450],256],13059:[[12450,12540,12523],256],13060:[[12452,12491,12531,12464],256],13061:[[12452,12531,12481],256],13062:[[12454,12457,12531],256],13063:[[12456,12473,12463,12540,12489],256],13064:[[12456,12540,12459,12540],256],13065:[[12458,12531,12473],256],13066:[[12458,12540,12512],256],13067:[[12459,12452,12522],256],13068:[[12459,12521,12483,12488],256],13069:[[12459,12525,12522,12540],256],13070:[[12460,12525,12531],256],13071:[[12460,12531,12510],256],13072:[[12462,12460],256],13073:[[12462,12491,12540],256],13074:[[12461,12517,12522,12540],256],13075:[[12462,12523,12480,12540],256],13076:[[12461,12525],256],13077:[[12461,12525,12464,12521,12512],256],13078:[[12461,12525,12513,12540,12488,12523],256],13079:[[12461,12525,12527,12483,12488],256],13080:[[12464,12521,12512],256],13081:[[12464,12521,12512,12488,12531],256],13082:[[12463,12523,12476,12452,12525],256],13083:[[12463,12525,12540,12493],256],13084:[[12465,12540,12473],256],13085:[[12467,12523,12490],256],13086:[[12467,12540,12509],256],13087:[[12469,12452,12463,12523],256],13088:[[12469,12531,12481,12540,12512],256],13089:[[12471,12522,12531,12464],256],13090:[[12475,12531,12481],256],13091:[[12475,12531,12488],256],13092:[[12480,12540,12473],256],13093:[[12487,12471],256],13094:[[12489,12523],256],13095:[[12488,12531],256],13096:[[12490,12494],256],13097:[[12494,12483,12488],256],13098:[[12495,12452,12484],256],13099:[[12497,12540,12475,12531,12488],256],13100:[[12497,12540,12484],256],13101:[[12496,12540,12524,12523],256],13102:[[12500,12450,12473,12488,12523],256],13103:[[12500,12463,12523],256],13104:[[12500,12467],256],13105:[[12499,12523],256],13106:[[12501,12449,12521,12483,12489],256],13107:[[12501,12451,12540,12488],256],13108:[[12502,12483,12471,12455,12523],256],13109:[[12501,12521,12531],256],13110:[[12504,12463,12479,12540,12523],256],13111:[[12506,12477],256],13112:[[12506,12491,12498],256],13113:[[12504,12523,12484],256],13114:[[12506,12531,12473],256],13115:[[12506,12540,12472],256],13116:[[12505,12540,12479],256],13117:[[12509,12452,12531,12488],256],13118:[[12508,12523,12488],256],13119:[[12507,12531],256],13120:[[12509,12531,12489],256],13121:[[12507,12540,12523],256],13122:[[12507,12540,12531],256],13123:[[12510,12452,12463,12525],256],13124:[[12510,12452,12523],256],13125:[[12510,12483,12495],256],13126:[[12510,12523,12463],256],13127:[[12510,12531,12471,12519,12531],256],13128:[[12511,12463,12525,12531],256],13129:[[12511,12522],256],13130:[[12511,12522,12496,12540,12523],256],13131:[[12513,12460],256],13132:[[12513,12460,12488,12531],256],13133:[[12513,12540,12488,12523],256],13134:[[12516,12540,12489],256],13135:[[12516,12540,12523],256],13136:[[12518,12450,12531],256],13137:[[12522,12483,12488,12523],256],13138:[[12522,12521],256],13139:[[12523,12500,12540],256],13140:[[12523,12540,12502,12523],256],13141:[[12524,12512],256],13142:[[12524,12531,12488,12466,12531],256],13143:[[12527,12483,12488],256],13144:[[48,28857],256],13145:[[49,28857],256],13146:[[50,28857],256],13147:[[51,28857],256],13148:[[52,28857],256],13149:[[53,28857],256],13150:[[54,28857],256],13151:[[55,28857],256],13152:[[56,28857],256],13153:[[57,28857],256],13154:[[49,48,28857],256],13155:[[49,49,28857],256],13156:[[49,50,28857],256],13157:[[49,51,28857],256],13158:[[49,52,28857],256],13159:[[49,53,28857],256],13160:[[49,54,28857],256],13161:[[49,55,28857],256],13162:[[49,56,28857],256],13163:[[49,57,28857],256],13164:[[50,48,28857],256],13165:[[50,49,28857],256],13166:[[50,50,28857],256],13167:[[50,51,28857],256],13168:[[50,52,28857],256],13169:[[104,80,97],256],13170:[[100,97],256],13171:[[65,85],256],13172:[[98,97,114],256],13173:[[111,86],256],13174:[[112,99],256],13175:[[100,109],256],13176:[[100,109,178],256],13177:[[100,109,179],256],13178:[[73,85],256],13179:[[24179,25104],256],13180:[[26157,21644],256],13181:[[22823,27491],256],13182:[[26126,27835],256],13183:[[26666,24335,20250,31038],256],13184:[[112,65],256],13185:[[110,65],256],13186:[[956,65],256],13187:[[109,65],256],13188:[[107,65],256],13189:[[75,66],256],13190:[[77,66],256],13191:[[71,66],256],13192:[[99,97,108],256],13193:[[107,99,97,108],256],13194:[[112,70],256],13195:[[110,70],256],13196:[[956,70],256],13197:[[956,103],256],13198:[[109,103],256],13199:[[107,103],256],13200:[[72,122],256],13201:[[107,72,122],256],13202:[[77,72,122],256],13203:[[71,72,122],256],13204:[[84,72,122],256],13205:[[956,8467],256],13206:[[109,8467],256],13207:[[100,8467],256],13208:[[107,8467],256],13209:[[102,109],256],13210:[[110,109],256],13211:[[956,109],256],13212:[[109,109],256],13213:[[99,109],256],13214:[[107,109],256],13215:[[109,109,178],256],13216:[[99,109,178],256],13217:[[109,178],256],13218:[[107,109,178],256],13219:[[109,109,179],256],13220:[[99,109,179],256],13221:[[109,179],256],13222:[[107,109,179],256],13223:[[109,8725,115],256],13224:[[109,8725,115,178],256],13225:[[80,97],256],13226:[[107,80,97],256],13227:[[77,80,97],256],13228:[[71,80,97],256],13229:[[114,97,100],256],13230:[[114,97,100,8725,115],256],13231:[[114,97,100,8725,115,178],256],13232:[[112,115],256],13233:[[110,115],256],13234:[[956,115],256],13235:[[109,115],256],13236:[[112,86],256],13237:[[110,86],256],13238:[[956,86],256],13239:[[109,86],256],13240:[[107,86],256],13241:[[77,86],256],13242:[[112,87],256],13243:[[110,87],256],13244:[[956,87],256],13245:[[109,87],256],13246:[[107,87],256],13247:[[77,87],256],13248:[[107,937],256],13249:[[77,937],256],13250:[[97,46,109,46],256],13251:[[66,113],256],13252:[[99,99],256],13253:[[99,100],256],13254:[[67,8725,107,103],256],13255:[[67,111,46],256],13256:[[100,66],256],13257:[[71,121],256],13258:[[104,97],256],13259:[[72,80],256],13260:[[105,110],256],13261:[[75,75],256],13262:[[75,77],256],13263:[[107,116],256],13264:[[108,109],256],13265:[[108,110],256],13266:[[108,111,103],256],13267:[[108,120],256],13268:[[109,98],256],13269:[[109,105,108],256],13270:[[109,111,108],256],13271:[[80,72],256],13272:[[112,46,109,46],256],13273:[[80,80,77],256],13274:[[80,82],256],13275:[[115,114],256],13276:[[83,118],256],13277:[[87,98],256],13278:[[86,8725,109],256],13279:[[65,8725,109],256],13280:[[49,26085],256],13281:[[50,26085],256],13282:[[51,26085],256],13283:[[52,26085],256],13284:[[53,26085],256],13285:[[54,26085],256],13286:[[55,26085],256],13287:[[56,26085],256],13288:[[57,26085],256],13289:[[49,48,26085],256],13290:[[49,49,26085],256],13291:[[49,50,26085],256],13292:[[49,51,26085],256],13293:[[49,52,26085],256],13294:[[49,53,26085],256],13295:[[49,54,26085],256],13296:[[49,55,26085],256],13297:[[49,56,26085],256],13298:[[49,57,26085],256],13299:[[50,48,26085],256],13300:[[50,49,26085],256],13301:[[50,50,26085],256],13302:[[50,51,26085],256],13303:[[50,52,26085],256],13304:[[50,53,26085],256],13305:[[50,54,26085],256],13306:[[50,55,26085],256],13307:[[50,56,26085],256],13308:[[50,57,26085],256],13309:[[51,48,26085],256],13310:[[51,49,26085],256],13311:[[103,97,108],256]}, + 42496:{42607:[,230],42612:[,230],42613:[,230],42614:[,230],42615:[,230],42616:[,230],42617:[,230],42618:[,230],42619:[,230],42620:[,230],42621:[,230],42655:[,230],42736:[,230],42737:[,230]}, + 42752:{42864:[[42863],256],43000:[[294],256],43001:[[339],256]}, + 43008:{43014:[,9],43204:[,9],43232:[,230],43233:[,230],43234:[,230],43235:[,230],43236:[,230],43237:[,230],43238:[,230],43239:[,230],43240:[,230],43241:[,230],43242:[,230],43243:[,230],43244:[,230],43245:[,230],43246:[,230],43247:[,230],43248:[,230],43249:[,230]}, + 43264:{43307:[,220],43308:[,220],43309:[,220],43347:[,9],43443:[,7],43456:[,9]}, + 43520:{43696:[,230],43698:[,230],43699:[,230],43700:[,220],43703:[,230],43704:[,230],43710:[,230],43711:[,230],43713:[,230],43766:[,9]}, + 43776:{44013:[,9]}, + 53504:{119134:[[119127,119141],512],119135:[[119128,119141],512],119136:[[119135,119150],512],119137:[[119135,119151],512],119138:[[119135,119152],512],119139:[[119135,119153],512],119140:[[119135,119154],512],119141:[,216],119142:[,216],119143:[,1],119144:[,1],119145:[,1],119149:[,226],119150:[,216],119151:[,216],119152:[,216],119153:[,216],119154:[,216],119163:[,220],119164:[,220],119165:[,220],119166:[,220],119167:[,220],119168:[,220],119169:[,220],119170:[,220],119173:[,230],119174:[,230],119175:[,230],119176:[,230],119177:[,230],119178:[,220],119179:[,220],119210:[,230],119211:[,230],119212:[,230],119213:[,230],119227:[[119225,119141],512],119228:[[119226,119141],512],119229:[[119227,119150],512],119230:[[119228,119150],512],119231:[[119227,119151],512],119232:[[119228,119151],512]}, + 53760:{119362:[,230],119363:[,230],119364:[,230]}, + 54272:{119808:[[65],256],119809:[[66],256],119810:[[67],256],119811:[[68],256],119812:[[69],256],119813:[[70],256],119814:[[71],256],119815:[[72],256],119816:[[73],256],119817:[[74],256],119818:[[75],256],119819:[[76],256],119820:[[77],256],119821:[[78],256],119822:[[79],256],119823:[[80],256],119824:[[81],256],119825:[[82],256],119826:[[83],256],119827:[[84],256],119828:[[85],256],119829:[[86],256],119830:[[87],256],119831:[[88],256],119832:[[89],256],119833:[[90],256],119834:[[97],256],119835:[[98],256],119836:[[99],256],119837:[[100],256],119838:[[101],256],119839:[[102],256],119840:[[103],256],119841:[[104],256],119842:[[105],256],119843:[[106],256],119844:[[107],256],119845:[[108],256],119846:[[109],256],119847:[[110],256],119848:[[111],256],119849:[[112],256],119850:[[113],256],119851:[[114],256],119852:[[115],256],119853:[[116],256],119854:[[117],256],119855:[[118],256],119856:[[119],256],119857:[[120],256],119858:[[121],256],119859:[[122],256],119860:[[65],256],119861:[[66],256],119862:[[67],256],119863:[[68],256],119864:[[69],256],119865:[[70],256],119866:[[71],256],119867:[[72],256],119868:[[73],256],119869:[[74],256],119870:[[75],256],119871:[[76],256],119872:[[77],256],119873:[[78],256],119874:[[79],256],119875:[[80],256],119876:[[81],256],119877:[[82],256],119878:[[83],256],119879:[[84],256],119880:[[85],256],119881:[[86],256],119882:[[87],256],119883:[[88],256],119884:[[89],256],119885:[[90],256],119886:[[97],256],119887:[[98],256],119888:[[99],256],119889:[[100],256],119890:[[101],256],119891:[[102],256],119892:[[103],256],119894:[[105],256],119895:[[106],256],119896:[[107],256],119897:[[108],256],119898:[[109],256],119899:[[110],256],119900:[[111],256],119901:[[112],256],119902:[[113],256],119903:[[114],256],119904:[[115],256],119905:[[116],256],119906:[[117],256],119907:[[118],256],119908:[[119],256],119909:[[120],256],119910:[[121],256],119911:[[122],256],119912:[[65],256],119913:[[66],256],119914:[[67],256],119915:[[68],256],119916:[[69],256],119917:[[70],256],119918:[[71],256],119919:[[72],256],119920:[[73],256],119921:[[74],256],119922:[[75],256],119923:[[76],256],119924:[[77],256],119925:[[78],256],119926:[[79],256],119927:[[80],256],119928:[[81],256],119929:[[82],256],119930:[[83],256],119931:[[84],256],119932:[[85],256],119933:[[86],256],119934:[[87],256],119935:[[88],256],119936:[[89],256],119937:[[90],256],119938:[[97],256],119939:[[98],256],119940:[[99],256],119941:[[100],256],119942:[[101],256],119943:[[102],256],119944:[[103],256],119945:[[104],256],119946:[[105],256],119947:[[106],256],119948:[[107],256],119949:[[108],256],119950:[[109],256],119951:[[110],256],119952:[[111],256],119953:[[112],256],119954:[[113],256],119955:[[114],256],119956:[[115],256],119957:[[116],256],119958:[[117],256],119959:[[118],256],119960:[[119],256],119961:[[120],256],119962:[[121],256],119963:[[122],256],119964:[[65],256],119966:[[67],256],119967:[[68],256],119970:[[71],256],119973:[[74],256],119974:[[75],256],119977:[[78],256],119978:[[79],256],119979:[[80],256],119980:[[81],256],119982:[[83],256],119983:[[84],256],119984:[[85],256],119985:[[86],256],119986:[[87],256],119987:[[88],256],119988:[[89],256],119989:[[90],256],119990:[[97],256],119991:[[98],256],119992:[[99],256],119993:[[100],256],119995:[[102],256],119997:[[104],256],119998:[[105],256],119999:[[106],256],120000:[[107],256],120001:[[108],256],120002:[[109],256],120003:[[110],256],120005:[[112],256],120006:[[113],256],120007:[[114],256],120008:[[115],256],120009:[[116],256],120010:[[117],256],120011:[[118],256],120012:[[119],256],120013:[[120],256],120014:[[121],256],120015:[[122],256],120016:[[65],256],120017:[[66],256],120018:[[67],256],120019:[[68],256],120020:[[69],256],120021:[[70],256],120022:[[71],256],120023:[[72],256],120024:[[73],256],120025:[[74],256],120026:[[75],256],120027:[[76],256],120028:[[77],256],120029:[[78],256],120030:[[79],256],120031:[[80],256],120032:[[81],256],120033:[[82],256],120034:[[83],256],120035:[[84],256],120036:[[85],256],120037:[[86],256],120038:[[87],256],120039:[[88],256],120040:[[89],256],120041:[[90],256],120042:[[97],256],120043:[[98],256],120044:[[99],256],120045:[[100],256],120046:[[101],256],120047:[[102],256],120048:[[103],256],120049:[[104],256],120050:[[105],256],120051:[[106],256],120052:[[107],256],120053:[[108],256],120054:[[109],256],120055:[[110],256],120056:[[111],256],120057:[[112],256],120058:[[113],256],120059:[[114],256],120060:[[115],256],120061:[[116],256],120062:[[117],256],120063:[[118],256]}, + 54528:{120064:[[119],256],120065:[[120],256],120066:[[121],256],120067:[[122],256],120068:[[65],256],120069:[[66],256],120071:[[68],256],120072:[[69],256],120073:[[70],256],120074:[[71],256],120077:[[74],256],120078:[[75],256],120079:[[76],256],120080:[[77],256],120081:[[78],256],120082:[[79],256],120083:[[80],256],120084:[[81],256],120086:[[83],256],120087:[[84],256],120088:[[85],256],120089:[[86],256],120090:[[87],256],120091:[[88],256],120092:[[89],256],120094:[[97],256],120095:[[98],256],120096:[[99],256],120097:[[100],256],120098:[[101],256],120099:[[102],256],120100:[[103],256],120101:[[104],256],120102:[[105],256],120103:[[106],256],120104:[[107],256],120105:[[108],256],120106:[[109],256],120107:[[110],256],120108:[[111],256],120109:[[112],256],120110:[[113],256],120111:[[114],256],120112:[[115],256],120113:[[116],256],120114:[[117],256],120115:[[118],256],120116:[[119],256],120117:[[120],256],120118:[[121],256],120119:[[122],256],120120:[[65],256],120121:[[66],256],120123:[[68],256],120124:[[69],256],120125:[[70],256],120126:[[71],256],120128:[[73],256],120129:[[74],256],120130:[[75],256],120131:[[76],256],120132:[[77],256],120134:[[79],256],120138:[[83],256],120139:[[84],256],120140:[[85],256],120141:[[86],256],120142:[[87],256],120143:[[88],256],120144:[[89],256],120146:[[97],256],120147:[[98],256],120148:[[99],256],120149:[[100],256],120150:[[101],256],120151:[[102],256],120152:[[103],256],120153:[[104],256],120154:[[105],256],120155:[[106],256],120156:[[107],256],120157:[[108],256],120158:[[109],256],120159:[[110],256],120160:[[111],256],120161:[[112],256],120162:[[113],256],120163:[[114],256],120164:[[115],256],120165:[[116],256],120166:[[117],256],120167:[[118],256],120168:[[119],256],120169:[[120],256],120170:[[121],256],120171:[[122],256],120172:[[65],256],120173:[[66],256],120174:[[67],256],120175:[[68],256],120176:[[69],256],120177:[[70],256],120178:[[71],256],120179:[[72],256],120180:[[73],256],120181:[[74],256],120182:[[75],256],120183:[[76],256],120184:[[77],256],120185:[[78],256],120186:[[79],256],120187:[[80],256],120188:[[81],256],120189:[[82],256],120190:[[83],256],120191:[[84],256],120192:[[85],256],120193:[[86],256],120194:[[87],256],120195:[[88],256],120196:[[89],256],120197:[[90],256],120198:[[97],256],120199:[[98],256],120200:[[99],256],120201:[[100],256],120202:[[101],256],120203:[[102],256],120204:[[103],256],120205:[[104],256],120206:[[105],256],120207:[[106],256],120208:[[107],256],120209:[[108],256],120210:[[109],256],120211:[[110],256],120212:[[111],256],120213:[[112],256],120214:[[113],256],120215:[[114],256],120216:[[115],256],120217:[[116],256],120218:[[117],256],120219:[[118],256],120220:[[119],256],120221:[[120],256],120222:[[121],256],120223:[[122],256],120224:[[65],256],120225:[[66],256],120226:[[67],256],120227:[[68],256],120228:[[69],256],120229:[[70],256],120230:[[71],256],120231:[[72],256],120232:[[73],256],120233:[[74],256],120234:[[75],256],120235:[[76],256],120236:[[77],256],120237:[[78],256],120238:[[79],256],120239:[[80],256],120240:[[81],256],120241:[[82],256],120242:[[83],256],120243:[[84],256],120244:[[85],256],120245:[[86],256],120246:[[87],256],120247:[[88],256],120248:[[89],256],120249:[[90],256],120250:[[97],256],120251:[[98],256],120252:[[99],256],120253:[[100],256],120254:[[101],256],120255:[[102],256],120256:[[103],256],120257:[[104],256],120258:[[105],256],120259:[[106],256],120260:[[107],256],120261:[[108],256],120262:[[109],256],120263:[[110],256],120264:[[111],256],120265:[[112],256],120266:[[113],256],120267:[[114],256],120268:[[115],256],120269:[[116],256],120270:[[117],256],120271:[[118],256],120272:[[119],256],120273:[[120],256],120274:[[121],256],120275:[[122],256],120276:[[65],256],120277:[[66],256],120278:[[67],256],120279:[[68],256],120280:[[69],256],120281:[[70],256],120282:[[71],256],120283:[[72],256],120284:[[73],256],120285:[[74],256],120286:[[75],256],120287:[[76],256],120288:[[77],256],120289:[[78],256],120290:[[79],256],120291:[[80],256],120292:[[81],256],120293:[[82],256],120294:[[83],256],120295:[[84],256],120296:[[85],256],120297:[[86],256],120298:[[87],256],120299:[[88],256],120300:[[89],256],120301:[[90],256],120302:[[97],256],120303:[[98],256],120304:[[99],256],120305:[[100],256],120306:[[101],256],120307:[[102],256],120308:[[103],256],120309:[[104],256],120310:[[105],256],120311:[[106],256],120312:[[107],256],120313:[[108],256],120314:[[109],256],120315:[[110],256],120316:[[111],256],120317:[[112],256],120318:[[113],256],120319:[[114],256]}, + 54784:{120320:[[115],256],120321:[[116],256],120322:[[117],256],120323:[[118],256],120324:[[119],256],120325:[[120],256],120326:[[121],256],120327:[[122],256],120328:[[65],256],120329:[[66],256],120330:[[67],256],120331:[[68],256],120332:[[69],256],120333:[[70],256],120334:[[71],256],120335:[[72],256],120336:[[73],256],120337:[[74],256],120338:[[75],256],120339:[[76],256],120340:[[77],256],120341:[[78],256],120342:[[79],256],120343:[[80],256],120344:[[81],256],120345:[[82],256],120346:[[83],256],120347:[[84],256],120348:[[85],256],120349:[[86],256],120350:[[87],256],120351:[[88],256],120352:[[89],256],120353:[[90],256],120354:[[97],256],120355:[[98],256],120356:[[99],256],120357:[[100],256],120358:[[101],256],120359:[[102],256],120360:[[103],256],120361:[[104],256],120362:[[105],256],120363:[[106],256],120364:[[107],256],120365:[[108],256],120366:[[109],256],120367:[[110],256],120368:[[111],256],120369:[[112],256],120370:[[113],256],120371:[[114],256],120372:[[115],256],120373:[[116],256],120374:[[117],256],120375:[[118],256],120376:[[119],256],120377:[[120],256],120378:[[121],256],120379:[[122],256],120380:[[65],256],120381:[[66],256],120382:[[67],256],120383:[[68],256],120384:[[69],256],120385:[[70],256],120386:[[71],256],120387:[[72],256],120388:[[73],256],120389:[[74],256],120390:[[75],256],120391:[[76],256],120392:[[77],256],120393:[[78],256],120394:[[79],256],120395:[[80],256],120396:[[81],256],120397:[[82],256],120398:[[83],256],120399:[[84],256],120400:[[85],256],120401:[[86],256],120402:[[87],256],120403:[[88],256],120404:[[89],256],120405:[[90],256],120406:[[97],256],120407:[[98],256],120408:[[99],256],120409:[[100],256],120410:[[101],256],120411:[[102],256],120412:[[103],256],120413:[[104],256],120414:[[105],256],120415:[[106],256],120416:[[107],256],120417:[[108],256],120418:[[109],256],120419:[[110],256],120420:[[111],256],120421:[[112],256],120422:[[113],256],120423:[[114],256],120424:[[115],256],120425:[[116],256],120426:[[117],256],120427:[[118],256],120428:[[119],256],120429:[[120],256],120430:[[121],256],120431:[[122],256],120432:[[65],256],120433:[[66],256],120434:[[67],256],120435:[[68],256],120436:[[69],256],120437:[[70],256],120438:[[71],256],120439:[[72],256],120440:[[73],256],120441:[[74],256],120442:[[75],256],120443:[[76],256],120444:[[77],256],120445:[[78],256],120446:[[79],256],120447:[[80],256],120448:[[81],256],120449:[[82],256],120450:[[83],256],120451:[[84],256],120452:[[85],256],120453:[[86],256],120454:[[87],256],120455:[[88],256],120456:[[89],256],120457:[[90],256],120458:[[97],256],120459:[[98],256],120460:[[99],256],120461:[[100],256],120462:[[101],256],120463:[[102],256],120464:[[103],256],120465:[[104],256],120466:[[105],256],120467:[[106],256],120468:[[107],256],120469:[[108],256],120470:[[109],256],120471:[[110],256],120472:[[111],256],120473:[[112],256],120474:[[113],256],120475:[[114],256],120476:[[115],256],120477:[[116],256],120478:[[117],256],120479:[[118],256],120480:[[119],256],120481:[[120],256],120482:[[121],256],120483:[[122],256],120484:[[305],256],120485:[[567],256],120488:[[913],256],120489:[[914],256],120490:[[915],256],120491:[[916],256],120492:[[917],256],120493:[[918],256],120494:[[919],256],120495:[[920],256],120496:[[921],256],120497:[[922],256],120498:[[923],256],120499:[[924],256],120500:[[925],256],120501:[[926],256],120502:[[927],256],120503:[[928],256],120504:[[929],256],120505:[[1012],256],120506:[[931],256],120507:[[932],256],120508:[[933],256],120509:[[934],256],120510:[[935],256],120511:[[936],256],120512:[[937],256],120513:[[8711],256],120514:[[945],256],120515:[[946],256],120516:[[947],256],120517:[[948],256],120518:[[949],256],120519:[[950],256],120520:[[951],256],120521:[[952],256],120522:[[953],256],120523:[[954],256],120524:[[955],256],120525:[[956],256],120526:[[957],256],120527:[[958],256],120528:[[959],256],120529:[[960],256],120530:[[961],256],120531:[[962],256],120532:[[963],256],120533:[[964],256],120534:[[965],256],120535:[[966],256],120536:[[967],256],120537:[[968],256],120538:[[969],256],120539:[[8706],256],120540:[[1013],256],120541:[[977],256],120542:[[1008],256],120543:[[981],256],120544:[[1009],256],120545:[[982],256],120546:[[913],256],120547:[[914],256],120548:[[915],256],120549:[[916],256],120550:[[917],256],120551:[[918],256],120552:[[919],256],120553:[[920],256],120554:[[921],256],120555:[[922],256],120556:[[923],256],120557:[[924],256],120558:[[925],256],120559:[[926],256],120560:[[927],256],120561:[[928],256],120562:[[929],256],120563:[[1012],256],120564:[[931],256],120565:[[932],256],120566:[[933],256],120567:[[934],256],120568:[[935],256],120569:[[936],256],120570:[[937],256],120571:[[8711],256],120572:[[945],256],120573:[[946],256],120574:[[947],256],120575:[[948],256]}, + 55040:{120576:[[949],256],120577:[[950],256],120578:[[951],256],120579:[[952],256],120580:[[953],256],120581:[[954],256],120582:[[955],256],120583:[[956],256],120584:[[957],256],120585:[[958],256],120586:[[959],256],120587:[[960],256],120588:[[961],256],120589:[[962],256],120590:[[963],256],120591:[[964],256],120592:[[965],256],120593:[[966],256],120594:[[967],256],120595:[[968],256],120596:[[969],256],120597:[[8706],256],120598:[[1013],256],120599:[[977],256],120600:[[1008],256],120601:[[981],256],120602:[[1009],256],120603:[[982],256],120604:[[913],256],120605:[[914],256],120606:[[915],256],120607:[[916],256],120608:[[917],256],120609:[[918],256],120610:[[919],256],120611:[[920],256],120612:[[921],256],120613:[[922],256],120614:[[923],256],120615:[[924],256],120616:[[925],256],120617:[[926],256],120618:[[927],256],120619:[[928],256],120620:[[929],256],120621:[[1012],256],120622:[[931],256],120623:[[932],256],120624:[[933],256],120625:[[934],256],120626:[[935],256],120627:[[936],256],120628:[[937],256],120629:[[8711],256],120630:[[945],256],120631:[[946],256],120632:[[947],256],120633:[[948],256],120634:[[949],256],120635:[[950],256],120636:[[951],256],120637:[[952],256],120638:[[953],256],120639:[[954],256],120640:[[955],256],120641:[[956],256],120642:[[957],256],120643:[[958],256],120644:[[959],256],120645:[[960],256],120646:[[961],256],120647:[[962],256],120648:[[963],256],120649:[[964],256],120650:[[965],256],120651:[[966],256],120652:[[967],256],120653:[[968],256],120654:[[969],256],120655:[[8706],256],120656:[[1013],256],120657:[[977],256],120658:[[1008],256],120659:[[981],256],120660:[[1009],256],120661:[[982],256],120662:[[913],256],120663:[[914],256],120664:[[915],256],120665:[[916],256],120666:[[917],256],120667:[[918],256],120668:[[919],256],120669:[[920],256],120670:[[921],256],120671:[[922],256],120672:[[923],256],120673:[[924],256],120674:[[925],256],120675:[[926],256],120676:[[927],256],120677:[[928],256],120678:[[929],256],120679:[[1012],256],120680:[[931],256],120681:[[932],256],120682:[[933],256],120683:[[934],256],120684:[[935],256],120685:[[936],256],120686:[[937],256],120687:[[8711],256],120688:[[945],256],120689:[[946],256],120690:[[947],256],120691:[[948],256],120692:[[949],256],120693:[[950],256],120694:[[951],256],120695:[[952],256],120696:[[953],256],120697:[[954],256],120698:[[955],256],120699:[[956],256],120700:[[957],256],120701:[[958],256],120702:[[959],256],120703:[[960],256],120704:[[961],256],120705:[[962],256],120706:[[963],256],120707:[[964],256],120708:[[965],256],120709:[[966],256],120710:[[967],256],120711:[[968],256],120712:[[969],256],120713:[[8706],256],120714:[[1013],256],120715:[[977],256],120716:[[1008],256],120717:[[981],256],120718:[[1009],256],120719:[[982],256],120720:[[913],256],120721:[[914],256],120722:[[915],256],120723:[[916],256],120724:[[917],256],120725:[[918],256],120726:[[919],256],120727:[[920],256],120728:[[921],256],120729:[[922],256],120730:[[923],256],120731:[[924],256],120732:[[925],256],120733:[[926],256],120734:[[927],256],120735:[[928],256],120736:[[929],256],120737:[[1012],256],120738:[[931],256],120739:[[932],256],120740:[[933],256],120741:[[934],256],120742:[[935],256],120743:[[936],256],120744:[[937],256],120745:[[8711],256],120746:[[945],256],120747:[[946],256],120748:[[947],256],120749:[[948],256],120750:[[949],256],120751:[[950],256],120752:[[951],256],120753:[[952],256],120754:[[953],256],120755:[[954],256],120756:[[955],256],120757:[[956],256],120758:[[957],256],120759:[[958],256],120760:[[959],256],120761:[[960],256],120762:[[961],256],120763:[[962],256],120764:[[963],256],120765:[[964],256],120766:[[965],256],120767:[[966],256],120768:[[967],256],120769:[[968],256],120770:[[969],256],120771:[[8706],256],120772:[[1013],256],120773:[[977],256],120774:[[1008],256],120775:[[981],256],120776:[[1009],256],120777:[[982],256],120778:[[988],256],120779:[[989],256],120782:[[48],256],120783:[[49],256],120784:[[50],256],120785:[[51],256],120786:[[52],256],120787:[[53],256],120788:[[54],256],120789:[[55],256],120790:[[56],256],120791:[[57],256],120792:[[48],256],120793:[[49],256],120794:[[50],256],120795:[[51],256],120796:[[52],256],120797:[[53],256],120798:[[54],256],120799:[[55],256],120800:[[56],256],120801:[[57],256],120802:[[48],256],120803:[[49],256],120804:[[50],256],120805:[[51],256],120806:[[52],256],120807:[[53],256],120808:[[54],256],120809:[[55],256],120810:[[56],256],120811:[[57],256],120812:[[48],256],120813:[[49],256],120814:[[50],256],120815:[[51],256],120816:[[52],256],120817:[[53],256],120818:[[54],256],120819:[[55],256],120820:[[56],256],120821:[[57],256],120822:[[48],256],120823:[[49],256],120824:[[50],256],120825:[[51],256],120826:[[52],256],120827:[[53],256],120828:[[54],256],120829:[[55],256],120830:[[56],256],120831:[[57],256]}, + 60928:{126464:[[1575],256],126465:[[1576],256],126466:[[1580],256],126467:[[1583],256],126469:[[1608],256],126470:[[1586],256],126471:[[1581],256],126472:[[1591],256],126473:[[1610],256],126474:[[1603],256],126475:[[1604],256],126476:[[1605],256],126477:[[1606],256],126478:[[1587],256],126479:[[1593],256],126480:[[1601],256],126481:[[1589],256],126482:[[1602],256],126483:[[1585],256],126484:[[1588],256],126485:[[1578],256],126486:[[1579],256],126487:[[1582],256],126488:[[1584],256],126489:[[1590],256],126490:[[1592],256],126491:[[1594],256],126492:[[1646],256],126493:[[1722],256],126494:[[1697],256],126495:[[1647],256],126497:[[1576],256],126498:[[1580],256],126500:[[1607],256],126503:[[1581],256],126505:[[1610],256],126506:[[1603],256],126507:[[1604],256],126508:[[1605],256],126509:[[1606],256],126510:[[1587],256],126511:[[1593],256],126512:[[1601],256],126513:[[1589],256],126514:[[1602],256],126516:[[1588],256],126517:[[1578],256],126518:[[1579],256],126519:[[1582],256],126521:[[1590],256],126523:[[1594],256],126530:[[1580],256],126535:[[1581],256],126537:[[1610],256],126539:[[1604],256],126541:[[1606],256],126542:[[1587],256],126543:[[1593],256],126545:[[1589],256],126546:[[1602],256],126548:[[1588],256],126551:[[1582],256],126553:[[1590],256],126555:[[1594],256],126557:[[1722],256],126559:[[1647],256],126561:[[1576],256],126562:[[1580],256],126564:[[1607],256],126567:[[1581],256],126568:[[1591],256],126569:[[1610],256],126570:[[1603],256],126572:[[1605],256],126573:[[1606],256],126574:[[1587],256],126575:[[1593],256],126576:[[1601],256],126577:[[1589],256],126578:[[1602],256],126580:[[1588],256],126581:[[1578],256],126582:[[1579],256],126583:[[1582],256],126585:[[1590],256],126586:[[1592],256],126587:[[1594],256],126588:[[1646],256],126590:[[1697],256],126592:[[1575],256],126593:[[1576],256],126594:[[1580],256],126595:[[1583],256],126596:[[1607],256],126597:[[1608],256],126598:[[1586],256],126599:[[1581],256],126600:[[1591],256],126601:[[1610],256],126603:[[1604],256],126604:[[1605],256],126605:[[1606],256],126606:[[1587],256],126607:[[1593],256],126608:[[1601],256],126609:[[1589],256],126610:[[1602],256],126611:[[1585],256],126612:[[1588],256],126613:[[1578],256],126614:[[1579],256],126615:[[1582],256],126616:[[1584],256],126617:[[1590],256],126618:[[1592],256],126619:[[1594],256],126625:[[1576],256],126626:[[1580],256],126627:[[1583],256],126629:[[1608],256],126630:[[1586],256],126631:[[1581],256],126632:[[1591],256],126633:[[1610],256],126635:[[1604],256],126636:[[1605],256],126637:[[1606],256],126638:[[1587],256],126639:[[1593],256],126640:[[1601],256],126641:[[1589],256],126642:[[1602],256],126643:[[1585],256],126644:[[1588],256],126645:[[1578],256],126646:[[1579],256],126647:[[1582],256],126648:[[1584],256],126649:[[1590],256],126650:[[1592],256],126651:[[1594],256]}, + 61696:{127232:[[48,46],256],127233:[[48,44],256],127234:[[49,44],256],127235:[[50,44],256],127236:[[51,44],256],127237:[[52,44],256],127238:[[53,44],256],127239:[[54,44],256],127240:[[55,44],256],127241:[[56,44],256],127242:[[57,44],256],127248:[[40,65,41],256],127249:[[40,66,41],256],127250:[[40,67,41],256],127251:[[40,68,41],256],127252:[[40,69,41],256],127253:[[40,70,41],256],127254:[[40,71,41],256],127255:[[40,72,41],256],127256:[[40,73,41],256],127257:[[40,74,41],256],127258:[[40,75,41],256],127259:[[40,76,41],256],127260:[[40,77,41],256],127261:[[40,78,41],256],127262:[[40,79,41],256],127263:[[40,80,41],256],127264:[[40,81,41],256],127265:[[40,82,41],256],127266:[[40,83,41],256],127267:[[40,84,41],256],127268:[[40,85,41],256],127269:[[40,86,41],256],127270:[[40,87,41],256],127271:[[40,88,41],256],127272:[[40,89,41],256],127273:[[40,90,41],256],127274:[[12308,83,12309],256],127275:[[67],256],127276:[[82],256],127277:[[67,68],256],127278:[[87,90],256],127280:[[65],256],127281:[[66],256],127282:[[67],256],127283:[[68],256],127284:[[69],256],127285:[[70],256],127286:[[71],256],127287:[[72],256],127288:[[73],256],127289:[[74],256],127290:[[75],256],127291:[[76],256],127292:[[77],256],127293:[[78],256],127294:[[79],256],127295:[[80],256],127296:[[81],256],127297:[[82],256],127298:[[83],256],127299:[[84],256],127300:[[85],256],127301:[[86],256],127302:[[87],256],127303:[[88],256],127304:[[89],256],127305:[[90],256],127306:[[72,86],256],127307:[[77,86],256],127308:[[83,68],256],127309:[[83,83],256],127310:[[80,80,86],256],127311:[[87,67],256],127338:[[77,67],256],127339:[[77,68],256],127376:[[68,74],256]}, + 61952:{127488:[[12411,12363],256],127489:[[12467,12467],256],127490:[[12469],256],127504:[[25163],256],127505:[[23383],256],127506:[[21452],256],127507:[[12487],256],127508:[[20108],256],127509:[[22810],256],127510:[[35299],256],127511:[[22825],256],127512:[[20132],256],127513:[[26144],256],127514:[[28961],256],127515:[[26009],256],127516:[[21069],256],127517:[[24460],256],127518:[[20877],256],127519:[[26032],256],127520:[[21021],256],127521:[[32066],256],127522:[[29983],256],127523:[[36009],256],127524:[[22768],256],127525:[[21561],256],127526:[[28436],256],127527:[[25237],256],127528:[[25429],256],127529:[[19968],256],127530:[[19977],256],127531:[[36938],256],127532:[[24038],256],127533:[[20013],256],127534:[[21491],256],127535:[[25351],256],127536:[[36208],256],127537:[[25171],256],127538:[[31105],256],127539:[[31354],256],127540:[[21512],256],127541:[[28288],256],127542:[[26377],256],127543:[[26376],256],127544:[[30003],256],127545:[[21106],256],127546:[[21942],256],127552:[[12308,26412,12309],256],127553:[[12308,19977,12309],256],127554:[[12308,20108,12309],256],127555:[[12308,23433,12309],256],127556:[[12308,28857,12309],256],127557:[[12308,25171,12309],256],127558:[[12308,30423,12309],256],127559:[[12308,21213,12309],256],127560:[[12308,25943,12309],256],127568:[[24471],256],127569:[[21487],256]}, + 63488:{194560:[[20029]],194561:[[20024]],194562:[[20033]],194563:[[131362]],194564:[[20320]],194565:[[20398]],194566:[[20411]],194567:[[20482]],194568:[[20602]],194569:[[20633]],194570:[[20711]],194571:[[20687]],194572:[[13470]],194573:[[132666]],194574:[[20813]],194575:[[20820]],194576:[[20836]],194577:[[20855]],194578:[[132380]],194579:[[13497]],194580:[[20839]],194581:[[20877]],194582:[[132427]],194583:[[20887]],194584:[[20900]],194585:[[20172]],194586:[[20908]],194587:[[20917]],194588:[[168415]],194589:[[20981]],194590:[[20995]],194591:[[13535]],194592:[[21051]],194593:[[21062]],194594:[[21106]],194595:[[21111]],194596:[[13589]],194597:[[21191]],194598:[[21193]],194599:[[21220]],194600:[[21242]],194601:[[21253]],194602:[[21254]],194603:[[21271]],194604:[[21321]],194605:[[21329]],194606:[[21338]],194607:[[21363]],194608:[[21373]],194609:[[21375]],194610:[[21375]],194611:[[21375]],194612:[[133676]],194613:[[28784]],194614:[[21450]],194615:[[21471]],194616:[[133987]],194617:[[21483]],194618:[[21489]],194619:[[21510]],194620:[[21662]],194621:[[21560]],194622:[[21576]],194623:[[21608]],194624:[[21666]],194625:[[21750]],194626:[[21776]],194627:[[21843]],194628:[[21859]],194629:[[21892]],194630:[[21892]],194631:[[21913]],194632:[[21931]],194633:[[21939]],194634:[[21954]],194635:[[22294]],194636:[[22022]],194637:[[22295]],194638:[[22097]],194639:[[22132]],194640:[[20999]],194641:[[22766]],194642:[[22478]],194643:[[22516]],194644:[[22541]],194645:[[22411]],194646:[[22578]],194647:[[22577]],194648:[[22700]],194649:[[136420]],194650:[[22770]],194651:[[22775]],194652:[[22790]],194653:[[22810]],194654:[[22818]],194655:[[22882]],194656:[[136872]],194657:[[136938]],194658:[[23020]],194659:[[23067]],194660:[[23079]],194661:[[23000]],194662:[[23142]],194663:[[14062]],194664:[[14076]],194665:[[23304]],194666:[[23358]],194667:[[23358]],194668:[[137672]],194669:[[23491]],194670:[[23512]],194671:[[23527]],194672:[[23539]],194673:[[138008]],194674:[[23551]],194675:[[23558]],194676:[[24403]],194677:[[23586]],194678:[[14209]],194679:[[23648]],194680:[[23662]],194681:[[23744]],194682:[[23693]],194683:[[138724]],194684:[[23875]],194685:[[138726]],194686:[[23918]],194687:[[23915]],194688:[[23932]],194689:[[24033]],194690:[[24034]],194691:[[14383]],194692:[[24061]],194693:[[24104]],194694:[[24125]],194695:[[24169]],194696:[[14434]],194697:[[139651]],194698:[[14460]],194699:[[24240]],194700:[[24243]],194701:[[24246]],194702:[[24266]],194703:[[172946]],194704:[[24318]],194705:[[140081]],194706:[[140081]],194707:[[33281]],194708:[[24354]],194709:[[24354]],194710:[[14535]],194711:[[144056]],194712:[[156122]],194713:[[24418]],194714:[[24427]],194715:[[14563]],194716:[[24474]],194717:[[24525]],194718:[[24535]],194719:[[24569]],194720:[[24705]],194721:[[14650]],194722:[[14620]],194723:[[24724]],194724:[[141012]],194725:[[24775]],194726:[[24904]],194727:[[24908]],194728:[[24910]],194729:[[24908]],194730:[[24954]],194731:[[24974]],194732:[[25010]],194733:[[24996]],194734:[[25007]],194735:[[25054]],194736:[[25074]],194737:[[25078]],194738:[[25104]],194739:[[25115]],194740:[[25181]],194741:[[25265]],194742:[[25300]],194743:[[25424]],194744:[[142092]],194745:[[25405]],194746:[[25340]],194747:[[25448]],194748:[[25475]],194749:[[25572]],194750:[[142321]],194751:[[25634]],194752:[[25541]],194753:[[25513]],194754:[[14894]],194755:[[25705]],194756:[[25726]],194757:[[25757]],194758:[[25719]],194759:[[14956]],194760:[[25935]],194761:[[25964]],194762:[[143370]],194763:[[26083]],194764:[[26360]],194765:[[26185]],194766:[[15129]],194767:[[26257]],194768:[[15112]],194769:[[15076]],194770:[[20882]],194771:[[20885]],194772:[[26368]],194773:[[26268]],194774:[[32941]],194775:[[17369]],194776:[[26391]],194777:[[26395]],194778:[[26401]],194779:[[26462]],194780:[[26451]],194781:[[144323]],194782:[[15177]],194783:[[26618]],194784:[[26501]],194785:[[26706]],194786:[[26757]],194787:[[144493]],194788:[[26766]],194789:[[26655]],194790:[[26900]],194791:[[15261]],194792:[[26946]],194793:[[27043]],194794:[[27114]],194795:[[27304]],194796:[[145059]],194797:[[27355]],194798:[[15384]],194799:[[27425]],194800:[[145575]],194801:[[27476]],194802:[[15438]],194803:[[27506]],194804:[[27551]],194805:[[27578]],194806:[[27579]],194807:[[146061]],194808:[[138507]],194809:[[146170]],194810:[[27726]],194811:[[146620]],194812:[[27839]],194813:[[27853]],194814:[[27751]],194815:[[27926]]}, + 63744:{63744:[[35912]],63745:[[26356]],63746:[[36554]],63747:[[36040]],63748:[[28369]],63749:[[20018]],63750:[[21477]],63751:[[40860]],63752:[[40860]],63753:[[22865]],63754:[[37329]],63755:[[21895]],63756:[[22856]],63757:[[25078]],63758:[[30313]],63759:[[32645]],63760:[[34367]],63761:[[34746]],63762:[[35064]],63763:[[37007]],63764:[[27138]],63765:[[27931]],63766:[[28889]],63767:[[29662]],63768:[[33853]],63769:[[37226]],63770:[[39409]],63771:[[20098]],63772:[[21365]],63773:[[27396]],63774:[[29211]],63775:[[34349]],63776:[[40478]],63777:[[23888]],63778:[[28651]],63779:[[34253]],63780:[[35172]],63781:[[25289]],63782:[[33240]],63783:[[34847]],63784:[[24266]],63785:[[26391]],63786:[[28010]],63787:[[29436]],63788:[[37070]],63789:[[20358]],63790:[[20919]],63791:[[21214]],63792:[[25796]],63793:[[27347]],63794:[[29200]],63795:[[30439]],63796:[[32769]],63797:[[34310]],63798:[[34396]],63799:[[36335]],63800:[[38706]],63801:[[39791]],63802:[[40442]],63803:[[30860]],63804:[[31103]],63805:[[32160]],63806:[[33737]],63807:[[37636]],63808:[[40575]],63809:[[35542]],63810:[[22751]],63811:[[24324]],63812:[[31840]],63813:[[32894]],63814:[[29282]],63815:[[30922]],63816:[[36034]],63817:[[38647]],63818:[[22744]],63819:[[23650]],63820:[[27155]],63821:[[28122]],63822:[[28431]],63823:[[32047]],63824:[[32311]],63825:[[38475]],63826:[[21202]],63827:[[32907]],63828:[[20956]],63829:[[20940]],63830:[[31260]],63831:[[32190]],63832:[[33777]],63833:[[38517]],63834:[[35712]],63835:[[25295]],63836:[[27138]],63837:[[35582]],63838:[[20025]],63839:[[23527]],63840:[[24594]],63841:[[29575]],63842:[[30064]],63843:[[21271]],63844:[[30971]],63845:[[20415]],63846:[[24489]],63847:[[19981]],63848:[[27852]],63849:[[25976]],63850:[[32034]],63851:[[21443]],63852:[[22622]],63853:[[30465]],63854:[[33865]],63855:[[35498]],63856:[[27578]],63857:[[36784]],63858:[[27784]],63859:[[25342]],63860:[[33509]],63861:[[25504]],63862:[[30053]],63863:[[20142]],63864:[[20841]],63865:[[20937]],63866:[[26753]],63867:[[31975]],63868:[[33391]],63869:[[35538]],63870:[[37327]],63871:[[21237]],63872:[[21570]],63873:[[22899]],63874:[[24300]],63875:[[26053]],63876:[[28670]],63877:[[31018]],63878:[[38317]],63879:[[39530]],63880:[[40599]],63881:[[40654]],63882:[[21147]],63883:[[26310]],63884:[[27511]],63885:[[36706]],63886:[[24180]],63887:[[24976]],63888:[[25088]],63889:[[25754]],63890:[[28451]],63891:[[29001]],63892:[[29833]],63893:[[31178]],63894:[[32244]],63895:[[32879]],63896:[[36646]],63897:[[34030]],63898:[[36899]],63899:[[37706]],63900:[[21015]],63901:[[21155]],63902:[[21693]],63903:[[28872]],63904:[[35010]],63905:[[35498]],63906:[[24265]],63907:[[24565]],63908:[[25467]],63909:[[27566]],63910:[[31806]],63911:[[29557]],63912:[[20196]],63913:[[22265]],63914:[[23527]],63915:[[23994]],63916:[[24604]],63917:[[29618]],63918:[[29801]],63919:[[32666]],63920:[[32838]],63921:[[37428]],63922:[[38646]],63923:[[38728]],63924:[[38936]],63925:[[20363]],63926:[[31150]],63927:[[37300]],63928:[[38584]],63929:[[24801]],63930:[[20102]],63931:[[20698]],63932:[[23534]],63933:[[23615]],63934:[[26009]],63935:[[27138]],63936:[[29134]],63937:[[30274]],63938:[[34044]],63939:[[36988]],63940:[[40845]],63941:[[26248]],63942:[[38446]],63943:[[21129]],63944:[[26491]],63945:[[26611]],63946:[[27969]],63947:[[28316]],63948:[[29705]],63949:[[30041]],63950:[[30827]],63951:[[32016]],63952:[[39006]],63953:[[20845]],63954:[[25134]],63955:[[38520]],63956:[[20523]],63957:[[23833]],63958:[[28138]],63959:[[36650]],63960:[[24459]],63961:[[24900]],63962:[[26647]],63963:[[29575]],63964:[[38534]],63965:[[21033]],63966:[[21519]],63967:[[23653]],63968:[[26131]],63969:[[26446]],63970:[[26792]],63971:[[27877]],63972:[[29702]],63973:[[30178]],63974:[[32633]],63975:[[35023]],63976:[[35041]],63977:[[37324]],63978:[[38626]],63979:[[21311]],63980:[[28346]],63981:[[21533]],63982:[[29136]],63983:[[29848]],63984:[[34298]],63985:[[38563]],63986:[[40023]],63987:[[40607]],63988:[[26519]],63989:[[28107]],63990:[[33256]],63991:[[31435]],63992:[[31520]],63993:[[31890]],63994:[[29376]],63995:[[28825]],63996:[[35672]],63997:[[20160]],63998:[[33590]],63999:[[21050]],194816:[[27966]],194817:[[28023]],194818:[[27969]],194819:[[28009]],194820:[[28024]],194821:[[28037]],194822:[[146718]],194823:[[27956]],194824:[[28207]],194825:[[28270]],194826:[[15667]],194827:[[28363]],194828:[[28359]],194829:[[147153]],194830:[[28153]],194831:[[28526]],194832:[[147294]],194833:[[147342]],194834:[[28614]],194835:[[28729]],194836:[[28702]],194837:[[28699]],194838:[[15766]],194839:[[28746]],194840:[[28797]],194841:[[28791]],194842:[[28845]],194843:[[132389]],194844:[[28997]],194845:[[148067]],194846:[[29084]],194847:[[148395]],194848:[[29224]],194849:[[29237]],194850:[[29264]],194851:[[149000]],194852:[[29312]],194853:[[29333]],194854:[[149301]],194855:[[149524]],194856:[[29562]],194857:[[29579]],194858:[[16044]],194859:[[29605]],194860:[[16056]],194861:[[16056]],194862:[[29767]],194863:[[29788]],194864:[[29809]],194865:[[29829]],194866:[[29898]],194867:[[16155]],194868:[[29988]],194869:[[150582]],194870:[[30014]],194871:[[150674]],194872:[[30064]],194873:[[139679]],194874:[[30224]],194875:[[151457]],194876:[[151480]],194877:[[151620]],194878:[[16380]],194879:[[16392]],194880:[[30452]],194881:[[151795]],194882:[[151794]],194883:[[151833]],194884:[[151859]],194885:[[30494]],194886:[[30495]],194887:[[30495]],194888:[[30538]],194889:[[16441]],194890:[[30603]],194891:[[16454]],194892:[[16534]],194893:[[152605]],194894:[[30798]],194895:[[30860]],194896:[[30924]],194897:[[16611]],194898:[[153126]],194899:[[31062]],194900:[[153242]],194901:[[153285]],194902:[[31119]],194903:[[31211]],194904:[[16687]],194905:[[31296]],194906:[[31306]],194907:[[31311]],194908:[[153980]],194909:[[154279]],194910:[[154279]],194911:[[31470]],194912:[[16898]],194913:[[154539]],194914:[[31686]],194915:[[31689]],194916:[[16935]],194917:[[154752]],194918:[[31954]],194919:[[17056]],194920:[[31976]],194921:[[31971]],194922:[[32000]],194923:[[155526]],194924:[[32099]],194925:[[17153]],194926:[[32199]],194927:[[32258]],194928:[[32325]],194929:[[17204]],194930:[[156200]],194931:[[156231]],194932:[[17241]],194933:[[156377]],194934:[[32634]],194935:[[156478]],194936:[[32661]],194937:[[32762]],194938:[[32773]],194939:[[156890]],194940:[[156963]],194941:[[32864]],194942:[[157096]],194943:[[32880]],194944:[[144223]],194945:[[17365]],194946:[[32946]],194947:[[33027]],194948:[[17419]],194949:[[33086]],194950:[[23221]],194951:[[157607]],194952:[[157621]],194953:[[144275]],194954:[[144284]],194955:[[33281]],194956:[[33284]],194957:[[36766]],194958:[[17515]],194959:[[33425]],194960:[[33419]],194961:[[33437]],194962:[[21171]],194963:[[33457]],194964:[[33459]],194965:[[33469]],194966:[[33510]],194967:[[158524]],194968:[[33509]],194969:[[33565]],194970:[[33635]],194971:[[33709]],194972:[[33571]],194973:[[33725]],194974:[[33767]],194975:[[33879]],194976:[[33619]],194977:[[33738]],194978:[[33740]],194979:[[33756]],194980:[[158774]],194981:[[159083]],194982:[[158933]],194983:[[17707]],194984:[[34033]],194985:[[34035]],194986:[[34070]],194987:[[160714]],194988:[[34148]],194989:[[159532]],194990:[[17757]],194991:[[17761]],194992:[[159665]],194993:[[159954]],194994:[[17771]],194995:[[34384]],194996:[[34396]],194997:[[34407]],194998:[[34409]],194999:[[34473]],195000:[[34440]],195001:[[34574]],195002:[[34530]],195003:[[34681]],195004:[[34600]],195005:[[34667]],195006:[[34694]],195007:[[17879]],195008:[[34785]],195009:[[34817]],195010:[[17913]],195011:[[34912]],195012:[[34915]],195013:[[161383]],195014:[[35031]],195015:[[35038]],195016:[[17973]],195017:[[35066]],195018:[[13499]],195019:[[161966]],195020:[[162150]],195021:[[18110]],195022:[[18119]],195023:[[35488]],195024:[[35565]],195025:[[35722]],195026:[[35925]],195027:[[162984]],195028:[[36011]],195029:[[36033]],195030:[[36123]],195031:[[36215]],195032:[[163631]],195033:[[133124]],195034:[[36299]],195035:[[36284]],195036:[[36336]],195037:[[133342]],195038:[[36564]],195039:[[36664]],195040:[[165330]],195041:[[165357]],195042:[[37012]],195043:[[37105]],195044:[[37137]],195045:[[165678]],195046:[[37147]],195047:[[37432]],195048:[[37591]],195049:[[37592]],195050:[[37500]],195051:[[37881]],195052:[[37909]],195053:[[166906]],195054:[[38283]],195055:[[18837]],195056:[[38327]],195057:[[167287]],195058:[[18918]],195059:[[38595]],195060:[[23986]],195061:[[38691]],195062:[[168261]],195063:[[168474]],195064:[[19054]],195065:[[19062]],195066:[[38880]],195067:[[168970]],195068:[[19122]],195069:[[169110]],195070:[[38923]],195071:[[38923]]}, + 64000:{64000:[[20999]],64001:[[24230]],64002:[[25299]],64003:[[31958]],64004:[[23429]],64005:[[27934]],64006:[[26292]],64007:[[36667]],64008:[[34892]],64009:[[38477]],64010:[[35211]],64011:[[24275]],64012:[[20800]],64013:[[21952]],64016:[[22618]],64018:[[26228]],64021:[[20958]],64022:[[29482]],64023:[[30410]],64024:[[31036]],64025:[[31070]],64026:[[31077]],64027:[[31119]],64028:[[38742]],64029:[[31934]],64030:[[32701]],64032:[[34322]],64034:[[35576]],64037:[[36920]],64038:[[37117]],64042:[[39151]],64043:[[39164]],64044:[[39208]],64045:[[40372]],64046:[[37086]],64047:[[38583]],64048:[[20398]],64049:[[20711]],64050:[[20813]],64051:[[21193]],64052:[[21220]],64053:[[21329]],64054:[[21917]],64055:[[22022]],64056:[[22120]],64057:[[22592]],64058:[[22696]],64059:[[23652]],64060:[[23662]],64061:[[24724]],64062:[[24936]],64063:[[24974]],64064:[[25074]],64065:[[25935]],64066:[[26082]],64067:[[26257]],64068:[[26757]],64069:[[28023]],64070:[[28186]],64071:[[28450]],64072:[[29038]],64073:[[29227]],64074:[[29730]],64075:[[30865]],64076:[[31038]],64077:[[31049]],64078:[[31048]],64079:[[31056]],64080:[[31062]],64081:[[31069]],64082:[[31117]],64083:[[31118]],64084:[[31296]],64085:[[31361]],64086:[[31680]],64087:[[32244]],64088:[[32265]],64089:[[32321]],64090:[[32626]],64091:[[32773]],64092:[[33261]],64093:[[33401]],64094:[[33401]],64095:[[33879]],64096:[[35088]],64097:[[35222]],64098:[[35585]],64099:[[35641]],64100:[[36051]],64101:[[36104]],64102:[[36790]],64103:[[36920]],64104:[[38627]],64105:[[38911]],64106:[[38971]],64107:[[24693]],64108:[[148206]],64109:[[33304]],64112:[[20006]],64113:[[20917]],64114:[[20840]],64115:[[20352]],64116:[[20805]],64117:[[20864]],64118:[[21191]],64119:[[21242]],64120:[[21917]],64121:[[21845]],64122:[[21913]],64123:[[21986]],64124:[[22618]],64125:[[22707]],64126:[[22852]],64127:[[22868]],64128:[[23138]],64129:[[23336]],64130:[[24274]],64131:[[24281]],64132:[[24425]],64133:[[24493]],64134:[[24792]],64135:[[24910]],64136:[[24840]],64137:[[24974]],64138:[[24928]],64139:[[25074]],64140:[[25140]],64141:[[25540]],64142:[[25628]],64143:[[25682]],64144:[[25942]],64145:[[26228]],64146:[[26391]],64147:[[26395]],64148:[[26454]],64149:[[27513]],64150:[[27578]],64151:[[27969]],64152:[[28379]],64153:[[28363]],64154:[[28450]],64155:[[28702]],64156:[[29038]],64157:[[30631]],64158:[[29237]],64159:[[29359]],64160:[[29482]],64161:[[29809]],64162:[[29958]],64163:[[30011]],64164:[[30237]],64165:[[30239]],64166:[[30410]],64167:[[30427]],64168:[[30452]],64169:[[30538]],64170:[[30528]],64171:[[30924]],64172:[[31409]],64173:[[31680]],64174:[[31867]],64175:[[32091]],64176:[[32244]],64177:[[32574]],64178:[[32773]],64179:[[33618]],64180:[[33775]],64181:[[34681]],64182:[[35137]],64183:[[35206]],64184:[[35222]],64185:[[35519]],64186:[[35576]],64187:[[35531]],64188:[[35585]],64189:[[35582]],64190:[[35565]],64191:[[35641]],64192:[[35722]],64193:[[36104]],64194:[[36664]],64195:[[36978]],64196:[[37273]],64197:[[37494]],64198:[[38524]],64199:[[38627]],64200:[[38742]],64201:[[38875]],64202:[[38911]],64203:[[38923]],64204:[[38971]],64205:[[39698]],64206:[[40860]],64207:[[141386]],64208:[[141380]],64209:[[144341]],64210:[[15261]],64211:[[16408]],64212:[[16441]],64213:[[152137]],64214:[[154832]],64215:[[163539]],64216:[[40771]],64217:[[40846]],195072:[[38953]],195073:[[169398]],195074:[[39138]],195075:[[19251]],195076:[[39209]],195077:[[39335]],195078:[[39362]],195079:[[39422]],195080:[[19406]],195081:[[170800]],195082:[[39698]],195083:[[40000]],195084:[[40189]],195085:[[19662]],195086:[[19693]],195087:[[40295]],195088:[[172238]],195089:[[19704]],195090:[[172293]],195091:[[172558]],195092:[[172689]],195093:[[40635]],195094:[[19798]],195095:[[40697]],195096:[[40702]],195097:[[40709]],195098:[[40719]],195099:[[40726]],195100:[[40763]],195101:[[173568]]}, + 64256:{64256:[[102,102],256],64257:[[102,105],256],64258:[[102,108],256],64259:[[102,102,105],256],64260:[[102,102,108],256],64261:[[383,116],256],64262:[[115,116],256],64275:[[1396,1398],256],64276:[[1396,1381],256],64277:[[1396,1387],256],64278:[[1406,1398],256],64279:[[1396,1389],256],64285:[[1497,1460],512],64286:[,26],64287:[[1522,1463],512],64288:[[1506],256],64289:[[1488],256],64290:[[1491],256],64291:[[1492],256],64292:[[1499],256],64293:[[1500],256],64294:[[1501],256],64295:[[1512],256],64296:[[1514],256],64297:[[43],256],64298:[[1513,1473],512],64299:[[1513,1474],512],64300:[[64329,1473],512],64301:[[64329,1474],512],64302:[[1488,1463],512],64303:[[1488,1464],512],64304:[[1488,1468],512],64305:[[1489,1468],512],64306:[[1490,1468],512],64307:[[1491,1468],512],64308:[[1492,1468],512],64309:[[1493,1468],512],64310:[[1494,1468],512],64312:[[1496,1468],512],64313:[[1497,1468],512],64314:[[1498,1468],512],64315:[[1499,1468],512],64316:[[1500,1468],512],64318:[[1502,1468],512],64320:[[1504,1468],512],64321:[[1505,1468],512],64323:[[1507,1468],512],64324:[[1508,1468],512],64326:[[1510,1468],512],64327:[[1511,1468],512],64328:[[1512,1468],512],64329:[[1513,1468],512],64330:[[1514,1468],512],64331:[[1493,1465],512],64332:[[1489,1471],512],64333:[[1499,1471],512],64334:[[1508,1471],512],64335:[[1488,1500],256],64336:[[1649],256],64337:[[1649],256],64338:[[1659],256],64339:[[1659],256],64340:[[1659],256],64341:[[1659],256],64342:[[1662],256],64343:[[1662],256],64344:[[1662],256],64345:[[1662],256],64346:[[1664],256],64347:[[1664],256],64348:[[1664],256],64349:[[1664],256],64350:[[1658],256],64351:[[1658],256],64352:[[1658],256],64353:[[1658],256],64354:[[1663],256],64355:[[1663],256],64356:[[1663],256],64357:[[1663],256],64358:[[1657],256],64359:[[1657],256],64360:[[1657],256],64361:[[1657],256],64362:[[1700],256],64363:[[1700],256],64364:[[1700],256],64365:[[1700],256],64366:[[1702],256],64367:[[1702],256],64368:[[1702],256],64369:[[1702],256],64370:[[1668],256],64371:[[1668],256],64372:[[1668],256],64373:[[1668],256],64374:[[1667],256],64375:[[1667],256],64376:[[1667],256],64377:[[1667],256],64378:[[1670],256],64379:[[1670],256],64380:[[1670],256],64381:[[1670],256],64382:[[1671],256],64383:[[1671],256],64384:[[1671],256],64385:[[1671],256],64386:[[1677],256],64387:[[1677],256],64388:[[1676],256],64389:[[1676],256],64390:[[1678],256],64391:[[1678],256],64392:[[1672],256],64393:[[1672],256],64394:[[1688],256],64395:[[1688],256],64396:[[1681],256],64397:[[1681],256],64398:[[1705],256],64399:[[1705],256],64400:[[1705],256],64401:[[1705],256],64402:[[1711],256],64403:[[1711],256],64404:[[1711],256],64405:[[1711],256],64406:[[1715],256],64407:[[1715],256],64408:[[1715],256],64409:[[1715],256],64410:[[1713],256],64411:[[1713],256],64412:[[1713],256],64413:[[1713],256],64414:[[1722],256],64415:[[1722],256],64416:[[1723],256],64417:[[1723],256],64418:[[1723],256],64419:[[1723],256],64420:[[1728],256],64421:[[1728],256],64422:[[1729],256],64423:[[1729],256],64424:[[1729],256],64425:[[1729],256],64426:[[1726],256],64427:[[1726],256],64428:[[1726],256],64429:[[1726],256],64430:[[1746],256],64431:[[1746],256],64432:[[1747],256],64433:[[1747],256],64467:[[1709],256],64468:[[1709],256],64469:[[1709],256],64470:[[1709],256],64471:[[1735],256],64472:[[1735],256],64473:[[1734],256],64474:[[1734],256],64475:[[1736],256],64476:[[1736],256],64477:[[1655],256],64478:[[1739],256],64479:[[1739],256],64480:[[1733],256],64481:[[1733],256],64482:[[1737],256],64483:[[1737],256],64484:[[1744],256],64485:[[1744],256],64486:[[1744],256],64487:[[1744],256],64488:[[1609],256],64489:[[1609],256],64490:[[1574,1575],256],64491:[[1574,1575],256],64492:[[1574,1749],256],64493:[[1574,1749],256],64494:[[1574,1608],256],64495:[[1574,1608],256],64496:[[1574,1735],256],64497:[[1574,1735],256],64498:[[1574,1734],256],64499:[[1574,1734],256],64500:[[1574,1736],256],64501:[[1574,1736],256],64502:[[1574,1744],256],64503:[[1574,1744],256],64504:[[1574,1744],256],64505:[[1574,1609],256],64506:[[1574,1609],256],64507:[[1574,1609],256],64508:[[1740],256],64509:[[1740],256],64510:[[1740],256],64511:[[1740],256]}, + 64512:{64512:[[1574,1580],256],64513:[[1574,1581],256],64514:[[1574,1605],256],64515:[[1574,1609],256],64516:[[1574,1610],256],64517:[[1576,1580],256],64518:[[1576,1581],256],64519:[[1576,1582],256],64520:[[1576,1605],256],64521:[[1576,1609],256],64522:[[1576,1610],256],64523:[[1578,1580],256],64524:[[1578,1581],256],64525:[[1578,1582],256],64526:[[1578,1605],256],64527:[[1578,1609],256],64528:[[1578,1610],256],64529:[[1579,1580],256],64530:[[1579,1605],256],64531:[[1579,1609],256],64532:[[1579,1610],256],64533:[[1580,1581],256],64534:[[1580,1605],256],64535:[[1581,1580],256],64536:[[1581,1605],256],64537:[[1582,1580],256],64538:[[1582,1581],256],64539:[[1582,1605],256],64540:[[1587,1580],256],64541:[[1587,1581],256],64542:[[1587,1582],256],64543:[[1587,1605],256],64544:[[1589,1581],256],64545:[[1589,1605],256],64546:[[1590,1580],256],64547:[[1590,1581],256],64548:[[1590,1582],256],64549:[[1590,1605],256],64550:[[1591,1581],256],64551:[[1591,1605],256],64552:[[1592,1605],256],64553:[[1593,1580],256],64554:[[1593,1605],256],64555:[[1594,1580],256],64556:[[1594,1605],256],64557:[[1601,1580],256],64558:[[1601,1581],256],64559:[[1601,1582],256],64560:[[1601,1605],256],64561:[[1601,1609],256],64562:[[1601,1610],256],64563:[[1602,1581],256],64564:[[1602,1605],256],64565:[[1602,1609],256],64566:[[1602,1610],256],64567:[[1603,1575],256],64568:[[1603,1580],256],64569:[[1603,1581],256],64570:[[1603,1582],256],64571:[[1603,1604],256],64572:[[1603,1605],256],64573:[[1603,1609],256],64574:[[1603,1610],256],64575:[[1604,1580],256],64576:[[1604,1581],256],64577:[[1604,1582],256],64578:[[1604,1605],256],64579:[[1604,1609],256],64580:[[1604,1610],256],64581:[[1605,1580],256],64582:[[1605,1581],256],64583:[[1605,1582],256],64584:[[1605,1605],256],64585:[[1605,1609],256],64586:[[1605,1610],256],64587:[[1606,1580],256],64588:[[1606,1581],256],64589:[[1606,1582],256],64590:[[1606,1605],256],64591:[[1606,1609],256],64592:[[1606,1610],256],64593:[[1607,1580],256],64594:[[1607,1605],256],64595:[[1607,1609],256],64596:[[1607,1610],256],64597:[[1610,1580],256],64598:[[1610,1581],256],64599:[[1610,1582],256],64600:[[1610,1605],256],64601:[[1610,1609],256],64602:[[1610,1610],256],64603:[[1584,1648],256],64604:[[1585,1648],256],64605:[[1609,1648],256],64606:[[32,1612,1617],256],64607:[[32,1613,1617],256],64608:[[32,1614,1617],256],64609:[[32,1615,1617],256],64610:[[32,1616,1617],256],64611:[[32,1617,1648],256],64612:[[1574,1585],256],64613:[[1574,1586],256],64614:[[1574,1605],256],64615:[[1574,1606],256],64616:[[1574,1609],256],64617:[[1574,1610],256],64618:[[1576,1585],256],64619:[[1576,1586],256],64620:[[1576,1605],256],64621:[[1576,1606],256],64622:[[1576,1609],256],64623:[[1576,1610],256],64624:[[1578,1585],256],64625:[[1578,1586],256],64626:[[1578,1605],256],64627:[[1578,1606],256],64628:[[1578,1609],256],64629:[[1578,1610],256],64630:[[1579,1585],256],64631:[[1579,1586],256],64632:[[1579,1605],256],64633:[[1579,1606],256],64634:[[1579,1609],256],64635:[[1579,1610],256],64636:[[1601,1609],256],64637:[[1601,1610],256],64638:[[1602,1609],256],64639:[[1602,1610],256],64640:[[1603,1575],256],64641:[[1603,1604],256],64642:[[1603,1605],256],64643:[[1603,1609],256],64644:[[1603,1610],256],64645:[[1604,1605],256],64646:[[1604,1609],256],64647:[[1604,1610],256],64648:[[1605,1575],256],64649:[[1605,1605],256],64650:[[1606,1585],256],64651:[[1606,1586],256],64652:[[1606,1605],256],64653:[[1606,1606],256],64654:[[1606,1609],256],64655:[[1606,1610],256],64656:[[1609,1648],256],64657:[[1610,1585],256],64658:[[1610,1586],256],64659:[[1610,1605],256],64660:[[1610,1606],256],64661:[[1610,1609],256],64662:[[1610,1610],256],64663:[[1574,1580],256],64664:[[1574,1581],256],64665:[[1574,1582],256],64666:[[1574,1605],256],64667:[[1574,1607],256],64668:[[1576,1580],256],64669:[[1576,1581],256],64670:[[1576,1582],256],64671:[[1576,1605],256],64672:[[1576,1607],256],64673:[[1578,1580],256],64674:[[1578,1581],256],64675:[[1578,1582],256],64676:[[1578,1605],256],64677:[[1578,1607],256],64678:[[1579,1605],256],64679:[[1580,1581],256],64680:[[1580,1605],256],64681:[[1581,1580],256],64682:[[1581,1605],256],64683:[[1582,1580],256],64684:[[1582,1605],256],64685:[[1587,1580],256],64686:[[1587,1581],256],64687:[[1587,1582],256],64688:[[1587,1605],256],64689:[[1589,1581],256],64690:[[1589,1582],256],64691:[[1589,1605],256],64692:[[1590,1580],256],64693:[[1590,1581],256],64694:[[1590,1582],256],64695:[[1590,1605],256],64696:[[1591,1581],256],64697:[[1592,1605],256],64698:[[1593,1580],256],64699:[[1593,1605],256],64700:[[1594,1580],256],64701:[[1594,1605],256],64702:[[1601,1580],256],64703:[[1601,1581],256],64704:[[1601,1582],256],64705:[[1601,1605],256],64706:[[1602,1581],256],64707:[[1602,1605],256],64708:[[1603,1580],256],64709:[[1603,1581],256],64710:[[1603,1582],256],64711:[[1603,1604],256],64712:[[1603,1605],256],64713:[[1604,1580],256],64714:[[1604,1581],256],64715:[[1604,1582],256],64716:[[1604,1605],256],64717:[[1604,1607],256],64718:[[1605,1580],256],64719:[[1605,1581],256],64720:[[1605,1582],256],64721:[[1605,1605],256],64722:[[1606,1580],256],64723:[[1606,1581],256],64724:[[1606,1582],256],64725:[[1606,1605],256],64726:[[1606,1607],256],64727:[[1607,1580],256],64728:[[1607,1605],256],64729:[[1607,1648],256],64730:[[1610,1580],256],64731:[[1610,1581],256],64732:[[1610,1582],256],64733:[[1610,1605],256],64734:[[1610,1607],256],64735:[[1574,1605],256],64736:[[1574,1607],256],64737:[[1576,1605],256],64738:[[1576,1607],256],64739:[[1578,1605],256],64740:[[1578,1607],256],64741:[[1579,1605],256],64742:[[1579,1607],256],64743:[[1587,1605],256],64744:[[1587,1607],256],64745:[[1588,1605],256],64746:[[1588,1607],256],64747:[[1603,1604],256],64748:[[1603,1605],256],64749:[[1604,1605],256],64750:[[1606,1605],256],64751:[[1606,1607],256],64752:[[1610,1605],256],64753:[[1610,1607],256],64754:[[1600,1614,1617],256],64755:[[1600,1615,1617],256],64756:[[1600,1616,1617],256],64757:[[1591,1609],256],64758:[[1591,1610],256],64759:[[1593,1609],256],64760:[[1593,1610],256],64761:[[1594,1609],256],64762:[[1594,1610],256],64763:[[1587,1609],256],64764:[[1587,1610],256],64765:[[1588,1609],256],64766:[[1588,1610],256],64767:[[1581,1609],256]}, + 64768:{64768:[[1581,1610],256],64769:[[1580,1609],256],64770:[[1580,1610],256],64771:[[1582,1609],256],64772:[[1582,1610],256],64773:[[1589,1609],256],64774:[[1589,1610],256],64775:[[1590,1609],256],64776:[[1590,1610],256],64777:[[1588,1580],256],64778:[[1588,1581],256],64779:[[1588,1582],256],64780:[[1588,1605],256],64781:[[1588,1585],256],64782:[[1587,1585],256],64783:[[1589,1585],256],64784:[[1590,1585],256],64785:[[1591,1609],256],64786:[[1591,1610],256],64787:[[1593,1609],256],64788:[[1593,1610],256],64789:[[1594,1609],256],64790:[[1594,1610],256],64791:[[1587,1609],256],64792:[[1587,1610],256],64793:[[1588,1609],256],64794:[[1588,1610],256],64795:[[1581,1609],256],64796:[[1581,1610],256],64797:[[1580,1609],256],64798:[[1580,1610],256],64799:[[1582,1609],256],64800:[[1582,1610],256],64801:[[1589,1609],256],64802:[[1589,1610],256],64803:[[1590,1609],256],64804:[[1590,1610],256],64805:[[1588,1580],256],64806:[[1588,1581],256],64807:[[1588,1582],256],64808:[[1588,1605],256],64809:[[1588,1585],256],64810:[[1587,1585],256],64811:[[1589,1585],256],64812:[[1590,1585],256],64813:[[1588,1580],256],64814:[[1588,1581],256],64815:[[1588,1582],256],64816:[[1588,1605],256],64817:[[1587,1607],256],64818:[[1588,1607],256],64819:[[1591,1605],256],64820:[[1587,1580],256],64821:[[1587,1581],256],64822:[[1587,1582],256],64823:[[1588,1580],256],64824:[[1588,1581],256],64825:[[1588,1582],256],64826:[[1591,1605],256],64827:[[1592,1605],256],64828:[[1575,1611],256],64829:[[1575,1611],256],64848:[[1578,1580,1605],256],64849:[[1578,1581,1580],256],64850:[[1578,1581,1580],256],64851:[[1578,1581,1605],256],64852:[[1578,1582,1605],256],64853:[[1578,1605,1580],256],64854:[[1578,1605,1581],256],64855:[[1578,1605,1582],256],64856:[[1580,1605,1581],256],64857:[[1580,1605,1581],256],64858:[[1581,1605,1610],256],64859:[[1581,1605,1609],256],64860:[[1587,1581,1580],256],64861:[[1587,1580,1581],256],64862:[[1587,1580,1609],256],64863:[[1587,1605,1581],256],64864:[[1587,1605,1581],256],64865:[[1587,1605,1580],256],64866:[[1587,1605,1605],256],64867:[[1587,1605,1605],256],64868:[[1589,1581,1581],256],64869:[[1589,1581,1581],256],64870:[[1589,1605,1605],256],64871:[[1588,1581,1605],256],64872:[[1588,1581,1605],256],64873:[[1588,1580,1610],256],64874:[[1588,1605,1582],256],64875:[[1588,1605,1582],256],64876:[[1588,1605,1605],256],64877:[[1588,1605,1605],256],64878:[[1590,1581,1609],256],64879:[[1590,1582,1605],256],64880:[[1590,1582,1605],256],64881:[[1591,1605,1581],256],64882:[[1591,1605,1581],256],64883:[[1591,1605,1605],256],64884:[[1591,1605,1610],256],64885:[[1593,1580,1605],256],64886:[[1593,1605,1605],256],64887:[[1593,1605,1605],256],64888:[[1593,1605,1609],256],64889:[[1594,1605,1605],256],64890:[[1594,1605,1610],256],64891:[[1594,1605,1609],256],64892:[[1601,1582,1605],256],64893:[[1601,1582,1605],256],64894:[[1602,1605,1581],256],64895:[[1602,1605,1605],256],64896:[[1604,1581,1605],256],64897:[[1604,1581,1610],256],64898:[[1604,1581,1609],256],64899:[[1604,1580,1580],256],64900:[[1604,1580,1580],256],64901:[[1604,1582,1605],256],64902:[[1604,1582,1605],256],64903:[[1604,1605,1581],256],64904:[[1604,1605,1581],256],64905:[[1605,1581,1580],256],64906:[[1605,1581,1605],256],64907:[[1605,1581,1610],256],64908:[[1605,1580,1581],256],64909:[[1605,1580,1605],256],64910:[[1605,1582,1580],256],64911:[[1605,1582,1605],256],64914:[[1605,1580,1582],256],64915:[[1607,1605,1580],256],64916:[[1607,1605,1605],256],64917:[[1606,1581,1605],256],64918:[[1606,1581,1609],256],64919:[[1606,1580,1605],256],64920:[[1606,1580,1605],256],64921:[[1606,1580,1609],256],64922:[[1606,1605,1610],256],64923:[[1606,1605,1609],256],64924:[[1610,1605,1605],256],64925:[[1610,1605,1605],256],64926:[[1576,1582,1610],256],64927:[[1578,1580,1610],256],64928:[[1578,1580,1609],256],64929:[[1578,1582,1610],256],64930:[[1578,1582,1609],256],64931:[[1578,1605,1610],256],64932:[[1578,1605,1609],256],64933:[[1580,1605,1610],256],64934:[[1580,1581,1609],256],64935:[[1580,1605,1609],256],64936:[[1587,1582,1609],256],64937:[[1589,1581,1610],256],64938:[[1588,1581,1610],256],64939:[[1590,1581,1610],256],64940:[[1604,1580,1610],256],64941:[[1604,1605,1610],256],64942:[[1610,1581,1610],256],64943:[[1610,1580,1610],256],64944:[[1610,1605,1610],256],64945:[[1605,1605,1610],256],64946:[[1602,1605,1610],256],64947:[[1606,1581,1610],256],64948:[[1602,1605,1581],256],64949:[[1604,1581,1605],256],64950:[[1593,1605,1610],256],64951:[[1603,1605,1610],256],64952:[[1606,1580,1581],256],64953:[[1605,1582,1610],256],64954:[[1604,1580,1605],256],64955:[[1603,1605,1605],256],64956:[[1604,1580,1605],256],64957:[[1606,1580,1581],256],64958:[[1580,1581,1610],256],64959:[[1581,1580,1610],256],64960:[[1605,1580,1610],256],64961:[[1601,1605,1610],256],64962:[[1576,1581,1610],256],64963:[[1603,1605,1605],256],64964:[[1593,1580,1605],256],64965:[[1589,1605,1605],256],64966:[[1587,1582,1610],256],64967:[[1606,1580,1610],256],65008:[[1589,1604,1746],256],65009:[[1602,1604,1746],256],65010:[[1575,1604,1604,1607],256],65011:[[1575,1603,1576,1585],256],65012:[[1605,1581,1605,1583],256],65013:[[1589,1604,1593,1605],256],65014:[[1585,1587,1608,1604],256],65015:[[1593,1604,1610,1607],256],65016:[[1608,1587,1604,1605],256],65017:[[1589,1604,1609],256],65018:[[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605],256],65019:[[1580,1604,32,1580,1604,1575,1604,1607],256],65020:[[1585,1740,1575,1604],256]}, + 65024:{65040:[[44],256],65041:[[12289],256],65042:[[12290],256],65043:[[58],256],65044:[[59],256],65045:[[33],256],65046:[[63],256],65047:[[12310],256],65048:[[12311],256],65049:[[8230],256],65056:[,230],65057:[,230],65058:[,230],65059:[,230],65060:[,230],65061:[,230],65062:[,230],65072:[[8229],256],65073:[[8212],256],65074:[[8211],256],65075:[[95],256],65076:[[95],256],65077:[[40],256],65078:[[41],256],65079:[[123],256],65080:[[125],256],65081:[[12308],256],65082:[[12309],256],65083:[[12304],256],65084:[[12305],256],65085:[[12298],256],65086:[[12299],256],65087:[[12296],256],65088:[[12297],256],65089:[[12300],256],65090:[[12301],256],65091:[[12302],256],65092:[[12303],256],65095:[[91],256],65096:[[93],256],65097:[[8254],256],65098:[[8254],256],65099:[[8254],256],65100:[[8254],256],65101:[[95],256],65102:[[95],256],65103:[[95],256],65104:[[44],256],65105:[[12289],256],65106:[[46],256],65108:[[59],256],65109:[[58],256],65110:[[63],256],65111:[[33],256],65112:[[8212],256],65113:[[40],256],65114:[[41],256],65115:[[123],256],65116:[[125],256],65117:[[12308],256],65118:[[12309],256],65119:[[35],256],65120:[[38],256],65121:[[42],256],65122:[[43],256],65123:[[45],256],65124:[[60],256],65125:[[62],256],65126:[[61],256],65128:[[92],256],65129:[[36],256],65130:[[37],256],65131:[[64],256],65136:[[32,1611],256],65137:[[1600,1611],256],65138:[[32,1612],256],65140:[[32,1613],256],65142:[[32,1614],256],65143:[[1600,1614],256],65144:[[32,1615],256],65145:[[1600,1615],256],65146:[[32,1616],256],65147:[[1600,1616],256],65148:[[32,1617],256],65149:[[1600,1617],256],65150:[[32,1618],256],65151:[[1600,1618],256],65152:[[1569],256],65153:[[1570],256],65154:[[1570],256],65155:[[1571],256],65156:[[1571],256],65157:[[1572],256],65158:[[1572],256],65159:[[1573],256],65160:[[1573],256],65161:[[1574],256],65162:[[1574],256],65163:[[1574],256],65164:[[1574],256],65165:[[1575],256],65166:[[1575],256],65167:[[1576],256],65168:[[1576],256],65169:[[1576],256],65170:[[1576],256],65171:[[1577],256],65172:[[1577],256],65173:[[1578],256],65174:[[1578],256],65175:[[1578],256],65176:[[1578],256],65177:[[1579],256],65178:[[1579],256],65179:[[1579],256],65180:[[1579],256],65181:[[1580],256],65182:[[1580],256],65183:[[1580],256],65184:[[1580],256],65185:[[1581],256],65186:[[1581],256],65187:[[1581],256],65188:[[1581],256],65189:[[1582],256],65190:[[1582],256],65191:[[1582],256],65192:[[1582],256],65193:[[1583],256],65194:[[1583],256],65195:[[1584],256],65196:[[1584],256],65197:[[1585],256],65198:[[1585],256],65199:[[1586],256],65200:[[1586],256],65201:[[1587],256],65202:[[1587],256],65203:[[1587],256],65204:[[1587],256],65205:[[1588],256],65206:[[1588],256],65207:[[1588],256],65208:[[1588],256],65209:[[1589],256],65210:[[1589],256],65211:[[1589],256],65212:[[1589],256],65213:[[1590],256],65214:[[1590],256],65215:[[1590],256],65216:[[1590],256],65217:[[1591],256],65218:[[1591],256],65219:[[1591],256],65220:[[1591],256],65221:[[1592],256],65222:[[1592],256],65223:[[1592],256],65224:[[1592],256],65225:[[1593],256],65226:[[1593],256],65227:[[1593],256],65228:[[1593],256],65229:[[1594],256],65230:[[1594],256],65231:[[1594],256],65232:[[1594],256],65233:[[1601],256],65234:[[1601],256],65235:[[1601],256],65236:[[1601],256],65237:[[1602],256],65238:[[1602],256],65239:[[1602],256],65240:[[1602],256],65241:[[1603],256],65242:[[1603],256],65243:[[1603],256],65244:[[1603],256],65245:[[1604],256],65246:[[1604],256],65247:[[1604],256],65248:[[1604],256],65249:[[1605],256],65250:[[1605],256],65251:[[1605],256],65252:[[1605],256],65253:[[1606],256],65254:[[1606],256],65255:[[1606],256],65256:[[1606],256],65257:[[1607],256],65258:[[1607],256],65259:[[1607],256],65260:[[1607],256],65261:[[1608],256],65262:[[1608],256],65263:[[1609],256],65264:[[1609],256],65265:[[1610],256],65266:[[1610],256],65267:[[1610],256],65268:[[1610],256],65269:[[1604,1570],256],65270:[[1604,1570],256],65271:[[1604,1571],256],65272:[[1604,1571],256],65273:[[1604,1573],256],65274:[[1604,1573],256],65275:[[1604,1575],256],65276:[[1604,1575],256]}, + 65280:{65281:[[33],256],65282:[[34],256],65283:[[35],256],65284:[[36],256],65285:[[37],256],65286:[[38],256],65287:[[39],256],65288:[[40],256],65289:[[41],256],65290:[[42],256],65291:[[43],256],65292:[[44],256],65293:[[45],256],65294:[[46],256],65295:[[47],256],65296:[[48],256],65297:[[49],256],65298:[[50],256],65299:[[51],256],65300:[[52],256],65301:[[53],256],65302:[[54],256],65303:[[55],256],65304:[[56],256],65305:[[57],256],65306:[[58],256],65307:[[59],256],65308:[[60],256],65309:[[61],256],65310:[[62],256],65311:[[63],256],65312:[[64],256],65313:[[65],256],65314:[[66],256],65315:[[67],256],65316:[[68],256],65317:[[69],256],65318:[[70],256],65319:[[71],256],65320:[[72],256],65321:[[73],256],65322:[[74],256],65323:[[75],256],65324:[[76],256],65325:[[77],256],65326:[[78],256],65327:[[79],256],65328:[[80],256],65329:[[81],256],65330:[[82],256],65331:[[83],256],65332:[[84],256],65333:[[85],256],65334:[[86],256],65335:[[87],256],65336:[[88],256],65337:[[89],256],65338:[[90],256],65339:[[91],256],65340:[[92],256],65341:[[93],256],65342:[[94],256],65343:[[95],256],65344:[[96],256],65345:[[97],256],65346:[[98],256],65347:[[99],256],65348:[[100],256],65349:[[101],256],65350:[[102],256],65351:[[103],256],65352:[[104],256],65353:[[105],256],65354:[[106],256],65355:[[107],256],65356:[[108],256],65357:[[109],256],65358:[[110],256],65359:[[111],256],65360:[[112],256],65361:[[113],256],65362:[[114],256],65363:[[115],256],65364:[[116],256],65365:[[117],256],65366:[[118],256],65367:[[119],256],65368:[[120],256],65369:[[121],256],65370:[[122],256],65371:[[123],256],65372:[[124],256],65373:[[125],256],65374:[[126],256],65375:[[10629],256],65376:[[10630],256],65377:[[12290],256],65378:[[12300],256],65379:[[12301],256],65380:[[12289],256],65381:[[12539],256],65382:[[12530],256],65383:[[12449],256],65384:[[12451],256],65385:[[12453],256],65386:[[12455],256],65387:[[12457],256],65388:[[12515],256],65389:[[12517],256],65390:[[12519],256],65391:[[12483],256],65392:[[12540],256],65393:[[12450],256],65394:[[12452],256],65395:[[12454],256],65396:[[12456],256],65397:[[12458],256],65398:[[12459],256],65399:[[12461],256],65400:[[12463],256],65401:[[12465],256],65402:[[12467],256],65403:[[12469],256],65404:[[12471],256],65405:[[12473],256],65406:[[12475],256],65407:[[12477],256],65408:[[12479],256],65409:[[12481],256],65410:[[12484],256],65411:[[12486],256],65412:[[12488],256],65413:[[12490],256],65414:[[12491],256],65415:[[12492],256],65416:[[12493],256],65417:[[12494],256],65418:[[12495],256],65419:[[12498],256],65420:[[12501],256],65421:[[12504],256],65422:[[12507],256],65423:[[12510],256],65424:[[12511],256],65425:[[12512],256],65426:[[12513],256],65427:[[12514],256],65428:[[12516],256],65429:[[12518],256],65430:[[12520],256],65431:[[12521],256],65432:[[12522],256],65433:[[12523],256],65434:[[12524],256],65435:[[12525],256],65436:[[12527],256],65437:[[12531],256],65438:[[12441],256],65439:[[12442],256],65440:[[12644],256],65441:[[12593],256],65442:[[12594],256],65443:[[12595],256],65444:[[12596],256],65445:[[12597],256],65446:[[12598],256],65447:[[12599],256],65448:[[12600],256],65449:[[12601],256],65450:[[12602],256],65451:[[12603],256],65452:[[12604],256],65453:[[12605],256],65454:[[12606],256],65455:[[12607],256],65456:[[12608],256],65457:[[12609],256],65458:[[12610],256],65459:[[12611],256],65460:[[12612],256],65461:[[12613],256],65462:[[12614],256],65463:[[12615],256],65464:[[12616],256],65465:[[12617],256],65466:[[12618],256],65467:[[12619],256],65468:[[12620],256],65469:[[12621],256],65470:[[12622],256],65474:[[12623],256],65475:[[12624],256],65476:[[12625],256],65477:[[12626],256],65478:[[12627],256],65479:[[12628],256],65482:[[12629],256],65483:[[12630],256],65484:[[12631],256],65485:[[12632],256],65486:[[12633],256],65487:[[12634],256],65490:[[12635],256],65491:[[12636],256],65492:[[12637],256],65493:[[12638],256],65494:[[12639],256],65495:[[12640],256],65498:[[12641],256],65499:[[12642],256],65500:[[12643],256],65504:[[162],256],65505:[[163],256],65506:[[172],256],65507:[[175],256],65508:[[166],256],65509:[[165],256],65510:[[8361],256],65512:[[9474],256],65513:[[8592],256],65514:[[8593],256],65515:[[8594],256],65516:[[8595],256],65517:[[9632],256],65518:[[9675],256]} +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/implement.js new file mode 100644 index 00000000000000..cfc710ea439174 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'normalize', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/index.js new file mode 100644 index 00000000000000..619b0965d69b9e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.normalize + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/is-implemented.js new file mode 100644 index 00000000000000..67c8d8da5cad63 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'æøåäüö'; + +module.exports = function () { + if (typeof str.normalize !== 'function') return false; + return str.normalize('NFKD') === 'æøåäüö'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/shim.js new file mode 100644 index 00000000000000..a379989775737a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/normalize/shim.js @@ -0,0 +1,289 @@ +// Taken from: https://github.com/walling/unorm/blob/master/lib/unorm.js + +/* + * UnicodeNormalizer 1.0.0 + * Copyright (c) 2008 Matsuza + * Dual licensed under the MIT (MIT-LICENSE.txt) and + * GPL (GPL-LICENSE.txt) licenses. + * $Date: 2008-06-05 16:44:17 +0200 (Thu, 05 Jun 2008) $ + * $Rev: 13309 $ +*/ + +'use strict'; + +var primitiveSet = require('../../../object/primitive-set') + , validValue = require('../../../object/valid-value') + , data = require('./_data') + + , floor = Math.floor + , forms = primitiveSet('NFC', 'NFD', 'NFKC', 'NFKD') + + , DEFAULT_FEATURE = [null, 0, {}], CACHE_THRESHOLD = 10, SBase = 0xAC00 + , LBase = 0x1100, VBase = 0x1161, TBase = 0x11A7, LCount = 19, VCount = 21 + , TCount = 28, NCount = VCount * TCount, SCount = LCount * NCount + , UChar, cache = {}, cacheCounter = [], i, fromCache, fromData, fromCpOnly + , fromRuleBasedJamo, fromCpFilter, strategies, UCharIterator + , RecursDecompIterator, DecompIterator, CompIterator, createIterator + , normalize; + +UChar = function (cp, feature) { + this.codepoint = cp; + this.feature = feature; +}; + +// Strategies +for (i = 0; i <= 0xFF; ++i) cacheCounter[i] = 0; + +fromCache = function (next, cp, needFeature) { + var ret = cache[cp]; + if (!ret) { + ret = next(cp, needFeature); + if (!!ret.feature && ++cacheCounter[(cp >> 8) & 0xFF] > CACHE_THRESHOLD) { + cache[cp] = ret; + } + } + return ret; +}; + +fromData = function (next, cp, needFeature) { + var hash = cp & 0xFF00, dunit = UChar.udata[hash] || {}, f = dunit[cp]; + return f ? new UChar(cp, f) : new UChar(cp, DEFAULT_FEATURE); +}; +fromCpOnly = function (next, cp, needFeature) { + return !!needFeature ? next(cp, needFeature) : new UChar(cp, null); +}; + +fromRuleBasedJamo = function (next, cp, needFeature) { + var c, base, i, arr, SIndex, TIndex, feature, j; + if (cp < LBase || (LBase + LCount <= cp && cp < SBase) || + (SBase + SCount < cp)) { + return next(cp, needFeature); + } + if (LBase <= cp && cp < LBase + LCount) { + c = {}; + base = (cp - LBase) * VCount; + for (i = 0; i < VCount; ++i) { + c[VBase + i] = SBase + TCount * (i + base); + } + arr = new Array(3); + arr[2] = c; + return new UChar(cp, arr); + } + + SIndex = cp - SBase; + TIndex = SIndex % TCount; + feature = []; + if (TIndex !== 0) { + feature[0] = [SBase + SIndex - TIndex, TBase + TIndex]; + } else { + feature[0] = [LBase + floor(SIndex / NCount), VBase + + floor((SIndex % NCount) / TCount)]; + feature[2] = {}; + for (j = 1; j < TCount; ++j) { + feature[2][TBase + j] = cp + j; + } + } + return new UChar(cp, feature); +}; + +fromCpFilter = function (next, cp, needFeature) { + return (cp < 60) || ((13311 < cp) && (cp < 42607)) + ? new UChar(cp, DEFAULT_FEATURE) : next(cp, needFeature); +}; + +strategies = [fromCpFilter, fromCache, fromCpOnly, fromRuleBasedJamo, fromData]; + +UChar.fromCharCode = strategies.reduceRight(function (next, strategy) { + return function (cp, needFeature) { return strategy(next, cp, needFeature); }; +}, null); + +UChar.isHighSurrogate = function (cp) { return cp >= 0xD800 && cp <= 0xDBFF; }; +UChar.isLowSurrogate = function (cp) { return cp >= 0xDC00 && cp <= 0xDFFF; }; + +UChar.prototype.prepFeature = function () { + if (!this.feature) { + this.feature = UChar.fromCharCode(this.codepoint, true).feature; + } +}; + +UChar.prototype.toString = function () { + var x; + if (this.codepoint < 0x10000) return String.fromCharCode(this.codepoint); + x = this.codepoint - 0x10000; + return String.fromCharCode(floor(x / 0x400) + 0xD800, x % 0x400 + 0xDC00); +}; + +UChar.prototype.getDecomp = function () { + this.prepFeature(); + return this.feature[0] || null; +}; + +UChar.prototype.isCompatibility = function () { + this.prepFeature(); + return !!this.feature[1] && (this.feature[1] & (1 << 8)); +}; +UChar.prototype.isExclude = function () { + this.prepFeature(); + return !!this.feature[1] && (this.feature[1] & (1 << 9)); +}; +UChar.prototype.getCanonicalClass = function () { + this.prepFeature(); + return !!this.feature[1] ? (this.feature[1] & 0xff) : 0; +}; +UChar.prototype.getComposite = function (following) { + var cp; + this.prepFeature(); + if (!this.feature[2]) return null; + cp = this.feature[2][following.codepoint]; + return cp ? UChar.fromCharCode(cp) : null; +}; + +UCharIterator = function (str) { + this.str = str; + this.cursor = 0; +}; +UCharIterator.prototype.next = function () { + if (!!this.str && this.cursor < this.str.length) { + var cp = this.str.charCodeAt(this.cursor++), d; + if (UChar.isHighSurrogate(cp) && this.cursor < this.str.length && + UChar.isLowSurrogate((d = this.str.charCodeAt(this.cursor)))) { + cp = (cp - 0xD800) * 0x400 + (d - 0xDC00) + 0x10000; + ++this.cursor; + } + return UChar.fromCharCode(cp); + } + this.str = null; + return null; +}; + +RecursDecompIterator = function (it, cano) { + this.it = it; + this.canonical = cano; + this.resBuf = []; +}; + +RecursDecompIterator.prototype.next = function () { + var recursiveDecomp, uchar; + recursiveDecomp = function (cano, uchar) { + var decomp = uchar.getDecomp(), ret, i, a, j; + if (!!decomp && !(cano && uchar.isCompatibility())) { + ret = []; + for (i = 0; i < decomp.length; ++i) { + a = recursiveDecomp(cano, UChar.fromCharCode(decomp[i])); + //ret.concat(a); //<-why does not this work? + //following block is a workaround. + for (j = 0; j < a.length; ++j) ret.push(a[j]); + } + return ret; + } + return [uchar]; + }; + if (this.resBuf.length === 0) { + uchar = this.it.next(); + if (!uchar) return null; + this.resBuf = recursiveDecomp(this.canonical, uchar); + } + return this.resBuf.shift(); +}; + +DecompIterator = function (it) { + this.it = it; + this.resBuf = []; +}; + +DecompIterator.prototype.next = function () { + var cc, uchar, inspt, uchar2, cc2; + if (this.resBuf.length === 0) { + do { + uchar = this.it.next(); + if (!uchar) break; + cc = uchar.getCanonicalClass(); + inspt = this.resBuf.length; + if (cc !== 0) { + for (inspt; inspt > 0; --inspt) { + uchar2 = this.resBuf[inspt - 1]; + cc2 = uchar2.getCanonicalClass(); + if (cc2 <= cc) break; + } + } + this.resBuf.splice(inspt, 0, uchar); + } while (cc !== 0); + } + return this.resBuf.shift(); +}; + +CompIterator = function (it) { + this.it = it; + this.procBuf = []; + this.resBuf = []; + this.lastClass = null; +}; + +CompIterator.prototype.next = function () { + var uchar, starter, composite, cc; + while (this.resBuf.length === 0) { + uchar = this.it.next(); + if (!uchar) { + this.resBuf = this.procBuf; + this.procBuf = []; + break; + } + if (this.procBuf.length === 0) { + this.lastClass = uchar.getCanonicalClass(); + this.procBuf.push(uchar); + } else { + starter = this.procBuf[0]; + composite = starter.getComposite(uchar); + cc = uchar.getCanonicalClass(); + if (!!composite && (this.lastClass < cc || this.lastClass === 0)) { + this.procBuf[0] = composite; + } else { + if (cc === 0) { + this.resBuf = this.procBuf; + this.procBuf = []; + } + this.lastClass = cc; + this.procBuf.push(uchar); + } + } + } + return this.resBuf.shift(); +}; + +createIterator = function (mode, str) { + switch (mode) { + case "NFD": + return new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), true) + ); + case "NFKD": + return new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), false) + ); + case "NFC": + return new CompIterator(new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), true) + )); + case "NFKC": + return new CompIterator(new DecompIterator( + new RecursDecompIterator(new UCharIterator(str), false) + )); + } + throw mode + " is invalid"; +}; +normalize = function (mode, str) { + var it = createIterator(mode, str), ret = "", uchar; + while (!!(uchar = it.next())) ret += uchar.toString(); + return ret; +}; + +/* Unicode data */ +UChar.udata = data; + +module.exports = function (/*form*/) { + var str = String(validValue(this)), form = arguments[0]; + if (form === undefined) form = 'NFC'; + else form = String(form); + if (!forms[form]) throw new RangeError('Invalid normalization form: ' + form); + return normalize(form, str); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/pad.js new file mode 100644 index 00000000000000..f227f239de98c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/pad.js @@ -0,0 +1,18 @@ +'use strict'; + +var toInteger = require('../../number/to-integer') + , value = require('../../object/valid-value') + , repeat = require('./repeat') + + , abs = Math.abs, max = Math.max; + +module.exports = function (fill/*, length*/) { + var self = String(value(this)) + , sLength = self.length + , length = arguments[1]; + + length = isNaN(length) ? 1 : toInteger(length); + fill = repeat.call(String(fill), abs(length)); + if (length >= 0) return fill.slice(0, max(0, length - sLength)) + self; + return self + (((sLength + length) >= 0) ? '' : fill.slice(length + sLength)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/plain-replace-all.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/plain-replace-all.js new file mode 100644 index 00000000000000..678b1cbcff4b8d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/plain-replace-all.js @@ -0,0 +1,16 @@ +'use strict'; + +var value = require('../../object/valid-value'); + +module.exports = function (search, replace) { + var index, pos = 0, str = String(value(this)), sl, rl; + search = String(search); + replace = String(replace); + sl = search.length; + rl = replace.length; + while ((index = str.indexOf(search, pos)) !== -1) { + str = str.slice(0, index) + replace + str.slice(index + sl); + pos = index + rl; + } + return str; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/plain-replace.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/plain-replace.js new file mode 100644 index 00000000000000..24ce16d3bce6e1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/plain-replace.js @@ -0,0 +1,10 @@ +'use strict'; + +var indexOf = String.prototype.indexOf, slice = String.prototype.slice; + +module.exports = function (search, replace) { + var index = indexOf.call(this, search); + if (index === -1) return String(this); + return slice.call(this, 0, index) + replace + + slice.call(this, index + String(search).length); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/implement.js new file mode 100644 index 00000000000000..4c39b9fbe66cc6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'repeat', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/index.js new file mode 100644 index 00000000000000..15a800e8de9509 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.repeat + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/is-implemented.js new file mode 100644 index 00000000000000..f7b8750f0fd8be --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/is-implemented.js @@ -0,0 +1,8 @@ +'use strict'; + +var str = 'foo'; + +module.exports = function () { + if (typeof str.repeat !== 'function') return false; + return (str.repeat(2) === 'foofoo'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/shim.js new file mode 100644 index 00000000000000..0a3928b2c0dd76 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/repeat/shim.js @@ -0,0 +1,22 @@ +// Thanks: http://www.2ality.com/2014/01/efficient-string-repeat.html + +'use strict'; + +var value = require('../../../object/valid-value') + , toInteger = require('../../../number/to-integer'); + +module.exports = function (count) { + var str = String(value(this)), result; + count = toInteger(count); + if (count < 0) throw new RangeError("Count must be >= 0"); + if (!isFinite(count)) throw new RangeError("Count must be < ∞"); + result = ''; + if (!count) return result; + while (true) { + if (count & 1) result += str; + count >>>= 1; + if (count <= 0) break; + str += str; + } + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/implement.js new file mode 100644 index 00000000000000..d4f1eaf547f4a8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String.prototype, 'startsWith', + { value: require('./shim'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/index.js new file mode 100644 index 00000000000000..ec66a7c0057878 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.prototype.startsWith + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/is-implemented.js new file mode 100644 index 00000000000000..a0556f196e9afa --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +var str = 'razdwatrzy'; + +module.exports = function () { + if (typeof str.startsWith !== 'function') return false; + return ((str.startsWith('trzy') === false) && + (str.startsWith('raz') === true)); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/shim.js new file mode 100644 index 00000000000000..aa5aaf4145ea58 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/#/starts-with/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var value = require('../../../object/valid-value') + , toInteger = require('../../../number/to-integer') + + , max = Math.max, min = Math.min; + +module.exports = function (searchString/*, position*/) { + var start, self = String(value(this)); + start = min(max(toInteger(arguments[1]), 0), self.length); + return (self.indexOf(searchString, start) === start); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/format-method.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/format-method.js new file mode 100644 index 00000000000000..f1de1e301d4238 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/format-method.js @@ -0,0 +1,24 @@ +'use strict'; + +var isCallable = require('../object/is-callable') + , value = require('../object/valid-value') + + , call = Function.prototype.call; + +module.exports = function (fmap) { + fmap = Object(value(fmap)); + return function (pattern) { + var context = value(this); + pattern = String(pattern); + return pattern.replace(/%([a-zA-Z]+)|\\([\u0000-\uffff])/g, + function (match, token, escape) { + var t, r; + if (escape) return escape; + t = token; + while (t && !(r = fmap[t])) t = t.slice(0, -1); + if (!r) return match; + if (isCallable(r)) r = call.call(r, context); + return r + token.slice(t.length); + }); + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/implement.js new file mode 100644 index 00000000000000..b062331cc597e2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String, 'fromCodePoint', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/index.js new file mode 100644 index 00000000000000..3f3110b6eb1f5a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.fromCodePoint + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/is-implemented.js new file mode 100644 index 00000000000000..840a20e3f36d87 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/is-implemented.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function () { + var fromCodePoint = String.fromCodePoint; + if (typeof fromCodePoint !== 'function') return false; + return fromCodePoint(0x1D306, 0x61, 0x1D307) === '\ud834\udf06a\ud834\udf07'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/shim.js new file mode 100644 index 00000000000000..41fd7378f81c53 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/from-code-point/shim.js @@ -0,0 +1,30 @@ +// Based on: +// http://norbertlindenberg.com/2012/05/ecmascript-supplementary-characters/ +// and: +// https://github.com/mathiasbynens/String.fromCodePoint/blob/master +// /fromcodepoint.js + +'use strict'; + +var floor = Math.floor, fromCharCode = String.fromCharCode; + +module.exports = function (codePoint/*, …codePoints*/) { + var chars = [], l = arguments.length, i, c, result = ''; + for (i = 0; i < l; ++i) { + c = Number(arguments[i]); + if (!isFinite(c) || c < 0 || c > 0x10FFFF || floor(c) !== c) { + throw new RangeError("Invalid code point " + c); + } + + if (c < 0x10000) { + chars.push(c); + } else { + c -= 0x10000; + chars.push((c >> 10) + 0xD800, (c % 0x400) + 0xDC00); + } + if (i + 1 !== l && chars.length <= 0x4000) continue; + result += fromCharCode.apply(null, chars); + chars.length = 0; + } + return result; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/index.js new file mode 100644 index 00000000000000..dbbcdf61f06cd8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + '#': require('./#'), + formatMethod: require('./format-method'), + fromCodePoint: require('./from-code-point'), + isString: require('./is-string'), + randomUniq: require('./random-uniq'), + raw: require('./raw') +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/is-string.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/is-string.js new file mode 100644 index 00000000000000..719aeec16c5aa5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/is-string.js @@ -0,0 +1,10 @@ +'use strict'; + +var toString = Object.prototype.toString + + , id = toString.call(''); + +module.exports = function (x) { + return (typeof x === 'string') || (x && (typeof x === 'object') && + ((x instanceof String) || (toString.call(x) === id))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/random-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/random-uniq.js new file mode 100644 index 00000000000000..54ae6f8c9fd3c3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/random-uniq.js @@ -0,0 +1,11 @@ +'use strict'; + +var generated = Object.create(null) + + , random = Math.random; + +module.exports = function () { + var str; + do { str = random().toString(36).slice(2); } while (generated[str]); + return str; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/implement.js new file mode 100644 index 00000000000000..c417e659b2086c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(String, 'raw', { value: require('./shim'), + configurable: true, enumerable: false, writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/index.js new file mode 100644 index 00000000000000..504a5de24bf3ce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = require('./is-implemented')() + ? String.raw + : require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/is-implemented.js new file mode 100644 index 00000000000000..d7204c0c49e8a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/is-implemented.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function () { + var raw = String.raw, test; + if (typeof raw !== 'function') return false; + test = ['foo\nbar', 'marko\n']; + test.raw = ['foo\\nbar', 'marko\\n']; + return raw(test, 'INSE\nRT') === 'foo\\nbarINSE\nRTmarko\\n'; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/shim.js new file mode 100644 index 00000000000000..7096efbc5671d1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/string/raw/shim.js @@ -0,0 +1,15 @@ +'use strict'; + +var toPosInt = require('../../number/to-pos-integer') + , validValue = require('../../object/valid-value') + + , reduce = Array.prototype.reduce; + +module.exports = function (callSite/*, …substitutions*/) { + var args, rawValue = Object(validValue(Object(validValue(callSite)).raw)); + if (!toPosInt(rawValue.length)) return ''; + args = arguments; + return reduce.call(rawValue, function (a, b, i) { + return a + String(args[i]) + b; + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/__tad.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/__tad.js new file mode 100644 index 00000000000000..884577887f5704 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/__tad.js @@ -0,0 +1,3 @@ +'use strict'; + +exports.context = null; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/implement.js new file mode 100644 index 00000000000000..f0605399e0274e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/@@iterator/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/shim.js new file mode 100644 index 00000000000000..e590d8f28e7c0e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/@@iterator/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: '1', done: false }); + a.deep(iterator.next(), { value: '2', done: false }); + a.deep(iterator.next(), { value: '3', done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/_compare-by-length.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/_compare-by-length.js new file mode 100644 index 00000000000000..e40c305b98fe68 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/_compare-by-length.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + var x = [4, 5, 6], y = { length: 8 }, w = {}, z = { length: 1 }; + + a.deep([x, y, w, z].sort(t), [w, z, x, y]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/binary-search.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/binary-search.js new file mode 100644 index 00000000000000..cf3317371b3491 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/binary-search.js @@ -0,0 +1,15 @@ +'use strict'; + +var compare = function (value) { return this - value; }; + +module.exports = function (t, a) { + var arr; + arr = [2, 5, 5, 8, 34, 67, 98, 345, 678]; + + // highest, equal match + a(t.call(arr, compare.bind(1)), 0, "All higher"); + a(t.call(arr, compare.bind(679)), arr.length - 1, "All lower"); + a(t.call(arr, compare.bind(4)), 0, "Mid"); + a(t.call(arr, compare.bind(5)), 2, "Match"); + a(t.call(arr, compare.bind(6)), 2, "Above"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/clear.js new file mode 100644 index 00000000000000..a5b1c977ad98cf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/clear.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + var x = [1, 2, {}, 4]; + a(t.call(x), x, "Returns same array"); + a.deep(x, [], "Empties array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/compact.js new file mode 100644 index 00000000000000..6390eb26dddf6b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/compact.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a(t.call(this).length, 3); + }, + "": function (t, a) { + var o, x, y, z; + o = {}; + x = [0, 1, "", null, o, false, undefined, true]; + y = x.slice(0); + + a.not(z = t.call(x), x, "Returns different object"); + a.deep(x, y, "Origin not changed"); + a.deep(z, [0, 1, "", o, false, true], "Result"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/implement.js new file mode 100644 index 00000000000000..3bdbe86812aaaa --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/concat/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/shim.js new file mode 100644 index 00000000000000..c30eb7eab08178 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/concat/shim.js @@ -0,0 +1,26 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr = [1, 3, 45], x = {}, subArr, subArr2, result; + + a.deep(t.call(arr, '2d', x, ['ere', 'fe', x], false, null), + [1, 3, 45, '2d', x, 'ere', 'fe', x, false, null], "Plain array"); + + subArr = new SubArray('lol', 'miszko'); + subArr2 = new SubArray('elo', 'fol'); + + result = t.call(subArr, 'df', arr, 'fef', subArr2, null); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, ['lol', 'miszko', 'df', 1, 3, 45, 'fef', 'elo', 'fol', null], + "Spreable by default"); + + SubArray.prototype['@@isConcatSpreadable'] = false; + + result = t.call(subArr, 'df', arr, 'fef', subArr2, null); + a.deep(result, ['lol', 'miszko', 'df', 1, 3, 45, 'fef', subArr2, null], + "Non spreadable"); + + delete SubArray.prototype['@@isConcatSpreadable']; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/contains.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/contains.js new file mode 100644 index 00000000000000..21404a17a61358 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/contains.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a(t.call(this, this[1]), true, "Contains"); + a(t.call(this, {}), false, "Does Not contain"); + }, + "": function (t, a) { + var o, x = {}, y = {}; + + o = [1, 'raz', x]; + + a(t.call(o, 1), true, "First"); + a(t.call(o, '1'), false, "Type coercion"); + a(t.call(o, 'raz'), true, "Primitive"); + a(t.call(o, 'foo'), false, "Primitive not found"); + a(t.call(o, x), true, "Object found"); + a(t.call(o, y), false, "Object not found"); + a(t.call(o, 1, 1), false, "Position"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/implement.js new file mode 100644 index 00000000000000..36070477d66802 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/copy-within/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/shim.js new file mode 100644 index 00000000000000..93c85ea3114c24 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/copy-within/shim.js @@ -0,0 +1,29 @@ +'use strict'; + +module.exports = function (t, a) { + var args, x; + + a.h1("2 args"); + x = [1, 2, 3, 4, 5]; + t.call(x, 0, 3); + a.deep(x, [4, 5, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 3), [1, 4, 5, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 2), [1, 3, 4, 5, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 2, 2), [1, 2, 3, 4, 5]); + + a.h1("3 args"); + a.deep(t.call([1, 2, 3, 4, 5], 0, 3, 4), [4, 2, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 3, 4), [1, 4, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 1, 2, 4), [1, 3, 4, 4, 5]); + + a.h1("Negative args"); + a.deep(t.call([1, 2, 3, 4, 5], 0, -2), [4, 5, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], 0, -2, -1), [4, 2, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], -4, -3, -2), [1, 3, 3, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], -4, -3, -1), [1, 3, 4, 4, 5]); + a.deep(t.call([1, 2, 3, 4, 5], -4, -3), [1, 3, 4, 5, 5]); + + a.h1("Array-likes"); + args = { 0: 1, 1: 2, 2: 3, length: 3 }; + a.deep(t.call(args, -2, 0), { '0': 1, '1': 1, '2': 2, length: 3 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/diff.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/diff.js new file mode 100644 index 00000000000000..bcfa3a0bd12f84 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/diff.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a.deep(t.call(this, this), []); + }, + "": function (t, a) { + var x = {}, y = {}; + + a.deep(t.call([1, 'raz', x, 2, 'trzy', y], [x, 2, 'trzy']), [1, 'raz', y], + "Scope longer"); + a.deep(t.call([1, 'raz', x], [x, 2, 'trzy', 1, y]), ['raz'], + "Arg longer"); + a.deep(t.call([1, 'raz', x], []), [1, 'raz', x], "Empty arg"); + a.deep(t.call([], [1, y, 'sdfs']), [], "Empty scope"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/e-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/e-index-of.js new file mode 100644 index 00000000000000..4cf6c6359d44ee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/e-index-of.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([3, 'raz', {}, x, {}], x), 3, "Regular"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN), 2, "NaN"); + a(t.call([3, 'raz', 0, {}, -0], -0), 2, "-0"); + a(t.call([3, 'raz', -0, {}, 0], +0), 2, "+0"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, 3), 4, "fromIndex"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, -1), 4, "fromIndex negative #1"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, -2), 4, "fromIndex negative #2"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, -3), 2, "fromIndex negative #3"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/e-last-index-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/e-last-index-of.js new file mode 100644 index 00000000000000..ed4f700421a8f1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/e-last-index-of.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([3, 'raz', {}, x, {}, x], x), 5, "Regular"); + a(t.call([3, 'raz', NaN, {}, x], NaN), 2, "NaN"); + a(t.call([3, 'raz', 0, {}, -0], -0), 4, "-0"); + a(t.call([3, 'raz', -0, {}, 0], +0), 4, "+0"); + a(t.call([3, 'raz', NaN, {}, NaN], NaN, 3), 2, "fromIndex"); + a(t.call([3, 'raz', NaN, 2, NaN], NaN, -1), 4, "Negative fromIndex #1"); + a(t.call([3, 'raz', NaN, 2, NaN], NaN, -2), 2, "Negative fromIndex #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/implement.js new file mode 100644 index 00000000000000..733209a1c80653 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/entries/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/shim.js new file mode 100644 index 00000000000000..bf40d31005df45 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/entries/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: [0, '1'], done: false }); + a.deep(iterator.next(), { value: [1, '2'], done: false }); + a.deep(iterator.next(), { value: [2, '3'], done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/exclusion.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/exclusion.js new file mode 100644 index 00000000000000..07b32d8e8cbf9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/exclusion.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var x = {}; + a.deep(t.call(this, this, [this[0], this[2], x]), [x]); + }, + "": function (t, a) { + var x = {}, y = {}; + + a.deep(t.call([x, y]), [x, y], "No arguments"); + a.deep(t.call([x, 1], [], []), [x, 1], "Empty arguments"); + a.deep(t.call([1, 'raz', x], [2, 'raz', y], [2, 'raz', x]), [1, y]); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/implement.js new file mode 100644 index 00000000000000..2a01d2850a18a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/fill/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/shim.js new file mode 100644 index 00000000000000..d67300fcc23be8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/fill/shim.js @@ -0,0 +1,18 @@ +// Taken from https://github.com/paulmillr/es6-shim/blob/master/test/array.js + +'use strict'; + +module.exports = function (t, a) { + var x; + + x = [1, 2, 3, 4, 5, 6]; + a(t.call(x, -1), x, "Returns self object"); + a.deep(x, [-1, -1, -1, -1, -1, -1], "Value"); + + a.deep(t.call([1, 2, 3, 4, 5, 6], -1, 3), [1, 2, 3, -1, -1, -1], + "Positive start"); + a.deep(t.call([1, 2, 3, 4, 5, 6], -1, -3), [1, 2, 3, -1, -1, -1], + "Negative start"); + a.deep(t.call([1, 2, 3, 4, 5, 6], -1, 9), [1, 2, 3, 4, 5, 6], + "Large start"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/implement.js new file mode 100644 index 00000000000000..6d6b87cc30a651 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/filter/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/shim.js new file mode 100644 index 00000000000000..e8b5c39849097f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/filter/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, Boolean), ['foo', '2d', x], "Plain array"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, Boolean); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, ['foo', '2d', x], "Result of subclass"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/implement.js new file mode 100644 index 00000000000000..8d85e618ccd6bc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/find-index/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/shim.js new file mode 100644 index 00000000000000..b5fee463811d49 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find-index/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +exports.__generic = function (t, a) { + var count = 0, o = {}, self = Object(this); + a(t.call(self, function (value, i, scope) { + a(value, this[i], "Value"); + a(i, count++, "Index"); + a(scope, this, "Scope"); + }, self), -1, "Falsy result"); + a(count, 3); + + count = -1; + a(t.call(this, function () { + return ++count ? o : null; + }, this), 1, "Truthy result"); + a(count, 1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/implement.js new file mode 100644 index 00000000000000..29fac41e013353 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/find/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/shim.js new file mode 100644 index 00000000000000..ad2e645067db5d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/find/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +exports.__generic = function (t, a) { + var count = 0, o = {}, self = Object(this); + a(t.call(self, function (value, i, scope) { + a(value, this[i], "Value"); + a(i, count++, "Index"); + a(scope, this, "Scope"); + }, self), undefined, "Falsy result"); + a(count, 3); + + count = -1; + a(t.call(this, function () { + return ++count ? o : null; + }, this), this[1], "Truthy result"); + a(count, 1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/first-index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/first-index.js new file mode 100644 index 00000000000000..4aebad64b44e51 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/first-index.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a(t.call([]), null, "Empty"); + a(t.call([null]), 0, "One value"); + a(t.call([1, 2, 3]), 0, "Many values"); + a(t.call(new Array(1000)), null, "Sparse empty"); + x = []; + x[883] = undefined; + x[890] = null; + a(t.call(x), 883, "Manual sparse, distant value"); + x = new Array(1000); + x[657] = undefined; + x[700] = null; + a(t.call(x), 657, "Sparse, distant value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/first.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/first.js new file mode 100644 index 00000000000000..87fde0357ef1b0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/first.js @@ -0,0 +1,13 @@ +'use strict'; + +exports.__generic = function (t, a) { + a(t.call(this), this[0]); +}; +exports[''] = function (t, a) { + var x; + a(t.call([]), undefined, "Empty"); + a(t.call(new Array(234), undefined, "Sparse empty")); + x = new Array(2342); + x[434] = {}; + a(t.call(x), x[434], "Sparse"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/flatten.js new file mode 100644 index 00000000000000..65f1214b04da93 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/flatten.js @@ -0,0 +1,12 @@ +'use strict'; + +var o = [1, 2, [3, 4, [5, 6], 7, 8], 9, 10]; + +module.exports = { + __generic: function (t, a) { + a(t.call(this).length, 3); + }, + "Nested Arrays": function (t, a) { + a(t.call(o).length, 10); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/for-each-right.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/for-each-right.js new file mode 100644 index 00000000000000..2d24569d94d86d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/for-each-right.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var count = 0, first, last, x, icount = this.length; + t.call(this, function (item, index, col) { + ++count; + if (!first) { + first = item; + } + last = item; + x = col; + a(index, --icount, "Index"); + }); + a(count, this.length, "Iterated"); + a(first, this[this.length - 1], "First is last"); + a(last, this[0], "Last is first"); + a.deep(x, Object(this), "Collection as third argument"); //jslint: skip + }, + "": function (t, a) { + var x = {}, y, count; + t.call([1], function () { y = this; }, x); + a(y, x, "Scope"); + y = 0; + t.call([3, 4, 4], function (a, i) { y += i; }); + a(y, 3, "Indexes"); + + x = [1, 3]; + x[5] = 'x'; + y = 0; + count = 0; + t.call(x, function (a, i) { ++count; y += i; }); + a(y, 6, "Misssing Indexes"); + a(count, 3, "Misssing Indexes, count"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/group.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/group.js new file mode 100644 index 00000000000000..32dc8c2dbb68bf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/group.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var count = 0, self; + + self = Object(this); + a.deep(t.call(self, function (v, i, scope) { + a(v, this[i], "Value"); + a(i, count++, "Index"); + a(scope, this, "Scope"); + return i; + }, self), { 0: [this[0]], 1: [this[1]], 2: [this[2]] }); + }, + "": function (t, a) { + var r; + r = t.call([2, 3, 3, 4, 5, 6, 7, 7, 23, 45, 34, 56], + function (v) { + return v % 2 ? 'odd' : 'even'; + }); + a.deep(r.odd, [3, 3, 5, 7, 7, 23, 45]); + a.deep(r.even, [2, 4, 6, 34, 56]); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/indexes-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/indexes-of.js new file mode 100644 index 00000000000000..3364170f1ec4a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/indexes-of.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a.deep(t.call(this, this[1]), [1]); + }, + "": function (t, a) { + var x = {}; + a.deep(t.call([1, 3, 5, 3, 5], 6), [], "No result"); + a.deep(t.call([1, 3, 5, 1, 3, 5, 1], 1), [0, 3, 6], "Some results"); + a.deep(t.call([], x), [], "Empty array"); + a.deep(t.call([x, 3, {}, x, 3, 5, x], x), [0, 3, 6], "Search for object"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/intersection.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/intersection.js new file mode 100644 index 00000000000000..b72b2fb074fc46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/intersection.js @@ -0,0 +1,24 @@ +'use strict'; + +var toArray = require('../../../array/to-array'); + +module.exports = { + __generic: function (t, a) { + a.deep(t.call(this, this, this), toArray(this)); + }, + "": function (t, a) { + var x = {}, y = {}, p, r; + a.deep(t.call([], [2, 3, 4]), [], "Empty #1"); + a.deep(t.call([2, 3, 4], []), [], "Empty #2"); + a.deep(t.call([2, 3, x], [y, 5, 7]), [], "Different"); + p = t.call([3, 5, 'raz', {}, 'dwa', x], [1, 3, 'raz', 'dwa', 'trzy', x, {}], + [3, 'raz', x, 65]); + r = [3, 'raz', x]; + p.sort(); + r.sort(); + a.deep(p, r, "Same parts"); + a.deep(t.call(r, r), r, "Same"); + a.deep(t.call([1, 2, x, 4, 5, y, 7], [7, y, 5, 4, x, 2, 1]), + [1, 2, x, 4, 5, y, 7], "Long reverse same"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/is-copy.js new file mode 100644 index 00000000000000..e7f80e7a8d4ebc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/is-copy.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([], []), true, "Empty"); + a(t.call([], {}), true, "Empty lists"); + a(t.call([1, x, 'raz'], [1, x, 'raz']), true, "Same"); + a(t.call([1, x, 'raz'], { 0: 1, 1: x, 2: 'raz', length: 3 }), true, + "Same lists"); + a(t.call([1, x, 'raz'], [x, 1, 'raz']), false, "Diff order"); + a(t.call([1, x], [1, x, 'raz']), false, "Diff length #1"); + a(t.call([1, x, 'raz'], [1, x]), false, "Diff length #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/is-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/is-uniq.js new file mode 100644 index 00000000000000..7349ba337135a7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/is-uniq.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}; + a(t.call([]), true, "Empty"); + a(t.call({}), true, "Empty lists"); + a(t.call([1, x, 'raz']), true, "Uniq"); + a(t.call([1, x, 1, 'raz']), false, "Not Uniq: primitive"); + a(t.call([1, x, '1', 'raz']), true, "Uniq: primitive"); + a(t.call([1, x, 1, {}, 'raz']), false, "Not Uniq: Obj"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/implement.js new file mode 100644 index 00000000000000..b0c1aa078f190e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/keys/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/shim.js new file mode 100644 index 00000000000000..a43c04cac103a6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/keys/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: 0, done: false }); + a.deep(iterator.next(), { value: 1, done: false }); + a.deep(iterator.next(), { value: 2, done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/last-index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/last-index.js new file mode 100644 index 00000000000000..a1cac1073f8862 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/last-index.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a(t.call([]), null, "Empty"); + a(t.call([null]), 0, "One value"); + a(t.call([1, 2, 3]), 2, "Many values"); + a(t.call(new Array(1000)), null, "Sparse empty"); + x = []; + x[883] = null; + x[890] = undefined; + a(t.call(x), 890, "Manual sparse, distant value"); + x = new Array(1000); + x[657] = null; + x[700] = undefined; + a(t.call(x), 700, "Sparse, distant value"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/last.js new file mode 100644 index 00000000000000..8d051bc8d2f5df --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/last.js @@ -0,0 +1,15 @@ +'use strict'; + +exports.__generic = function (t, a) { + a(t.call(this), this[this.length - 1]); +}; + +exports[''] = function (t, a) { + var x; + a(t.call([]), undefined, "Empty"); + a(t.call(new Array(234), undefined, "Sparse empty")); + x = new Array(2342); + x[434] = {}; + x[450] = {}; + a(t.call(x), x[450], "Sparse"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/implement.js new file mode 100644 index 00000000000000..cdcbc8df6206a5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/map/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/shim.js new file mode 100644 index 00000000000000..bbfefe8e333dc8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/map/shim.js @@ -0,0 +1,19 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, Boolean), [true, false, false, true, false, true, false], + "Plain array"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, Boolean); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, [true, false, false, true, false, true, false], + "Result of subclass"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/remove.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/remove.js new file mode 100644 index 00000000000000..3ebdca2d0183df --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/remove.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + var y = {}, z = {}, x = [9, z, 5, y, 'foo']; + t.call(x, y); + a.deep(x, [9, z, 5, 'foo']); + t.call(x, {}); + a.deep(x, [9, z, 5, 'foo'], "Not existing"); + t.call(x, 5); + a.deep(x, [9, z, 'foo'], "Primitive"); + x = [9, z, 5, y, 'foo']; + t.call(x, z, 5, 'foo'); + a.deep(x, [9, y], "More than one argument"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/separate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/separate.js new file mode 100644 index 00000000000000..42918b59711e32 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/separate.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x = [], y = {}, z = {}; + a.deep(t.call(x, y), [], "Empty"); + a.not(t.call(x), x, "Returns copy"); + a.deep(t.call([1], y), [1], "One"); + a.deep(t.call([1, 'raz'], y), [1, y, 'raz'], "One"); + a.deep(t.call([1, 'raz', x], y), [1, y, 'raz', y, x], "More"); + x = new Array(1000); + x[23] = 2; + x[3453] = 'raz'; + x[500] = z; + a.deep(t.call(x, y), [2, y, z, y, 'raz'], "Sparse"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/implement.js new file mode 100644 index 00000000000000..855ae2fa4df88e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/slice/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/shim.js new file mode 100644 index 00000000000000..f674f3470037f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/slice/shim.js @@ -0,0 +1,17 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, 2, 4), [0, '2d'], "Plain array: result"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, 2, 4); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, [0, '2d'], "Subclass: result"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/some-right.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/some-right.js new file mode 100644 index 00000000000000..900771a6f818a4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/some-right.js @@ -0,0 +1,43 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + var count = 0, first, last, x, icount = this.length; + t.call(this, function (item, index, col) { + ++count; + if (!first) { + first = item; + } + last = item; + x = col; + a(index, --icount, "Index"); + }); + a(count, this.length, "Iterated"); + a(first, this[this.length - 1], "First is last"); + a(last, this[0], "Last is first"); + a.deep(x, Object(this), "Collection as third argument"); //jslint: skip + }, + "": function (t, a) { + var x = {}, y, count; + t.call([1], function () { y = this; }, x); + a(y, x, "Scope"); + y = 0; + t.call([3, 4, 4], function (a, i) { y += i; }); + a(y, 3, "Indexes"); + + x = [1, 3]; + x[5] = 'x'; + y = 0; + count = 0; + a(t.call(x, function (a, i) { ++count; y += i; }), false, "Return"); + a(y, 6, "Misssing Indexes"); + a(count, 3, "Misssing Indexes, count"); + + count = 0; + a(t.call([-2, -3, -4, 2, -5], function (item) { + ++count; + return item > 0; + }), true, "Return"); + a(count, 2, "Break after true is returned"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/implement.js new file mode 100644 index 00000000000000..0d9f46188b528b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/splice/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/shim.js new file mode 100644 index 00000000000000..2c751e672400e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/splice/shim.js @@ -0,0 +1,19 @@ +'use strict'; + +var SubArray = require('../../../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr, x = {}, subArr, result; + + arr = ['foo', undefined, 0, '2d', false, x, null]; + + a.deep(t.call(arr, 2, 2, 'bar'), [0, '2d'], "Plain array: result"); + a.deep(arr, ["foo", undefined, "bar", false, x, null], "Plain array: change"); + + subArr = new SubArray('foo', undefined, 0, '2d', false, x, null); + + result = t.call(subArr, 2, 2, 'bar'); + a(result instanceof SubArray, true, "Instance of subclass"); + a.deep(result, [0, '2d'], "Subclass: result"); + a.deep(subArr, ["foo", undefined, "bar", false, x, null], "Subclass: change"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/uniq.js new file mode 100644 index 00000000000000..2f7e6c4ed1feb5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/uniq.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = { + __generic: function (t, a) { + a(t.call(this).length, 3); + }, + "": function (t, a) { + var o, x = {}, y = {}, z = {}, w; + o = [1, 2, x, 3, 1, 'raz', '1', y, x, 'trzy', z, 'raz']; + + a.not(w = t.call(o), o, "Returns different object"); + a.deep(w, [1, 2, x, 3, 'raz', '1', y, 'trzy', z], "Result"); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/implement.js new file mode 100644 index 00000000000000..9f40138c254b30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../array/#/values/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/shim.js new file mode 100644 index 00000000000000..e590d8f28e7c0e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/#/values/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.__generic = function (t, a) { + var iterator = t.call(this); + a.deep(iterator.next(), { value: '1', done: false }); + a.deep(iterator.next(), { value: '2', done: false }); + a.deep(iterator.next(), { value: '3', done: false }); + a.deep(iterator.next(), { value: undefined, done: true }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/__scopes.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/__scopes.js new file mode 100644 index 00000000000000..fc240d304869bb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/__scopes.js @@ -0,0 +1,9 @@ +'use strict'; + +exports.Array = ['1', '2', '3']; + +exports.Arguments = (function () { + return arguments; +}('1', '2', '3')); + +exports.String = "123"; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_is-extensible.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_is-extensible.js new file mode 100644 index 00000000000000..d387126fe111ed --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_is-extensible.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'boolean'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_sub-array-dummy-safe.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_sub-array-dummy-safe.js new file mode 100644 index 00000000000000..29d8699d461a85 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_sub-array-dummy-safe.js @@ -0,0 +1,7 @@ +'use strict'; + +var isArray = Array.isArray; + +module.exports = function (t, a) { + t((t === null) || isArray(t.prototype), true); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_sub-array-dummy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_sub-array-dummy.js new file mode 100644 index 00000000000000..29d8699d461a85 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/_sub-array-dummy.js @@ -0,0 +1,7 @@ +'use strict'; + +var isArray = Array.isArray; + +module.exports = function (t, a) { + t((t === null) || isArray(t.prototype), true); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/implement.js new file mode 100644 index 00000000000000..e0db846f99a0d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../array/from/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/shim.js new file mode 100644 index 00000000000000..310302ac486645 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/from/shim.js @@ -0,0 +1,60 @@ +// Some tests taken from: https://github.com/mathiasbynens/Array.from/blob/master/tests/tests.js + +'use strict'; + +module.exports = function (t, a) { + var o = [1, 2, 3], MyType; + a.not(t(o), o, "Array"); + a.deep(t(o), o, "Array: same content"); + a.deep(t('12r3v'), ['1', '2', 'r', '3', 'v'], "String"); + a.deep(t((function () { return arguments; }(3, o, 'raz'))), + [3, o, 'raz'], "Arguments"); + a.deep(t((function () { return arguments; }(3))), [3], + "Arguments with one numeric value"); + + a.deep(t({ 0: 'raz', 1: 'dwa', length: 2 }), ['raz', 'dwa'], "Other"); + + a.deep(t(o, function (val) { return (val + 2) * 10; }, 10), [30, 40, 50], + "Mapping"); + + a.throws(function () { t(); }, TypeError, "Undefined"); + a.deep(t(3), [], "Primitive"); + + a(t.length, 1, "Length"); + a.deep(t({ length: 0 }), [], "No values Array-like"); + a.deep(t({ length: -1 }), [], "Invalid length Array-like"); + a.deep(t({ length: -Infinity }), [], "Invalid length Array-like #2"); + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.deep(t(false), [], "Boolean"); + a.deep(t(-Infinity), [], "Inifity"); + a.deep(t(-0), [], "-0"); + a.deep(t(+0), [], "+0"); + a.deep(t(1), [], "1"); + a.deep(t(+Infinity), [], "+Infinity"); + a.deep(t({}), [], "Plain object"); + a.deep(t({ length: 1 }), [undefined], "Sparse array-like"); + a.deep(t({ '0': 'a', '1': 'b', length: 2 }, function (x) { return x + x; }), ['aa', 'bb'], + "Map"); + a.deep(t({ '0': 'a', '1': 'b', length: 2 }, function (x) { return String(this); }, undefined), + ['undefined', 'undefined'], "Map context"); + a.deep(t({ '0': 'a', '1': 'b', length: 2 }, function (x) { return String(this); }, 'x'), + ['x', 'x'], "Map primitive context"); + a.throws(function () { t({}, 'foo', 'x'); }, TypeError, "Non callable for map"); + + a.deep(t.call(null, { length: 1, '0': 'a' }), ['a'], "Null context"); + + a(t({ __proto__: { '0': 'abc', length: 1 } })[0], 'abc', "Values on prototype"); + + a.throws(function () { t.call(function () { return Object.freeze({}); }, {}); }, + TypeError, "Contructor producing freezed objects"); + + // Ensure no setters are called for the indexes + // Ensure no setters are called for the indexes + MyType = function () {}; + Object.defineProperty(MyType.prototype, '0', { + set: function (x) { throw new Error('Setter called: ' + x); } + }); + a.deep(t.call(MyType, { '0': 'abc', length: 1 }), { '0': 'abc', length: 1 }, + "Defined not set"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/generate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/generate.js new file mode 100644 index 00000000000000..d72e056887838b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/generate.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = {}; + a.deep(t(3), [undefined, undefined, undefined], "Just length"); + a.deep(t(0, 'x'), [], "No repeat"); + a.deep(t(1, x, y), [x], "Arguments length larger than repeat number"); + a.deep(t(3, x), [x, x, x], "Single argument"); + a.deep(t(5, x, y), [x, y, x, y, x], "Many arguments"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/is-plain-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/is-plain-array.js new file mode 100644 index 00000000000000..871a08aec21ff9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/is-plain-array.js @@ -0,0 +1,18 @@ +'use strict'; + +var SubArray = require('../../array/_sub-array-dummy-safe'); + +module.exports = function (t, a) { + var arr = [1, 2, 3]; + a(t(arr), true, "Array"); + a(t(null), false, "Null"); + a(t(), false, "Undefined"); + a(t('234'), false, "String"); + a(t(23), false, "Number"); + a(t({}), false, "Plain object"); + a(t({ length: 1, 0: 'raz' }), false, "Array-like"); + a(t(Object.create(arr)), false, "Array extension"); + if (!SubArray) return; + a(t(new SubArray(23)), false, "Subclass instance"); + a(t(Array.prototype), false, "Array.prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/implement.js new file mode 100644 index 00000000000000..30d53be2d7abbe --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../array/of/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/shim.js new file mode 100644 index 00000000000000..e6974420c1c274 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/of/shim.js @@ -0,0 +1,68 @@ +// Most tests taken from https://github.com/mathiasbynens/Array.of/blob/master/tests/tests.js +// Thanks @mathiasbynens + +'use strict'; + +var defineProperty = Object.defineProperty; + +module.exports = function (t, a) { + var x = {}, testObject, MyType; + + a.deep(t(), [], "No arguments"); + a.deep(t(3), [3], "One numeric argument"); + a.deep(t(3, 'raz', null, x, undefined), [3, 'raz', null, x, undefined], + "Many arguments"); + + a(t.length, 0, "Length"); + + a.deep(t('abc'), ['abc'], "String"); + a.deep(t(undefined), [undefined], "Undefined"); + a.deep(t(null), [null], "Null"); + a.deep(t(false), [false], "Boolean"); + a.deep(t(-Infinity), [-Infinity], "Infinity"); + a.deep(t(-0), [-0], "-0"); + a.deep(t(+0), [+0], "+0"); + a.deep(t(1), [1], "1"); + a.deep(t(1, 2, 3), [1, 2, 3], "Numeric args"); + a.deep(t(+Infinity), [+Infinity], "+Infinity"); + a.deep(t({ '0': 'a', '1': 'b', '2': 'c', length: 3 }), + [{ '0': 'a', '1': 'b', '2': 'c', length: 3 }], "Array like"); + a.deep(t(undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity), + [undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity], "Falsy arguments"); + + a.h1("Null context"); + a.deep(t.call(null, 'abc'), ['abc'], "String"); + a.deep(t.call(null, undefined), [undefined], "Undefined"); + a.deep(t.call(null, null), [null], "Null"); + a.deep(t.call(null, false), [false], "Boolean"); + a.deep(t.call(null, -Infinity), [-Infinity], "-Infinity"); + a.deep(t.call(null, -0), [-0], "-0"); + a.deep(t.call(null, +0), [+0], "+0"); + a.deep(t.call(null, 1), [1], "1"); + a.deep(t.call(null, 1, 2, 3), [1, 2, 3], "Numeric"); + a.deep(t.call(null, +Infinity), [+Infinity], "+Infinity"); + a.deep(t.call(null, { '0': 'a', '1': 'b', '2': 'c', length: 3 }), + [{ '0': 'a', '1': 'b', '2': 'c', length: 3 }], "Array-like"); + a.deep(t.call(null, undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity), + [undefined, null, false, -Infinity, -0, +0, 1, 2, +Infinity], "Falsy"); + + a.h1("Other constructor context"); + a.deep(t.call(Object, 1, 2, 3), { '0': 1, '1': 2, '2': 3, length: 3 }, "Many arguments"); + + testObject = Object(3); + testObject[0] = 1; + testObject[1] = 2; + testObject[2] = 3; + testObject.length = 3; + a.deep(t.call(Object, 1, 2, 3), testObject, "Test object"); + a(t.call(Object).length, 0, "No arguments"); + a.throws(function () { t.call(function () { return Object.freeze({}); }); }, TypeError, + "Frozen instance"); + + // Ensure no setters are called for the indexes + MyType = function () {}; + defineProperty(MyType.prototype, '0', { + set: function (x) { throw new Error('Setter called: ' + x); } + }); + a.deep(t.call(MyType, 'abc'), { '0': 'abc', length: 1 }, "Define, not set"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/to-array.js new file mode 100644 index 00000000000000..4985b5eaee9769 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/to-array.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var o = [1, 2, 3]; + a(t(o), o, "Array"); + a.deep(t('12r3v'), ['1', '2', 'r', '3', 'v'], "String"); + a.deep(t((function () { return arguments; }(3, o, 'raz'))), + [3, o, 'raz'], "Arguments"); + a.deep(t((function () { return arguments; }(3))), [3], + "Arguments with one numeric value"); + + a.deep(t({ 0: 'raz', 1: 'dwa', length: 2 }), ['raz', 'dwa'], "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/valid-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/valid-array.js new file mode 100644 index 00000000000000..3732192d1bbd1f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/array/valid-array.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(0); }, TypeError, "Number"); + a.throws(function () { t(true); }, TypeError, "Boolean"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + a(t(x = []), x, "Array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/boolean/is-boolean.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/boolean/is-boolean.js new file mode 100644 index 00000000000000..4e6b3cb73e4f3b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/boolean/is-boolean.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(false), true, "Boolean"); + a(t(new Boolean(false)), true, "Boolean object"); + a(t(new Date()), false, "Date"); + a(t(new String('raz')), false, "String object"); + a(t({}), false, "Plain object"); + a(t(/a/), false, "Regular expression"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/copy.js new file mode 100644 index 00000000000000..767c5e16a4d053 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/copy.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var o = new Date(), o2; + + o2 = t.call(o); + a.not(o, o2, "Different objects"); + a.ok(o2 instanceof Date, "Instance of Date"); + a(o.getTime(), o2.getTime(), "Same time"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/days-in-month.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/days-in-month.js new file mode 100644 index 00000000000000..9ddba55f74ac40 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/days-in-month.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2001, 0, 1)), 31, "January"); + a(t.call(new Date(2001, 1, 1)), 28, "February"); + a(t.call(new Date(2000, 1, 1)), 29, "February (leap)"); + a(t.call(new Date(2001, 2, 1)), 31, "March"); + a(t.call(new Date(2001, 3, 1)), 30, "April"); + a(t.call(new Date(2001, 4, 1)), 31, "May"); + a(t.call(new Date(2001, 5, 1)), 30, "June"); + a(t.call(new Date(2001, 6, 1)), 31, "July"); + a(t.call(new Date(2001, 7, 1)), 31, "August"); + a(t.call(new Date(2001, 8, 1)), 30, "September"); + a(t.call(new Date(2001, 9, 1)), 31, "October"); + a(t.call(new Date(2001, 10, 1)), 30, "November"); + a(t.call(new Date(2001, 11, 1)), 31, "December"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-day.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-day.js new file mode 100644 index 00000000000000..d4f4a9087c059e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-day.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2000, 0, 1, 13, 32, 34, 234)).valueOf(), + new Date(2000, 0, 1).valueOf()); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-month.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-month.js new file mode 100644 index 00000000000000..b4a81bef6d0850 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-month.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2000, 0, 15, 13, 32, 34, 234)).valueOf(), + new Date(2000, 0, 1).valueOf()); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-year.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-year.js new file mode 100644 index 00000000000000..aae117e769b52c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/floor-year.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(new Date(2000, 5, 13, 13, 32, 34, 234)).valueOf(), + new Date(2000, 0, 1).valueOf()); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/format.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/format.js new file mode 100644 index 00000000000000..e68e4bf782ef30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/#/format.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + var dt = new Date(2011, 2, 3, 3, 5, 5, 32); + a(t.call(dt, ' %Y.%y.%m.%d.%H.%M.%S.%L '), ' 2011.11.03.03.03.05.05.032 '); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/is-date.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/is-date.js new file mode 100644 index 00000000000000..109093dfbe32f8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/is-date.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(true), false, "Boolean"); + a(t(new Date()), true, "Date"); + a(t(new String('raz')), false, "String object"); + a(t({}), false, "Plain object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/valid-date.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/valid-date.js new file mode 100644 index 00000000000000..98787e40781687 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/date/valid-date.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var d = new Date(); + a(t(d), d, "Date"); + a.throws(function () { + t({}); + }, "Object"); + a.throws(function () { + t({ valueOf: function () { return 20; } }); + }, "Number object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/#/throw.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/#/throw.js new file mode 100644 index 00000000000000..1213cfc3b12791 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/#/throw.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var e = new Error(); + try { + t.call(e); + } catch (e2) { + a(e2, e); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/custom.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/custom.js new file mode 100644 index 00000000000000..d4ff500c9b30f2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/custom.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var T = t, err = new T('My Error', 'MY_ERROR', { errno: 123 }); + a(err instanceof Error, true, "Instance of error"); + a(err.constructor, Error, "Constructor"); + a(err.name, 'Error', "Name"); + a(String(err), 'Error: My Error', "String representation"); + a(err.code, 'MY_ERROR', "Code"); + a(err.errno, 123, "Errno"); + a(typeof err.stack, 'string', "Stack trace"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/is-error.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/is-error.js new file mode 100644 index 00000000000000..f8b5e2000eb769 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/is-error.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(), false, "Undefined"); + a(t(1), false, "Primitive"); + a(t({}), false, "Objectt"); + a(t({ toString: function () { return '[object Error]'; } }), false, + "Fake error"); + a(t(new Error()), true, "Error"); + a(t(new EvalError()), true, "EvalError"); + a(t(new RangeError()), true, "RangeError"); + a(t(new ReferenceError()), true, "ReferenceError"); + a(t(new SyntaxError()), true, "SyntaxError"); + a(t(new TypeError()), true, "TypeError"); + a(t(new URIError()), true, "URIError"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/valid-error.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/valid-error.js new file mode 100644 index 00000000000000..e04cdb33b7cdf4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/error/valid-error.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var e = new Error(); + a(t(e), e, "Error"); + a.throws(function () { + t({}); + }, "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/compose.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/compose.js new file mode 100644 index 00000000000000..83de5e844ac87d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/compose.js @@ -0,0 +1,9 @@ +'use strict'; + +var f = function (a, b) { return ['a', arguments.length, a, b]; } + , g = function (a) { return ['b', arguments.length].concat(a); } + , h = function (a) { return ['c', arguments.length].concat(a); }; + +module.exports = function (t, a) { + a.deep(t.call(h, g, f)(1, 2), ['c', 1, 'b', 1, 'a', 2, 1, 2]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/copy.js new file mode 100644 index 00000000000000..7a22e2f249276e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/copy.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = function (t, a) { + var foo = 'raz', bar = 'dwa' + , fn = function marko(a, b) { return this + a + b + foo + bar; } + , result, o = {}; + + fn.prototype = o; + + fn.foo = 'raz'; + + result = t.call(fn); + + a(result.length, fn.length, "Length"); + a(result.name, fn.name, "Length"); + a(result.call('marko', 'el', 'fe'), 'markoelferazdwa', "Body"); + a(result.prototype, fn.prototype, "Prototype"); + a(result.foo, fn.foo, "Custom property"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/curry.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/curry.js new file mode 100644 index 00000000000000..18fb0389e79b26 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/curry.js @@ -0,0 +1,18 @@ +'use strict'; + +var toArray = require('../../../array/to-array') + + , f = function () { return toArray(arguments); }; + +module.exports = function (t, a) { + var x, y = {}, z; + a.deep(t.call(f, 0, 1, 2)(3), [], "0 arguments"); + x = t.call(f, 5, {}); + a(x.length, 5, "Length #1"); + z = x(1, 2); + a(z.length, 3, "Length #2"); + z = z(3, 4); + a(z.length, 1, "Length #1"); + a.deep(z(5, 6), [1, 2, 3, 4, 5], "Many arguments"); + a.deep(x(8, 3)(y, 45)('raz', 6), [8, 3, y, 45, 'raz'], "Many arguments #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/lock.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/lock.js new file mode 100644 index 00000000000000..44a12d7b56c748 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/lock.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(function () { + return arguments.length; + })(1, 2, 3), 0); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/not.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/not.js new file mode 100644 index 00000000000000..c0f5e9d4b989a5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/not.js @@ -0,0 +1,11 @@ +'use strict'; + +var identity = require('../../../function/identity') + , noop = require('../../../function/noop'); + +module.exports = function (t, a) { + a(t.call(identity)(''), true, "Falsy"); + a(t.call(noop)(), true, "Undefined"); + a(t.call(identity)({}), false, "Any object"); + a(t.call(identity)(true), false, "True"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/partial.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/partial.js new file mode 100644 index 00000000000000..bd00ce752f5202 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/partial.js @@ -0,0 +1,9 @@ +'use strict'; + +var toArray = require('../../../array/to-array') + + , f = function () { return toArray(arguments); }; + +module.exports = function (t, a) { + a.deep(t.call(f, 1)(2, 3), [1, 2, 3]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/spread.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/spread.js new file mode 100644 index 00000000000000..b82dfecfe95045 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/spread.js @@ -0,0 +1,8 @@ +'use strict'; + +var f = function (a, b) { return this[a] + this[b]; } + , o = { a: 3, b: 4 }; + +module.exports = function (t, a) { + a(t.call(f).call(o, ['a', 'b']), 7); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/to-string-tokens.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/to-string-tokens.js new file mode 100644 index 00000000000000..4c54d30354b405 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/#/to-string-tokens.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t.call(function (a, b) { return this[a] + this[b]; }), + { args: 'a, b', body: ' return this[a] + this[b]; ' }); + a.deep(t.call(function () {}), + { args: '', body: '' }); + a.deep(t.call(function (raz) {}), + { args: 'raz', body: '' }); + a.deep(t.call(function () { Object(); }), + { args: '', body: ' Object(); ' }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/_define-length.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/_define-length.js new file mode 100644 index 00000000000000..8f037e857eaa09 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/_define-length.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var foo = 'raz', bar = 'dwa' + , fn = function (a, b) { return this + a + b + foo + bar; } + , result; + + result = t(fn, 3); + a(result.call('marko', 'el', 'fe'), 'markoelferazdwa', "Content"); + a(result.length, 3, "Length"); + a(result.prototype, fn.prototype, "Prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/constant.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/constant.js new file mode 100644 index 00000000000000..fda52aa43710c1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/constant.js @@ -0,0 +1,7 @@ +'use strict'; + +var o = {}; + +module.exports = function (t, a) { + a(t(o)(), o); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/identity.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/identity.js new file mode 100644 index 00000000000000..8013e2e5af1288 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/identity.js @@ -0,0 +1,7 @@ +'use strict'; + +var o = {}; + +module.exports = function (t, a) { + a(t(o), o); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/invoke.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/invoke.js new file mode 100644 index 00000000000000..fcce4aaaaafb87 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/invoke.js @@ -0,0 +1,9 @@ +'use strict'; + +var constant = require('../../function/constant') + + , o = { b: constant('c') }; + +module.exports = function (t, a) { + a(t('b')(o), 'c'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/is-arguments.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/is-arguments.js new file mode 100644 index 00000000000000..f8de8812a5035d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/is-arguments.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + var args, dummy; + args = (function () { return arguments; }()); + dummy = { '0': 1, '1': 2 }; + Object.defineProperty(dummy, 'length', { value: 2 }); + a(t(args), true, "Arguments"); + a(t(dummy), false, "Dummy"); + a(t([]), false, "Array"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/is-function.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/is-function.js new file mode 100644 index 00000000000000..83acc42f9a6637 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/is-function.js @@ -0,0 +1,8 @@ +'use strict'; + +var o = { call: Function.prototype.call, apply: Function.prototype.apply }; + +module.exports = function (t, a) { + a(t(function () {}), true, "Function is function"); + a(t(o), false, "Plain object is not function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/noop.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/noop.js new file mode 100644 index 00000000000000..4305c6fcfd51cd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/noop.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t(1, 2, 3), 'undefined'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/pluck.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/pluck.js new file mode 100644 index 00000000000000..5bf9583ad52b3e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/pluck.js @@ -0,0 +1,7 @@ +'use strict'; + +var o = { foo: 'bar' }; + +module.exports = function (t, a) { + a(t('foo')(o), o.foo); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/valid-function.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/valid-function.js new file mode 100644 index 00000000000000..59b16233b37978 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/function/valid-function.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var f = function () {}; + a(t(f), f, "Function"); + f = new Function(); + a(t(f), f, "Function"); + a.throws(function () { + t({}); + }, "Object"); + a.throws(function () { + t(/re/); + }, "RegExp"); + a.throws(function () { + t({ call: function () { return 20; } }); + }, "Plain object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/global.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/global.js new file mode 100644 index 00000000000000..1f452aefb09827 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/global.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.ok(t && typeof t === 'object'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/for-each.js new file mode 100644 index 00000000000000..0fed8ad898990e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/for-each.js @@ -0,0 +1,40 @@ +'use strict'; + +var ArrayIterator = require('es6-iterator/array') + + , slice = Array.prototype.slice; + +module.exports = function (t, a) { + var i = 0, x = ['raz', 'dwa', 'trzy'], y = {}; + t(x, function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Array " + i + "#"); + a(this, y, "Array: context: " + (i++) + "#"); + }, y); + i = 0; + t((function () { return arguments; }('raz', 'dwa', 'trzy')), function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Arguments" + i + "#"); + a(this, y, "Arguments: context: " + (i++) + "#"); + }, y); + i = 0; + t({ 0: 'raz', 1: 'dwa', 2: 'trzy', length: 3 }, function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Array-like" + i + "#"); + a(this, y, "Array-like: context: " + (i++) + "#"); + }, y); + i = 0; + t(x = 'foo', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Regular String: context: " + (i++) + "#"); + }, y); + i = 0; + x = ['r', '💩', 'z']; + t('r💩z', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Unicode String: context: " + (i++) + "#"); + }, y); + i = 0; + t(new ArrayIterator(x), function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Iterator " + i + "#"); + a(this, y, "Iterator: context: " + (i++) + "#"); + }, y); + +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/is.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/is.js new file mode 100644 index 00000000000000..c0d2a43ebfe17c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/is.js @@ -0,0 +1,20 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (t, a) { + var x; + a(t([]), true, "Array"); + a(t(""), true, "String"); + a(t((function () { return arguments; }())), true, "Arguments"); + a(t({ length: 0 }), true, "List object"); + a(t(function () {}), false, "Function"); + a(t({}), false, "Plain object"); + a(t(/raz/), false, "Regexp"); + a(t(), false, "No argument"); + a(t(null), false, "Null"); + a(t(undefined), false, "Undefined"); + x = {}; + x[iteratorSymbol] = function () {}; + a(t(x), true, "Iterable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate-object.js new file mode 100644 index 00000000000000..da12529bc0368c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate-object.js @@ -0,0 +1,20 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a.throws(function () { t(''); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); + x = {}; + x[iteratorSymbol] = function () {}; + a(t(x), x, "Iterable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate.js new file mode 100644 index 00000000000000..bcc2ad3d0aa1c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate.js @@ -0,0 +1,20 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a(t(''), '', "''"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); + x = {}; + x[iteratorSymbol] = function () {}; + a(t(x), x, "Iterable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/_pack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/_pack-ieee754.js new file mode 100644 index 00000000000000..9041431d7769c9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/_pack-ieee754.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t(1.337, 8, 23), [63, 171, 34, 209]); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/_unpack-ieee754.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/_unpack-ieee754.js new file mode 100644 index 00000000000000..ca30b8208dbb95 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/_unpack-ieee754.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t([63, 171, 34, 209], 8, 23), 1.3370000123977661); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/implement.js new file mode 100644 index 00000000000000..01fb6d08224e2a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/acosh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/shim.js new file mode 100644 index 00000000000000..3d710c7930d454 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/acosh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-1), NaN, "Negative"); + a(t(0), NaN, "Zero"); + a(t(0.5), NaN, "Below 1"); + a(t(1), 0, "1"); + a(t(2), 1.3169578969248166, "Other"); + a(t(Infinity), Infinity, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/implement.js new file mode 100644 index 00000000000000..d1fceceee13449 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/asinh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/shim.js new file mode 100644 index 00000000000000..d9fbe49edc2d99 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/asinh/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(-2), -1.4436354751788103, "Negative"); + a(t(2), 1.4436354751788103, "Positive"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/implement.js new file mode 100644 index 00000000000000..cba8fad83e4082 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/atanh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/shim.js new file mode 100644 index 00000000000000..a857b496686048 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/atanh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-2), NaN, "Less than -1"); + a(t(2), NaN, "Greater than 1"); + a(t(-1), -Infinity, "-1"); + a(t(1), Infinity, "1"); + a(t(0), 0, "Zero"); + a(t(0.5), 0.5493061443340549, "Ohter"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/implement.js new file mode 100644 index 00000000000000..374d4b383f5c5f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/cbrt/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/shim.js new file mode 100644 index 00000000000000..43ab68b848f61a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cbrt/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(-1), -1, "-1"); + a(t(1), 1, "1"); + a(t(2), 1.2599210498948732, "Ohter"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/implement.js new file mode 100644 index 00000000000000..44f8815526b7ec --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/clz32/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/shim.js new file mode 100644 index 00000000000000..a769b39b85b644 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/clz32/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(1), 31, "1"); + a(t(1000), 22, "1000"); + a(t(), 32, "No arguments"); + a(t(Infinity), 32, "Infinity"); + a(t(-Infinity), 32, "-Infinity"); + a(t("foo"), 32, "String"); + a(t(true), 31, "Boolean"); + a(t(3.5), 30, "Float"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/implement.js new file mode 100644 index 00000000000000..f3c712b1dfc977 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/cosh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/shim.js new file mode 100644 index 00000000000000..419c12367dbcd2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/cosh/shim.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 1, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), Infinity, "-Infinity"); + a(t(1), 1.5430806348152437, "1"); + a(t(Number.MAX_VALUE), Infinity); + a(t(-Number.MAX_VALUE), Infinity); + a(t(Number.MIN_VALUE), 1); + a(t(-Number.MIN_VALUE), 1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/implement.js new file mode 100644 index 00000000000000..c21296725dc07b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/expm1/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/shim.js new file mode 100644 index 00000000000000..15f0e796ce565b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/expm1/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -1, "-Infinity"); + a(t(1).toFixed(15), '1.718281828459045', "1"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/implement.js new file mode 100644 index 00000000000000..c909af7c300b22 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/fround/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/shim.js new file mode 100644 index 00000000000000..4ef6d4ea9b199b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/fround/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(1.337), 1.3370000123977661, "1"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/implement.js new file mode 100644 index 00000000000000..99466464c122bc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/hypot/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/shim.js new file mode 100644 index 00000000000000..91d950a5d32899 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/hypot/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(), 0, "No arguments"); + a(t(0, -0, 0), 0, "Zeros"); + a(t(4, NaN, Infinity), Infinity, "Infinity"); + a(t(4, NaN, -Infinity), Infinity, "Infinity"); + a(t(4, NaN, 34), NaN, "NaN"); + a(t(3, 4), 5, "#1"); + a(t(3, 4, 5), 7.0710678118654755, "#2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/implement.js new file mode 100644 index 00000000000000..7b2a2a61653299 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/imul/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/shim.js new file mode 100644 index 00000000000000..a2ca7fe78321ce --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/imul/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(), 0, "No arguments"); + a(t(0, 0), 0, "Zeros"); + a(t(2, 4), 8, "#1"); + a(t(-1, 8), -8, "#2"); + a(t(0xfffffffe, 5), -10, "#3"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/implement.js new file mode 100644 index 00000000000000..4b3b4a4569fb81 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/log10/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/shim.js new file mode 100644 index 00000000000000..5fa0d5be3af861 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log10/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-0.5), NaN, "Less than 0"); + a(t(0), -Infinity, "0"); + a(t(1), 0, "1"); + a(t(Infinity), Infinity, "Infinity"); + a(t(2), 0.3010299956639812, "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/implement.js new file mode 100644 index 00000000000000..5d269bd3eaf09b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/log1p/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/shim.js new file mode 100644 index 00000000000000..d495ce0496b76d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log1p/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-1.5), NaN, "Less than -1"); + a(t(-1), -Infinity, "-1"); + a(t(0), 0, "0"); + a(t(Infinity), Infinity, "Infinity"); + a(t(1), 0.6931471805599453, "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/implement.js new file mode 100644 index 00000000000000..92b501ac72abed --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/log2/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/shim.js new file mode 100644 index 00000000000000..faa9c32a8537ab --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/log2/shim.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(-0.5), NaN, "Less than 0"); + a(t(0), -Infinity, "0"); + a(t(1), 0, "1"); + a(t(Infinity), Infinity, "Infinity"); + a(t(3).toFixed(15), '1.584962500721156', "Other"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/implement.js new file mode 100644 index 00000000000000..5875c42d608eb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/sign/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/shim.js new file mode 100644 index 00000000000000..b6b89c15889dc4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sign/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +var is = require('../../../object/is'); + +module.exports = function (t, a) { + a(is(t(0), +0), true, "+0"); + a(is(t(-0), -0), true, "-0"); + a(t({}), NaN, true, "NaN"); + a(t(-234234234), -1, "Negative"); + a(t(234234234), 1, "Positive"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/implement.js new file mode 100644 index 00000000000000..e52089e4507156 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/sinh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/shim.js new file mode 100644 index 00000000000000..4f63b59e735bf0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/sinh/shim.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(t(1), 1.1752011936438014, "1"); + a(t(Number.MAX_VALUE), Infinity); + a(t(-Number.MAX_VALUE), -Infinity); + a(t(Number.MIN_VALUE), 5e-324); + a(t(-Number.MIN_VALUE), -5e-324); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/implement.js new file mode 100644 index 00000000000000..a96bf193366b30 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/tanh/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/shim.js new file mode 100644 index 00000000000000..2c67aaf47049fd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/tanh/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), 1, "Infinity"); + a(t(-Infinity), -1, "-Infinity"); + a(t(1), 0.7615941559557649, "1"); + a(t(Number.MAX_VALUE), 1); + a(t(-Number.MAX_VALUE), -1); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/implement.js new file mode 100644 index 00000000000000..1830e61f69794d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../math/trunc/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/shim.js new file mode 100644 index 00000000000000..9e5eed7910e13c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/math/trunc/shim.js @@ -0,0 +1,16 @@ +'use strict'; + +var is = require('../../../object/is'); + +module.exports = function (t, a) { + a(t({}), NaN, "NaN"); + a(t(0), 0, "Zero"); + a(t(Infinity), Infinity, "Infinity"); + a(t(-Infinity), -Infinity, "-Infinity"); + a(is(t(0.234), 0), true, "0"); + a(is(t(-0.234), -0), true, "-0"); + a(t(13.7), 13, "Positive #1"); + a(t(12.3), 12, "Positive #2"); + a(t(-12.3), -12, "Negative #1"); + a(t(-14.7), -14, "Negative #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/#/pad.js new file mode 100644 index 00000000000000..e02082353348dc --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/#/pad.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(78, 4), '0078'); + a(t.call(65.12323, 4, 3), '0065.123', "Precision"); + a(t.call(65, 4, 3), '0065.000', "Precision integer"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/implement.js new file mode 100644 index 00000000000000..574da75dcebb7f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/epsilon/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/index.js new file mode 100644 index 00000000000000..c892fd47d41c16 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/epsilon/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/implement.js new file mode 100644 index 00000000000000..b35345fa6ee762 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-finite/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/shim.js new file mode 100644 index 00000000000000..5205d1c2602520 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-finite/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), true, "Number"); + a(t('23'), false, "Not numeric"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/implement.js new file mode 100644 index 00000000000000..127149ceeda9b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/shim.js new file mode 100644 index 00000000000000..3f3985c3a05522 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-integer/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), true, "Number"); + a(t(2.34), false, "Float"); + a(t('23'), false, "Not numeric"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/implement.js new file mode 100644 index 00000000000000..2f01d6d30ad9f6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-nan/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/shim.js new file mode 100644 index 00000000000000..425723e74b07b9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-nan/shim.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), false, "Number"); + a(t({}), false, "Not numeric"); + a(t(NaN), true, "NaN"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-number.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-number.js new file mode 100644 index 00000000000000..275133476a61ff --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-number.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(0), true, "Zero"); + a(t(NaN), true, "NaN"); + a(t(Infinity), true, "Infinity"); + a(t(12), true, "Number"); + a(t(false), false, "Boolean"); + a(t(new Date()), false, "Date"); + a(t(new Number(2)), true, "Number object"); + a(t('asdfaf'), false, "String"); + a(t(''), false, "Empty String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/implement.js new file mode 100644 index 00000000000000..33667e2e9afb60 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/is-safe-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/shim.js new file mode 100644 index 00000000000000..77e06674711795 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/is-safe-integer/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(2), true, "Number"); + a(t(2.34), false, "Float"); + a(t(Math.pow(2, 53)), false, "Too large"); + a(t(Math.pow(2, 53) - 1), true, "Maximum"); + a(t('23'), false, "Not numeric"); + a(t(NaN), false, "NaN"); + a(t(Infinity), false, "Infinity"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/implement.js new file mode 100644 index 00000000000000..bef00ca413d3cb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/max-safe-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/index.js new file mode 100644 index 00000000000000..c892fd47d41c16 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/max-safe-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/implement.js new file mode 100644 index 00000000000000..fa440248bf47a6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../number/min-safe-integer/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/index.js new file mode 100644 index 00000000000000..c892fd47d41c16 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/index.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(typeof t, 'number'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/min-safe-integer/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-integer.js new file mode 100644 index 00000000000000..ff326ba7a95bbb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-integer.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "NaN"); + a(t(20), 20, "Positive integer"); + a(t('-20'), -20, "String negative integer"); + a(t(Infinity), Infinity, "Infinity"); + a(t(15.343), 15, "Float"); + a(t(-15.343), -15, "Negative float"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-pos-integer.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-pos-integer.js new file mode 100644 index 00000000000000..2f3b4e674ecc4b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-pos-integer.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "NaN"); + a(t(20), 20, "Positive integer"); + a(t(-20), 0, "Negative integer"); + a(t(Infinity), Infinity, "Infinity"); + a(t(15.343), 15, "Float"); + a(t(-15.343), 0, "Negative float"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-uint32.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-uint32.js new file mode 100644 index 00000000000000..00d05bdfe346d7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/number/to-uint32.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "Not numeric"); + a(t(-4), 4294967292, "Negative"); + a(t(133432), 133432, "Positive"); + a(t(8589934592), 0, "Greater than maximum"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/_iterate.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/_iterate.js new file mode 100644 index 00000000000000..179afed88ee845 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/_iterate.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { raz: 1, dwa: 2, trzy: 3 } + , o2 = {}, o3 = {}, arr, i = -1; + + t = t('forEach'); + t(o, function (value, name, self, index) { + o2[name] = value; + a(index, ++i, "Index"); + a(self, o, "Self"); + a(this, o3, "Scope"); + }, o3); + a.deep(o2, o); + + arr = []; + o2 = {}; + i = -1; + t(o, function (value, name, self, index) { + arr.push(value); + o2[name] = value; + a(index, ++i, "Index"); + a(self, o, "Self"); + a(this, o3, "Scope"); + }, o3, function (a, b) { + return o[b] - o[a]; + }); + a.deep(o2, o, "Sort by Values: Content"); + a.deep(arr, [3, 2, 1], "Sort by Values: Order"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/implement.js new file mode 100644 index 00000000000000..40065594187cb9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../object/assign/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/shim.js new file mode 100644 index 00000000000000..9afe5f658c45b7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/assign/shim.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + var o1 = { a: 1, b: 2 } + , o2 = { b: 3, c: 4 }; + + a(t(o1, o2), o1, "Returns self"); + a.deep(o1, { a: 1, b: 3, c: 4 }, "Single: content"); + + a.deep(t({}, o1, o2), { a: 1, b: 3, c: 4 }, "Multi argument"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/clear.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/clear.js new file mode 100644 index 00000000000000..bfc08cc208420b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/clear.js @@ -0,0 +1,13 @@ +'use strict'; + +var isEmpty = require('../../object/is-empty'); + +module.exports = function (t, a) { + var x = {}; + a(t(x), x, "Empty: Returns same object"); + a(isEmpty(x), true, "Empty: Not changed"); + x.foo = 'raz'; + x.bar = 'dwa'; + a(t(x), x, "Same object"); + a(isEmpty(x), true, "Emptied"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/compact.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/compact.js new file mode 100644 index 00000000000000..9c9064c7886445 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/compact.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = {}, z; + z = t(x); + a.not(z, x, "Returns different object"); + a.deep(z, {}, "Empty on empty"); + + x = { foo: 'bar', a: 0, b: false, c: '', d: '0', e: null, bar: y, + elo: undefined }; + z = t(x); + a.deep(z, { foo: 'bar', a: 0, b: false, c: '', d: '0', bar: y }, + "Cleared null values"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/compare.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/compare.js new file mode 100644 index 00000000000000..cb9424109c334b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/compare.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var d = new Date(); + + a.ok(t(12, 3) > 0, "Numbers"); + a.ok(t(2, 13) < 0, "Numbers #2"); + a.ok(t("aaa", "aa") > 0, "Strings"); + a.ok(t("aa", "ab") < 0, "Strings #2"); + a(t("aa", "aa"), 0, "Strings same"); + a(t(d, new Date(d.getTime())), 0, "Same date"); + a.ok(t(d, new Date(d.getTime() + 1)) < 0, "Different date"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/copy-deep.js new file mode 100644 index 00000000000000..a4023bc8ac4bf6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/copy-deep.js @@ -0,0 +1,24 @@ +'use strict'; + +var stringify = JSON.stringify; + +module.exports = function (t, a) { + var o = { 1: 'raz', 2: 'dwa', 3: 'trzy' } + , no = t(o); + + a.not(no, o, "Return different object"); + a(stringify(no), stringify(o), "Match properties and values"); + + o = { foo: 'bar', raz: { dwa: 'dwa', + trzy: { cztery: 'pięć', 'sześć': 'siedem' }, osiem: {}, + 'dziewięć': function () { } }, 'dziesięć': 10 }; + o.raz.rec = o; + + no = t(o); + a.not(o.raz, no.raz, "Deep"); + a.not(o.raz.trzy, no.raz.trzy, "Deep #2"); + a(stringify(o.raz.trzy), stringify(no.raz.trzy), "Deep content"); + a(no.raz.rec, no, "Recursive"); + a.not(o.raz.osiem, no.raz.osiem, "Empty object"); + a(o.raz['dziewięć'], no.raz['dziewięć'], "Function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/copy.js new file mode 100644 index 00000000000000..2f222ef809c6d7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/copy.js @@ -0,0 +1,19 @@ +'use strict'; + +var stringify = JSON.stringify; + +module.exports = function (t, a) { + var o = { 1: 'raz', 2: 'dwa', 3: 'trzy' } + , no = t(o); + + a.not(no, o, "Return different object"); + a(stringify(no), stringify(o), "Match properties and values"); + + o = { foo: 'bar', raz: { dwa: 'dwa', + trzy: { cztery: 'pięć', 'sześć': 'siedem' }, osiem: {}, + 'dziewięć': function () { } }, 'dziesięć': 10 }; + o.raz.rec = o; + + no = t(o); + a(o.raz, no.raz, "Shallow"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/count.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/count.js new file mode 100644 index 00000000000000..494f4f163515eb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/count.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), 0, "Empty"); + a(t({ raz: 1, dwa: null, trzy: undefined, cztery: 0 }), 4, + "Some properties"); + a(t(Object.defineProperties({}, { + raz: { value: 'raz' }, + dwa: { value: 'dwa', enumerable: true } + })), 1, "Some properties hidden"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/create.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/create.js new file mode 100644 index 00000000000000..8b7be214136d2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/create.js @@ -0,0 +1,22 @@ +'use strict'; + +var setPrototypeOf = require('../../object/set-prototype-of') + + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (t, a) { + var x = {}, obj; + + a(getPrototypeOf(t(x)), x, "Normal object"); + a(getPrototypeOf(t(null)), + (setPrototypeOf && setPrototypeOf.nullPolyfill) || null, "Null"); + + a.h1("Properties"); + a.h2("Normal object"); + a(getPrototypeOf(obj = t(x, { foo: { value: 'bar' } })), x, "Prototype"); + a(obj.foo, 'bar', "Property"); + a.h2("Null"); + a(getPrototypeOf(obj = t(null, { foo: { value: 'bar2' } })), + (setPrototypeOf && setPrototypeOf.nullPolyfill) || null, "Prototype"); + a(obj.foo, 'bar2', "Property"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/eq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/eq.js new file mode 100644 index 00000000000000..02b3f0027cbf82 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/eq.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var o = {}; + a(t(o, {}), false, "Different objects"); + a(t(o, o), true, "Same objects"); + a(t('1', '1'), true, "Same primitive"); + a(t('1', 1), false, "Different primitive types"); + a(t(NaN, NaN), true, "NaN"); + a(t(0, 0), true, "0,0"); + a(t(0, -0), true, "0,-0"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/every.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/every.js new file mode 100644 index 00000000000000..07d5bbbd61f7af --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/every.js @@ -0,0 +1,21 @@ +'use strict'; + +var o = { 1: 1, 2: 2, 3: 3 }; + +module.exports = function (t, a) { + var o2 = {}; + t(o, function (value, name) { + o2[name] = value; + return true; + }); + a(JSON.stringify(o2), JSON.stringify(o), "Iterates"); + + a(t(o, function () { + return true; + }), true, "Succeeds"); + + a(t(o, function () { + return false; + }), false, "Fails"); + +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/filter.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/filter.js new file mode 100644 index 00000000000000..7307da8640fcd1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/filter.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ 1: 1, 2: 2, 3: 3, 4: 4 }, + function (value) { return Boolean(value % 2); }), { 1: 1, 3: 3 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/first-key.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/first-key.js new file mode 100644 index 00000000000000..8169cd235344d9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/first-key.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = Object.create(null); + a(t(x), null, "Normal: Empty"); + a(t(y), null, "Null extension: Empty"); + x.foo = 'raz'; + x.bar = 343; + a(['foo', 'bar'].indexOf(t(x)) !== -1, true, "Normal"); + y.elo = 'foo'; + y.mar = 'wew'; + a(['elo', 'mar'].indexOf(t(y)) !== -1, true, "Null extension"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/flatten.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/flatten.js new file mode 100644 index 00000000000000..ca342eab9c8ae4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/flatten.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ a: { aa: 1, ab: 2 }, b: { ba: 3, bb: 4 } }), + { aa: 1, ab: 2, ba: 3, bb: 4 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/for-each.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/for-each.js new file mode 100644 index 00000000000000..8690d1e82179aa --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/for-each.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { raz: 1, dwa: 2, trzy: 3 } + , o2 = {}; + a(t(o, function (value, name) { + o2[name] = value; + }), undefined, "Return"); + a.deep(o2, o); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/get-property-names.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/get-property-names.js new file mode 100644 index 00000000000000..b91c3dd50e7bbf --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/get-property-names.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { first: 1, second: 4 }, r1, r2; + o = Object.create(o, { + third: { value: null } + }); + o.first = 2; + o = Object.create(o); + o.fourth = 3; + + r1 = t(o); + r1.sort(); + r2 = ['first', 'second', 'third', 'fourth'] + .concat(Object.getOwnPropertyNames(Object.prototype)); + r2.sort(); + a.deep(r1, r2); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-array-like.js new file mode 100644 index 00000000000000..6295973ca81acd --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-array-like.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + a(t([]), true, "Array"); + a(t(""), true, "String"); + a(t((function () { return arguments; }())), true, "Arguments"); + a(t({ length: 0 }), true, "List object"); + a(t(function () {}), false, "Function"); + a(t({}), false, "Plain object"); + a(t(/raz/), false, "Regexp"); + a(t(), false, "No argument"); + a(t(null), false, "Null"); + a(t(undefined), false, "Undefined"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-callable.js new file mode 100644 index 00000000000000..625e221d2c3811 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-callable.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(function () {}), true, "Function"); + a(t({}), false, "Object"); + a(t(), false, "Undefined"); + a(t(null), false, "Null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-copy-deep.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-copy-deep.js new file mode 100644 index 00000000000000..4f14cbbe8108b2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-copy-deep.js @@ -0,0 +1,46 @@ +'use strict'; + +module.exports = function (t, a) { + var x, y; + + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 3 }), true, "Same"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 4 }), false, + "Different property value"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2 }), false, + "Property only in source"); + a(t({ 1: 1, 2: 2 }, { 1: 1, 2: 2, 3: 4 }), false, + "Property only in target"); + + a(t("raz", "dwa"), false, "String: diff"); + a(t("raz", "raz"), true, "String: same"); + a(t("32", 32), false, "String & Number"); + + a(t([1, 'raz', true], [1, 'raz', true]), true, "Array: same"); + a(t([1, 'raz', undefined], [1, 'raz']), false, "Array: diff"); + a(t(['foo'], ['one']), false, "Array: One value comparision"); + + x = { foo: { bar: { mar: {} } } }; + y = { foo: { bar: { mar: {} } } }; + a(t(x, y), true, "Deep"); + + a(t({ foo: { bar: { mar: 'foo' } } }, { foo: { bar: { mar: {} } } }), + false, "Deep: false"); + + x = { foo: { bar: { mar: {} } } }; + x.rec = { foo: x }; + + y = { foo: { bar: { mar: {} } } }; + y.rec = { foo: x }; + + a(t(x, y), true, "Object: Infinite Recursion: Same #1"); + + x.rec.foo = y; + a(t(x, y), true, "Object: Infinite Recursion: Same #2"); + + x.rec.foo = x; + y.rec.foo = y; + a(t(x, y), true, "Object: Infinite Recursion: Same #3"); + + y.foo.bar.mar = 'raz'; + a(t(x, y), false, "Object: Infinite Recursion: Diff"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-copy.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-copy.js new file mode 100644 index 00000000000000..394e2ed94c09f0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-copy.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 3 }), true, "Same"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 4 }), false, + "Different property value"); + a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2 }), false, + "Property only in source"); + a(t({ 1: 1, 2: 2 }, { 1: 1, 2: 2, 3: 4 }), false, + "Property only in target"); + + a(t("raz", "dwa"), false, "String: diff"); + a(t("raz", "raz"), true, "String: same"); + a(t("32", 32), false, "String & Number"); + + a(t([1, 'raz', true], [1, 'raz', true]), true, "Array: same"); + a(t([1, 'raz', undefined], [1, 'raz']), false, "Array: diff"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-empty.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-empty.js new file mode 100644 index 00000000000000..b560c2c36b0d4b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-empty.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), true, "Empty"); + a(t({ 1: 1 }), false, "Not empty"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-object.js new file mode 100644 index 00000000000000..72c8aa6daf4a3a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-object.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(true), false, "Boolean"); + a(t(null), false, "Null"); + a(t(new Date()), true, "Date"); + a(t(new String('raz')), true, "String object"); + a(t({}), true, "Plain object"); + a(t(/a/), true, "Regular expression"); + a(t(function () {}), true, "Function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-plain-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-plain-object.js new file mode 100644 index 00000000000000..e988829d558ad0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is-plain-object.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function (t, a) { + a(t({}), true, "Empty {} is plain object"); + a(t({ a: true }), true, "{} with property is plain object"); + a(t({ prototype: 1, constructor: 2, __proto__: 3 }), true, + "{} with any property keys is plain object"); + a(t(null), false, "Null is not plain object"); + a(t('string'), false, "Primitive is not plain object"); + a(t(function () {}), false, "Function is not plain object"); + a(t(Object.create({})), false, + "Object whose prototype is not Object.prototype is not plain object"); + a(t(Object.create(Object.prototype)), true, + "Object whose prototype is Object.prototype is plain object"); + a(t(Object.create(null)), true, + "Object whose prototype is null is plain object"); + a(t(Object.prototype), false, "Object.prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is.js new file mode 100644 index 00000000000000..4f8948cbf344e1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/is.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var o = {}; + a(t(o, {}), false, "Different objects"); + a(t(o, o), true, "Same objects"); + a(t('1', '1'), true, "Same primitive"); + a(t('1', 1), false, "Different primitive types"); + a(t(NaN, NaN), true, "NaN"); + a(t(0, 0), true, "0,0"); + a(t(0, -0), false, "0,-0"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/key-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/key-of.js new file mode 100644 index 00000000000000..a9225a048c5c91 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/key-of.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + var x = {}, y = {} + , o = { foo: 'bar', raz: x, trzy: 'cztery', five: '6' }; + + a(t(o, 'bar'), 'foo', "First property"); + a(t(o, 6), null, "Primitive that's not there"); + a(t(o, x), 'raz', "Object"); + a(t(o, y), null, "Object that's not there"); + a(t(o, '6'), 'five', "Last property"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/implement.js new file mode 100644 index 00000000000000..179e1e5612ea8f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../object/keys/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/shim.js new file mode 100644 index 00000000000000..ed29eebcd751f7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/keys/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ foo: 'bar' }), ['foo'], "Object"); + a.deep(t('raz'), ['0', '1', '2'], "Primitive"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Undefined"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/map-keys.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/map-keys.js new file mode 100644 index 00000000000000..be84825b1be711 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/map-keys.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t({ 1: 1, 2: 2, 3: 3 }, function (key, value) { + return 'x' + (key + value); + }), { x11: 1, x22: 2, x33: 3 }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/map.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/map.js new file mode 100644 index 00000000000000..f9cc09c01b3933 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/map.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var obj = { 1: 1, 2: 2, 3: 3 }; + a.deep(t(obj, function (value, key, context) { + a(context, obj, "Context argument"); + return (value + 1) + key; + }), { 1: '21', 2: '32', 3: '43' }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/mixin-prototypes.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/mixin-prototypes.js new file mode 100644 index 00000000000000..d1c727a95a7371 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/mixin-prototypes.js @@ -0,0 +1,67 @@ +'use strict'; + +module.exports = function (t, a) { + var o, o1, o2, x, y = {}, z = {}; + o = { inherited: true, visible: 23 }; + o1 = Object.create(o); + o1.visible = z; + o1.nonremovable = 'raz'; + Object.defineProperty(o1, 'hidden', { value: 'hidden' }); + + o2 = Object.defineProperties({}, { nonremovable: { value: y } }); + o2.other = 'other'; + + try { t(o2, o1); } catch (ignore) {} + + a(o2.visible, z, "Enumerable"); + a(o1.hidden, 'hidden', "Not Enumerable"); + a(o2.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(o2.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(o2.inherited, true, "Extend deep"); + + a(o2.nonremovable, y, "Do not overwrite non configurable"); + a(o2.other, 'other', "Own kept"); + + x = {}; + t(x, o2); + try { t(x, o1); } catch (ignore) {} + + a(x.visible, z, "Enumerable"); + a(x.hidden, 'hidden', "Not Enumerable"); + a(x.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(x.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(x.inherited, true, "Extend deep"); + + a(x.nonremovable, y, "Ignored non configurable"); + a(x.other, 'other', "Other"); + + x.visible = 3; + a(x.visible, 3, "Writable is writable"); + + x = {}; + t(x, o1); + a.throws(function () { + x.hidden = 3; + }, "Not writable is not writable"); + + x = {}; + t(x, o1); + delete x.visible; + a.ok(!x.hasOwnProperty('visible'), "Configurable is configurable"); + + x = {}; + t(x, o1); + a.throws(function () { + delete x.hidden; + }, "Not configurable is not configurable"); + + x = Object.defineProperty({}, 'foo', + { configurable: false, writable: true, enumerable: false, value: 'bar' }); + + try { t(x, { foo: 'lorem' }); } catch (ignore) {} + a(x.foo, 'bar', "Writable, not enumerable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/mixin.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/mixin.js new file mode 100644 index 00000000000000..866005b03df29b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/mixin.js @@ -0,0 +1,69 @@ +'use strict'; + +module.exports = function (t, a) { + var o, o1, o2, x, y = {}, z = {}; + o = { inherited: true }; + o1 = Object.create(o); + o1.visible = z; + o1.nonremovable = 'raz'; + Object.defineProperty(o1, 'hidden', { value: 'hidden' }); + + o2 = Object.defineProperties({}, { nonremovable: { value: y } }); + o2.other = 'other'; + + try { t(o2, o1); } catch (ignore) {} + + a(o2.visible, z, "Enumerable"); + a(o1.hidden, 'hidden', "Not Enumerable"); + a(o2.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(o2.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(o2.hasOwnProperty('inherited'), false, "Extend only own"); + a(o2.inherited, undefined, "Extend ony own: value"); + + a(o2.nonremovable, y, "Do not overwrite non configurable"); + a(o2.other, 'other', "Own kept"); + + x = {}; + t(x, o2); + try { t(x, o1); } catch (ignore) {} + + a(x.visible, z, "Enumerable"); + a(x.hidden, 'hidden', "Not Enumerable"); + a(x.propertyIsEnumerable('visible'), true, "Enumerable is enumerable"); + a(x.propertyIsEnumerable('hidden'), false, + "Not enumerable is not enumerable"); + + a(x.hasOwnProperty('inherited'), false, "Extend only own"); + a(x.inherited, undefined, "Extend ony own: value"); + + a(x.nonremovable, y, "Ignored non configurable"); + a(x.other, 'other', "Other"); + + x.visible = 3; + a(x.visible, 3, "Writable is writable"); + + x = {}; + t(x, o1); + a.throws(function () { + x.hidden = 3; + }, "Not writable is not writable"); + + x = {}; + t(x, o1); + delete x.visible; + a.ok(!x.hasOwnProperty('visible'), "Configurable is configurable"); + + x = {}; + t(x, o1); + a.throws(function () { + delete x.hidden; + }, "Not configurable is not configurable"); + + x = Object.defineProperty({}, 'foo', + { configurable: false, writable: true, enumerable: false, value: 'bar' }); + + try { t(x, { foo: 'lorem' }); } catch (ignore) {} + a(x.foo, 'bar', "Writable, not enumerable"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/normalize-options.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/normalize-options.js new file mode 100644 index 00000000000000..0d2d4da04a53b1 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/normalize-options.js @@ -0,0 +1,32 @@ +'use strict'; + +var create = Object.create, defineProperty = Object.defineProperty; + +module.exports = function (t, a) { + var x = { foo: 'raz', bar: 'dwa' }, y; + y = t(x); + a.not(y, x, "Returns copy"); + a.deep(y, x, "Plain"); + + x = { raz: 'one', dwa: 'two' }; + defineProperty(x, 'get', { + configurable: true, + enumerable: true, + get: function () { return this.dwa; } + }); + x = create(x); + x.trzy = 'three'; + x.cztery = 'four'; + x = create(x); + x.dwa = 'two!'; + x.trzy = 'three!'; + x.piec = 'five'; + x.szesc = 'six'; + + a.deep(t(x), { raz: 'one', dwa: 'two!', trzy: 'three!', cztery: 'four', + piec: 'five', szesc: 'six', get: 'two!' }, "Deep object"); + + a.deep(t({ marko: 'raz', raz: 'foo' }, x, { szesc: 'elo', siedem: 'bibg' }), + { marko: 'raz', raz: 'one', dwa: 'two!', trzy: 'three!', cztery: 'four', + piec: 'five', szesc: 'elo', siedem: 'bibg', get: 'two!' }, "Multiple options"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/primitive-set.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/primitive-set.js new file mode 100644 index 00000000000000..839857eab3dd85 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/primitive-set.js @@ -0,0 +1,15 @@ +'use strict'; + +var getPropertyNames = require('../../object/get-property-names') + , isPlainObject = require('../../object/is-plain-object'); + +module.exports = function (t, a) { + var x = t(); + a(isPlainObject(x), true, "Plain object"); + a.deep(getPropertyNames(x), [], "No properties"); + x.foo = 'bar'; + a.deep(getPropertyNames(x), ['foo'], "Extensible"); + + a.deep(t('raz', 'dwa', 3), { raz: true, dwa: true, 3: true }, + "Arguments handling"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/safe-traverse.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/safe-traverse.js new file mode 100644 index 00000000000000..d30cdefe68b8b6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/safe-traverse.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var obj = { foo: { bar: { lorem: 12 } } }; + a(t(obj), obj, "No props"); + a(t(obj, 'foo'), obj.foo, "One"); + a(t(obj, 'raz'), undefined, "One: Fail"); + a(t(obj, 'foo', 'bar'), obj.foo.bar, "Two"); + a(t(obj, 'dsd', 'raz'), undefined, "Two: Fail #1"); + a(t(obj, 'foo', 'raz'), undefined, "Two: Fail #2"); + a(t(obj, 'foo', 'bar', 'lorem'), obj.foo.bar.lorem, "Three"); + a(t(obj, 'dsd', 'raz', 'fef'), undefined, "Three: Fail #1"); + a(t(obj, 'foo', 'raz', 'asdf'), undefined, "Three: Fail #2"); + a(t(obj, 'foo', 'bar', 'asd'), undefined, "Three: Fail #3"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/serialize.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/serialize.js new file mode 100644 index 00000000000000..43eed6a8616f9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/serialize.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = function (t, a) { + var fn = function (raz, dwa) { return raz + dwa; }; + a(t(), 'undefined', "Undefined"); + a(t(null), 'null', "Null"); + a(t(null), 'null', "Null"); + a(t('raz'), '"raz"', "String"); + a(t('raz"ddwa\ntrzy'), '"raz\\"ddwa\\ntrzy"', "String with escape"); + a(t(false), 'false', "Booelean"); + a(t(fn), String(fn), "Function"); + + a(t(/raz-dwa/g), '/raz-dwa/g', "RegExp"); + a(t(new Date(1234567)), 'new Date(1234567)', "Date"); + a(t([]), '[]', "Empty array"); + a(t([undefined, false, null, 'raz"ddwa\ntrzy', fn, /raz/g, new Date(1234567), ['foo']]), + '[undefined,false,null,"raz\\"ddwa\\ntrzy",' + String(fn) + + ',/raz/g,new Date(1234567),["foo"]]', "Rich Array"); + a(t({}), '{}', "Empty object"); + a(t({ raz: undefined, dwa: false, trzy: null, cztery: 'raz"ddwa\ntrzy', piec: fn, szesc: /raz/g, + siedem: new Date(1234567), osiem: ['foo', 32], dziewiec: { foo: 'bar', dwa: 343 } }), + '{"raz":undefined,"dwa":false,"trzy":null,"cztery":"raz\\"ddwa\\ntrzy","piec":' + String(fn) + + ',"szesc":/raz/g,"siedem":new Date(1234567),"osiem":["foo",32],' + + '"dziewiec":{"foo":"bar","dwa":343}}', "Rich object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/implement.js new file mode 100644 index 00000000000000..30b2ac4b96ba2e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +var create = require('../../../object/create') + , isImplemented = require('../../../object/set-prototype-of/is-implemented'); + +module.exports = function (a) { a(isImplemented(create), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/index.js new file mode 100644 index 00000000000000..aec2605cc2661a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var create = require('../../../object/create') + + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (t, a) { + var x = {}, y = {}; + + if (t === null) return; + a(t(x, y), x, "Return self object"); + a(getPrototypeOf(x), y, "Object"); + a.throws(function () { t(x); }, TypeError, "Undefined"); + a.throws(function () { t('foo'); }, TypeError, "Primitive"); + a(getPrototypeOf(t(x, null)), t.nullPolyfill || null, "Null"); + x = create(null); + a.h1("Change null prototype"); + a(t(x, y), x, "Result"); + a(getPrototypeOf(x), y, "Prototype"); + a.h1("Set null prototype"); + a(t(y, null), y, "Result"); + a(getPrototypeOf(y), t.nullPolyfill || null, "Prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/shim.js new file mode 100644 index 00000000000000..aec2605cc2661a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/set-prototype-of/shim.js @@ -0,0 +1,23 @@ +'use strict'; + +var create = require('../../../object/create') + + , getPrototypeOf = Object.getPrototypeOf; + +module.exports = function (t, a) { + var x = {}, y = {}; + + if (t === null) return; + a(t(x, y), x, "Return self object"); + a(getPrototypeOf(x), y, "Object"); + a.throws(function () { t(x); }, TypeError, "Undefined"); + a.throws(function () { t('foo'); }, TypeError, "Primitive"); + a(getPrototypeOf(t(x, null)), t.nullPolyfill || null, "Null"); + x = create(null); + a.h1("Change null prototype"); + a(t(x, y), x, "Result"); + a(getPrototypeOf(x), y, "Prototype"); + a.h1("Set null prototype"); + a(t(y, null), y, "Result"); + a(getPrototypeOf(y), t.nullPolyfill || null, "Prototype"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/some.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/some.js new file mode 100644 index 00000000000000..490431e7acd543 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/some.js @@ -0,0 +1,23 @@ +'use strict'; + +var o = { 1: 1, 2: 2, 3: 3 }; + +module.exports = function (t, a) { + var o2 = {}, i = 0; + t(o, function (value, name) { + o2[name] = value; + return false; + }); + a(JSON.stringify(o2), JSON.stringify(o), "Iterates"); + + a(t(o, function () { + ++i; + return true; + }), true, "Succeeds"); + a(i, 1, "Stops iteration after condition is met"); + + a(t(o, function () { + return false; + }), false, "Fails"); + +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/to-array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/to-array.js new file mode 100644 index 00000000000000..1f4beef7eae835 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/to-array.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var o = { 1: 1, 2: 2, 3: 3 }, o1 = {} + , o2 = t(o, function (value, name, self) { + a(self, o, "Self"); + a(this, o1, "Scope"); + return value + Number(name); + }, o1); + a.deep(o2, [2, 4, 6]); + + t(o).sort().forEach(function (item) { + a.deep(item, [item[0], o[item[0]]], "Default"); + }); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/unserialize.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/unserialize.js new file mode 100644 index 00000000000000..405eef112ff76e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/unserialize.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = function (t, a) { + var fn = function (raz, dwa) { return raz + dwa; }; + a(t('undefined'), undefined, "Undefined"); + a(t('null'), null, "Null"); + a(t('"raz"'), 'raz', "String"); + a(t('"raz\\"ddwa\\ntrzy"'), 'raz"ddwa\ntrzy', "String with escape"); + a(t('false'), false, "Booelean"); + a(String(t(String(fn))), String(fn), "Function"); + + a.deep(t('/raz-dwa/g'), /raz-dwa/g, "RegExp"); + a.deep(t('new Date(1234567)'), new Date(1234567), "Date"); + a.deep(t('[]'), [], "Empty array"); + a.deep(t('[undefined,false,null,"raz\\"ddwa\\ntrzy",/raz/g,new Date(1234567),["foo"]]'), + [undefined, false, null, 'raz"ddwa\ntrzy', /raz/g, new Date(1234567), ['foo']], "Rich Array"); + a.deep(t('{}'), {}, "Empty object"); + a.deep(t('{"raz":undefined,"dwa":false,"trzy":null,"cztery":"raz\\"ddwa\\ntrzy",' + + '"szesc":/raz/g,"siedem":new Date(1234567),"osiem":["foo",32],' + + '"dziewiec":{"foo":"bar","dwa":343}}'), + { raz: undefined, dwa: false, trzy: null, cztery: 'raz"ddwa\ntrzy', szesc: /raz/g, + siedem: new Date(1234567), osiem: ['foo', 32], dziewiec: { foo: 'bar', dwa: 343 } }, + "Rich object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-callable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-callable.js new file mode 100644 index 00000000000000..b40540b6ba61b0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-callable.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var f = function () {}; + a(t(f), f, "Function"); + a.throws(function () { + t({}); + }, "Not Function"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-object.js new file mode 100644 index 00000000000000..eaa8e7bcb364b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-object.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a.throws(function () { t(''); }, TypeError, "''"); + a(t(x = {}), x, "Object"); + a(t(x = function () {}), x, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + a(t(x = new Date()), x, "Date"); + + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-value.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-value.js new file mode 100644 index 00000000000000..f1eeafa9778863 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/valid-value.js @@ -0,0 +1,19 @@ +'use strict'; + +var numIsNaN = require('../../number/is-nan'); + +module.exports = function (t, a) { + var x; + a(t(0), 0, "0"); + a(t(false), false, "false"); + a(t(''), '', "''"); + a(numIsNaN(t(NaN)), true, "NaN"); + a(t(x = {}), x, "{}"); + + a.throws(function () { + t(); + }, "Undefined"); + a.throws(function () { + t(null); + }, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-array-like-object.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-array-like-object.js new file mode 100644 index 00000000000000..2f3e31b442ebcb --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-array-like-object.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a.throws(function () { t(''); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-array-like.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-array-like.js new file mode 100644 index 00000000000000..53bd11249e3d04 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-array-like.js @@ -0,0 +1,15 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(0); }, TypeError, "0"); + a.throws(function () { t(false); }, TypeError, "false"); + a(t(''), '', "''"); + a.throws(function () { t({}); }, TypeError, "Plain Object"); + a.throws(function () { t(function () {}); }, TypeError, "Function"); + a(t(x = new String('raz')), x, "String object"); //jslint: ignore + + a(t(x = { length: 1 }), x, "Array like"); + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "null"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-stringifiable-value.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-stringifiable-value.js new file mode 100644 index 00000000000000..ae9bd17a59a028 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-stringifiable-value.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a(t(0), "0"); + a(t(false), "false"); + a(t(''), ""); + a(t({}), String({}), "Object"); + a(t(x = function () {}), String(x), "Function"); + a(t(x = new String('raz')), String(x), "String object"); //jslint: ignore + a(t(x = new Date()), String(x), "Date"); + + a.throws(function () { t(Object.create(null)); }, TypeError, "Null prototype object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-stringifiable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-stringifiable.js new file mode 100644 index 00000000000000..4a46bb521900db --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/object/validate-stringifiable.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = function (t, a) { + var x; + a(t(), 'undefined', "Undefined"); + a(t(null), 'null', "Null"); + a(t(0), "0"); + a(t(false), "false"); + a(t(''), ""); + a(t({}), String({}), "Object"); + a(t(x = function () {}), String(x), "Function"); + a(t(x = new String('raz')), String(x), "String object"); //jslint: ignore + a(t(x = new Date()), String(x), "Date"); + + a.throws(function () { t(Object.create(null)); }, TypeError, "Null prototype object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/index.js new file mode 100644 index 00000000000000..ca2bd650615889 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var indexTest = require('tad/lib/utils/index-test') + + , path = require('path').resolve(__dirname, '../../../reg-exp/#'); + +module.exports = function (t, a, d) { + indexTest(indexTest.readDir(path).aside(function (data) { + delete data.sticky; + delete data.unicode; + }))(t, a, d); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/is-sticky.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/is-sticky.js new file mode 100644 index 00000000000000..e154ac2916557f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/is-sticky.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var re; + a(t.call(/raz/), false, "Normal"); + a(t.call(/raz/g), false, "Global"); + try { re = new RegExp('raz', 'y'); } catch (ignore) {} + if (!re) return; + a(t.call(re), true, "Sticky"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/is-unicode.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/is-unicode.js new file mode 100644 index 00000000000000..2ffb9e869bd6a3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/is-unicode.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function (t, a) { + var re; + a(t.call(/raz/), false, "Normal"); + a(t.call(/raz/g), false, "Global"); + try { re = new RegExp('raz', 'u'); } catch (ignore) {} + if (!re) return; + a(t.call(re), true, "Unicode"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/implement.js new file mode 100644 index 00000000000000..89825a45f6148d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/match/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/shim.js new file mode 100644 index 00000000000000..5249139fff2277 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/match/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + var result = ['foo']; + result.index = 0; + result.input = 'foobar'; + a.deep(t.call(/foo/, 'foobar'), result); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/implement.js new file mode 100644 index 00000000000000..c32b23a6d03e79 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/replace/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/shim.js new file mode 100644 index 00000000000000..2b378fd594e2ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/replace/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(/foo/, 'foobar', 'mar'), 'marbar'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/implement.js new file mode 100644 index 00000000000000..ff1b8087f2c697 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/search/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/shim.js new file mode 100644 index 00000000000000..596bcdb92ed203 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/search/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(/foo/, 'barfoo'), 3); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/implement.js new file mode 100644 index 00000000000000..1cee441806c065 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/split/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/shim.js new file mode 100644 index 00000000000000..6a95cd03d6ce68 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/split/shim.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a.deep(t.call(/\|/, 'bar|foo'), ['bar', 'foo']); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/sticky/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/sticky/implement.js new file mode 100644 index 00000000000000..d94e7b98d8fe46 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/sticky/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/sticky/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/sticky/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/sticky/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/sticky/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/unicode/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/unicode/implement.js new file mode 100644 index 00000000000000..9b1aa0f2ab992d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/unicode/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../reg-exp/#/unicode/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/unicode/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/unicode/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/#/unicode/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/escape.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/escape.js new file mode 100644 index 00000000000000..5b00f67f28ce45 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/escape.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + var str = "(?:^te|er)s{2}t\\[raz]+$"; + a(RegExp('^' + t(str) + '$').test(str), true); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/is-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/is-reg-exp.js new file mode 100644 index 00000000000000..785ca28c2ecb2c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/is-reg-exp.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = function (t, a) { + a(t('arar'), false, "String"); + a(t(12), false, "Number"); + a(t(true), false, "Boolean"); + a(t(new Date()), false, "Date"); + a(t(new String('raz')), false, "String object"); + a(t({}), false, "Plain object"); + a(t(/a/), true, "Regular expression"); + a(t(new RegExp('a')), true, "Regular expression via constructor"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/valid-reg-exp.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/valid-reg-exp.js new file mode 100644 index 00000000000000..cd12cf126a609a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/reg-exp/valid-reg-exp.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = function (t, a) { + var r = /raz/; + a(t(r), r, "Direct"); + r = new RegExp('foo'); + a(t(r), r, "Constructor"); + a.throws(function () { + t({}); + }, "Object"); + a.throws(function () { + t(function () {}); + }, "Function"); + a.throws(function () { + t({ exec: function () { return 20; } }); + }, "Plain object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/implement.js new file mode 100644 index 00000000000000..09bf3361acd6a2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/@@iterator/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/shim.js new file mode 100644 index 00000000000000..3b0e0b7547ece9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/@@iterator/shim.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + var it = t.call('r💩z'); + a.deep(it.next(), { done: false, value: 'r' }, "#1"); + a.deep(it.next(), { done: false, value: '💩' }, "#2"); + a.deep(it.next(), { done: false, value: 'z' }, "#3"); + a.deep(it.next(), { done: true, value: undefined }, "End"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/at.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/at.js new file mode 100644 index 00000000000000..2447a9f64d5d83 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/at.js @@ -0,0 +1,97 @@ +// See tests at https://github.com/mathiasbynens/String.prototype.at + +'use strict'; + +module.exports = function (t, a) { + a(t.length, 1, "Length"); + + a.h1("BMP"); + a(t.call('abc\uD834\uDF06def', -Infinity), '', "-Infinity"); + a(t.call('abc\uD834\uDF06def', -1), '', "-1"); + a(t.call('abc\uD834\uDF06def', -0), 'a', "-0"); + a(t.call('abc\uD834\uDF06def', +0), 'a', "+0"); + a(t.call('abc\uD834\uDF06def', 1), 'b', "1"); + a(t.call('abc\uD834\uDF06def', 3), '\uD834\uDF06', "3"); + a(t.call('abc\uD834\uDF06def', 4), '\uDF06', "4"); + a(t.call('abc\uD834\uDF06def', 5), 'd', "5"); + a(t.call('abc\uD834\uDF06def', 42), '', "42"); + a(t.call('abc\uD834\uDF06def', +Infinity), '', "+Infinity"); + a(t.call('abc\uD834\uDF06def', null), 'a', "null"); + a(t.call('abc\uD834\uDF06def', undefined), 'a', "undefined"); + a(t.call('abc\uD834\uDF06def'), 'a', "No argument"); + a(t.call('abc\uD834\uDF06def', false), 'a', "false"); + a(t.call('abc\uD834\uDF06def', NaN), 'a', "NaN"); + a(t.call('abc\uD834\uDF06def', ''), 'a', "Empty string"); + a(t.call('abc\uD834\uDF06def', '_'), 'a', "_"); + a(t.call('abc\uD834\uDF06def', '1'), 'b', "'1'"); + a(t.call('abc\uD834\uDF06def', []), 'a', "[]"); + a(t.call('abc\uD834\uDF06def', {}), 'a', "{}"); + a(t.call('abc\uD834\uDF06def', -0.9), 'a', "-0.9"); + a(t.call('abc\uD834\uDF06def', 1.9), 'b', "1.9"); + a(t.call('abc\uD834\uDF06def', 7.9), 'f', "7.9"); + a(t.call('abc\uD834\uDF06def', Math.pow(2, 32)), '', "Big number"); + + a.h1("Astral symbol"); + a(t.call('\uD834\uDF06def', -Infinity), '', "-Infinity"); + a(t.call('\uD834\uDF06def', -1), '', "-1"); + a(t.call('\uD834\uDF06def', -0), '\uD834\uDF06', "-0"); + a(t.call('\uD834\uDF06def', +0), '\uD834\uDF06', "+0"); + a(t.call('\uD834\uDF06def', 1), '\uDF06', "1"); + a(t.call('\uD834\uDF06def', 2), 'd', "2"); + a(t.call('\uD834\uDF06def', 3), 'e', "3"); + a(t.call('\uD834\uDF06def', 4), 'f', "4"); + a(t.call('\uD834\uDF06def', 42), '', "42"); + a(t.call('\uD834\uDF06def', +Infinity), '', "+Infinity"); + a(t.call('\uD834\uDF06def', null), '\uD834\uDF06', "null"); + a(t.call('\uD834\uDF06def', undefined), '\uD834\uDF06', "undefined"); + a(t.call('\uD834\uDF06def'), '\uD834\uDF06', "No arguments"); + a(t.call('\uD834\uDF06def', false), '\uD834\uDF06', "false"); + a(t.call('\uD834\uDF06def', NaN), '\uD834\uDF06', "NaN"); + a(t.call('\uD834\uDF06def', ''), '\uD834\uDF06', "Empty string"); + a(t.call('\uD834\uDF06def', '_'), '\uD834\uDF06', "_"); + a(t.call('\uD834\uDF06def', '1'), '\uDF06', "'1'"); + + a.h1("Lone high surrogates"); + a(t.call('\uD834abc', -Infinity), '', "-Infinity"); + a(t.call('\uD834abc', -1), '', "-1"); + a(t.call('\uD834abc', -0), '\uD834', "-0"); + a(t.call('\uD834abc', +0), '\uD834', "+0"); + a(t.call('\uD834abc', 1), 'a', "1"); + a(t.call('\uD834abc', 42), '', "42"); + a(t.call('\uD834abc', +Infinity), '', "Infinity"); + a(t.call('\uD834abc', null), '\uD834', "null"); + a(t.call('\uD834abc', undefined), '\uD834', "undefined"); + a(t.call('\uD834abc'), '\uD834', "No arguments"); + a(t.call('\uD834abc', false), '\uD834', "false"); + a(t.call('\uD834abc', NaN), '\uD834', "NaN"); + a(t.call('\uD834abc', ''), '\uD834', "Empty string"); + a(t.call('\uD834abc', '_'), '\uD834', "_"); + a(t.call('\uD834abc', '1'), 'a', "'a'"); + + a.h1("Lone low surrogates"); + a(t.call('\uDF06abc', -Infinity), '', "-Infinity"); + a(t.call('\uDF06abc', -1), '', "-1"); + a(t.call('\uDF06abc', -0), '\uDF06', "-0"); + a(t.call('\uDF06abc', +0), '\uDF06', "+0"); + a(t.call('\uDF06abc', 1), 'a', "1"); + a(t.call('\uDF06abc', 42), '', "42"); + a(t.call('\uDF06abc', +Infinity), '', "+Infinity"); + a(t.call('\uDF06abc', null), '\uDF06', "null"); + a(t.call('\uDF06abc', undefined), '\uDF06', "undefined"); + a(t.call('\uDF06abc'), '\uDF06', "No arguments"); + a(t.call('\uDF06abc', false), '\uDF06', "false"); + a(t.call('\uDF06abc', NaN), '\uDF06', "NaN"); + a(t.call('\uDF06abc', ''), '\uDF06', "Empty string"); + a(t.call('\uDF06abc', '_'), '\uDF06', "_"); + a(t.call('\uDF06abc', '1'), 'a', "'1'"); + + a.h1("Context"); + a.throws(function () { t.call(undefined); }, TypeError, "Undefined"); + a.throws(function () { t.call(undefined, 4); }, TypeError, + "Undefined + argument"); + a.throws(function () { t.call(null); }, TypeError, "Null"); + a.throws(function () { t.call(null, 4); }, TypeError, "Null + argument"); + a(t.call(42, 0), '4', "Number #1"); + a(t.call(42, 1), '2', "Number #2"); + a(t.call({ toString: function () { return 'abc'; } }, 2), 'c', "Object"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/camel-to-hyphen.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/camel-to-hyphen.js new file mode 100644 index 00000000000000..8b47a8158a29d3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/camel-to-hyphen.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('razDwaTRzy4yFoo45My'), 'raz-dwa-t-rzy4y-foo45-my'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/capitalize.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/capitalize.js new file mode 100644 index 00000000000000..fa11ff8eeff856 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/capitalize.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('raz'), 'Raz', "Word"); + a(t.call('BLA'), 'BLA', "Uppercase"); + a(t.call(''), '', "Empty"); + a(t.call('a'), 'A', "One letter"); + a(t.call('this is a test'), 'This is a test', "Sentence"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/case-insensitive-compare.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/case-insensitive-compare.js new file mode 100644 index 00000000000000..01a90c39ce8307 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/case-insensitive-compare.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call("AA", "aa"), 0, "Same"); + a.ok(t.call("Amber", "zebra") < 0, "Less"); + a.ok(t.call("Zebra", "amber") > 0, "Greater"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/implement.js new file mode 100644 index 00000000000000..5e33cd715ff47b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/implement.js @@ -0,0 +1,6 @@ +'use strict'; + +var isImplemented = + require('../../../../string/#/code-point-at/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/shim.js new file mode 100644 index 00000000000000..0df4751c564421 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/code-point-at/shim.js @@ -0,0 +1,81 @@ +// Taken from: https://github.com/mathiasbynens/String.prototype.codePointAt +// /blob/master/tests/tests.js + +'use strict'; + +module.exports = function (t, a) { + a(t.length, 1, "Length"); + + // String that starts with a BMP symbol + a(t.call('abc\uD834\uDF06def', ''), 0x61); + a(t.call('abc\uD834\uDF06def', '_'), 0x61); + a(t.call('abc\uD834\uDF06def'), 0x61); + a(t.call('abc\uD834\uDF06def', -Infinity), undefined); + a(t.call('abc\uD834\uDF06def', -1), undefined); + a(t.call('abc\uD834\uDF06def', -0), 0x61); + a(t.call('abc\uD834\uDF06def', 0), 0x61); + a(t.call('abc\uD834\uDF06def', 3), 0x1D306); + a(t.call('abc\uD834\uDF06def', 4), 0xDF06); + a(t.call('abc\uD834\uDF06def', 5), 0x64); + a(t.call('abc\uD834\uDF06def', 42), undefined); + a(t.call('abc\uD834\uDF06def', Infinity), undefined); + a(t.call('abc\uD834\uDF06def', Infinity), undefined); + a(t.call('abc\uD834\uDF06def', NaN), 0x61); + a(t.call('abc\uD834\uDF06def', false), 0x61); + a(t.call('abc\uD834\uDF06def', null), 0x61); + a(t.call('abc\uD834\uDF06def', undefined), 0x61); + + // String that starts with an astral symbol + a(t.call('\uD834\uDF06def', ''), 0x1D306); + a(t.call('\uD834\uDF06def', '1'), 0xDF06); + a(t.call('\uD834\uDF06def', '_'), 0x1D306); + a(t.call('\uD834\uDF06def'), 0x1D306); + a(t.call('\uD834\uDF06def', -1), undefined); + a(t.call('\uD834\uDF06def', -0), 0x1D306); + a(t.call('\uD834\uDF06def', 0), 0x1D306); + a(t.call('\uD834\uDF06def', 1), 0xDF06); + a(t.call('\uD834\uDF06def', 42), undefined); + a(t.call('\uD834\uDF06def', false), 0x1D306); + a(t.call('\uD834\uDF06def', null), 0x1D306); + a(t.call('\uD834\uDF06def', undefined), 0x1D306); + + // Lone high surrogates + a(t.call('\uD834abc', ''), 0xD834); + a(t.call('\uD834abc', '_'), 0xD834); + a(t.call('\uD834abc'), 0xD834); + a(t.call('\uD834abc', -1), undefined); + a(t.call('\uD834abc', -0), 0xD834); + a(t.call('\uD834abc', 0), 0xD834); + a(t.call('\uD834abc', false), 0xD834); + a(t.call('\uD834abc', NaN), 0xD834); + a(t.call('\uD834abc', null), 0xD834); + a(t.call('\uD834abc', undefined), 0xD834); + + // Lone low surrogates + a(t.call('\uDF06abc', ''), 0xDF06); + a(t.call('\uDF06abc', '_'), 0xDF06); + a(t.call('\uDF06abc'), 0xDF06); + a(t.call('\uDF06abc', -1), undefined); + a(t.call('\uDF06abc', -0), 0xDF06); + a(t.call('\uDF06abc', 0), 0xDF06); + a(t.call('\uDF06abc', false), 0xDF06); + a(t.call('\uDF06abc', NaN), 0xDF06); + a(t.call('\uDF06abc', null), 0xDF06); + a(t.call('\uDF06abc', undefined), 0xDF06); + + a.throws(function () { t.call(undefined); }, TypeError); + a.throws(function () { t.call(undefined, 4); }, TypeError); + a.throws(function () { t.call(null); }, TypeError); + a.throws(function () { t.call(null, 4); }, TypeError); + a(t.call(42, 0), 0x34); + a(t.call(42, 1), 0x32); + a(t.call({ toString: function () { return 'abc'; } }, 2), 0x63); + + a.throws(function () { t.apply(undefined); }, TypeError); + a.throws(function () { t.apply(undefined, [4]); }, TypeError); + a.throws(function () { t.apply(null); }, TypeError); + a.throws(function () { t.apply(null, [4]); }, TypeError); + a(t.apply(42, [0]), 0x34); + a(t.apply(42, [1]), 0x32); + a(t.apply({ toString: function () { return 'abc'; } }, [2]), 0x63); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/implement.js new file mode 100644 index 00000000000000..220f50d4672f13 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/contains/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/shim.js new file mode 100644 index 00000000000000..a0ea4db20812e5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/contains/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('raz', ''), true, "Empty"); + a(t.call('', ''), true, "Both Empty"); + a(t.call('raz', 'raz'), true, "Same"); + a(t.call('razdwa', 'raz'), true, "Starts with"); + a(t.call('razdwa', 'dwa'), true, "Ends with"); + a(t.call('razdwa', 'zdw'), true, "In middle"); + a(t.call('', 'raz'), false, "Something in empty"); + a(t.call('az', 'raz'), false, "Longer"); + a(t.call('azasdfasdf', 'azff'), false, "Not found"); + a(t.call('razdwa', 'raz', 1), false, "Position"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/implement.js new file mode 100644 index 00000000000000..93bd2ddcd6dc20 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/ends-with/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/shim.js new file mode 100644 index 00000000000000..e4b93c407bc2b5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/ends-with/shim.js @@ -0,0 +1,16 @@ +// In some parts copied from: +// http://closure-library.googlecode.com/svn/trunk/closure/goog/ +// string/string_test.html + +'use strict'; + +module.exports = function (t, a) { + a(t.call('abc', ''), true, "Empty needle"); + a(t.call('abcd', 'cd'), true, "Ends with needle"); + a(t.call('abcd', 'abcd'), true, "Needle equals haystack"); + a(t.call('abcd', 'ab'), false, "Doesn't end with needle"); + a(t.call('abc', 'defg'), false, "Length trick"); + a(t.call('razdwa', 'zd', 3), false, "Position: false"); + a(t.call('razdwa', 'zd', 4), true, "Position: true"); + a(t.call('razdwa', 'zd', 5), false, "Position: false #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/hyphen-to-camel.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/hyphen-to-camel.js new file mode 100644 index 00000000000000..bd7ded4befbc7d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/hyphen-to-camel.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('raz-dwa-t-rzy-4y-rtr4-tiu-45-pa'), 'razDwaTRzy4yRtr4Tiu45Pa'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/indent.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/indent.js new file mode 100644 index 00000000000000..eb92b36f5438d6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/indent.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('ra\nzz', ''), 'ra\nzz', "Empty"); + a(t.call('ra\nzz', '\t', 3), '\t\t\tra\n\t\t\tzz', "String repeat"); + a(t.call('ra\nzz\nsss\nfff\n', '\t'), '\tra\n\tzz\n\tsss\n\tfff\n', + "Multi-line"); + a(t.call('ra\n\nzz\n', '\t'), '\tra\n\n\tzz\n', "Don't touch empty lines"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/last.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/last.js new file mode 100644 index 00000000000000..ad36a213c6053e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/last.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call(''), null, "Null"); + a(t.call('abcdef'), 'f', "String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/_data.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/_data.js new file mode 100644 index 00000000000000..c741addb0055a9 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/_data.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t[0], 'object'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/implement.js new file mode 100644 index 00000000000000..4886c9b834285b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/normalize/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/shim.js new file mode 100644 index 00000000000000..28e27f595247be --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/normalize/shim.js @@ -0,0 +1,13 @@ +// Taken from: https://github.com/walling/unorm/blob/master/test/es6-shim.js + +'use strict'; + +var str = 'äiti'; + +module.exports = function (t, a) { + a(t.call(str), "\u00e4iti"); + a(t.call(str, "NFC"), "\u00e4iti"); + a(t.call(str, "NFD"), "a\u0308iti"); + a(t.call(str, "NFKC"), "\u00e4iti"); + a(t.call(str, "NFKD"), "a\u0308iti"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/pad.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/pad.js new file mode 100644 index 00000000000000..28c3fcaa10c4da --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/pad.js @@ -0,0 +1,24 @@ +'use strict'; + +var partial = require('../../../function/#/partial'); + +module.exports = { + Left: function (t, a) { + t = partial.call(t, 'x', 5); + + a(t.call('yy'), 'xxxyy'); + a(t.call(''), 'xxxxx', "Empty string"); + + a(t.call('yyyyy'), 'yyyyy', 'Equal length'); + a(t.call('yyyyyyy'), 'yyyyyyy', 'Longer'); + }, + Right: function (t, a) { + t = partial.call(t, 'x', -5); + + a(t.call('yy'), 'yyxxx'); + a(t.call(''), 'xxxxx', "Empty string"); + + a(t.call('yyyyy'), 'yyyyy', 'Equal length'); + a(t.call('yyyyyyy'), 'yyyyyyy', 'Longer'); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/plain-replace-all.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/plain-replace-all.js new file mode 100644 index 00000000000000..a425c87a40553b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/plain-replace-all.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('razdwatrzy', 'dwa', 'olera'), 'razoleratrzy', "Basic"); + a(t.call('razdwatrzy', 'dwa', 'ole$&a'), 'razole$&atrzy', "Inserts"); + a(t.call('razdwa', 'ola', 'sdfs'), 'razdwa', "No replace"); + + a(t.call('$raz$$dwa$trzy$', '$', '&&'), '&&raz&&&&dwa&&trzy&&', "Multi"); + a(t.call('$raz$$dwa$$$$trzy$', '$$', '&'), '$raz&dwa&&trzy$', + "Multi many chars"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/plain-replace.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/plain-replace.js new file mode 100644 index 00000000000000..54522ed749fe37 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/plain-replace.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('razdwatrzy', 'dwa', 'olera'), 'razoleratrzy', "Basic"); + a(t.call('razdwatrzy', 'dwa', 'ole$&a'), 'razole$&atrzy', "Inserts"); + a(t.call('razdwa', 'ola', 'sdfs'), 'razdwa', "No replace"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/implement.js new file mode 100644 index 00000000000000..7ff65a811068b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/repeat/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/shim.js new file mode 100644 index 00000000000000..7e0d077ec4bdb6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/repeat/shim.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function (t, a) { + a(t.call('a', 0), '', "Empty"); + a(t.call('a', 1), 'a', "1"); + a(t.call('\t', 5), '\t\t\t\t\t', "Whitespace"); + a(t.call('raz', 3), 'razrazraz', "Many chars"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/implement.js new file mode 100644 index 00000000000000..fc8490fc916ac3 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../../string/#/starts-with/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/shim.js new file mode 100644 index 00000000000000..e0e123b324e115 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/#/starts-with/shim.js @@ -0,0 +1,14 @@ +// Inspired and in some parts copied from: +// http://closure-library.googlecode.com/svn/trunk/closure/goog +// /string/string_test.html + +'use strict'; + +module.exports = function (t, a) { + a(t.call('abc', ''), true, "Empty needle"); + a(t.call('abcd', 'ab'), true, "Starts with needle"); + a(t.call('abcd', 'abcd'), true, "Needle equals haystack"); + a(t.call('abcd', 'bcde', 1), false, "Needle larger than haystack"); + a(!t.call('abcd', 'cd'), true, "Doesn't start with needle"); + a(t.call('abcd', 'bc', 1), true, "Position"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/format-method.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/format-method.js new file mode 100644 index 00000000000000..bb5561ee45bb59 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/format-method.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function (t, a) { + t = t({ a: 'A', aa: 'B', ab: 'C', b: 'D', + c: function () { return ++this.a; } }); + a(t.call({ a: 0 }, ' %a%aab%abb%b\\%aa%ab%c%c '), ' ABbCbD%aaC12 '); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/implement.js new file mode 100644 index 00000000000000..0aceb97efdcf36 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../string/from-code-point/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/shim.js new file mode 100644 index 00000000000000..88cda3d6364719 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/from-code-point/shim.js @@ -0,0 +1,47 @@ +// Taken from: https://github.com/mathiasbynens/String.fromCodePoint/blob/master +// /tests/tests.js + +'use strict'; + +var pow = Math.pow; + +module.exports = function (t, a) { + var counter, result; + + a(t.length, 1, "Length"); + a(String.propertyIsEnumerable('fromCodePoint'), false, "Not enumerable"); + + a(t(''), '\0', "Empty string"); + a(t(), '', "No arguments"); + a(t(-0), '\0', "-0"); + a(t(0), '\0', "0"); + a(t(0x1D306), '\uD834\uDF06', "Unicode"); + a(t(0x1D306, 0x61, 0x1D307), '\uD834\uDF06a\uD834\uDF07', "Complex unicode"); + a(t(0x61, 0x62, 0x1D307), 'ab\uD834\uDF07', "Complex"); + a(t(false), '\0', "false"); + a(t(null), '\0', "null"); + + a.throws(function () { t('_'); }, RangeError, "_"); + a.throws(function () { t(Infinity); }, RangeError, "Infinity"); + a.throws(function () { t(-Infinity); }, RangeError, "-Infinity"); + a.throws(function () { t(-1); }, RangeError, "-1"); + a.throws(function () { t(0x10FFFF + 1); }, RangeError, "Range error #1"); + a.throws(function () { t(3.14); }, RangeError, "Range error #2"); + a.throws(function () { t(3e-2); }, RangeError, "Range error #3"); + a.throws(function () { t(-Infinity); }, RangeError, "Range error #4"); + a.throws(function () { t(+Infinity); }, RangeError, "Range error #5"); + a.throws(function () { t(NaN); }, RangeError, "Range error #6"); + a.throws(function () { t(undefined); }, RangeError, "Range error #7"); + a.throws(function () { t({}); }, RangeError, "Range error #8"); + a.throws(function () { t(/re/); }, RangeError, "Range error #9"); + + counter = pow(2, 15) * 3 / 2; + result = []; + while (--counter >= 0) result.push(0); // one code unit per symbol + t.apply(null, result); // must not throw + + counter = pow(2, 15) * 3 / 2; + result = []; + while (--counter >= 0) result.push(0xFFFF + 1); // two code units per symbol + t.apply(null, result); // must not throw +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/is-string.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/is-string.js new file mode 100644 index 00000000000000..32f595829168ee --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/is-string.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function (t, a) { + a(t(null), false, "Null"); + a(t(''), true, "Empty string"); + a(t(12), false, "Number"); + a(t(false), false, "Boolean"); + a(t(new Date()), false, "Date"); + a(t(new String('raz')), true, "String object"); + a(t('asdfaf'), true, "String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/random-uniq.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/random-uniq.js new file mode 100644 index 00000000000000..6791ac266e7530 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/random-uniq.js @@ -0,0 +1,14 @@ +'use strict'; + +var isValidFormat = RegExp.prototype.test.bind(/^[a-z0-9]+$/); + +module.exports = function (t, a) { + a(typeof t(), 'string'); + a.ok(t().length > 7); + a.not(t(), t()); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); + a.ok(isValidFormat(t())); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/implement.js new file mode 100644 index 00000000000000..59416de3af53ad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/implement.js @@ -0,0 +1,5 @@ +'use strict'; + +var isImplemented = require('../../../string/raw/is-implemented'); + +module.exports = function (a) { a(isImplemented(), true); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/index.js new file mode 100644 index 00000000000000..2e0bfa3249d806 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./shim'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/shim.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/shim.js new file mode 100644 index 00000000000000..025ed780455667 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/string/raw/shim.js @@ -0,0 +1,15 @@ +// Partially taken from: +// https://github.com/paulmillr/es6-shim/blob/master/test/string.js + +'use strict'; + +module.exports = function (t, a) { + var callSite = []; + + callSite.raw = ["The total is ", " ($", " with tax)"]; + a(t(callSite, '{total}', '{total * 1.01}'), + 'The total is {total} (${total * 1.01} with tax)'); + + callSite.raw = []; + a(t(callSite, '{total}', '{total * 1.01}'), ''); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/#/chain.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/#/chain.js new file mode 100644 index 00000000000000..6dc1543b354531 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/#/chain.js @@ -0,0 +1,40 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('../') + , validIterable = require('../valid-iterable') + + , push = Array.prototype.push + , defineProperties = Object.defineProperties + , IteratorChain; + +IteratorChain = function (iterators) { + defineProperties(this, { + __iterators__: d('', iterators), + __current__: d('w', iterators.shift()) + }); +}; +if (setPrototypeOf) setPrototypeOf(IteratorChain, Iterator); + +IteratorChain.prototype = Object.create(Iterator.prototype, { + constructor: d(IteratorChain), + next: d(function () { + var result; + if (!this.__current__) return { done: true, value: undefined }; + result = this.__current__.next(); + while (result.done) { + this.__current__ = this.__iterators__.shift(); + if (!this.__current__) return { done: true, value: undefined }; + result = this.__current__.next(); + } + return result; + }) +}); + +module.exports = function () { + var iterators = [this]; + push.apply(iterators, arguments); + iterators.forEach(validIterable); + return new IteratorChain(iterators); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.lint b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.lint new file mode 100644 index 00000000000000..cf54d815684b2f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.lint @@ -0,0 +1,11 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.travis.yml new file mode 100644 index 00000000000000..02c277cf565442 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-iterator@medikoo.com + +script: "npm test && npm run lint" diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/CHANGES new file mode 100644 index 00000000000000..a2d1ec7c2af31c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/CHANGES @@ -0,0 +1,28 @@ +v0.1.3 -- 2015.02.02 +* Update dependencies +* Fix spelling of LICENSE + +v0.1.2 -- 2014.11.19 +* Optimise internal `_next` to not verify internal's list length at all times + (#2 thanks @RReverser) +* Fix documentation examples +* Configure lint scripts + +v0.1.1 -- 2014.04.29 +* Fix es6-symbol dependency version + +v0.1.0 -- 2014.04.29 +* Assure strictly npm hosted dependencies +* Remove sparse arrays dedicated handling (as per spec) +* Add: isIterable, validIterable and chain (method) +* Remove toArray, it's addressed by Array.from (polyfil can be found in es5-ext/array/from) +* Add break possiblity to 'forOf' via 'doBreak' function argument +* Provide dedicated iterator for array-likes (ArrayIterator) and for strings (StringIterator) +* Provide @@toStringTag symbol +* When available rely on @@iterator symbol +* Remove 32bit integer maximum list length restriction +* Improve Iterator internals +* Update to use latest version of dependencies + +v0.0.0 -- 2013.10.12 +Initial (dev version) \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/LICENSE new file mode 100644 index 00000000000000..04724a3ab1b70b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/README.md b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/README.md new file mode 100644 index 00000000000000..288373da7ab506 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/README.md @@ -0,0 +1,148 @@ +# es6-iterator +## ECMAScript 6 Iterator interface + +### Installation + + $ npm install es6-iterator + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +## API + +### Constructors + +#### Iterator(list) _(es6-iterator)_ + +Abstract Iterator interface. Meant for extensions and not to be used on its own. + +Accepts any _list_ object (technically object with numeric _length_ property). + +_Mind it doesn't iterate strings properly, for that use dedicated [StringIterator](#string-iterator)_ + +```javascript +var Iterator = require('es6-iterator') +var iterator = new Iterator([1, 2, 3]); + +iterator.next(); // { value: 1, done: false } +iterator.next(); // { value: 2, done: false } +iterator.next(); // { value: 3, done: false } +iterator.next(); // { value: undefined, done: true } +``` + + +#### ArrayIterator(arrayLike[, kind]) _(es6-iterator/array)_ + +Dedicated for arrays and array-likes. Supports three iteration kinds: +* __value__ _(default)_ - Iterates values +* __key__ - Iterates indexes +* __key+value__ - Iterates keys and indexes, each iteration value is in _[key, value]_ form. + + +```javascript +var ArrayIterator = require('es6-iterator/array') +var iterator = new ArrayIterator([1, 2, 3], 'key+value'); + +iterator.next(); // { value: [0, 1], done: false } +iterator.next(); // { value: [1, 2], done: false } +iterator.next(); // { value: [2, 3], done: false } +iterator.next(); // { value: undefined, done: true } +``` + +May also be used for _arguments_ objects: + +```javascript +(function () { + var iterator = new ArrayIterator(arguments); + + iterator.next(); // { value: 1, done: false } + iterator.next(); // { value: 2, done: false } + iterator.next(); // { value: 3, done: false } + iterator.next(); // { value: undefined, done: true } +}(1, 2, 3)); +``` + +#### StringIterator(str) _(es6-iterator/string)_ + +Assures proper iteration over unicode symbols. +See: http://mathiasbynens.be/notes/javascript-unicode + +```javascript +var StringIterator = require('es6-iterator/string'); +var iterator = new StringIterator('f🙈o🙉o🙊'); + +iterator.next(); // { value: 'f', done: false } +iterator.next(); // { value: '🙈', done: false } +iterator.next(); // { value: 'o', done: false } +iterator.next(); // { value: '🙉', done: false } +iterator.next(); // { value: 'o', done: false } +iterator.next(); // { value: '🙊', done: false } +iterator.next(); // { value: undefined, done: true } +``` + +### Function utilities + +#### forOf(iterable, callback[, thisArg]) _(es6-iterator/for-of)_ + +Polyfill for ECMAScript 6 [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) statement. + +``` +var forOf = require('es6-iterator/for-of'); +var result = []; + +forOf('🙈🙉🙊', function (monkey) { result.push(monkey); }); +console.log(result); // ['🙈', '🙉', '🙊']; +``` + +Optionally you can break iteration at any point: + +```javascript +var result = []; + +forOf([1,2,3,4]', function (val, doBreak) { + result.push(monkey); + if (val >= 3) doBreak(); +}); +console.log(result); // [1, 2, 3]; +``` + +#### get(obj) _(es6-iterator/get)_ + +Return iterator for any iterable object. + +```javascript +var getIterator = require('es6-iterator/get'); +var iterator = get([1,2,3]); + +iterator.next(); // { value: 1, done: false } +iterator.next(); // { value: 2, done: false } +iterator.next(); // { value: 3, done: false } +iterator.next(); // { value: undefined, done: true } +``` + +#### isIterable(obj) _(es6-iterator/is-iterable)_ + +Whether _obj_ is iterable + +```javascript +var isIterable = require('es6-iterator/is-iterable'); + +isIterable(null); // false +isIterable(true); // false +isIterable('str'); // true +isIterable(['a', 'r', 'r']); // true +isIterable(new ArrayIterator([])); // true +``` + +#### validIterable(obj) _(es6-iterator/valid-iterable)_ + +If _obj_ is an iterable it is returned. Otherwise _TypeError_ is thrown. + +### Method extensions + +#### iterator.chain(iterator1[, …iteratorn]) _(es6-iterator/#/chain)_ + +Chain multiple iterators into one. + +### Tests [![Build Status](https://travis-ci.org/medikoo/es6-iterator.png)](https://travis-ci.org/medikoo/es6-iterator) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/array.js new file mode 100644 index 00000000000000..885ad0a4fd7870 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/array.js @@ -0,0 +1,30 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , contains = require('es5-ext/string/#/contains') + , d = require('d') + , Iterator = require('./') + + , defineProperty = Object.defineProperty + , ArrayIterator; + +ArrayIterator = module.exports = function (arr, kind) { + if (!(this instanceof ArrayIterator)) return new ArrayIterator(arr, kind); + Iterator.call(this, arr); + if (!kind) kind = 'value'; + else if (contains.call(kind, 'key+value')) kind = 'key+value'; + else if (contains.call(kind, 'key')) kind = 'key'; + else kind = 'value'; + defineProperty(this, '__kind__', d('', kind)); +}; +if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); + +ArrayIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(ArrayIterator), + _resolve: d(function (i) { + if (this.__kind__ === 'value') return this.__list__[i]; + if (this.__kind__ === 'key+value') return [i, this.__list__[i]]; + return i; + }), + toString: d(function () { return '[object Array Iterator]'; }) +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/for-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/for-of.js new file mode 100644 index 00000000000000..111f5522735204 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/for-of.js @@ -0,0 +1,44 @@ +'use strict'; + +var callable = require('es5-ext/object/valid-callable') + , isString = require('es5-ext/string/is-string') + , get = require('./get') + + , isArray = Array.isArray, call = Function.prototype.call; + +module.exports = function (iterable, cb/*, thisArg*/) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code; + if (isArray(iterable)) mode = 'array'; + else if (isString(iterable)) mode = 'string'; + else iterable = get(iterable); + + callable(cb); + doBreak = function () { broken = true; }; + if (mode === 'array') { + iterable.some(function (value) { + call.call(cb, thisArg, value, doBreak); + if (broken) return true; + }); + return; + } + if (mode === 'string') { + l = iterable.length; + for (i = 0; i < l; ++i) { + char = iterable[i]; + if ((i + 1) < l) { + code = char.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i]; + } + call.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); + + while (!result.done) { + call.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/get.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/get.js new file mode 100644 index 00000000000000..38230fd85a2101 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/get.js @@ -0,0 +1,13 @@ +'use strict'; + +var isString = require('es5-ext/string/is-string') + , ArrayIterator = require('./array') + , StringIterator = require('./string') + , iterable = require('./valid-iterable') + , iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (obj) { + if (typeof iterable(obj)[iteratorSymbol] === 'function') return obj[iteratorSymbol](); + if (isString(obj)) return new StringIterator(obj); + return new ArrayIterator(obj); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/index.js new file mode 100644 index 00000000000000..10fd08958f68c7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/index.js @@ -0,0 +1,90 @@ +'use strict'; + +var clear = require('es5-ext/array/#/clear') + , assign = require('es5-ext/object/assign') + , callable = require('es5-ext/object/valid-callable') + , value = require('es5-ext/object/valid-value') + , d = require('d') + , autoBind = require('d/auto-bind') + , Symbol = require('es6-symbol') + + , defineProperty = Object.defineProperty + , defineProperties = Object.defineProperties + , Iterator; + +module.exports = Iterator = function (list, context) { + if (!(this instanceof Iterator)) return new Iterator(list, context); + defineProperties(this, { + __list__: d('w', value(list)), + __context__: d('w', context), + __nextIndex__: d('w', 0) + }); + if (!context) return; + callable(context.on); + context.on('_add', this._onAdd); + context.on('_delete', this._onDelete); + context.on('_clear', this._onClear); +}; + +defineProperties(Iterator.prototype, assign({ + constructor: d(Iterator), + _next: d(function () { + var i; + if (!this.__list__) return; + if (this.__redo__) { + i = this.__redo__.shift(); + if (i !== undefined) return i; + } + if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; + this._unBind(); + }), + next: d(function () { return this._createResult(this._next()); }), + _createResult: d(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: d(function (i) { return this.__list__[i]; }), + _unBind: d(function () { + this.__list__ = null; + delete this.__redo__; + if (!this.__context__) return; + this.__context__.off('_add', this._onAdd); + this.__context__.off('_delete', this._onDelete); + this.__context__.off('_clear', this._onClear); + this.__context__ = null; + }), + toString: d(function () { return '[object Iterator]'; }) +}, autoBind({ + _onAdd: d(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + defineProperty(this, '__redo__', d('c', [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: d(function (index) { + var i; + if (index >= this.__nextIndex__) return; + --this.__nextIndex__; + if (!this.__redo__) return; + i = this.__redo__.indexOf(index); + if (i !== -1) this.__redo__.splice(i, 1); + this.__redo__.forEach(function (redo, i) { + if (redo > index) this.__redo__[i] = --redo; + }, this); + }), + _onClear: d(function () { + if (this.__redo__) clear.call(this.__redo__); + this.__nextIndex__ = 0; + }) +}))); + +defineProperty(Iterator.prototype, Symbol.iterator, d(function () { + return this; +})); +defineProperty(Iterator.prototype, Symbol.toStringTag, d('', 'Iterator')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/is-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/is-iterable.js new file mode 100644 index 00000000000000..bbcf10492e1dc0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/is-iterable.js @@ -0,0 +1,13 @@ +'use strict'; + +var isString = require('es5-ext/string/is-string') + , iteratorSymbol = require('es6-symbol').iterator + + , isArray = Array.isArray; + +module.exports = function (value) { + if (value == null) return false; + if (isArray(value)) return true; + if (isString(value)) return true; + return (typeof value[iteratorSymbol] === 'function'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/package.json b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/package.json new file mode 100644 index 00000000000000..593d080e609275 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/package.json @@ -0,0 +1,66 @@ +{ + "name": "es6-iterator", + "version": "0.1.3", + "description": "Iterator abstraction based on ES6 specification", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "iterator", + "array", + "list", + "set", + "map", + "generator" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-iterator.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.5", + "es6-symbol": "~2.0.1" + }, + "devDependencies": { + "event-emitter": "~0.3.3", + "tad": "~0.2.1", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "2addc362c6f139e4941cf4726eeb59e5960c5cef", + "bugs": { + "url": "https://github.com/medikoo/es6-iterator/issues" + }, + "homepage": "https://github.com/medikoo/es6-iterator", + "_id": "es6-iterator@0.1.3", + "_shasum": "d6f58b8c4fc413c249b4baa19768f8e4d7c8944e", + "_from": "es6-iterator@>=0.1.1 <0.2.0", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.11.16", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "d6f58b8c4fc413c249b4baa19768f8e4d7c8944e", + "tarball": "http://registry.npmjs.org/es6-iterator/-/es6-iterator-0.1.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-0.1.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/string.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/string.js new file mode 100644 index 00000000000000..cdb39ea4e49931 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/string.js @@ -0,0 +1,37 @@ +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols + +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , d = require('d') + , Iterator = require('./') + + , defineProperty = Object.defineProperty + , StringIterator; + +StringIterator = module.exports = function (str) { + if (!(this instanceof StringIterator)) return new StringIterator(str); + str = String(str); + Iterator.call(this, str); + defineProperty(this, '__length__', d('', str.length)); + +}; +if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); + +StringIterator.prototype = Object.create(Iterator.prototype, { + constructor: d(StringIterator), + _next: d(function () { + if (!this.__list__) return; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + }), + _resolve: d(function (i) { + var char = this.__list__[i], code; + if (this.__nextIndex__ === this.__length__) return char; + code = char.charCodeAt(0); + if ((code >= 0xD800) && (code <= 0xDBFF)) return char + this.__list__[this.__nextIndex__++]; + return char; + }), + toString: d(function () { return '[object String Iterator]'; }) +}); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/#/chain.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/#/chain.js new file mode 100644 index 00000000000000..a414c66d78f44f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/#/chain.js @@ -0,0 +1,23 @@ +'use strict'; + +var Iterator = require('../../'); + +module.exports = function (t, a) { + var i1 = new Iterator(['raz', 'dwa', 'trzy']) + , i2 = new Iterator(['cztery', 'pięć', 'sześć']) + , i3 = new Iterator(['siedem', 'osiem', 'dziewięć']) + + , iterator = t.call(i1, i2, i3); + + a.deep(iterator.next(), { done: false, value: 'raz' }, "#1"); + a.deep(iterator.next(), { done: false, value: 'dwa' }, "#2"); + a.deep(iterator.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(iterator.next(), { done: false, value: 'cztery' }, "#4"); + a.deep(iterator.next(), { done: false, value: 'pięć' }, "#5"); + a.deep(iterator.next(), { done: false, value: 'sześć' }, "#6"); + a.deep(iterator.next(), { done: false, value: 'siedem' }, "#7"); + a.deep(iterator.next(), { done: false, value: 'osiem' }, "#8"); + a.deep(iterator.next(), { done: false, value: 'dziewięć' }, "#9"); + a.deep(iterator.next(), { done: true, value: undefined }, "Done #1"); + a.deep(iterator.next(), { done: true, value: undefined }, "Done #2"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/array.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/array.js new file mode 100644 index 00000000000000..ae7c2199e84a72 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/array.js @@ -0,0 +1,67 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (T) { + return { + Values: function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it; + + it = new T(x); + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.splice(1, 0, 'elo'); + a.deep(it.next(), { done: false, value: 'dwa' }, "Insert"); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + x.pop(); + a.deep(it.next(), { done: false, value: 'pięć' }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Keys & Values": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it; + + it = new T(x, 'key+value'); + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: [0, 'raz'] }, "#1"); + a.deep(it.next(), { done: false, value: [1, 'dwa'] }, "#2"); + x.splice(1, 0, 'elo'); + a.deep(it.next(), { done: false, value: [2, 'dwa'] }, "Insert"); + a.deep(it.next(), { done: false, value: [3, 'trzy'] }, "#3"); + a.deep(it.next(), { done: false, value: [4, 'cztery'] }, "#4"); + x.pop(); + a.deep(it.next(), { done: false, value: [5, 'pięć'] }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + Keys: function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], it; + + it = new T(x, 'key'); + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: 0 }, "#1"); + a.deep(it.next(), { done: false, value: 1 }, "#2"); + x.splice(1, 0, 'elo'); + a.deep(it.next(), { done: false, value: 2 }, "Insert"); + a.deep(it.next(), { done: false, value: 3 }, "#3"); + a.deep(it.next(), { done: false, value: 4 }, "#4"); + x.pop(); + a.deep(it.next(), { done: false, value: 5 }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + Sparse: function (a) { + var x = new Array(6), it; + + x[2] = 'raz'; + x[4] = 'dwa'; + it = new T(x); + a.deep(it.next(), { done: false, value: undefined }, "#1"); + a.deep(it.next(), { done: false, value: undefined }, "#2"); + a.deep(it.next(), { done: false, value: 'raz' }, "#3"); + a.deep(it.next(), { done: false, value: undefined }, "#4"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#5"); + a.deep(it.next(), { done: false, value: undefined }, "#6"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/for-of.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/for-of.js new file mode 100644 index 00000000000000..502e7b767f61b2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/for-of.js @@ -0,0 +1,35 @@ +'use strict'; + +var ArrayIterator = require('../array') + + , slice = Array.prototype.slice; + +module.exports = function (t, a) { + var i = 0, x = ['raz', 'dwa', 'trzy'], y = {}, called = 0; + t(x, function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Array " + i + "#"); + a(this, y, "Array: context: " + (i++) + "#"); + }, y); + i = 0; + t(x = 'foo', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Regular String: context: " + (i++) + "#"); + }, y); + i = 0; + x = ['r', '💩', 'z']; + t('r💩z', function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "String " + i + "#"); + a(this, y, "Unicode String: context: " + (i++) + "#"); + }, y); + i = 0; + t(new ArrayIterator(x), function () { + a.deep(slice.call(arguments, 0, 1), [x[i]], "Iterator " + i + "#"); + a(this, y, "Iterator: context: " + (i++) + "#"); + }, y); + + t(x = ['raz', 'dwa', 'trzy'], function (value, doBreak) { + ++called; + return doBreak(); + }); + a(called, 1, "Break"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/get.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/get.js new file mode 100644 index 00000000000000..7309590cba5689 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/get.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , Iterator = require('../'); + +module.exports = function (t, a) { + var iterator; + a.throws(function () { t(); }, TypeError, "Null"); + a.throws(function () { t({}); }, TypeError, "Plain object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + iterator = {}; + iterator[iteratorSymbol] = function () { return new Iterator([]); }; + a(t(iterator) instanceof Iterator, true, "Iterator"); + a(String(t([])), '[object Array Iterator]', " Array"); + a(String(t('foo')), '[object String Iterator]', "String"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/index.js new file mode 100644 index 00000000000000..ea3621adfebeb5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/index.js @@ -0,0 +1,99 @@ +'use strict'; + +var ee = require('event-emitter') + , iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (T) { + return { + "": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć'], it, y, z; + + it = new T(x); + a(it[iteratorSymbol](), it, "@@iterator"); + y = it.next(); + a.deep(y, { done: false, value: 'raz' }, "#1"); + z = it.next(); + a.not(y, z, "Recreate result"); + a.deep(z, { done: false, value: 'dwa' }, "#2"); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + a.deep(it.next(), { done: false, value: 'pięć' }, "#5"); + a.deep(y = it.next(), { done: true, value: undefined }, "End"); + a.not(y, it.next(), "Recreate result on dead"); + }, + Emited: function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + y.emit('_add', x.push('sześć') - 1); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + x.splice(1, 0, 'półtora'); + y.emit('_add', 1); + a.deep(it.next(), { done: false, value: 'półtora' }, "Insert"); + x.splice(5, 1); + y.emit('_delete', 5); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + a.deep(it.next(), { done: false, value: 'sześć' }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited #2": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.splice(1, 0, 'półtora'); + y.emit('_add', 1); + x.splice(1, 0, '1.25'); + y.emit('_add', 1); + x.splice(0, 1); + y.emit('_delete', 0); + a.deep(it.next(), { done: false, value: 'półtora' }, "Insert"); + a.deep(it.next(), { done: false, value: '1.25' }, "Insert #2"); + a.deep(it.next(), { done: false, value: 'trzy' }, "#3"); + a.deep(it.next(), { done: false, value: 'cztery' }, "#4"); + x.splice(5, 1); + y.emit('_delete', 5); + a.deep(it.next(), { done: false, value: 'sześć' }, "#5"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #1": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.length = 0; + y.emit('_clear'); + a.deep(it.next(), { done: true, value: undefined }, "End"); + }, + "Emited: Clear #2": function (a) { + var x = ['raz', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć'], y, it; + + y = ee(); + it = new T(x, y); + a.deep(it.next(), { done: false, value: 'raz' }, "#1"); + a.deep(it.next(), { done: false, value: 'dwa' }, "#2"); + x.length = 0; + y.emit('_clear'); + x.push('foo'); + x.push('bar'); + a.deep(it.next(), { done: false, value: 'foo' }, "#3"); + a.deep(it.next(), { done: false, value: 'bar' }, "#4"); + x.splice(1, 0, 'półtora'); + y.emit('_add', 1); + x.splice(1, 0, '1.25'); + y.emit('_add', 1); + x.splice(0, 1); + y.emit('_delete', 0); + a.deep(it.next(), { done: false, value: 'półtora' }, "Insert"); + a.deep(it.next(), { done: false, value: '1.25' }, "Insert #2"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + } + }; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/is-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/is-iterable.js new file mode 100644 index 00000000000000..7c5c59b6d75a62 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/is-iterable.js @@ -0,0 +1,18 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , Iterator = require('../'); + +module.exports = function (t, a) { + var iterator; + a(t(), false, "Undefined"); + a(t(123), false, "Number"); + a(t({}), false, "Plain object"); + a(t({ length: 0 }), false, "Array-like"); + iterator = {}; + iterator[iteratorSymbol] = function () { return new Iterator([]); }; + a(t(iterator), true, "Iterator"); + a(t([]), true, "Array"); + a(t('foo'), true, "String"); + a(t(''), true, "Empty string"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/string.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/string.js new file mode 100644 index 00000000000000..d11855f2511609 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/string.js @@ -0,0 +1,23 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator; + +module.exports = function (T, a) { + var it = new T('foobar'); + + a(it[iteratorSymbol](), it, "@@iterator"); + a.deep(it.next(), { done: false, value: 'f' }, "#1"); + a.deep(it.next(), { done: false, value: 'o' }, "#2"); + a.deep(it.next(), { done: false, value: 'o' }, "#3"); + a.deep(it.next(), { done: false, value: 'b' }, "#4"); + a.deep(it.next(), { done: false, value: 'a' }, "#5"); + a.deep(it.next(), { done: false, value: 'r' }, "#6"); + a.deep(it.next(), { done: true, value: undefined }, "End"); + + a.h1("Outside of BMP"); + it = new T('r💩z'); + a.deep(it.next(), { done: false, value: 'r' }, "#1"); + a.deep(it.next(), { done: false, value: '💩' }, "#2"); + a.deep(it.next(), { done: false, value: 'z' }, "#3"); + a.deep(it.next(), { done: true, value: undefined }, "End"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/valid-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/valid-iterable.js new file mode 100644 index 00000000000000..7760b017826085 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/test/valid-iterable.js @@ -0,0 +1,16 @@ +'use strict'; + +var iteratorSymbol = require('es6-symbol').iterator + , Iterator = require('../'); + +module.exports = function (t, a) { + var obj; + a.throws(function () { t(); }, TypeError, "Undefined"); + a.throws(function () { t({}); }, TypeError, "Plain object"); + a.throws(function () { t({ length: 0 }); }, TypeError, "Array-like"); + obj = {}; + obj[iteratorSymbol] = function () { return new Iterator([]); }; + a(t(obj), obj, "Iterator"); + obj = []; + a(t(obj), obj, 'Array'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/valid-iterable.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/valid-iterable.js new file mode 100644 index 00000000000000..d330997cb1d6af --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-iterator/valid-iterable.js @@ -0,0 +1,8 @@ +'use strict'; + +var isIterable = require('./is-iterable'); + +module.exports = function (value) { + if (!isIterable(value)) throw new TypeError(value + " is not iterable"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.lint b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.lint new file mode 100644 index 00000000000000..1851752f99bfda --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.lint @@ -0,0 +1,13 @@ +@root + +module + +tabs +indent 2 +maxlen 100 + +ass +nomen +plusplus +newcap +vars diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.npmignore b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.npmignore new file mode 100644 index 00000000000000..155e41f69142ef --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.npmignore @@ -0,0 +1,4 @@ +.DS_Store +/node_modules +/npm-debug.log +/.lintcache diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.travis.yml b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.travis.yml new file mode 100644 index 00000000000000..afd3509a26b27d --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 + +notifications: + email: + - medikoo+es6-symbol@medikoo.com diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/CHANGES b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/CHANGES new file mode 100644 index 00000000000000..df8c27efc38de2 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/CHANGES @@ -0,0 +1,34 @@ +v2.0.1 -- 2015.01.28 +* Fix Symbol.prototype[Symbol.isPrimitive] implementation +* Improve validation within Symbol.prototype.toString and + Symbol.prototype.valueOf + +v2.0.0 -- 2015.01.28 +* Update up to changes in specification: + * Implement `for` and `keyFor` + * Remove `Symbol.create` and `Symbol.isRegExp` + * Add `Symbol.match`, `Symbol.replace`, `Symbol.search`, `Symbol.species` and + `Symbol.split` +* Rename `validSymbol` to `validateSymbol` +* Improve documentation +* Remove dead test modules + +v1.0.0 -- 2015.01.26 +* Fix enumerability for symbol properties set normally (e.g. obj[symbol] = value) +* Introduce initialization via hidden constructor +* Fix isSymbol handling of polyfill values when native Symbol is present +* Fix spelling of LICENSE +* Configure lint scripts + +v0.1.1 -- 2014.10.07 +* Fix isImplemented, so it returns true in case of polyfill +* Improve documentations + +v0.1.0 -- 2014.04.28 +* Assure strictly npm dependencies +* Update to use latest versions of dependencies +* Fix implementation detection so it doesn't crash on `String(symbol)` +* throw on `new Symbol()` (as decided by TC39) + +v0.0.0 -- 2013.11.15 +* Initial (dev) version \ No newline at end of file diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/LICENSE b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/LICENSE new file mode 100644 index 00000000000000..04724a3ab1b70b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2013-2015 Mariusz Nowak (www.medikoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/README.md b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/README.md new file mode 100644 index 00000000000000..95d6780ba78cb4 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/README.md @@ -0,0 +1,71 @@ +# es6-symbol +## ECMAScript 6 Symbol polyfill + +For more information about symbols see following links +- [Symbols in ECMAScript 6 by Axel Rauschmayer](http://www.2ality.com/2014/12/es6-symbols.html) +- [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) +- [Specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-constructor) + +### Limitations + +Underneath it uses real string property names which can easily be retrieved, however accidental collision with other property names is unlikely. + +### Usage + +If you'd like to use native version when it exists and fallback to polyfill if it doesn't (but without implementing `Symbol` on global scope), do: + +```javascript +var Symbol = require('es6-symbol'); +``` + +If you want to make sure your environment implements `Symbol`, do: + +```javascript +require('es6-symbol/implement'); +``` + +If you strictly want to use polyfill even if native `Symbol` exists (hard to find a good reason for that), do: + +```javascript +var Symbol = require('es6-symbol/polyfill'); +``` + +#### API + +Best is to refer to [specification](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-objects). Still if you want quick look, follow examples: + +```javascript +var Symbol = require('es6-symbol'); + +var symbol = Symbol('My custom symbol'); +var x = {}; + +x[symbol] = 'foo'; +console.log(x[symbol]); 'foo' + +// Detect iterable: +var iterator, result; +if (possiblyIterable[Symbol.iterator]) { + iterator = possiblyIterable[Symbol.iterator](); + result = iterator.next(); + while(!result.done) { + console.log(result.value); + result = iterator.next(); + } +} +``` + +### Installation +#### NPM + +In your project path: + + $ npm install es6-symbol + +##### Browser + +To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/) + +## Tests [![Build Status](https://travis-ci.org/medikoo/es6-symbol.png)](https://travis-ci.org/medikoo/es6-symbol) + + $ npm test diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/implement.js new file mode 100644 index 00000000000000..153edacdbedf9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/implement.js @@ -0,0 +1,7 @@ +'use strict'; + +if (!require('./is-implemented')()) { + Object.defineProperty(require('es5-ext/global'), 'Symbol', + { value: require('./polyfill'), configurable: true, enumerable: false, + writable: true }); +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/index.js new file mode 100644 index 00000000000000..609f1faf551164 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-implemented.js new file mode 100644 index 00000000000000..53759f32124b1c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-implemented.js @@ -0,0 +1,18 @@ +'use strict'; + +module.exports = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + if (typeof Symbol.iterator === 'symbol') return true; + + // Return 'true' for polyfills + if (typeof Symbol.isConcatSpreadable !== 'object') return false; + if (typeof Symbol.iterator !== 'object') return false; + if (typeof Symbol.toPrimitive !== 'object') return false; + if (typeof Symbol.toStringTag !== 'object') return false; + if (typeof Symbol.unscopables !== 'object') return false; + + return true; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-native-implemented.js new file mode 100644 index 00000000000000..a8cb8b8681ee69 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-native-implemented.js @@ -0,0 +1,8 @@ +// Exports true if environment provides native `Symbol` implementation + +'use strict'; + +module.exports = (function () { + if (typeof Symbol !== 'function') return false; + return (typeof Symbol.iterator === 'symbol'); +}()); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-symbol.js new file mode 100644 index 00000000000000..beeba2cb4fa23f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/is-symbol.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function (x) { + return (x && ((typeof x === 'symbol') || (x['@@toStringTag'] === 'Symbol'))) || false; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/package.json b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/package.json new file mode 100644 index 00000000000000..0efffeaec90658 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/package.json @@ -0,0 +1,63 @@ +{ + "name": "es6-symbol", + "version": "2.0.1", + "description": "ECMAScript6 Symbol polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "symbol", + "private", + "property", + "es6", + "ecmascript", + "harmony" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-symbol.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.5" + }, + "devDependencies": { + "tad": "~0.2.1", + "xlint": "~0.2.2", + "xlint-jslint-medikoo": "~0.1.2" + }, + "scripts": { + "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", + "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "51f6938d7830269fefa38f02eb912f5472b3ccd7", + "bugs": { + "url": "https://github.com/medikoo/es6-symbol/issues" + }, + "homepage": "https://github.com/medikoo/es6-symbol", + "_id": "es6-symbol@2.0.1", + "_shasum": "761b5c67cfd4f1d18afb234f691d678682cb3bf3", + "_from": "es6-symbol@>=2.0.1 <2.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "761b5c67cfd4f1d18afb234f691d678682cb3bf3", + "tarball": "http://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-2.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/polyfill.js new file mode 100644 index 00000000000000..735eb676b23c9b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/polyfill.js @@ -0,0 +1,77 @@ +'use strict'; + +var d = require('d') + , validateSymbol = require('./validate-symbol') + + , create = Object.create, defineProperties = Object.defineProperties + , defineProperty = Object.defineProperty, objPrototype = Object.prototype + , Symbol, HiddenSymbol, globalSymbols = create(null); + +var generateName = (function () { + var created = create(null); + return function (desc) { + var postfix = 0, name; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + defineProperty(objPrototype, name, d.gs(null, function (value) { + defineProperty(this, name, d(value)); + })); + return name; + }; +}()); + +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor'); + return Symbol(description); +}; +module.exports = Symbol = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor'); + symbol = create(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: d('', description), + __name__: d('', generateName(description)) + }); +}; +defineProperties(Symbol, { + for: d(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = Symbol(String(key))); + }), + keyFor: d(function (s) { + var key; + validateSymbol(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + hasInstance: d('', Symbol('hasInstance')), + isConcatSpreadable: d('', Symbol('isConcatSpreadable')), + iterator: d('', Symbol('iterator')), + match: d('', Symbol('match')), + replace: d('', Symbol('replace')), + search: d('', Symbol('search')), + species: d('', Symbol('species')), + split: d('', Symbol('split')), + toPrimitive: d('', Symbol('toPrimitive')), + toStringTag: d('', Symbol('toStringTag')), + unscopables: d('', Symbol('unscopables')) +}); +defineProperties(HiddenSymbol.prototype, { + constructor: d(Symbol), + toString: d('', function () { return this.__name__; }) +}); + +defineProperties(Symbol.prototype, { + toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), + valueOf: d(function () { return validateSymbol(this); }) +}); +defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', + function () { return validateSymbol(this); })); +defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol')); + +defineProperty(HiddenSymbol.prototype, Symbol.toPrimitive, + d('c', Symbol.prototype[Symbol.toPrimitive])); +defineProperty(HiddenSymbol.prototype, Symbol.toStringTag, + d('c', Symbol.prototype[Symbol.toStringTag])); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/implement.js new file mode 100644 index 00000000000000..eb35c3018835c7 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof Symbol, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/index.js new file mode 100644 index 00000000000000..62b3296df6fc5e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/index.js @@ -0,0 +1,12 @@ +'use strict'; + +var d = require('d') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-implemented.js new file mode 100644 index 00000000000000..bb0d64536ebbae --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-implemented.js @@ -0,0 +1,14 @@ +'use strict'; + +var global = require('es5-ext/global') + , polyfill = require('../polyfill'); + +module.exports = function (t, a) { + var cache; + a(typeof t(), 'boolean'); + cache = global.Symbol; + global.Symbol = polyfill; + a(t(), true); + if (cache === undefined) delete global.Symbol; + else global.Symbol = cache; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-symbol.js new file mode 100644 index 00000000000000..ac24b9abbff4e6 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/is-symbol.js @@ -0,0 +1,16 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof Symbol !== 'undefined') { + a(t(Symbol()), true, "Native"); + } + a(t(SymbolPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/polyfill.js new file mode 100644 index 00000000000000..83fb5e9253677b --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/polyfill.js @@ -0,0 +1,27 @@ +'use strict'; + +var d = require('d') + , isSymbol = require('../is-symbol') + + , defineProperty = Object.defineProperty; + +module.exports = function (T, a) { + var symbol = T('test'), x = {}; + defineProperty(x, symbol, d('foo')); + a(x.test, undefined, "Name"); + a(x[symbol], 'foo', "Get"); + a(x instanceof T, false); + + a(isSymbol(symbol), true, "Symbol"); + a(isSymbol(T.iterator), true, "iterator"); + a(isSymbol(T.toStringTag), true, "toStringTag"); + + x = {}; + x[symbol] = 'foo'; + a.deep(Object.getOwnPropertyDescriptor(x, symbol), { configurable: true, enumerable: false, + value: 'foo', writable: true }); + symbol = T.for('marko'); + a(isSymbol(symbol), true); + a(T.for('marko'), symbol); + a(T.keyFor(symbol), 'marko'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/validate-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/validate-symbol.js new file mode 100644 index 00000000000000..2c8f84c8239b6e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/test/validate-symbol.js @@ -0,0 +1,19 @@ +'use strict'; + +var SymbolPoly = require('../polyfill'); + +module.exports = function (t, a) { + var symbol; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof Symbol !== 'undefined') { + symbol = Symbol(); + a(t(symbol), symbol, "Native"); + } + symbol = SymbolPoly(); + a(t(symbol), symbol, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/validate-symbol.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/validate-symbol.js new file mode 100644 index 00000000000000..42750043d4271c --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es6-symbol/validate-symbol.js @@ -0,0 +1,8 @@ +'use strict'; + +var isSymbol = require('./is-symbol'); + +module.exports = function (value) { + if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/package.json b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/package.json new file mode 100644 index 00000000000000..07973dfab3e479 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/package.json @@ -0,0 +1,64 @@ +{ + "name": "es6-weak-map", + "version": "0.1.4", + "description": "ECMAScript6 WeakMap polyfill", + "author": { + "name": "Mariusz Nowak", + "email": "medyk@medikoo.com", + "url": "http://www.medikoo.com/" + }, + "keywords": [ + "map", + "weakmap", + "collection", + "es6", + "harmony", + "list", + "hash", + "gc" + ], + "repository": { + "type": "git", + "url": "git://github.com/medikoo/es6-weak-map.git" + }, + "dependencies": { + "d": "~0.1.1", + "es5-ext": "~0.10.6", + "es6-iterator": "~0.1.3", + "es6-symbol": "~2.0.1" + }, + "devDependencies": { + "tad": "~0.2.2" + }, + "scripts": { + "test": "node ./node_modules/tad/bin/tad" + }, + "license": "MIT", + "gitHead": "e68802395b82a700257374c379cfaafe84ee8552", + "bugs": { + "url": "https://github.com/medikoo/es6-weak-map/issues" + }, + "homepage": "https://github.com/medikoo/es6-weak-map", + "_id": "es6-weak-map@0.1.4", + "_shasum": "706cef9e99aa236ba7766c239c8b9e286ea7d228", + "_from": "es6-weak-map@>=0.1.2 <0.2.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + }, + "maintainers": [ + { + "name": "medikoo", + "email": "medikoo+npm@medikoo.com" + } + ], + "dist": { + "shasum": "706cef9e99aa236ba7766c239c8b9e286ea7d228", + "tarball": "http://registry.npmjs.org/es6-weak-map/-/es6-weak-map-0.1.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-0.1.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/polyfill.js new file mode 100644 index 00000000000000..1d15660ac7de91 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/polyfill.js @@ -0,0 +1,75 @@ +'use strict'; + +var setPrototypeOf = require('es5-ext/object/set-prototype-of') + , object = require('es5-ext/object/valid-object') + , value = require('es5-ext/object/valid-value') + , d = require('d') + , getIterator = require('es6-iterator/get') + , forOf = require('es6-iterator/for-of') + , toStringTagSymbol = require('es6-symbol').toStringTag + , isNative = require('./is-native-implemented') + + , isArray = Array.isArray, defineProperty = Object.defineProperty, random = Math.random + , hasOwnProperty = Object.prototype.hasOwnProperty + , genId, WeakMapPoly; + +genId = (function () { + var generated = Object.create(null); + return function () { + var id; + do { id = random().toString(36).slice(2); } while (generated[id]); + generated[id] = true; + return id; + }; +}()); + +module.exports = WeakMapPoly = function (/*iterable*/) { + var iterable = arguments[0]; + if (!(this instanceof WeakMapPoly)) return new WeakMapPoly(iterable); + if (this.__weakMapData__ !== undefined) { + throw new TypeError(this + " cannot be reinitialized"); + } + if (iterable != null) { + if (!isArray(iterable)) iterable = getIterator(iterable); + } + defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId())); + if (!iterable) return; + forOf(iterable, function (val) { + value(val); + this.set(val[0], val[1]); + }, this); +}; + +if (isNative) { + if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap); + WeakMapPoly.prototype = Object.create(WeakMap.prototype, { + constructor: d(WeakMapPoly) + }); +} + +Object.defineProperties(WeakMapPoly.prototype, { + clear: d(function () { + defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId())); + }), + delete: d(function (key) { + if (hasOwnProperty.call(object(key), this.__weakMapData__)) { + delete key[this.__weakMapData__]; + return true; + } + return false; + }), + get: d(function (key) { + if (hasOwnProperty.call(object(key), this.__weakMapData__)) { + return key[this.__weakMapData__]; + } + }), + has: d(function (key) { + return hasOwnProperty.call(object(key), this.__weakMapData__); + }), + set: d(function (key, value) { + defineProperty(object(key), this.__weakMapData__, d('c', value)); + return this; + }), + toString: d(function () { return '[object WeakMap]'; }) +}); +defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap')); diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/implement.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/implement.js new file mode 100644 index 00000000000000..860027ed290974 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/implement.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof WeakMap, 'function'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/index.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/index.js new file mode 100644 index 00000000000000..9b26e4fa7e4a01 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/index.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function (T, a) { + var x = {}; + a((new T([[x, 'foo']])).get(x), 'foo'); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-implemented.js new file mode 100644 index 00000000000000..1a8832889bf493 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t(), 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-native-implemented.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-native-implemented.js new file mode 100644 index 00000000000000..df8ba0323f0cad --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-native-implemented.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = function (t, a) { a(typeof t, 'boolean'); }; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-weak-map.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-weak-map.js new file mode 100644 index 00000000000000..ba8c04519ca204 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/is-weak-map.js @@ -0,0 +1,16 @@ +'use strict'; + +var WeakMapPoly = require('../polyfill'); + +module.exports = function (t, a) { + a(t(undefined), false, "Undefined"); + a(t(null), false, "Null"); + a(t(true), false, "Primitive"); + a(t('raz'), false, "String"); + a(t({}), false, "Object"); + a(t([]), false, "Array"); + if (typeof WeakMap !== 'undefined') { + a(t(new WeakMap()), true, "Native"); + } + a(t(new WeakMapPoly()), true, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/polyfill.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/polyfill.js new file mode 100644 index 00000000000000..1a4885be8354e0 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/polyfill.js @@ -0,0 +1,22 @@ +'use strict'; + +module.exports = function (T, a) { + var x = {}, y = {}, z = {}, arr = [[x, 'raz'], [y, 'dwa']], map = new T(arr); + + a(map instanceof T, true, "WeakMap"); + a(map.has(x), true, "Has: true"); + a(map.get(x), 'raz', "Get: contains"); + a(map.has(z), false, "Has: false"); + a(map.get(z), undefined, "Get: doesn't contain"); + a(map.set(z, 'trzy'), map, "Set: return"); + a(map.has(z), true, "Add"); + a(map.delete({}), false, "Delete: false"); + + a(map.delete(x), true, "Delete: true"); + a(map.get(x), undefined, "Get: after delete"); + a(map.has(x), false, "Has: after delete"); + + a(map.has(y), true, "Has: pre clear"); + map.clear(); + a(map.has(y), false, "Has: after clear"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/valid-weak-map.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/valid-weak-map.js new file mode 100644 index 00000000000000..a7823421a7c503 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/test/valid-weak-map.js @@ -0,0 +1,19 @@ +'use strict'; + +var WeakMapPoly = require('../polyfill'); + +module.exports = function (t, a) { + var map; + a.throws(function () { t(undefined); }, TypeError, "Undefined"); + a.throws(function () { t(null); }, TypeError, "Null"); + a.throws(function () { t(true); }, TypeError, "Primitive"); + a.throws(function () { t('raz'); }, TypeError, "String"); + a.throws(function () { t({}); }, TypeError, "Object"); + a.throws(function () { t([]); }, TypeError, "Array"); + if (typeof WeakMap !== 'undefined') { + map = new WeakMap(); + a(t(map), map, "Native"); + } + map = new WeakMapPoly(); + a(t(map), map, "Polyfill"); +}; diff --git a/tools/eslint/node_modules/escope/node_modules/es6-weak-map/valid-weak-map.js b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/valid-weak-map.js new file mode 100644 index 00000000000000..bfb579fecd6d72 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/es6-weak-map/valid-weak-map.js @@ -0,0 +1,8 @@ +'use strict'; + +var isWeakMap = require('./is-weak-map'); + +module.exports = function (x) { + if (!isWeakMap(x)) throw new TypeError(x + " is not a WeakMap"); + return x; +}; diff --git a/tools/eslint/node_modules/escope/node_modules/esrecurse/README.md b/tools/eslint/node_modules/escope/node_modules/esrecurse/README.md new file mode 100644 index 00000000000000..e767592faab07e --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/esrecurse/README.md @@ -0,0 +1,86 @@ +### Esrecurse [![Build Status](https://secure.travis-ci.org/estools/esrecurse.png)](http://travis-ci.org/estools/esrecurse) + +Esrecurse ([esrecurse](http://github.com/estools/esrecurse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +recursive traversing functionality. + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +esrecurse.visit(ast, { + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); +``` + +We can use `Visitor` instance. + +```javascript +var visitor = new esrecurse.Visitor({ + XXXStatement: function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); + } +}); + +visitor.visit(ast); +``` + +We can inherit `Visitor` instance easily. + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + this.visit(node.left); + // do something... + this.visit(node.right); +}; +``` + +And you can invoke default visiting operation inside custom visit operation. + +```javascript +function DerivedVisitor() { + esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); +} +util.inherits(DerivedVisitor, esrecurse.Visitor); +DerivedVisitor.prototype.XXXStatement = function (node) { + // do something... + this.visitChildren(node); +}; +``` + +### License + +Copyright (C) 2014 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js b/tools/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js new file mode 100644 index 00000000000000..0774f86f6bc6de --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/esrecurse/esrecurse.js @@ -0,0 +1,122 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; + + var estraverse, + isArray, + objectKeys; + + estraverse = require('estraverse'); + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + objectKeys = Object.keys || function (o) { + var keys = [], key; + for (key in o) { + keys.push(key); + } + return keys; + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; + } + + function Visitor(visitor) { + this.__visitor = visitor || this; + } + + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + + children = estraverse.VisitorKeys[type]; + if (!children) { + children = objectKeys(node); + } + + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (Array.isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; + + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; + + if (node == null) { + return; + } + + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = require('./package.json').version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor) { + var v = new Visitor(visitor); + v.visit(node); + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/node_modules/esrecurse/gulpfile.coffee b/tools/eslint/node_modules/escope/node_modules/esrecurse/gulpfile.coffee new file mode 100644 index 00000000000000..e7781896774265 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/esrecurse/gulpfile.coffee @@ -0,0 +1,79 @@ +# Copyright (C) 2014 Yusuke Suzuki +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +gulp = require 'gulp' +mocha = require 'gulp-mocha' +eslint = require 'gulp-eslint' +minimist = require 'minimist' +git = require 'gulp-git' +bump = require 'gulp-bump' +filter = require 'gulp-filter' +tagVersion = require 'gulp-tag-version' +require 'coffee-script/register' + +SOURCE = [ + '*.js' +] + +ESLINT_OPTION = + rules: + 'quotes': 0 + 'eqeqeq': 0 + 'no-use-before-define': 0 + 'no-shadow': 0 + 'no-new': 0 + 'no-underscore-dangle': 0 + 'no-multi-spaces': false + 'no-native-reassign': 0 + 'no-loop-func': 0 + env: + 'node': true + +gulp.task 'test', -> + options = minimist process.argv.slice(2), + string: 'test', + default: + test: 'test/*.coffee' + return gulp.src(options.test).pipe(mocha reporter: 'spec') + +gulp.task 'lint', -> + return gulp.src(SOURCE) + .pipe(eslint(ESLINT_OPTION)) + .pipe(eslint.formatEach('stylish', process.stderr)) + .pipe(eslint.failOnError()) + +inc = (importance) -> + gulp.src(['./package.json']) + .pipe(bump({type: importance})) + .pipe(gulp.dest('./')) + .pipe(git.commit('Bumps package version')) + .pipe(filter('package.json')) + .pipe(tagVersion({ + prefix: '' + })) + +gulp.task 'travis', [ 'lint', 'test' ] +gulp.task 'default', [ 'travis' ] + +gulp.task 'patch', [ ], -> inc('patch') +gulp.task 'minor', [ ], -> inc('minor') +gulp.task 'major', [ ], -> inc('major') diff --git a/tools/eslint/node_modules/escope/node_modules/esrecurse/package.json b/tools/eslint/node_modules/escope/node_modules/esrecurse/package.json new file mode 100644 index 00000000000000..70f7d8569aaf79 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/esrecurse/package.json @@ -0,0 +1,71 @@ +{ + "name": "esrecurse", + "description": "ECMAScript scope analyzer", + "homepage": "http://github.com/estools/esrecurse", + "main": "esrecurse.js", + "version": "3.1.1", + "engines": { + "node": ">=0.10.0" + }, + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + { + "name": "michaelficarra", + "email": "npm@michael.ficarra.me" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/estools/esrecurse.git" + }, + "dependencies": { + "estraverse": "~3.1.0" + }, + "devDependencies": { + "chai": "^2.1.1", + "coffee-script": "^1.9.1", + "esprima": "^2.1.0", + "gulp": "~3.8.10", + "gulp-bump": "^0.2.2", + "gulp-eslint": "^0.6.0", + "gulp-filter": "^2.0.2", + "gulp-git": "^1.1.0", + "gulp-mocha": "~2.0.0", + "gulp-tag-version": "^1.2.1", + "jsdoc": "~3.3.0-alpha10", + "minimist": "^1.1.0" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/estools/esrecurse/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "gulp travis", + "unit-test": "gulp test", + "lint": "gulp lint" + }, + "gitHead": "600a8aac5e7b313875a873134fd110b47a76fc77", + "bugs": { + "url": "https://github.com/estools/esrecurse/issues" + }, + "_id": "esrecurse@3.1.1", + "_shasum": "8feb963699d4d1b2d65a576cd4b1296672a0f0e9", + "_from": "esrecurse@>=3.1.1 <4.0.0", + "_npmVersion": "2.0.0-alpha-5", + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "dist": { + "shasum": "8feb963699d4d1b2d65a576cd4b1296672a0f0e9", + "tarball": "http://registry.npmjs.org/esrecurse/-/esrecurse-3.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-3.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/node_modules/estraverse/.jshintrc b/tools/eslint/node_modules/escope/node_modules/estraverse/.jshintrc new file mode 100644 index 00000000000000..f642dae7683b81 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/estraverse/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/tools/eslint/node_modules/escope/node_modules/estraverse/LICENSE.BSD b/tools/eslint/node_modules/escope/node_modules/estraverse/LICENSE.BSD new file mode 100644 index 00000000000000..3e580c355a96e5 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/estraverse/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/escope/node_modules/estraverse/README.md b/tools/eslint/node_modules/escope/node_modules/estraverse/README.md new file mode 100644 index 00000000000000..4242c513309e9a --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/estraverse/README.md @@ -0,0 +1,124 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.png)](http://travis-ci.org/estools/estraverse) + +Estraverse ([estraverse](http://github.com/estools/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/estools/esmangle). + +### Documentation + +You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Extending the exising traversing rules. + keys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } +}); +``` + +By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Iterating the child **nodes** of unknown nodes. + fallback: 'iteration' +}); +``` + +### License + +Copyright (C) 2012-2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/escope/node_modules/estraverse/estraverse.js b/tools/eslint/node_modules/escope/node_modules/estraverse/estraverse.js new file mode 100644 index 00000000000000..a668aa3e61123f --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/estraverse/estraverse.js @@ -0,0 +1,841 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + + var Syntax, + isArray, + VisitorOption, + VisitorKeys, + objectCreate, + objectKeys, + BREAK, + SKIP, + REMOVE; + + function ignoreJSHintError() { } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + function lowerBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + + objectCreate = Object.create || (function () { + function F() { } + + return function (o) { + F.prototype = o; + return new F(); + }; + })(); + + objectKeys = Object.keys || function (o) { + var keys = [], key; + for (key in o) { + keys.push(key); + } + return keys; + }; + + function extend(to, from) { + var keys = objectKeys(from), key, i, len; + for (i = 0, len = keys.length; i < len; i += 1) { + key = keys[i]; + to[key] = from[key]; + } + return to; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + SuperExpression: 'SuperExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + SuperExpression: ['super'], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = visitor.fallback === 'iteration'; + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = extend(objectCreate(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = element.wrap || node.type; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = objectKeys(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = element.wrap || node.type; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = objectKeys(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = require('./package.json').version; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/node_modules/estraverse/gulpfile.js b/tools/eslint/node_modules/escope/node_modules/estraverse/gulpfile.js new file mode 100644 index 00000000000000..8772bbcca542a8 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/estraverse/gulpfile.js @@ -0,0 +1,70 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +'use strict'; + +var gulp = require('gulp'), + git = require('gulp-git'), + bump = require('gulp-bump'), + filter = require('gulp-filter'), + tagVersion = require('gulp-tag-version'); + +var TEST = [ 'test/*.js' ]; +var POWERED = [ 'powered-test/*.js' ]; +var SOURCE = [ 'src/**/*.js' ]; + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ + prefix: '' + })); +} + +gulp.task('patch', [ ], function () { return inc('patch'); }) +gulp.task('minor', [ ], function () { return inc('minor'); }) +gulp.task('major', [ ], function () { return inc('major'); }) diff --git a/tools/eslint/node_modules/escope/node_modules/estraverse/package.json b/tools/eslint/node_modules/escope/node_modules/estraverse/package.json new file mode 100644 index 00000000000000..94ac9832e95781 --- /dev/null +++ b/tools/eslint/node_modules/escope/node_modules/estraverse/package.json @@ -0,0 +1,66 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/estools/estraverse", + "main": "estraverse.js", + "version": "3.1.0", + "engines": { + "node": ">=0.10.0" + }, + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + { + "name": "michaelficarra", + "email": "npm@michael.ficarra.me" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/estools/estraverse.git" + }, + "devDependencies": { + "chai": "^2.1.1", + "coffee-script": "^1.8.0", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.2.1", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/estools/estraverse/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers coffee:coffee-script/register" + }, + "gitHead": "166ebbe0a8d45ceb2391b6f5ef5d1bab6bfb267a", + "bugs": { + "url": "https://github.com/estools/estraverse/issues" + }, + "_id": "estraverse@3.1.0", + "_shasum": "15e28a446b8b82bc700ccc8b96c78af4da0d6cba", + "_from": "estraverse@>=3.1.0 <4.0.0", + "_npmVersion": "2.0.0-alpha-5", + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "dist": { + "shasum": "15e28a446b8b82bc700ccc8b96c78af4da0d6cba", + "tarball": "http://registry.npmjs.org/estraverse/-/estraverse-3.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/estraverse/-/estraverse-3.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/package.json b/tools/eslint/node_modules/escope/package.json new file mode 100644 index 00000000000000..1e1219930358ed --- /dev/null +++ b/tools/eslint/node_modules/escope/package.json @@ -0,0 +1,86 @@ +{ + "name": "escope", + "description": "ECMAScript scope analyzer", + "homepage": "http://github.com/estools/escope.html", + "main": "lib/index.js", + "version": "3.0.1", + "engines": { + "node": ">=0.4.0" + }, + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + { + "name": "michaelficarra", + "email": "npm@michael.ficarra.me" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/estools/escope.git" + }, + "dependencies": { + "es6-map": "^0.1.1", + "es6-weak-map": "^0.1.2", + "esrecurse": "^3.1.1", + "estraverse": "^3.1.0" + }, + "devDependencies": { + "acorn": "^0.12.0", + "babel": "^4.7.12", + "browserify": "^9.0.3", + "chai": "^2.1.1", + "coffee-script": "^1.9.1", + "espree": "^1.11.0", + "esprima": "^2.1.0", + "gulp": "~3.8.10", + "gulp-babel": "^4.0.0", + "gulp-bump": "^0.3.0", + "gulp-coffee": "^2.2.0", + "gulp-eslint": "^0.6.0", + "gulp-espower": "^0.10.0", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-mocha": "~2.0.0", + "gulp-plumber": "^1.0.0", + "gulp-sourcemaps": "^1.3.0", + "gulp-tag-version": "^1.2.1", + "jsdoc": "=3.3.0-alpha13", + "lazypipe": "^0.2.2", + "minimist": "^1.1.0", + "vinyl-source-stream": "^1.0.0" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/estools/escope/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "gulp travis", + "unit-test": "gulp test", + "lint": "gulp lint", + "jsdoc": "jsdoc src/*.js README.md" + }, + "gitHead": "cd455a35658733600ebaef603021b90801272a2f", + "bugs": { + "url": "https://github.com/estools/escope/issues" + }, + "_id": "escope@3.0.1", + "_shasum": "cc150f270852c3b68841370b2184739de18b5d61", + "_from": "escope@>=3.0.0 <4.0.0", + "_npmVersion": "2.0.0-alpha-5", + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "dist": { + "shasum": "cc150f270852c3b68841370b2184739de18b5d61", + "tarball": "http://registry.npmjs.org/escope/-/escope-3.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/escope/-/escope-3.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/escope/src/definition.js b/tools/eslint/node_modules/escope/src/definition.js new file mode 100644 index 00000000000000..faef9387c274b4 --- /dev/null +++ b/tools/eslint/node_modules/escope/src/definition.js @@ -0,0 +1,78 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import Variable from './variable'; + +/** + * @class Definition + */ +export default class Definition { + constructor(type, name, node, parent, index, kind) { + /** + * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; + /** + * @member {esprima.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; + /** + * @member {esprima.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; + /** + * @member {esprima.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; + /** + * @member {Number?} Definition#index - the index in the declaration statement. + */ + this.index = index; + /** + * @member {String?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} + +/** + * @class ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} + +export { + ParameterDefinition, + Definition +} + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/src/index.js b/tools/eslint/node_modules/escope/src/index.js new file mode 100644 index 00000000000000..66a6ea9b6d2f9c --- /dev/null +++ b/tools/eslint/node_modules/escope/src/index.js @@ -0,0 +1,139 @@ +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. esprima is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ + +/*jslint bitwise:true */ + +import assert from 'assert'; + +import ScopeManager from './scope-manager'; +import Referencer from './referencer'; +import Reference from './reference'; +import Variable from './variable'; +import Scope from './scope'; +import { version } from '../package.json'; + +function defaultOptions() { + return { + optimistic: false, + directive: false, + nodejsScope: false, + sourceType: 'script', // one of ['script', 'module'] + ecmaVersion: 5 + }; +} + +function updateDeeply(target, override) { + var key, val; + + function isHashObject(target) { + return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); + } + + for (key in override) { + if (override.hasOwnProperty(key)) { + val = override[key]; + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} + +/** + * Main interface function. Takes an Esprima syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {esprima.Tree} tree + * @param {Object} providedOptions - Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag + * @param {boolean} [providedOptions.directive=false]- the directive flag + * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' + * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered + * @return {ScopeManager} + */ +export function analyze(tree, providedOptions) { + var scopeManager, referencer, options; + + options = updateDeeply(defaultOptions(), providedOptions); + + scopeManager = new ScopeManager(options); + + referencer = new Referencer(scopeManager); + referencer.visit(tree); + + assert(scopeManager.__currentScope === null, 'currentScope should be null.'); + + return scopeManager; +} + +export { + /** @name module:escope.version */ + version, + /** @name module:escope.Reference */ + Reference, + /** @name module:escope.Variable */ + Variable, + /** @name module:escope.Scope */ + Scope, + /** @name module:escope.ScopeManager */ + ScopeManager +}; + + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/src/reference.js b/tools/eslint/node_modules/escope/src/reference.js new file mode 100644 index 00000000000000..36b4d12810b09f --- /dev/null +++ b/tools/eslint/node_modules/escope/src/reference.js @@ -0,0 +1,149 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; + +/** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ +export default class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial) { + /** + * Identifier syntax node. + * @member {esprima#Identifier} Reference#identifier + */ + this.identifier = ident; + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { + /** + * If reference is writeable, this is the tree being written to it. + * @member {esprima#Node} Reference#writeExpr + */ + this.writeExpr = writeExpr; + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } + + /** + * Whether the reference is static. + * @method Reference#isStatic + * @return {boolean} + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @return {boolean} + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } + + /** + * Whether the reference is readable. + * @method Reference#isRead + * @return {boolean} + */ + isRead() { + return !!(this.flag & Reference.READ); + } + + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @return {boolean} + */ + isReadOnly() { + return this.flag === Reference.READ; + } + + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @return {boolean} + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @return {boolean} + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} + +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/src/referencer.js b/tools/eslint/node_modules/escope/src/referencer.js new file mode 100644 index 00000000000000..a337be0d4551ef --- /dev/null +++ b/tools/eslint/node_modules/escope/src/referencer.js @@ -0,0 +1,593 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +import { Syntax } from 'estraverse'; +import esrecurse from 'esrecurse'; +import Reference from './reference'; +import Variable from './variable'; +import { ParameterDefinition, Definition } from './definition'; +import assert from 'assert'; + +class PatternVisitor extends esrecurse.Visitor { + constructor(rootPattern, referencer, callback) { + super(); + this.referencer = referencer; + this.callback = callback; + } + + perform(pattern) { + if (pattern.type === Syntax.Identifier) { + this.callback(pattern, true); + return; + } + this.visit(pattern); + } + + Identifier(pattern) { + this.callback(pattern, false); + } + + ObjectPattern(pattern) { + var i, iz, property; + for (i = 0, iz = pattern.properties.length; i < iz; ++i) { + property = pattern.properties[i]; + if (property.shorthand) { + this.visit(property.key); + continue; + } + this.visit(property.value); + } + } + + ArrayPattern(pattern) { + var i, iz, element; + for (i = 0, iz = pattern.elements.length; i < iz; ++i) { + element = pattern.elements[i]; + if (element) { + this.visit(element); + } + } + } + + AssignmentPattern(pattern) { + this.visit(pattern.left); + // FIXME: Condier TDZ scope. + this.referencer.visit(pattern.right); + } +} + +function traverseIdentifierInPattern(rootPattern, referencer, callback) { + var visitor = new PatternVisitor(rootPattern, referencer, callback); + visitor.perform(rootPattern); +} + +function isPattern(node) { + var nodeType = node.type; + return nodeType === Syntax.Identifier || nodeType === Syntax.ObjectPattern || nodeType === Syntax.ArrayPattern || nodeType === Syntax.SpreadElement || nodeType === Syntax.RestElement || nodeType === Syntax.AssignmentPattern; +} + +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. + +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(); + this.declaration = declaration; + this.referencer = referencer; + } + + visitImport(id, specifier) { + this.referencer.visitPattern(id, (pattern) => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } + + ImportNamespaceSpecifier(node) { + let local = (node.local || node.id); + if (local) { + this.visitImport(local, node); + } + } + + ImportDefaultSpecifier(node) { + let local = (node.local || node.id); + this.visitImport(local, node); + } + + ImportSpecifier(node) { + let local = (node.local || node.id); + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} + +// Referencing variables and creating bindings. +export default class Referencer extends esrecurse.Visitor { + constructor(scopeManager) { + super(); + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } + + currentScope() { + return this.scopeManager.__currentScope; + } + + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } + + pushInnerMethodDefinition(isInnerMethodDefinition) { + var previous = this.isInnerMethodDefinition; + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } + + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + + materializeTDZScope(node, iterationNode) { + // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation + // TDZ scope hides the declaration's names. + this.scopeManager.__nestTDZScope(node, iterationNode); + this.visitVariableDeclaration(this.currentScope(), Variable.TDZ, iterationNode.left, 0); + } + + materializeIterationScope(node) { + // Generate iteration scope for upper ForIn/ForOf Statements. + var letOrConstDecl; + this.scopeManager.__nestForScope(node); + letOrConstDecl = node.left; + this.visitVariableDeclaration(this.currentScope(), Variable.Variable, letOrConstDecl, 0); + this.visitPattern(letOrConstDecl.declarations[0].id, (pattern) => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true); + }); + } + + visitPattern(node, callback) { + traverseIdentifierInPattern(node, this, callback); + } + + visitFunction(node) { + var i, iz; + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. + if (node.type === Syntax.FunctionDeclaration) { + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], (pattern) => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + false + )); + }); + } + + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: 'RestElement', + argument: node.rest + }, (pattern) => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } + + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + + this.close(node); + } + + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } + + // FIXME: Maybe consider TDZ. + this.visit(node.superClass); + + this.scopeManager.__nestClassScope(node); + + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + this.visit(node.body); + + this.close(node); + } + + visitProperty(node) { + var previous, isMethodDefinition; + if (node.computed) { + this.visit(node.key); + } + + isMethodDefinition = node.type === Syntax.MethodDefinition || node.method; + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } + + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== 'var') { + this.materializeTDZScope(node.right, node); + this.visit(node.right); + this.close(node.right); + + this.materializeIterationScope(node); + this.visit(node.body); + this.close(node); + } else { + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, (pattern) => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true); + }); + } else { + if (!isPattern(node.left)) { + this.visit(node.left); + } + this.visitPattern(node.left, (pattern) => { + var maybeImplicitGlobal = null; + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern: pattern, + node: node + }; + } + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true); + }); + } + this.visit(node.right); + this.visit(node.body); + } + } + + visitVariableDeclaration(variableTargetScope, type, node, index) { + var decl, init; + + decl = node.declarations[index]; + init = decl.init; + this.visitPattern(decl.id, (pattern, toplevel) => { + variableTargetScope.__define(pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + )); + + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !toplevel); + } + }); + } + + AssignmentExpression(node) { + if (isPattern(node.left)) { + if (node.operator === '=') { + this.visitPattern(node.left, (pattern, toplevel) => { + var maybeImplicitGlobal = null; + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern: pattern, + node: node + }; + } + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !toplevel); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + + this.visitPattern(node.param, (pattern) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + node.param, + node, + null, + null, + null + )); + }); + this.visit(node.body); + + this.close(node); + } + + Program(node) { + this.scopeManager.__nestGlobalScope(node); + + if (this.scopeManager.__isNodejsScope()) { + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } + + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } + + this.visitChildren(node); + this.close(node); + } + + Identifier(node) { + this.currentScope().__referencing(node); + } + + UpdateExpression(node) { + if (isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } + + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } + + Property(node) { + this.visitProperty(node); + } + + MethodDefinition(node) { + this.visitProperty(node); + } + + BreakStatement() {} + + ContinueStatement() {} + + LabeledStatement(node) { + this.visit(node.body); + } + + ForStatement(node) { + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== 'var') { + this.scopeManager.__nestForScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ClassExpression(node) { + this.visitClass(node); + } + + ClassDeclaration(node) { + this.visitClass(node); + } + + CallExpression(node) { + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') { + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } + + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); + } + + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } + + WithStatement(node) { + this.visit(node.object); + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + + this.visit(node.body); + + this.close(node); + } + + VariableDeclaration(node) { + var variableTargetScope, i, iz, decl; + variableTargetScope = (node.kind === 'var') ? this.currentScope().variableScope : this.currentScope(); + for (i = 0, iz = node.declarations.length; i < iz; ++i) { + decl = node.declarations[i]; + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + + // sec 13.11.8 + SwitchStatement(node) { + var i, iz; + + this.visit(node.discriminant); + + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } + + for (i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } + + this.close(node); + } + + FunctionDeclaration(node) { + this.visitFunction(node); + } + + FunctionExpression(node) { + this.visitFunction(node); + } + + ForOfStatement(node) { + this.visitForIn(node); + } + + ForInStatement(node) { + this.visitForIn(node); + } + + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + + ImportDeclaration(node) { + var importer; + + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), 'ImportDeclaration should appear when the mode is ES6 and in the module context.'); + + importer = new Importer(node, this); + importer.visit(node); + } + + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + + this.visitChildren(node); + } + + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + + ExportSpecifier(node) { + let local = (node.id || node.local); + this.visit(local); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/src/scope-manager.js b/tools/eslint/node_modules/escope/src/scope-manager.js new file mode 100644 index 00000000000000..63e66e0d8e234a --- /dev/null +++ b/tools/eslint/node_modules/escope/src/scope-manager.js @@ -0,0 +1,222 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import WeakMap from 'es6-weak-map'; +import Scope from './scope'; +import assert from 'assert'; + +import { + GlobalScope, + CatchScope, + WithScope, + ModuleScope, + ClassScope, + SwitchScope, + FunctionScope, + ForScope, + TDZScope, + FunctionExpressionNameScope, + BlockScope +} from './scope'; + +/** + * @class ScopeManager + */ +export default class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + } + + __useDirective() { + return this.__options.directive; + } + + __isOptimistic() { + return this.__options.optimistic; + } + + __ignoreEval() { + return this.__options.ignoreEval; + } + + __isNodejsScope() { + return this.__options.nodejsScope; + } + + isModule() { + return this.__options.sourceType === 'module'; + } + + // Returns appropliate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + + /** + * acquire scope from node. + * @method ScopeManager#acquire + * @param {Esprima.Node} node - node for the acquired scope. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @return {Scope?} + */ + acquire(node, inner) { + var scopes, scope, i, iz; + + function predicate(scope) { + if (scope.type === 'function' && scope.functionExpressionScope) { + return false; + } + if (scope.type === 'TDZ') { + return false; + } + return true; + } + + scopes = this.__get(node); + if (!scopes || scopes.length === 0) { + return null; + } + + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } + + if (inner) { + for (i = scopes.length - 1; i >= 0; --i) { + scope = scopes[i]; + if (predicate(scope)) { + return scope; + } + } + } else { + for (i = 0, iz = scopes.length; i < iz; ++i) { + scope = scopes[i]; + if (predicate(scope)) { + return scope; + } + } + } + + return null; + } + + /** + * acquire all scopes from node. + * @method ScopeManager#acquireAll + * @param {Esprima.Node} node - node for the acquired scope. + * @return {Scope[]?} + */ + acquireAll(node) { + return this.__get(node); + } + + /** + * release the node. + * @method ScopeManager#release + * @param {Esprima.Node} node - releasing node. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @return {Scope?} upper scope for the node. + */ + release(node, inner) { + var scopes, scope; + scopes = this.__get(node); + if (scopes && scopes.length) { + scope = scopes[0].upper; + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + + attach() { } + + detach() { } + + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } + + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + + __nestBlockScope(node, isMethodDefinition) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestTDZScope(node) { + return this.__nestScope(new TDZScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/src/scope.js b/tools/eslint/node_modules/escope/src/scope.js new file mode 100644 index 00000000000000..d48bef540842fa --- /dev/null +++ b/tools/eslint/node_modules/escope/src/scope.js @@ -0,0 +1,596 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +import { Syntax } from 'estraverse'; +import Map from 'es6-map'; + +import Reference from './reference'; +import Variable from './variable'; +import Definition from './definition'; +import assert from 'assert'; + +function isStrictScope(scope, block, isMethodDefinition, useDirective) { + var body, i, iz, stmt, expr; + + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + // ArrowFunctionExpression's scope is always strict scope. + if (block.type === Syntax.ArrowFunctionExpression) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === 'class' || scope.type === 'module') { + return true; + } + + if (scope.type === 'block' || scope.type === 'switch') { + return false; + } + + if (scope.type === 'function') { + if (block.type === 'Program') { + body = block; + } else { + body = block.body; + } + } else if (scope.type === 'global') { + body = block; + } else { + return false; + } + + // Search 'use strict' directive. + if (useDirective) { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== 'DirectiveStatement') { + break; + } + if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') { + return true; + } + } + } else { + for (i = 0, iz = body.body.length; i < iz; ++i) { + stmt = body.body[i]; + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + expr = stmt.expression; + if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') { + break; + } + if (expr.raw != null) { + if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') { + return true; + } + } else { + if (expr.value === 'use strict') { + return true; + } + } + } + } + return false; +} + +function registerScope(scopeManager, scope) { + var scopes; + + scopeManager.scopes.push(scope); + + scopes = scopeManager.__nodeToScope.get(scope.block); + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [ scope ]); + } +} + +/** + * @class Scope + */ +export default class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + /** + * One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. + * @member {String} Scope#type + */ + this.type = type; + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its prarent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === 'global' || this.type === 'with'; + /** + * A reference to the scope-defining syntax node. + * @member {esprima.Node} Scope#block + */ + this.block = block; + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; + + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + (this.type === 'global' || this.type === 'function' || this.type === 'module') ? this : upperScope.variableScope; + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; + + this.__left = []; + + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); + + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } + + registerScope(scopeManager, this); + } + + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } + + __staticClose(scopeManager) { + // static resolve + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + let ref = this.__left[i]; + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } + } + + __dynamicClose(scopeManager) { + // This path is for "global" and "function with eval" environment. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + // notify all names are through to global + let ref = this.__left[i]; + let current = this; + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + this.__staticClose(); + } else { + this.__dynamicClose(); + } + + this.__left = null; + return this.upper; + } + + __resolve(ref) { + var variable, name; + name = ref.identifier.name; + if (this.set.has(name)) { + variable = this.set.get(name); + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; + return true; + } + return false; + } + + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + + __defineGeneric(name, set, variables, node, def) { + var variable; + + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + + if (def) { + variable.defs.push(def); + } + if (node) { + variable.identifiers.push(node); + } + } + + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def); + } + } + + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial) { + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; + } + + // Specially handle like `this`. + if (node.name === 'super') { + return; + } + + let ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial); + this.references.push(ref); + this.__left.push(ref); + } + + __detectEval() { + var current; + current = this; + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } + + __detectThis() { + this.thisFound = true; + } + + __isClosed() { + return this.__left === null; + } + + /** + * returns resolved {Reference} + * @method Scope#resolve + * @param {Esprima.Identifier} ident - identifier to be resolved. + * @return {Reference} + */ + resolve(ident) { + var ref, i, iz; + assert(this.__isClosed(), 'Scope should be closed.'); + assert(ident.type === Syntax.Identifier, 'Target should be identifier.'); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + + /** + * returns this scope is static + * @method Scope#isStatic + * @return {boolean} + */ + isStatic() { + return !this.dynamic; + } + + /** + * returns this scope has materialized arguments + * @method Scope#isArgumentsMaterialized + * @return {boolean} + */ + isArgumentsMaterialized() { + return true; + } + + /** + * returns this scope has materialized `this` reference + * @method Scope#isThisMaterialized + * @return {boolean} + */ + isThisMaterialized() { + return true; + } + + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (var i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} + +export class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, 'global', null, block, false); + this.implicit = { + set: new Map(), + variables: [], + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } + + __close(scopeManager) { + let implicit = []; + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + let ref = this.__left[i]; + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } + + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + let info = implicit[i]; + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); + + } + + this.implicit.left = this.__left; + + return super.__close(scopeManager); + } + + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def); + } + } +} + +export class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'module', upperScope, block, false); + } +} + +export class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'function-expression-name', upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} + +export class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'catch', upperScope, block, false); + } +} + +export class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'with', upperScope, block, false); + } + + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } + + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + let ref = this.__left[i]; + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; + + return this.upper; + } +} + +export class TDZScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'TDZ', upperScope, block, false); + } +} + +export class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'block', upperScope, block, false); + } +} + +export class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'switch', upperScope, block, false); + } +} + +export class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, 'function', upperScope, block, isMethodDefinition); + + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } + + isArgumentsMaterialized() { + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + + if (!this.isStatic()) { + return true; + } + + let variable = this.set.get('arguments'); + assert(variable, 'Always have arguments variable.'); + return variable.tainted || variable.references.length !== 0; + } + + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } + + __defineArguments() { + this.__defineGeneric( + 'arguments', + this.set, + this.variables, + null, + null); + this.taints.set('arguments', true); + } +} + +export class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'for', upperScope, block, false); + } +} + +export class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, 'class', upperScope, block, false); + } +} + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/src/variable.js b/tools/eslint/node_modules/escope/src/variable.js new file mode 100644 index 00000000000000..3945b380b55f7a --- /dev/null +++ b/tools/eslint/node_modules/escope/src/variable.js @@ -0,0 +1,81 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ +export default class Variable { + constructor(name, scope) { + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {esprima.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; + + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; + + this.tainted = false; + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} + +Variable.CatchClause = 'CatchClause'; +Variable.Parameter = 'Parameter'; +Variable.FunctionName = 'FunctionName'; +Variable.ClassName = 'ClassName'; +Variable.Variable = 'Variable'; +Variable.ImportBinding = 'ImportBinding'; +Variable.TDZ = 'TDZ'; +Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable'; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/escope/third_party/espree.js b/tools/eslint/node_modules/escope/third_party/espree.js new file mode 100644 index 00000000000000..26df9ee6ae621e --- /dev/null +++ b/tools/eslint/node_modules/escope/third_party/espree.js @@ -0,0 +1,122 @@ +/* + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +var espree = require('espree'); + +module.exports = function (code) { + return espree.parse(code, { + + // attach range information to each node + range: true, + + // attach line/column location information to each node + loc: true, + + // create a top-level comments array containing all comments + comments: true, + + // attach comments to the closest relevant node as leadingComments and + // trailingComments + attachComment: true, + + // create a top-level tokens array containing all tokens + tokens: true, + + // try to continue parsing if an error is encountered, store errors in a + // top-level errors array + tolerant: true, + + // specify parsing features (default only has blockBindings: true) + ecmaFeatures: { + + // enable parsing of arrow functions + arrowFunctions: true, + + // enable parsing of let/const + blockBindings: true, + + // enable parsing of destructured arrays and objects + destructuring: true, + + // enable parsing of regular expression y flag + regexYFlag: true, + + // enable parsing of regular expression u flag + regexUFlag: true, + + // enable parsing of template strings + templateStrings: true, + + // enable parsing of binary literals + binaryLiterals: true, + + // enable parsing of ES6 octal literals + octalLiterals: true, + + // enable parsing unicode code point escape sequences + unicodeCodePointEscapes: true, + + // enable parsing of default parameters + defaultParams: true, + + // enable parsing of rest parameters + restParams: true, + + // enable parsing of for-of statement + forOf: true, + + // enable parsing computed object literal properties + objectLiteralComputedProperties: true, + + // enable parsing of shorthand object literal methods + objectLiteralShorthandMethods: true, + + // enable parsing of shorthand object literal properties + objectLiteralShorthandProperties: true, + + // Allow duplicate object literal properties (except '__proto__') + objectLiteralDuplicateProperties: true, + + // enable parsing of generators/yield + generators: true, + + // enable parsing spread operator + spread: true, + + // enable parsing classes + classes: true, + + // enable parsing of modules + modules: true, + + // enable React JSX parsing + jsx: true, + + // enable return in global scope + globalReturn: true + } + }); +}; + +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/espree/README.md b/tools/eslint/node_modules/espree/README.md new file mode 100644 index 00000000000000..fcbb79ab56d4fa --- /dev/null +++ b/tools/eslint/node_modules/espree/README.md @@ -0,0 +1,222 @@ +# Espree + +Espree is an actively-maintained fork Esprima, a high performance, +standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +parser written in ECMAScript (also popularly known as +[JavaScript](http://en.wikipedia.org/wiki/JavaScript)). + +## Features + +- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) +- Implements [ESTree](https://github.com/estree/estree) (both ES5 and ES6 specs) as the AST format. +- Optional tracking of syntax node location (index-based and line-column) +- Heavily tested and battle-hardened by inclusion in [ESLint](http://eslint.org) + +## Usage + +Install: + +``` +npm i espree --save +``` + +And in your Node.js code: + +```javascript +var espree = require("espree"); + +var ast = espree.parse(code); +``` + +There is a second argument to `parse()` that allows you to specify various options: + +```javascript +var espree = require("espree"); + +var ast = espree.parse(code, { + + // attach range information to each node + range: true, + + // attach line/column location information to each node + loc: true, + + // create a top-level comments array containing all comments + comments: true, + + // attach comments to the closest relevant node as leadingComments and + // trailingComments + attachComment: true, + + // create a top-level tokens array containing all tokens + tokens: true, + + // try to continue parsing if an error is encountered, store errors in a + // top-level errors array + tolerant: true, + + // specify parsing features (default only has blockBindings: true) + ecmaFeatures: { + + // enable parsing of arrow functions + arrowFunctions: true, + + // enable parsing of let/const + blockBindings: true, + + // enable parsing of destructured arrays and objects + destructuring: true, + + // enable parsing of regular expression y flag + regexYFlag: true, + + // enable parsing of regular expression u flag + regexUFlag: true, + + // enable parsing of template strings + templateStrings: true, + + // enable parsing of binary literals + binaryLiterals: true, + + // enable parsing of ES6 octal literals + octalLiterals: true, + + // enable parsing unicode code point escape sequences + unicodeCodePointEscapes: true, + + // enable parsing of default parameters + defaultParams: true, + + // enable parsing of rest parameters + restParams: true, + + // enable parsing of for-of statement + forOf: true, + + // enable parsing computed object literal properties + objectLiteralComputedProperties: true, + + // enable parsing of shorthand object literal methods + objectLiteralShorthandMethods: true, + + // enable parsing of shorthand object literal properties + objectLiteralShorthandProperties: true, + + // Allow duplicate object literal properties (except '__proto__') + objectLiteralDuplicateProperties: true, + + // enable parsing of generators/yield + generators: true, + + // enable parsing spread operator + spread: true, + + // enable parsing classes + classes: true, + + // enable parsing of modules + modules: true, + + // enable React JSX parsing + jsx: true, + + // enable return in global scope + globalReturn: true + } +}); +``` + +## Plans + +Espree starts as a fork of Esprima v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree's first version is therefore v1.2.2 and is 100% compatible with Esprima v1.2.2 as a drop-in replacement. The version number will be incremented based on [semantic versioning](http://semver.org/) as features and bug fixes are added. + +The immediate plans are: + +1. Move away from giant files and move towards small, modular files that are easier to manage. +1. Move towards CommonJS for all files and use browserify to create browser bundles. +1. Support ECMAScript version filtering, allowing users to specify which version the parser should work in (similar to Acorn's `ecmaVersion` property). +1. Add tests to track comment attachment. +1. Add well-thought-out features that are useful for tools developers. +1. Add full support for ECMAScript 6. +1. Add optional parsing of JSX. + +## Esprima Compatibility Going Forward + +The primary goal is to produce the exact same AST structure as Esprima and Acorn, and that takes precedence over anything else. (The AST structure being the ESTree API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. + +Espree may also deviate from Esprima in the interface it exposes. + +## Frequent and Incremental Releases + +Espree will not do giant releases. Releases will happen periodically as changes are made and incremental releases will be made towards larger goals. For instance, we will not have one big release for ECMAScript 6 support. Instead, we will implement ECMAScript 6, piece-by-piece, hiding those pieces behind an `ecmaFeatures` property that allows you to opt-in to use those features. + +## Contributing + +Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing.html), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). + +Espree is licensed under a permissive BSD 2-clause license. + +## Build Commands + +* `npm test` - run all linting and tests +* `npm run lint` - run all linting +* `npm run browserify` - creates a version of Espree that is usable in a browser + +## Known Incompatibilities + +In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. + +### Esprima 1.2.2 + +* None. + +### Esprima/Harmony Branch + +* Esprima/Harmony uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. +* Espree uses ESTree format for the AST nodes whereas Esprima/Harmony uses a nonstandard format. + +### Esprima-FB + +* All Esprima/Harmony incompatibilities. + +## Frequently Asked Questions + +### Why are you forking Esprima? + +[ESLint](http://eslint.org) has been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development has increased dramatically and Esprima has fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that has caused our users frustration. + +We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. + +### Have you tried working with Esprima? + +Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima. Unfortunately, we've been unable to make much progress towards getting our needs addressed. + +We are actively working with Esprima as part of its adoption by the jQuery Foundation. We are hoping to reconcile Espree with Esprima at some point in the future, but there are some different philosophies around how the projects work that need to be worked through. We're committed to a goal of merging Espree back into Esprima, or at the very least, to have Espree track Esprima as an upstream target so there's no duplication of effort. In the meantime, we will continue to update and maintain Espree. + +### Why don't you just use Facebook's Esprima fork? + +`esprima-fb` is Facebook's Esprima fork that features JSX and Flow type annotations. We tried working with `esprima-fb` in our evaluation of how to support ECMAScript 6 and JSX in ESLint. Unfortunately, we were hampered by bugs that were part of Esprima (not necessarily Facebook's code). Since `esprima-fb` tracks the Esprima Harmony branch, that means we still were unable to get fixes or features we needed in a timely manner. + +### Why don't you just use Acorn? + +Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. + +We expect there are other tools like ESLint that rely on more than just the AST produced by Esprima, and so a drop-in replacement will help those projects as well as ESLint. + +### What ECMAScript 6 features do you support? + +All of them. + +### Why use Espree instead of Esprima? + +* Faster turnaround time on bug fixes +* More frequent releases +* Better communication and responsiveness to issues +* Ongoing development + +### Why use Espree instead of Esprima-FB? + +* Opt-in to just the ECMAScript 6 features you want +* JSX support is off by default, so you're not forced to use it to use ECMAScript 6 +* Stricter ECMAScript 6 support diff --git a/tools/eslint/node_modules/espree/bin/esparse.js b/tools/eslint/node_modules/espree/bin/esparse.js new file mode 100755 index 00000000000000..4a9984aab05c9d --- /dev/null +++ b/tools/eslint/node_modules/espree/bin/esparse.js @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true rhino:true */ + +var fs, espree, fname, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + espree = require('espree'); +} else if (typeof load === 'function') { + try { + load('espree.js'); + } catch (e) { + load('../espree.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using espree version', espree.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } +}); + +if (typeof fname !== 'string') { + console.log('Error: no input file.'); + process.exit(1); +} + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +try { + content = fs.readFileSync(fname, 'utf-8'); + syntax = espree.parse(content, options); + console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/tools/eslint/node_modules/espree/bin/esvalidate.js b/tools/eslint/node_modules/espree/bin/esvalidate.js new file mode 100755 index 00000000000000..7631d0a29d6a0e --- /dev/null +++ b/tools/eslint/node_modules/espree/bin/esvalidate.js @@ -0,0 +1,199 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true plusplus:true node:true rhino:true */ +/*global phantom:true */ + +var fs, system, espree, options, fnames, count; + +if (typeof espree === 'undefined') { + // PhantomJS can only require() relative files + if (typeof phantom === 'object') { + fs = require('fs'); + system = require('system'); + espree = require('./espree'); + } else if (typeof require === 'function') { + fs = require('fs'); + espree = require('espree'); + } else if (typeof load === 'function') { + try { + load('espree.js'); + } catch (e) { + load('../espree.js'); + } + } +} + +// Shims to Node.js objects when running under PhantomJS 1.7+. +if (typeof phantom === 'object') { + fs.readFileSync = fs.read; + process = { + argv: [].slice.call(system.args), + exit: phantom.exit + }; + process.argv.unshift('phantomjs'); +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using espree version', espree.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else { + fnames.push(entry); + } +}); + +if (fnames.length === 0) { + console.log('Error: no input file.'); + process.exit(1); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; +fnames.forEach(function (fname) { + var content, timestamp, syntax, name; + try { + content = fs.readFileSync(fname, 'utf-8'); + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = espree.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log('Error: ' + e.message); + } + } +}); + +if (options.format === 'junit') { + console.log(''); +} + +if (count > 0) { + process.exit(1); +} + +if (count === 0 && typeof phantom === 'object') { + process.exit(0); +} diff --git a/tools/eslint/node_modules/espree/espree.js b/tools/eslint/node_modules/espree/espree.js new file mode 100644 index 00000000000000..a0d9d4809630c2 --- /dev/null +++ b/tools/eslint/node_modules/espree/espree.js @@ -0,0 +1,5473 @@ +/* +Copyright (C) 2015 Fred K. Schott +Copyright (C) 2013 Ariya Hidayat +Copyright (C) 2013 Thaddee Tyl +Copyright (C) 2013 Mathias Bynens +Copyright (C) 2012 Ariya Hidayat +Copyright (C) 2012 Mathias Bynens +Copyright (C) 2012 Joost-Wim Boekesteijn +Copyright (C) 2012 Kris Kowal +Copyright (C) 2012 Yusuke Suzuki +Copyright (C) 2012 Arpad Borsos +Copyright (C) 2011 Ariya Hidayat + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*eslint no-undefined:0, no-use-before-define: 0*/ + +"use strict"; + +var syntax = require("./lib/syntax"), + tokenInfo = require("./lib/token-info"), + astNodeTypes = require("./lib/ast-node-types"), + astNodeFactory = require("./lib/ast-node-factory"), + defaultFeatures = require("./lib/features"), + Messages = require("./lib/messages"), + XHTMLEntities = require("./lib/xhtml-entities"), + StringMap = require("./lib/string-map"), + commentAttachment = require("./lib/comment-attachment"); + +var Token = tokenInfo.Token, + TokenName = tokenInfo.TokenName, + FnExprTokens = tokenInfo.FnExprTokens, + Regex = syntax.Regex, + PropertyKind, + source, + strict, + index, + lineNumber, + lineStart, + length, + lookahead, + state, + extra; + +PropertyKind = { + Data: 1, + Get: 2, + Set: 4 +}; + + +// Ensure the condition is true, otherwise throw an error. +// This is only to have a better contract semantic, i.e. another safety net +// to catch a logic error. The condition shall be fulfilled in normal case. +// Do NOT use this to enforce a certain condition on any user input. + +function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error("ASSERT: " + message); + } +} + +// 7.4 Comments + +function addComment(type, value, start, end, loc) { + var comment; + + assert(typeof start === "number", "Comment must have valid position"); + + // Because the way the actual token is scanned, often the comments + // (if any) are skipped twice during the lexical analysis. + // Thus, we need to skip adding a comment if the comment array already + // handled it. + if (state.lastCommentStart >= start) { + return; + } + state.lastCommentStart = start; + + comment = { + type: type, + value: value + }; + if (extra.range) { + comment.range = [start, end]; + } + if (extra.loc) { + comment.loc = loc; + } + extra.comments.push(comment); + + if (extra.attachComment) { + commentAttachment.addComment(comment); + } +} + +function skipSingleLineComment(offset) { + var start, loc, ch, comment; + + start = index - offset; + loc = { + start: { + line: lineNumber, + column: index - lineStart - offset + } + }; + + while (index < length) { + ch = source.charCodeAt(index); + ++index; + if (syntax.isLineTerminator(ch)) { + if (extra.comments) { + comment = source.slice(start + offset, index - 1); + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + addComment("Line", comment, start, index - 1, loc); + } + if (ch === 13 && source.charCodeAt(index) === 10) { + ++index; + } + ++lineNumber; + lineStart = index; + return; + } + } + + if (extra.comments) { + comment = source.slice(start + offset, index); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment("Line", comment, start, index, loc); + } +} + +function skipMultiLineComment() { + var start, loc, ch, comment; + + if (extra.comments) { + start = index - 2; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (syntax.isLineTerminator(ch)) { + if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { + ++index; + } + ++lineNumber; + ++index; + lineStart = index; + if (index >= length) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + } else if (ch === 0x2A) { + // Block comment ends with "*/". + if (source.charCodeAt(index + 1) === 0x2F) { + ++index; + ++index; + if (extra.comments) { + comment = source.slice(start + 2, index - 2); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment("Block", comment, start, index, loc); + } + return; + } + ++index; + } else { + ++index; + } + } + + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); +} + +function skipComment() { + var ch, start; + + start = (index === 0); + while (index < length) { + ch = source.charCodeAt(index); + + if (syntax.isWhiteSpace(ch)) { + ++index; + } else if (syntax.isLineTerminator(ch)) { + ++index; + if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { + ++index; + } + ++lineNumber; + lineStart = index; + start = true; + } else if (ch === 0x2F) { // U+002F is "/" + ch = source.charCodeAt(index + 1); + if (ch === 0x2F) { + ++index; + ++index; + skipSingleLineComment(2); + start = true; + } else if (ch === 0x2A) { // U+002A is "*" + ++index; + ++index; + skipMultiLineComment(); + } else { + break; + } + } else if (start && ch === 0x2D) { // U+002D is "-" + // U+003E is ">" + if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { + // "-->" is a single-line comment + index += 3; + skipSingleLineComment(3); + } else { + break; + } + } else if (ch === 0x3C) { // U+003C is "<" + if (source.slice(index + 1, index + 4) === "!--") { + ++index; // `<` + ++index; // `!` + ++index; // `-` + ++index; // `-` + skipSingleLineComment(4); + } else { + break; + } + } else { + break; + } + } +} + +function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === "u") ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && syntax.isHexDigit(source[index])) { + ch = source[index++]; + code = code * 16 + "0123456789abcdef".indexOf(ch.toLowerCase()); + } else { + return ""; + } + } + return String.fromCharCode(code); +} + +/** + * Scans an extended unicode code point escape sequence from source. Throws an + * error if the sequence is empty or if the code point value is too large. + * @returns {string} The string created by the Unicode escape sequence. + * @private + */ +function scanUnicodeCodePointEscape() { + var ch, code, cu1, cu2; + + ch = source[index]; + code = 0; + + // At least one hex digit is required. + if (ch === "}") { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + while (index < length) { + ch = source[index++]; + if (!syntax.isHexDigit(ch)) { + break; + } + code = code * 16 + "0123456789abcdef".indexOf(ch.toLowerCase()); + } + + if (code > 0x10FFFF || ch !== "}") { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + // UTF-16 Encoding + if (code <= 0xFFFF) { + return String.fromCharCode(code); + } + cu1 = ((code - 0x10000) >> 10) + 0xD800; + cu2 = ((code - 0x10000) & 1023) + 0xDC00; + return String.fromCharCode(cu1, cu2); +} + +function getEscapedIdentifier() { + var ch, id; + + ch = source.charCodeAt(index++); + id = String.fromCharCode(ch); + + // "\u" (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + if (source.charCodeAt(index) !== 0x75) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + ++index; + ch = scanHexEscape("u"); + if (!ch || ch === "\\" || !syntax.isIdentifierStart(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + id = ch; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (!syntax.isIdentifierPart(ch)) { + break; + } + ++index; + id += String.fromCharCode(ch); + + // "\u" (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + id = id.substr(0, id.length - 1); + if (source.charCodeAt(index) !== 0x75) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + ++index; + ch = scanHexEscape("u"); + if (!ch || ch === "\\" || !syntax.isIdentifierPart(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + id += ch; + } + } + + return id; +} + +function getIdentifier() { + var start, ch; + + start = index++; + while (index < length) { + ch = source.charCodeAt(index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + index = start; + return getEscapedIdentifier(); + } + if (syntax.isIdentifierPart(ch)) { + ++index; + } else { + break; + } + } + + return source.slice(start, index); +} + +function scanIdentifier() { + var start, id, type; + + start = index; + + // Backslash (U+005C) starts an escaped character. + id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); + + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = Token.Identifier; + } else if (syntax.isKeyword(id, strict, extra.ecmaFeatures)) { + type = Token.Keyword; + } else if (id === "null") { + type = Token.NullLiteral; + } else if (id === "true" || id === "false") { + type = Token.BooleanLiteral; + } else { + type = Token.Identifier; + } + + return { + type: type, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + + +// 7.7 Punctuators + +function scanPunctuator() { + var start = index, + code = source.charCodeAt(index), + code2, + ch1 = source[index], + ch2, + ch3, + ch4; + + switch (code) { + // Check for most common single-character punctuators. + case 40: // ( open bracket + case 41: // ) close bracket + case 59: // ; semicolon + case 44: // , comma + case 91: // [ + case 93: // ] + case 58: // : + case 63: // ? + case 126: // ~ + ++index; + + if (extra.tokenize && code === 40) { + extra.openParenToken = extra.tokens.length; + } + + return { + type: Token.Punctuator, + value: String.fromCharCode(code), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + + case 123: // { open curly brace + case 125: // } close curly brace + ++index; + + if (extra.tokenize && code === 123) { + extra.openCurlyToken = extra.tokens.length; + } + + // lookahead2 function can cause tokens to be scanned twice and in doing so + // would wreck the curly stack by pushing the same token onto the stack twice. + // curlyLastIndex ensures each token is pushed or popped exactly once + if (index > state.curlyLastIndex) { + state.curlyLastIndex = index; + if (code === 123) { + state.curlyStack.push("{"); + } else { + state.curlyStack.pop(); + } + } + + return { + type: Token.Punctuator, + value: String.fromCharCode(code), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + + default: + code2 = source.charCodeAt(index + 1); + + // "=" (char #61) marks an assignment or comparison operator. + if (code2 === 61) { + switch (code) { + case 37: // % + case 38: // & + case 42: // *: + case 43: // + + case 45: // - + case 47: // / + case 60: // < + case 62: // > + case 94: // ^ + case 124: // | + index += 2; + return { + type: Token.Punctuator, + value: String.fromCharCode(code) + String.fromCharCode(code2), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + + case 33: // ! + case 61: // = + index += 2; + + // !== and === + if (source.charCodeAt(index) === 61) { + ++index; + } + return { + type: Token.Punctuator, + value: source.slice(start, index), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + default: + break; + } + } + break; + } + + // Peek more characters. + + ch2 = source[index + 1]; + ch3 = source[index + 2]; + ch4 = source[index + 3]; + + // 4-character punctuator: >>>= + + if (ch1 === ">" && ch2 === ">" && ch3 === ">") { + if (ch4 === "=") { + index += 4; + return { + type: Token.Punctuator, + value: ">>>=", + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // 3-character punctuators: === !== >>> <<= >>= + + if (ch1 === ">" && ch2 === ">" && ch3 === ">") { + index += 3; + return { + type: Token.Punctuator, + value: ">>>", + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === "<" && ch2 === "<" && ch3 === "=") { + index += 3; + return { + type: Token.Punctuator, + value: "<<=", + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === ">" && ch2 === ">" && ch3 === "=") { + index += 3; + return { + type: Token.Punctuator, + value: ">>=", + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // The ... operator (spread, restParams, JSX, etc.) + if (extra.ecmaFeatures.spread || + extra.ecmaFeatures.restParams || + (extra.ecmaFeatures.jsx && state.inJSXSpreadAttribute) + ) { + if (ch1 === "." && ch2 === "." && ch3 === ".") { + index += 3; + return { + type: Token.Punctuator, + value: "...", + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + // Other 2-character punctuators: ++ -- << >> && || + if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) { + index += 2; + return { + type: Token.Punctuator, + value: ch1 + ch2, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + // the => for arrow functions + if (extra.ecmaFeatures.arrowFunctions) { + if (ch1 === "=" && ch2 === ">") { + index += 2; + return { + type: Token.Punctuator, + value: "=>", + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + } + + if ("<>=!+-*%&|^/".indexOf(ch1) >= 0) { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + if (ch1 === ".") { + ++index; + return { + type: Token.Punctuator, + value: ch1, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); +} + +// 7.8.3 Numeric Literals + +function scanHexLiteral(start) { + var number = ""; + + while (index < length) { + if (!syntax.isHexDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + if (syntax.isIdentifierStart(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + return { + type: Token.NumericLiteral, + value: parseInt("0x" + number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +function scanBinaryLiteral(start) { + var ch, number = ""; + + while (index < length) { + ch = source[index]; + if (ch !== "0" && ch !== "1") { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + // only 0b or 0B + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + + if (index < length) { + ch = source.charCodeAt(index); + /* istanbul ignore else */ + if (syntax.isIdentifierStart(ch) || syntax.isDecimalDigit(ch)) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + } + + return { + type: Token.NumericLiteral, + value: parseInt(number, 2), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +function scanOctalLiteral(prefix, start) { + var number, octal; + + if (syntax.isOctalDigit(prefix)) { + octal = true; + number = "0" + source[index++]; + } else { + octal = false; + ++index; + number = ""; + } + + while (index < length) { + if (!syntax.isOctalDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (!octal && number.length === 0) { + // only 0o or 0O + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + if (syntax.isIdentifierStart(source.charCodeAt(index)) || syntax.isDecimalDigit(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: octal, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(syntax.isDecimalDigit(ch.charCodeAt(0)) || (ch === "."), + "Numeric literal must start with a decimal digit or a decimal point"); + + start = index; + number = ""; + if (ch !== ".") { + number = source[index++]; + ch = source[index]; + + // Hex number starts with "0x". + // Octal number starts with "0". + if (number === "0") { + if (ch === "x" || ch === "X") { + ++index; + return scanHexLiteral(start); + } + + // Binary number in ES6 starts with '0b' + if (extra.ecmaFeatures.binaryLiterals) { + if (ch === "b" || ch === "B") { + ++index; + return scanBinaryLiteral(start); + } + } + + if ((extra.ecmaFeatures.octalLiterals && (ch === "o" || ch === "O")) || syntax.isOctalDigit(ch)) { + return scanOctalLiteral(ch, start); + } + + // decimal number starts with "0" such as "09" is illegal. + if (ch && syntax.isDecimalDigit(ch.charCodeAt(0))) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + } + + while (syntax.isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === ".") { + number += source[index++]; + while (syntax.isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === "e" || ch === "E") { + number += source[index++]; + + ch = source[index]; + if (ch === "+" || ch === "-") { + number += source[index++]; + } + if (syntax.isDecimalDigit(source.charCodeAt(index))) { + while (syntax.isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + } else { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + } + + if (syntax.isIdentifierStart(source.charCodeAt(index))) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + return { + type: Token.NumericLiteral, + value: parseFloat(number), + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +/** + * Scan a string escape sequence and return its special character. + * @param {string} ch The starting character of the given sequence. + * @returns {Object} An object containing the character and a flag + * if the escape sequence was an octal. + * @private + */ +function scanEscapeSequence(ch) { + var code, + unescaped, + restore, + escapedCh, + octal = false; + + // An escape sequence cannot be empty + if (!ch) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + if (syntax.isLineTerminator(ch.charCodeAt(0))) { + ++lineNumber; + if (ch === "\r" && source[index] === "\n") { + ++index; + } + lineStart = index; + escapedCh = ""; + } else if (ch === "u" && source[index] === "{") { + // Handle ES6 extended unicode code point escape sequences. + if (extra.ecmaFeatures.unicodeCodePointEscapes) { + ++index; + escapedCh = scanUnicodeCodePointEscape(); + } else { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + } else if (ch === "u" || ch === "x") { + // Handle other unicode and hex codes normally + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + escapedCh = unescaped; + } else { + index = restore; + escapedCh = ch; + } + } else if (ch === "n") { + escapedCh = "\n"; + } else if (ch === "r") { + escapedCh = "\r"; + } else if (ch === "t") { + escapedCh = "\t"; + } else if (ch === "b") { + escapedCh = "\b"; + } else if (ch === "f") { + escapedCh = "\f"; + } else if (ch === "v") { + escapedCh = "\v"; + } else if (syntax.isOctalDigit(ch)) { + code = "01234567".indexOf(ch); + + // \0 is not octal escape sequence + if (code !== 0) { + octal = true; + } + + if (index < length && syntax.isOctalDigit(source[index])) { + octal = true; + code = code * 8 + "01234567".indexOf(source[index++]); + + // 3 digits are only allowed when string starts with 0, 1, 2, 3 + if ("0123".indexOf(ch) >= 0 && + index < length && + syntax.isOctalDigit(source[index])) { + code = code * 8 + "01234567".indexOf(source[index++]); + } + } + escapedCh = String.fromCharCode(code); + } else { + escapedCh = ch; + } + + return { + ch: escapedCh, + octal: octal + }; +} + +function scanStringLiteral() { + var str = "", + ch, + escapedSequence, + octal = false, + start = index, + startLineNumber = lineNumber, + startLineStart = lineStart, + quote = source[index]; + + assert((quote === "'" || quote === "\""), + "String literal must starts with a quote"); + + ++index; + + while (index < length) { + ch = source[index++]; + + if (syntax.isLineTerminator(ch.charCodeAt(0))) { + break; + } else if (ch === quote) { + quote = ""; + break; + } else if (ch === "\\") { + ch = source[index++]; + escapedSequence = scanEscapeSequence(ch); + str += escapedSequence.ch; + octal = escapedSequence.octal || octal; + } else { + str += ch; + } + } + + if (quote !== "") { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + return { + type: Token.StringLiteral, + value: str, + octal: octal, + startLineNumber: startLineNumber, + startLineStart: startLineStart, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +/** + * Scan a template string and return a token. This scans both the first and + * subsequent pieces of a template string and assumes that the first backtick + * or the closing } have already been scanned. + * @returns {Token} The template string token. + * @private + */ +function scanTemplate() { + var cooked = "", + ch, + escapedSequence, + start = index, + terminated = false, + tail = false, + head = (source[index] === "`"); + + ++index; + + while (index < length) { + ch = source[index++]; + + if (ch === "`") { + tail = true; + terminated = true; + break; + } else if (ch === "$") { + if (source[index] === "{") { + ++index; + terminated = true; + break; + } + cooked += ch; + } else if (ch === "\\") { + ch = source[index++]; + escapedSequence = scanEscapeSequence(ch); + + if (escapedSequence.octal) { + throwError({}, Messages.TemplateOctalLiteral); + } + + cooked += escapedSequence.ch; + + } else if (syntax.isLineTerminator(ch.charCodeAt(0))) { + ++lineNumber; + if (ch === "\r" && source[index] === "\n") { + ++index; + } + lineStart = index; + cooked += "\n"; + } else { + cooked += ch; + } + } + + if (!terminated) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + if (index > state.curlyLastIndex) { + state.curlyLastIndex = index; + + if (!tail) { + state.curlyStack.push("template"); + } + + if (!head) { + state.curlyStack.pop(); + } + } + + return { + type: Token.Template, + value: { + cooked: cooked, + raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) + }, + head: head, + tail: tail, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +function testRegExp(pattern, flags) { + var tmp = pattern, + validFlags = "gmsi"; + + if (extra.ecmaFeatures.regexYFlag) { + validFlags += "y"; + } + + if (extra.ecmaFeatures.regexUFlag) { + validFlags += "u"; + } + + if (!RegExp("^[" + validFlags + "]*$").test(flags)) { + throwError({}, Messages.InvalidRegExpFlag); + } + + + if (flags.indexOf("u") >= 0) { + // Replace each astral symbol and every Unicode code point + // escape sequence with a single ASCII symbol to avoid throwing on + // regular expressions that are only valid in combination with the + // `/u` flag. + // Note: replacing with the ASCII symbol `x` might cause false + // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a + // perfectly valid pattern that is equivalent to `[a-b]`, but it + // would be replaced by `[x-b]` which throws an error. + tmp = tmp + .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { + if (parseInt($1, 16) <= 0x10FFFF) { + return "x"; + } + throwError({}, Messages.InvalidRegExp); + }) + .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x"); + } + + // First, detect invalid regular expressions. + try { + RegExp(tmp); + } catch (e) { + throwError({}, Messages.InvalidRegExp); + } + + // Return a regular expression object for this pattern-flag pair, or + // `null` in case the current environment doesn't support the flags it + // uses. + try { + return new RegExp(pattern, flags); + } catch (exception) { + return null; + } +} + +function scanRegExpBody() { + var ch, str, classMarker, terminated, body; + + ch = source[index]; + assert(ch === "/", "Regular expression literal must start with a slash"); + str = source[index++]; + + classMarker = false; + terminated = false; + while (index < length) { + ch = source[index++]; + str += ch; + if (ch === "\\") { + ch = source[index++]; + // ECMA-262 7.8.5 + if (syntax.isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } + str += ch; + } else if (syntax.isLineTerminator(ch.charCodeAt(0))) { + throwError({}, Messages.UnterminatedRegExp); + } else if (classMarker) { + if (ch === "]") { + classMarker = false; + } + } else { + if (ch === "/") { + terminated = true; + break; + } else if (ch === "[") { + classMarker = true; + } + } + } + + if (!terminated) { + throwError({}, Messages.UnterminatedRegExp); + } + + // Exclude leading and trailing slash. + body = str.substr(1, str.length - 2); + return { + value: body, + literal: str + }; +} + +function scanRegExpFlags() { + var ch, str, flags, restore; + + str = ""; + flags = ""; + while (index < length) { + ch = source[index]; + if (!syntax.isIdentifierPart(ch.charCodeAt(0))) { + break; + } + + ++index; + if (ch === "\\" && index < length) { + ch = source[index]; + if (ch === "u") { + ++index; + restore = index; + ch = scanHexEscape("u"); + if (ch) { + flags += ch; + for (str += "\\u"; restore < index; ++restore) { + str += source[restore]; + } + } else { + index = restore; + flags += "u"; + str += "\\u"; + } + throwErrorTolerant({}, Messages.UnexpectedToken, "ILLEGAL"); + } else { + str += "\\"; + throwErrorTolerant({}, Messages.UnexpectedToken, "ILLEGAL"); + } + } else { + flags += ch; + str += ch; + } + } + + return { + value: flags, + literal: str + }; +} + +function scanRegExp() { + var start, body, flags, value; + + lookahead = null; + skipComment(); + start = index; + + body = scanRegExpBody(); + flags = scanRegExpFlags(); + value = testRegExp(body.value, flags.value); + + if (extra.tokenize) { + return { + type: Token.RegularExpression, + value: value, + regex: { + pattern: body.value, + flags: flags.value + }, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; + } + + return { + literal: body.literal + flags.literal, + value: value, + regex: { + pattern: body.value, + flags: flags.value + }, + range: [start, index] + }; +} + +function collectRegex() { + var pos, loc, regex, token; + + skipComment(); + + pos = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + regex = scanRegExp(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + /* istanbul ignore next */ + if (!extra.tokenize) { + // Pop the previous token, which is likely "/" or "/=" + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === "Punctuator") { + if (token.value === "/" || token.value === "/=") { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: "RegularExpression", + value: regex.literal, + regex: regex.regex, + range: [pos, index], + loc: loc + }); + } + + return regex; +} + +function isIdentifierName(token) { + return token.type === Token.Identifier || + token.type === Token.Keyword || + token.type === Token.BooleanLiteral || + token.type === Token.NullLiteral; +} + +function advanceSlash() { + var prevToken, + checkToken; + // Using the following algorithm: + // https://github.com/mozilla/sweet.js/wiki/design + prevToken = extra.tokens[extra.tokens.length - 1]; + if (!prevToken) { + // Nothing before that: it cannot be a division. + return collectRegex(); + } + if (prevToken.type === "Punctuator") { + if (prevToken.value === "]") { + return scanPunctuator(); + } + if (prevToken.value === ")") { + checkToken = extra.tokens[extra.openParenToken - 1]; + if (checkToken && + checkToken.type === "Keyword" && + (checkToken.value === "if" || + checkToken.value === "while" || + checkToken.value === "for" || + checkToken.value === "with")) { + return collectRegex(); + } + return scanPunctuator(); + } + if (prevToken.value === "}") { + // Dividing a function by anything makes little sense, + // but we have to check for that. + if (extra.tokens[extra.openCurlyToken - 3] && + extra.tokens[extra.openCurlyToken - 3].type === "Keyword") { + // Anonymous function. + checkToken = extra.tokens[extra.openCurlyToken - 4]; + if (!checkToken) { + return scanPunctuator(); + } + } else if (extra.tokens[extra.openCurlyToken - 4] && + extra.tokens[extra.openCurlyToken - 4].type === "Keyword") { + // Named function. + checkToken = extra.tokens[extra.openCurlyToken - 5]; + if (!checkToken) { + return collectRegex(); + } + } else { + return scanPunctuator(); + } + // checkToken determines whether the function is + // a declaration or an expression. + if (FnExprTokens.indexOf(checkToken.value) >= 0) { + // It is an expression. + return scanPunctuator(); + } + // It is a declaration. + return collectRegex(); + } + return collectRegex(); + } + if (prevToken.type === "Keyword") { + return collectRegex(); + } + return scanPunctuator(); +} + +function advance() { + var ch, + allowJSX = extra.ecmaFeatures.jsx, + allowTemplateStrings = extra.ecmaFeatures.templateStrings; + + /* + * If JSX isn't allowed or JSX is allowed and we're not inside an JSX child, + * then skip any comments. + */ + if (!allowJSX || !state.inJSXChild) { + skipComment(); + } + + if (index >= length) { + return { + type: Token.EOF, + lineNumber: lineNumber, + lineStart: lineStart, + range: [index, index] + }; + } + + // if inside an JSX child, then abort regular tokenization + if (allowJSX && state.inJSXChild) { + return advanceJSXChild(); + } + + ch = source.charCodeAt(index); + + // Very common: ( and ) and ; + if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { + return scanPunctuator(); + } + + // String literal starts with single quote (U+0027) or double quote (U+0022). + if (ch === 0x27 || ch === 0x22) { + if (allowJSX && state.inJSXTag) { + return scanJSXStringLiteral(); + } + + return scanStringLiteral(); + } + + if (allowJSX && state.inJSXTag && syntax.isJSXIdentifierStart(ch)) { + return scanJSXIdentifier(); + } + + // Template strings start with backtick (U+0096) or closing curly brace (125) and backtick. + if (allowTemplateStrings) { + + // template strings start with backtick (96) or open curly (125) but only if the open + // curly closes a previously opened curly from a template. + if (ch === 96 || (ch === 125 && state.curlyStack[state.curlyStack.length - 1] === "template")) { + return scanTemplate(); + } + } + + if (syntax.isIdentifierStart(ch)) { + return scanIdentifier(); + } + + // Dot (.) U+002E can also start a floating-point number, hence the need + // to check the next character. + if (ch === 0x2E) { + if (syntax.isDecimalDigit(source.charCodeAt(index + 1))) { + return scanNumericLiteral(); + } + return scanPunctuator(); + } + + if (syntax.isDecimalDigit(ch)) { + return scanNumericLiteral(); + } + + // Slash (/) U+002F can also start a regex. + if (extra.tokenize && ch === 0x2F) { + return advanceSlash(); + } + + return scanPunctuator(); +} + +function collectToken() { + var loc, token, range, value, entry, + allowJSX = extra.ecmaFeatures.jsx; + + /* istanbul ignore else */ + if (!allowJSX || !state.inJSXChild) { + skipComment(); + } + + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + token = advance(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (token.type !== Token.EOF) { + range = [token.range[0], token.range[1]]; + value = source.slice(token.range[0], token.range[1]); + entry = { + type: TokenName[token.type], + value: value, + range: range, + loc: loc + }; + if (token.regex) { + entry.regex = { + pattern: token.regex.pattern, + flags: token.regex.flags + }; + } + extra.tokens.push(entry); + } + + return token; +} + +function lex() { + var token; + + token = lookahead; + index = token.range[1]; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + + lookahead = (typeof extra.tokens !== "undefined") ? collectToken() : advance(); + + index = token.range[1]; + lineNumber = token.lineNumber; + lineStart = token.lineStart; + + return token; +} + +function peek() { + var pos, + line, + start; + + pos = index; + line = lineNumber; + start = lineStart; + + lookahead = (typeof extra.tokens !== "undefined") ? collectToken() : advance(); + + index = pos; + lineNumber = line; + lineStart = start; +} + +function lookahead2() { + var adv, pos, line, start, result; + + // If we are collecting the tokens, don't grab the next one yet. + /* istanbul ignore next */ + adv = (typeof extra.advance === "function") ? extra.advance : advance; + + pos = index; + line = lineNumber; + start = lineStart; + + // Scan for the next immediate token. + /* istanbul ignore if */ + if (lookahead === null) { + lookahead = adv(); + } + index = lookahead.range[1]; + lineNumber = lookahead.lineNumber; + lineStart = lookahead.lineStart; + + // Grab the token right after. + result = adv(); + index = pos; + lineNumber = line; + lineStart = start; + + return result; +} + + +//------------------------------------------------------------------------------ +// JSX +//------------------------------------------------------------------------------ + +function getQualifiedJSXName(object) { + if (object.type === astNodeTypes.JSXIdentifier) { + return object.name; + } + if (object.type === astNodeTypes.JSXNamespacedName) { + return object.namespace.name + ":" + object.name.name; + } + /* istanbul ignore else */ + if (object.type === astNodeTypes.JSXMemberExpression) { + return ( + getQualifiedJSXName(object.object) + "." + + getQualifiedJSXName(object.property) + ); + } + /* istanbul ignore next */ + throwUnexpected(object); +} + +function scanJSXIdentifier() { + var ch, start, value = ""; + + start = index; + while (index < length) { + ch = source.charCodeAt(index); + if (!syntax.isJSXIdentifierPart(ch)) { + break; + } + value += source[index++]; + } + + return { + type: Token.JSXIdentifier, + value: value, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +function scanJSXEntity() { + var ch, str = "", start = index, count = 0, code; + ch = source[index]; + assert(ch === "&", "Entity must start with an ampersand"); + index++; + while (index < length && count++ < 10) { + ch = source[index++]; + if (ch === ";") { + break; + } + str += ch; + } + + // Well-formed entity (ending was found). + if (ch === ";") { + // Numeric entity. + if (str[0] === "#") { + if (str[1] === "x") { + code = +("0" + str.substr(1)); + } else { + // Removing leading zeros in order to avoid treating as octal in old browsers. + code = +str.substr(1).replace(Regex.LeadingZeros, ""); + } + + if (!isNaN(code)) { + return String.fromCharCode(code); + } + /* istanbul ignore else */ + } else if (XHTMLEntities[str]) { + return XHTMLEntities[str]; + } + } + + // Treat non-entity sequences as regular text. + index = start + 1; + return "&"; +} + +function scanJSXText(stopChars) { + var ch, str = "", start; + start = index; + while (index < length) { + ch = source[index]; + if (stopChars.indexOf(ch) !== -1) { + break; + } + if (ch === "&") { + str += scanJSXEntity(); + } else { + index++; + if (ch === "\r" && source[index] === "\n") { + str += ch; + ch = source[index]; + index++; + } + if (syntax.isLineTerminator(ch.charCodeAt(0))) { + ++lineNumber; + lineStart = index; + } + str += ch; + } + } + return { + type: Token.JSXText, + value: str, + lineNumber: lineNumber, + lineStart: lineStart, + range: [start, index] + }; +} + +function scanJSXStringLiteral() { + var innerToken, quote, start; + + quote = source[index]; + assert((quote === "\"" || quote === "'"), + "String literal must starts with a quote"); + + start = index; + ++index; + + innerToken = scanJSXText([quote]); + + if (quote !== source[index]) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + ++index; + + innerToken.range = [start, index]; + + return innerToken; +} + +/* + * Between JSX opening and closing tags (e.g. HERE), anything that + * is not another JSX tag and is not an expression wrapped by {} is text. + */ +function advanceJSXChild() { + var ch = source.charCodeAt(index); + + // { (123) and < (60) + if (ch !== 123 && ch !== 60) { + return scanJSXText(["<", "{"]); + } + + return scanPunctuator(); +} + +function parseJSXIdentifier() { + var token, marker = markerCreate(); + + if (lookahead.type !== Token.JSXIdentifier) { + throwUnexpected(lookahead); + } + + token = lex(); + return markerApply(marker, astNodeFactory.createJSXIdentifier(token.value)); +} + +function parseJSXNamespacedName() { + var namespace, name, marker = markerCreate(); + + namespace = parseJSXIdentifier(); + expect(":"); + name = parseJSXIdentifier(); + + return markerApply(marker, astNodeFactory.createJSXNamespacedName(namespace, name)); +} + +function parseJSXMemberExpression() { + var marker = markerCreate(), + expr = parseJSXIdentifier(); + + while (match(".")) { + lex(); + expr = markerApply(marker, astNodeFactory.createJSXMemberExpression(expr, parseJSXIdentifier())); + } + + return expr; +} + +function parseJSXElementName() { + if (lookahead2().value === ":") { + return parseJSXNamespacedName(); + } + if (lookahead2().value === ".") { + return parseJSXMemberExpression(); + } + + return parseJSXIdentifier(); +} + +function parseJSXAttributeName() { + if (lookahead2().value === ":") { + return parseJSXNamespacedName(); + } + + return parseJSXIdentifier(); +} + +function parseJSXAttributeValue() { + var value, marker; + if (match("{")) { + value = parseJSXExpressionContainer(); + if (value.expression.type === astNodeTypes.JSXEmptyExpression) { + throwError( + value, + "JSX attributes must only be assigned a non-empty " + + "expression" + ); + } + } else if (match("<")) { + value = parseJSXElement(); + } else if (lookahead.type === Token.JSXText) { + marker = markerCreate(); + value = markerApply(marker, astNodeFactory.createLiteralFromSource(lex(), source)); + } else { + throwError({}, Messages.InvalidJSXAttributeValue); + } + return value; +} + +function parseJSXEmptyExpression() { + var marker = markerCreatePreserveWhitespace(); + while (source.charAt(index) !== "}") { + index++; + } + return markerApply(marker, astNodeFactory.createJSXEmptyExpression()); +} + +function parseJSXExpressionContainer() { + var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); + + origInJSXChild = state.inJSXChild; + origInJSXTag = state.inJSXTag; + state.inJSXChild = false; + state.inJSXTag = false; + + expect("{"); + + if (match("}")) { + expression = parseJSXEmptyExpression(); + } else { + expression = parseExpression(); + } + + state.inJSXChild = origInJSXChild; + state.inJSXTag = origInJSXTag; + + expect("}"); + + return markerApply(marker, astNodeFactory.createJSXExpressionContainer(expression)); +} + +function parseJSXSpreadAttribute() { + var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); + + origInJSXChild = state.inJSXChild; + origInJSXTag = state.inJSXTag; + state.inJSXChild = false; + state.inJSXTag = false; + state.inJSXSpreadAttribute = true; + + expect("{"); + expect("..."); + + state.inJSXSpreadAttribute = false; + + expression = parseAssignmentExpression(); + + state.inJSXChild = origInJSXChild; + state.inJSXTag = origInJSXTag; + + expect("}"); + + return markerApply(marker, astNodeFactory.createJSXSpreadAttribute(expression)); +} + +function parseJSXAttribute() { + var name, marker; + + if (match("{")) { + return parseJSXSpreadAttribute(); + } + + marker = markerCreate(); + + name = parseJSXAttributeName(); + + // HTML empty attribute + if (match("=")) { + lex(); + return markerApply(marker, astNodeFactory.createJSXAttribute(name, parseJSXAttributeValue())); + } + + return markerApply(marker, astNodeFactory.createJSXAttribute(name)); +} + +function parseJSXChild() { + var token, marker; + if (match("{")) { + token = parseJSXExpressionContainer(); + } else if (lookahead.type === Token.JSXText) { + marker = markerCreatePreserveWhitespace(); + token = markerApply(marker, astNodeFactory.createLiteralFromSource(lex(), source)); + } else { + token = parseJSXElement(); + } + return token; +} + +function parseJSXClosingElement() { + var name, origInJSXChild, origInJSXTag, marker = markerCreate(); + origInJSXChild = state.inJSXChild; + origInJSXTag = state.inJSXTag; + state.inJSXChild = false; + state.inJSXTag = true; + expect("<"); + expect("/"); + name = parseJSXElementName(); + // Because advance() (called by lex() called by expect()) expects there + // to be a valid token after >, it needs to know whether to look for a + // standard JS token or an JSX text node + state.inJSXChild = origInJSXChild; + state.inJSXTag = origInJSXTag; + expect(">"); + return markerApply(marker, astNodeFactory.createJSXClosingElement(name)); +} + +function parseJSXOpeningElement() { + var name, attributes = [], selfClosing = false, origInJSXChild, + origInJSXTag, marker = markerCreate(); + + origInJSXChild = state.inJSXChild; + origInJSXTag = state.inJSXTag; + state.inJSXChild = false; + state.inJSXTag = true; + + expect("<"); + + name = parseJSXElementName(); + + while (index < length && + lookahead.value !== "/" && + lookahead.value !== ">") { + attributes.push(parseJSXAttribute()); + } + + state.inJSXTag = origInJSXTag; + + if (lookahead.value === "/") { + expect("/"); + // Because advance() (called by lex() called by expect()) expects + // there to be a valid token after >, it needs to know whether to + // look for a standard JS token or an JSX text node + state.inJSXChild = origInJSXChild; + expect(">"); + selfClosing = true; + } else { + state.inJSXChild = true; + expect(">"); + } + return markerApply(marker, astNodeFactory.createJSXOpeningElement(name, attributes, selfClosing)); +} + +function parseJSXElement() { + var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate(); + + origInJSXChild = state.inJSXChild; + origInJSXTag = state.inJSXTag; + openingElement = parseJSXOpeningElement(); + + if (!openingElement.selfClosing) { + while (index < length) { + state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because one

two
; + * + * the default error message is a bit incomprehensible. Since it"s + * rarely (never?) useful to write a less-than sign after an JSX + * element, we disallow it here in the parser in order to provide a + * better error message. (In the rare case that the less-than operator + * was intended, the left tag can be wrapped in parentheses.) + */ + if (!origInJSXChild && match("<")) { + throwError(lookahead, Messages.AdjacentJSXElements); + } + + return markerApply(marker, astNodeFactory.createJSXElement(openingElement, closingElement, children)); +} + +//------------------------------------------------------------------------------ +// Location markers +//------------------------------------------------------------------------------ + +/** + * Applies location information to the given node by using the given marker. + * The marker indicates the point at which the node is said to have to begun + * in the source code. + * @param {Object} marker The marker to use for the node. + * @param {ASTNode} node The AST node to apply location information to. + * @returns {ASTNode} The node that was passed in. + * @private + */ +function markerApply(marker, node) { + + // add range information to the node if present + if (extra.range) { + node.range = [marker.offset, index]; + } + + // add location information the node if present + if (extra.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.col + }, + end: { + line: lineNumber, + column: index - lineStart + } + }; + // Attach extra.source information to the location, if present + if (extra.source) { + node.loc.source = extra.source; + } + } + + // attach leading and trailing comments if requested + if (extra.attachComment) { + commentAttachment.processComment(node); + } + + return node; +} + +/** + * Creates a location marker in the source code. Location markers are used for + * tracking where tokens and nodes appear in the source code. + * @returns {Object} A marker object or undefined if the parser doesn't have + * any location information. + * @private + */ +function markerCreate() { + + if (!extra.loc && !extra.range) { + return undefined; + } + + skipComment(); + + return { + offset: index, + line: lineNumber, + col: index - lineStart + }; +} + +/** + * Creates a location marker in the source code. Location markers are used for + * tracking where tokens and nodes appear in the source code. This method + * doesn't skip comments or extra whitespace which is important for JSX. + * @returns {Object} A marker object or undefined if the parser doesn't have + * any location information. + * @private + */ +function markerCreatePreserveWhitespace() { + + if (!extra.loc && !extra.range) { + return undefined; + } + + return { + offset: index, + line: lineNumber, + col: index - lineStart + }; +} + + +//------------------------------------------------------------------------------ +// Syntax Tree Delegate +//------------------------------------------------------------------------------ + +// Return true if there is a line terminator before the next token. + +function peekLineTerminator() { + var pos, line, start, found; + + pos = index; + line = lineNumber; + start = lineStart; + skipComment(); + found = lineNumber !== line; + index = pos; + lineNumber = line; + lineStart = start; + + return found; +} + +// Throw an exception + +function throwError(token, messageFormat) { + + var error, + args = Array.prototype.slice.call(arguments, 2), + msg = messageFormat.replace( + /%(\d)/g, + function (whole, index) { + assert(index < args.length, "Message reference must be in range"); + return args[index]; + } + ); + + if (typeof token.lineNumber === "number") { + error = new Error("Line " + token.lineNumber + ": " + msg); + error.index = token.range[0]; + error.lineNumber = token.lineNumber; + error.column = token.range[0] - lineStart + 1; + } else { + error = new Error("Line " + lineNumber + ": " + msg); + error.index = index; + error.lineNumber = lineNumber; + error.column = index - lineStart + 1; + } + + error.description = msg; + throw error; +} + +function throwErrorTolerant() { + try { + throwError.apply(null, arguments); + } catch (e) { + if (extra.errors) { + extra.errors.push(e); + } else { + throw e; + } + } +} + + +// Throw an exception because of the token. + +function throwUnexpected(token) { + + if (token.type === Token.EOF) { + throwError(token, Messages.UnexpectedEOS); + } + + if (token.type === Token.NumericLiteral) { + throwError(token, Messages.UnexpectedNumber); + } + + if (token.type === Token.StringLiteral || token.type === Token.JSXText) { + throwError(token, Messages.UnexpectedString); + } + + if (token.type === Token.Identifier) { + throwError(token, Messages.UnexpectedIdentifier); + } + + if (token.type === Token.Keyword) { + if (syntax.isFutureReservedWord(token.value)) { + throwError(token, Messages.UnexpectedReserved); + } else if (strict && syntax.isStrictModeReservedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictReservedWord); + return; + } + throwError(token, Messages.UnexpectedToken, token.value); + } + + if (token.type === Token.Template) { + throwError(token, Messages.UnexpectedTemplate, token.value.raw); + } + + // BooleanLiteral, NullLiteral, or Punctuator. + throwError(token, Messages.UnexpectedToken, token.value); +} + +// Expect the next token to match the specified punctuator. +// If not, an exception will be thrown. + +function expect(value) { + var token = lex(); + if (token.type !== Token.Punctuator || token.value !== value) { + throwUnexpected(token); + } +} + +// Expect the next token to match the specified keyword. +// If not, an exception will be thrown. + +function expectKeyword(keyword) { + var token = lex(); + if (token.type !== Token.Keyword || token.value !== keyword) { + throwUnexpected(token); + } +} + +// Return true if the next token matches the specified punctuator. + +function match(value) { + return lookahead.type === Token.Punctuator && lookahead.value === value; +} + +// Return true if the next token matches the specified keyword + +function matchKeyword(keyword) { + return lookahead.type === Token.Keyword && lookahead.value === keyword; +} + +// Return true if the next token matches the specified contextual keyword +// (where an identifier is sometimes a keyword depending on the context) + +function matchContextualKeyword(keyword) { + return lookahead.type === Token.Identifier && lookahead.value === keyword; +} + +// Return true if the next token is an assignment operator + +function matchAssign() { + var op; + + if (lookahead.type !== Token.Punctuator) { + return false; + } + op = lookahead.value; + return op === "=" || + op === "*=" || + op === "/=" || + op === "%=" || + op === "+=" || + op === "-=" || + op === "<<=" || + op === ">>=" || + op === ">>>=" || + op === "&=" || + op === "^=" || + op === "|="; +} + +function consumeSemicolon() { + var line; + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(index) === 0x3B || match(";")) { + lex(); + return; + } + + line = lineNumber; + skipComment(); + if (lineNumber !== line) { + return; + } + + if (lookahead.type !== Token.EOF && !match("}")) { + throwUnexpected(lookahead); + } +} + +// Return true if provided expression is LeftHandSideExpression + +function isLeftHandSide(expr) { + return expr.type === astNodeTypes.Identifier || expr.type === astNodeTypes.MemberExpression; +} + +// 11.1.4 Array Initialiser + +function parseArrayInitialiser() { + var elements = [], + marker = markerCreate(), + tmp; + + expect("["); + + while (!match("]")) { + if (match(",")) { + lex(); // only get here when you have [a,,] or similar + elements.push(null); + } else { + tmp = parseSpreadOrAssignmentExpression(); + elements.push(tmp); + if (!(match("]"))) { + expect(","); // handles the common case of comma-separated values + } + } + } + + expect("]"); + + return markerApply(marker, astNodeFactory.createArrayExpression(elements)); +} + +// 11.1.5 Object Initialiser + +function parsePropertyFunction(paramInfo, options) { + var previousStrict = strict, + previousYieldAllowed = state.yieldAllowed, + generator = options ? options.generator : false, + body; + + state.yieldAllowed = generator; + + /* + * Esprima uses parseConciseBody() here, which is incorrect. Object literal + * methods must have braces. + */ + body = parseFunctionSourceElements(); + + if (strict && paramInfo.firstRestricted) { + throwErrorTolerant(paramInfo.firstRestricted, Messages.StrictParamName); + } + + if (strict && paramInfo.stricted) { + throwErrorTolerant(paramInfo.stricted, paramInfo.message); + } + + strict = previousStrict; + state.yieldAllowed = previousYieldAllowed; + + return markerApply(options.marker, astNodeFactory.createFunctionExpression( + null, + paramInfo.params, + body, + generator, + body.type !== astNodeTypes.BlockStatement + )); +} + +function parsePropertyMethodFunction(options) { + var previousStrict = strict, + marker = markerCreate(), + params, + method; + + strict = true; + + params = parseParams(); + + if (params.stricted) { + throwErrorTolerant(params.stricted, params.message); + } + + method = parsePropertyFunction(params, { + generator: options ? options.generator : false, + marker: marker + }); + + strict = previousStrict; + + return method; +} + +function parseObjectPropertyKey() { + var marker = markerCreate(), + token = lex(), + allowObjectLiteralComputed = extra.ecmaFeatures.objectLiteralComputedProperties, + expr, + result; + + // Note: This function is called only from parseObjectProperty(), where + // EOF and Punctuator tokens are already filtered out. + + switch (token.type) { + case Token.StringLiteral: + case Token.NumericLiteral: + if (strict && token.octal) { + throwErrorTolerant(token, Messages.StrictOctalLiteral); + } + return markerApply(marker, astNodeFactory.createLiteralFromSource(token, source)); + + case Token.Identifier: + case Token.BooleanLiteral: + case Token.NullLiteral: + case Token.Keyword: + return markerApply(marker, astNodeFactory.createIdentifier(token.value)); + + case Token.Punctuator: + if ((!state.inObjectLiteral || allowObjectLiteralComputed) && + token.value === "[") { + // For computed properties we should skip the [ and ], and + // capture in marker only the assignment expression itself. + marker = markerCreate(); + expr = parseAssignmentExpression(); + result = markerApply(marker, expr); + expect("]"); + return result; + } + + // no default + } + + throwUnexpected(token); +} + +function lookaheadPropertyName() { + switch (lookahead.type) { + case Token.Identifier: + case Token.StringLiteral: + case Token.BooleanLiteral: + case Token.NullLiteral: + case Token.NumericLiteral: + case Token.Keyword: + return true; + case Token.Punctuator: + return lookahead.value === "["; + // no default + } + return false; +} + +// This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals, +// it might be called at a position where there is in fact a short hand identifier pattern or a data property. +// This can only be determined after we consumed up to the left parentheses. +// In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller +// is responsible to visit other options. +function tryParseMethodDefinition(token, key, computed, marker) { + var value, options, methodMarker; + + if (token.type === Token.Identifier) { + // check for `get` and `set`; + + if (token.value === "get" && lookaheadPropertyName()) { + + computed = match("["); + key = parseObjectPropertyKey(); + methodMarker = markerCreate(); + expect("("); + expect(")"); + + value = parsePropertyFunction({ + params: [], + stricted: null, + firstRestricted: null, + message: null + }, { + marker: methodMarker + }); + + return markerApply(marker, astNodeFactory.createProperty("get", key, value, false, false, computed)); + + } else if (token.value === "set" && lookaheadPropertyName()) { + computed = match("["); + key = parseObjectPropertyKey(); + methodMarker = markerCreate(); + expect("("); + + options = { + params: [], + defaultCount: 0, + stricted: null, + firstRestricted: null, + paramSet: new StringMap() + }; + if (match(")")) { + throwErrorTolerant(lookahead, Messages.UnexpectedToken, lookahead.value); + } else { + parseParam(options); + } + expect(")"); + + value = parsePropertyFunction(options, { marker: methodMarker }); + return markerApply(marker, astNodeFactory.createProperty("set", key, value, false, false, computed)); + } + } + + if (match("(")) { + value = parsePropertyMethodFunction(); + return markerApply(marker, astNodeFactory.createProperty("init", key, value, true, false, computed)); + } + + // Not a MethodDefinition. + return null; +} + +/** + * Parses Generator Properties + * @param {ASTNode} key The property key (usually an identifier). + * @param {Object} marker The marker to use for the node. + * @returns {ASTNode} The generator property node. + */ +function parseGeneratorProperty(key, marker) { + + var computed = (lookahead.type === Token.Punctuator && lookahead.value === "["); + + if (!match("(")) { + throwUnexpected(lex()); + } + + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + key, + parsePropertyMethodFunction({ generator: true }), + true, + false, + computed + ) + ); +} + +// TODO(nzakas): Update to match Esprima +function parseObjectProperty() { + var token, key, id, computed, methodMarker, options; + var allowComputed = extra.ecmaFeatures.objectLiteralComputedProperties, + allowMethod = extra.ecmaFeatures.objectLiteralShorthandMethods, + allowShorthand = extra.ecmaFeatures.objectLiteralShorthandProperties, + allowGenerators = extra.ecmaFeatures.generators, + allowDestructuring = extra.ecmaFeatures.destructuring, + marker = markerCreate(); + + token = lookahead; + computed = (token.value === "[" && token.type === Token.Punctuator); + + if (token.type === Token.Identifier || (allowComputed && computed)) { + + id = parseObjectPropertyKey(); + + /* + * Check for getters and setters. Be careful! "get" and "set" are legal + * method names. It's only a getter or setter if followed by a space. + */ + if (token.value === "get" && + !(match(":") || match("(") || match(",") || match("}"))) { + computed = (lookahead.value === "["); + key = parseObjectPropertyKey(); + methodMarker = markerCreate(); + expect("("); + expect(")"); + + return markerApply( + marker, + astNodeFactory.createProperty( + "get", + key, + parsePropertyFunction({ + generator: false + }, { + marker: methodMarker + }), + false, + false, + computed + ) + ); + } + + if (token.value === "set" && + !(match(":") || match("(") || match(",") || match("}"))) { + computed = (lookahead.value === "["); + key = parseObjectPropertyKey(); + methodMarker = markerCreate(); + expect("("); + + options = { + params: [], + defaultCount: 0, + stricted: null, + firstRestricted: null, + paramSet: new StringMap() + }; + + if (match(")")) { + throwErrorTolerant(lookahead, Messages.UnexpectedToken, lookahead.value); + } else { + parseParam(options); + } + + expect(")"); + + return markerApply( + marker, + astNodeFactory.createProperty( + "set", + key, + parsePropertyFunction(options, { + marker: methodMarker + }), + false, + false, + computed + ) + ); + } + + // normal property (key:value) + if (match(":")) { + lex(); + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + id, + parseAssignmentExpression(), + false, + false, + computed + ) + ); + } + + // method shorthand (key(){...}) + if (allowMethod && match("(")) { + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + id, + parsePropertyMethodFunction({ generator: false }), + true, + false, + computed + ) + ); + } + + // destructuring defaults (shorthand syntax) + if (allowDestructuring && match("=")) { + lex(); + var value = parseAssignmentExpression(); + var prop = markerApply(marker, astNodeFactory.createAssignmentExpression("=", id, value)); + prop.type = astNodeTypes.AssignmentPattern; + var fullProperty = astNodeFactory.createProperty( + "init", + id, + prop, + false, + true, // shorthand + computed + ); + return markerApply(marker, fullProperty); + } + + /* + * Only other possibility is that this is a shorthand property. Computed + * properties cannot use shorthand notation, so that's a syntax error. + * If shorthand properties aren't allow, then this is an automatic + * syntax error. Destructuring is another case with a similar shorthand syntax. + */ + if (computed || (!allowShorthand && !allowDestructuring)) { + throwUnexpected(lookahead); + } + + // shorthand property + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + id, + id, + false, + true, + false + ) + ); + } + + // only possibility in this branch is a shorthand generator + if (token.type === Token.EOF || token.type === Token.Punctuator) { + if (!allowGenerators || !match("*") || !allowMethod) { + throwUnexpected(token); + } + + lex(); + + id = parseObjectPropertyKey(); + + return parseGeneratorProperty(id, marker); + + } + + /* + * If we've made it here, then that means the property name is represented + * by a string (i.e, { "foo": 2}). The only options here are normal + * property with a colon or a method. + */ + key = parseObjectPropertyKey(); + + // check for property value + if (match(":")) { + lex(); + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + key, + parseAssignmentExpression(), + false, + false, + false + ) + ); + } + + // check for method + if (allowMethod && match("(")) { + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + key, + parsePropertyMethodFunction(), + true, + false, + false + ) + ); + } + + // no other options, this is bad + throwUnexpected(lex()); +} + +function getFieldName(key) { + var toString = String; + if (key.type === astNodeTypes.Identifier) { + return key.name; + } + return toString(key.value); +} + +function parseObjectInitialiser() { + var marker = markerCreate(), + allowDuplicates = extra.ecmaFeatures.objectLiteralDuplicateProperties, + properties = [], + property, + name, + propertyFn, + kind, + storedKind, + previousInObjectLiteral = state.inObjectLiteral, + kindMap = new StringMap(); + + state.inObjectLiteral = true; + + expect("{"); + + while (!match("}")) { + + property = parseObjectProperty(); + + if (!property.computed) { + + name = getFieldName(property.key); + propertyFn = (property.kind === "get") ? PropertyKind.Get : PropertyKind.Set; + kind = (property.kind === "init") ? PropertyKind.Data : propertyFn; + + if (kindMap.has(name)) { + storedKind = kindMap.get(name); + if (storedKind === PropertyKind.Data) { + if (kind === PropertyKind.Data && name === "__proto__" && allowDuplicates) { + // Duplicate '__proto__' literal properties are forbidden in ES 6 + throwErrorTolerant({}, Messages.DuplicatePrototypeProperty); + } else if (strict && kind === PropertyKind.Data && !allowDuplicates) { + // Duplicate literal properties are only forbidden in ES 5 strict mode + throwErrorTolerant({}, Messages.StrictDuplicateProperty); + } else if (kind !== PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } + } else { + if (kind === PropertyKind.Data) { + throwErrorTolerant({}, Messages.AccessorDataProperty); + } else if (storedKind & kind) { + throwErrorTolerant({}, Messages.AccessorGetSet); + } + } + kindMap.set(name, storedKind | kind); + } else { + kindMap.set(name, kind); + } + } + + properties.push(property); + + if (!match("}")) { + expect(","); + } + } + + expect("}"); + + state.inObjectLiteral = previousInObjectLiteral; + + return markerApply(marker, astNodeFactory.createObjectExpression(properties)); +} + +/** + * Parse a template string element and return its ASTNode representation + * @param {Object} option Parsing & scanning options + * @param {Object} option.head True if this element is the first in the + * template string, false otherwise. + * @returns {ASTNode} The template element node with marker info applied + * @private + */ +function parseTemplateElement(option) { + var marker, token; + + if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) { + throwError({}, Messages.UnexpectedToken, "ILLEGAL"); + } + + marker = markerCreate(); + token = lex(); + + return markerApply( + marker, + astNodeFactory.createTemplateElement( + { + raw: token.value.raw, + cooked: token.value.cooked + }, + token.tail + ) + ); +} + +/** + * Parse a template string literal and return its ASTNode representation + * @returns {ASTNode} The template literal node with marker info applied + * @private + */ +function parseTemplateLiteral() { + var quasi, quasis, expressions, marker = markerCreate(); + + quasi = parseTemplateElement({ head: true }); + quasis = [ quasi ]; + expressions = []; + + while (!quasi.tail) { + expressions.push(parseExpression()); + quasi = parseTemplateElement({ head: false }); + quasis.push(quasi); + } + + return markerApply(marker, astNodeFactory.createTemplateLiteral(quasis, expressions)); +} + +// 11.1.6 The Grouping Operator + +function parseGroupExpression() { + var expr; + + expect("("); + + ++state.parenthesisCount; + + expr = parseExpression(); + + expect(")"); + + return expr; +} + + +// 11.1 Primary Expressions + +function parsePrimaryExpression() { + var type, token, expr, + marker, + allowJSX = extra.ecmaFeatures.jsx, + allowClasses = extra.ecmaFeatures.classes, + allowSuper = allowClasses || extra.ecmaFeatures.superInFunctions; + + if (match("(")) { + return parseGroupExpression(); + } + + if (match("[")) { + return parseArrayInitialiser(); + } + + if (match("{")) { + return parseObjectInitialiser(); + } + + if (allowJSX && match("<")) { + return parseJSXElement(); + } + + type = lookahead.type; + marker = markerCreate(); + + if (type === Token.Identifier) { + expr = astNodeFactory.createIdentifier(lex().value); + } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { + if (strict && lookahead.octal) { + throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); + } + expr = astNodeFactory.createLiteralFromSource(lex(), source); + } else if (type === Token.Keyword) { + if (matchKeyword("function")) { + return parseFunctionExpression(); + } + + if (allowSuper && matchKeyword("super") && state.inFunctionBody) { + marker = markerCreate(); + lex(); + return markerApply(marker, astNodeFactory.createSuper()); + } + + if (matchKeyword("this")) { + marker = markerCreate(); + lex(); + return markerApply(marker, astNodeFactory.createThisExpression()); + } + + if (allowClasses && matchKeyword("class")) { + return parseClassExpression(); + } + + throwUnexpected(lex()); + } else if (type === Token.BooleanLiteral) { + token = lex(); + token.value = (token.value === "true"); + expr = astNodeFactory.createLiteralFromSource(token, source); + } else if (type === Token.NullLiteral) { + token = lex(); + token.value = null; + expr = astNodeFactory.createLiteralFromSource(token, source); + } else if (match("/") || match("/=")) { + if (typeof extra.tokens !== "undefined") { + expr = astNodeFactory.createLiteralFromSource(collectRegex(), source); + } else { + expr = astNodeFactory.createLiteralFromSource(scanRegExp(), source); + } + peek(); + } else if (type === Token.Template) { + return parseTemplateLiteral(); + } else { + throwUnexpected(lex()); + } + + return markerApply(marker, expr); +} + +// 11.2 Left-Hand-Side Expressions + +function parseArguments() { + var args = [], arg; + + expect("("); + if (!match(")")) { + while (index < length) { + arg = parseSpreadOrAssignmentExpression(); + args.push(arg); + + if (match(")")) { + break; + } + + expect(","); + } + } + + expect(")"); + + return args; +} + +function parseSpreadOrAssignmentExpression() { + if (match("...")) { + var marker = markerCreate(); + lex(); + return markerApply(marker, astNodeFactory.createSpreadElement(parseAssignmentExpression())); + } + return parseAssignmentExpression(); +} + +function parseNonComputedProperty() { + var token, + marker = markerCreate(); + + token = lex(); + + if (!isIdentifierName(token)) { + throwUnexpected(token); + } + + return markerApply(marker, astNodeFactory.createIdentifier(token.value)); +} + +function parseNonComputedMember() { + expect("."); + + return parseNonComputedProperty(); +} + +function parseComputedMember() { + var expr; + + expect("["); + + expr = parseExpression(); + + expect("]"); + + return expr; +} + +function parseNewExpression() { + var callee, args, + marker = markerCreate(); + + expectKeyword("new"); + callee = parseLeftHandSideExpression(); + args = match("(") ? parseArguments() : []; + + return markerApply(marker, astNodeFactory.createNewExpression(callee, args)); +} + +function parseLeftHandSideExpressionAllowCall() { + var expr, args, + previousAllowIn = state.allowIn, + marker = markerCreate(); + + state.allowIn = true; + expr = matchKeyword("new") ? parseNewExpression() : parsePrimaryExpression(); + state.allowIn = previousAllowIn; + + // only start parsing template literal if the lookahead is a head (beginning with `) + while (match(".") || match("[") || match("(") || (lookahead.type === Token.Template && lookahead.head)) { + if (match("(")) { + args = parseArguments(); + expr = markerApply(marker, astNodeFactory.createCallExpression(expr, args)); + } else if (match("[")) { + expr = markerApply(marker, astNodeFactory.createMemberExpression("[", expr, parseComputedMember())); + } else if (match(".")) { + expr = markerApply(marker, astNodeFactory.createMemberExpression(".", expr, parseNonComputedMember())); + } else { + expr = markerApply(marker, astNodeFactory.createTaggedTemplateExpression(expr, parseTemplateLiteral())); + } + } + + return expr; +} + +function parseLeftHandSideExpression() { + var expr, + previousAllowIn = state.allowIn, + marker = markerCreate(); + + expr = matchKeyword("new") ? parseNewExpression() : parsePrimaryExpression(); + state.allowIn = previousAllowIn; + + // only start parsing template literal if the lookahead is a head (beginning with `) + while (match(".") || match("[") || (lookahead.type === Token.Template && lookahead.head)) { + if (match("[")) { + expr = markerApply(marker, astNodeFactory.createMemberExpression("[", expr, parseComputedMember())); + } else if (match(".")) { + expr = markerApply(marker, astNodeFactory.createMemberExpression(".", expr, parseNonComputedMember())); + } else { + expr = markerApply(marker, astNodeFactory.createTaggedTemplateExpression(expr, parseTemplateLiteral())); + } + } + + return expr; +} + + +// 11.3 Postfix Expressions + +function parsePostfixExpression() { + var expr, token, + marker = markerCreate(); + + expr = parseLeftHandSideExpressionAllowCall(); + + if (lookahead.type === Token.Punctuator) { + if ((match("++") || match("--")) && !peekLineTerminator()) { + // 11.3.1, 11.3.2 + if (strict && expr.type === astNodeTypes.Identifier && syntax.isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPostfix); + } + + if (!isLeftHandSide(expr)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + token = lex(); + expr = markerApply(marker, astNodeFactory.createPostfixExpression(token.value, expr)); + } + } + + return expr; +} + +// 11.4 Unary Operators + +function parseUnaryExpression() { + var token, expr, + marker; + + if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { + expr = parsePostfixExpression(); + } else if (match("++") || match("--")) { + marker = markerCreate(); + token = lex(); + expr = parseUnaryExpression(); + // 11.4.4, 11.4.5 + if (strict && expr.type === astNodeTypes.Identifier && syntax.isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.StrictLHSPrefix); + } + + if (!isLeftHandSide(expr)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + expr = astNodeFactory.createUnaryExpression(token.value, expr); + expr = markerApply(marker, expr); + } else if (match("+") || match("-") || match("~") || match("!")) { + marker = markerCreate(); + token = lex(); + expr = parseUnaryExpression(); + expr = astNodeFactory.createUnaryExpression(token.value, expr); + expr = markerApply(marker, expr); + } else if (matchKeyword("delete") || matchKeyword("void") || matchKeyword("typeof")) { + marker = markerCreate(); + token = lex(); + expr = parseUnaryExpression(); + expr = astNodeFactory.createUnaryExpression(token.value, expr); + expr = markerApply(marker, expr); + if (strict && expr.operator === "delete" && expr.argument.type === astNodeTypes.Identifier) { + throwErrorTolerant({}, Messages.StrictDelete); + } + } else { + expr = parsePostfixExpression(); + } + + return expr; +} + +function binaryPrecedence(token, allowIn) { + var prec = 0; + + if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { + return 0; + } + + switch (token.value) { + case "||": + prec = 1; + break; + + case "&&": + prec = 2; + break; + + case "|": + prec = 3; + break; + + case "^": + prec = 4; + break; + + case "&": + prec = 5; + break; + + case "==": + case "!=": + case "===": + case "!==": + prec = 6; + break; + + case "<": + case ">": + case "<=": + case ">=": + case "instanceof": + prec = 7; + break; + + case "in": + prec = allowIn ? 7 : 0; + break; + + case "<<": + case ">>": + case ">>>": + prec = 8; + break; + + case "+": + case "-": + prec = 9; + break; + + case "*": + case "/": + case "%": + prec = 11; + break; + + default: + break; + } + + return prec; +} + +// 11.5 Multiplicative Operators +// 11.6 Additive Operators +// 11.7 Bitwise Shift Operators +// 11.8 Relational Operators +// 11.9 Equality Operators +// 11.10 Binary Bitwise Operators +// 11.11 Binary Logical Operators +function parseBinaryExpression() { + var expr, token, prec, previousAllowIn, stack, right, operator, left, i, + marker, markers; + + previousAllowIn = state.allowIn; + state.allowIn = true; + + marker = markerCreate(); + left = parseUnaryExpression(); + + token = lookahead; + prec = binaryPrecedence(token, previousAllowIn); + if (prec === 0) { + return left; + } + token.prec = prec; + lex(); + + markers = [marker, markerCreate()]; + right = parseUnaryExpression(); + + stack = [left, token, right]; + + while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { + + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { + right = stack.pop(); + operator = stack.pop().value; + left = stack.pop(); + expr = astNodeFactory.createBinaryExpression(operator, left, right); + markers.pop(); + marker = markers.pop(); + markerApply(marker, expr); + stack.push(expr); + markers.push(marker); + } + + // Shift. + token = lex(); + token.prec = prec; + stack.push(token); + markers.push(markerCreate()); + expr = parseUnaryExpression(); + stack.push(expr); + } + + state.allowIn = previousAllowIn; + + // Final reduce to clean-up the stack. + i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + expr = astNodeFactory.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); + i -= 2; + marker = markers.pop(); + markerApply(marker, expr); + } + + return expr; +} + +// 11.12 Conditional Operator + +function parseConditionalExpression() { + var expr, previousAllowIn, consequent, alternate, + marker = markerCreate(); + + expr = parseBinaryExpression(); + + if (match("?")) { + lex(); + previousAllowIn = state.allowIn; + state.allowIn = true; + consequent = parseAssignmentExpression(); + state.allowIn = previousAllowIn; + expect(":"); + alternate = parseAssignmentExpression(); + + expr = astNodeFactory.createConditionalExpression(expr, consequent, alternate); + markerApply(marker, expr); + } + + return expr; +} + +// [ES6] 14.2 Arrow Function + +function parseConciseBody() { + if (match("{")) { + return parseFunctionSourceElements(); + } + return parseAssignmentExpression(); +} + +function reinterpretAsCoverFormalsList(expressions) { + var i, len, param, params, options, + allowRestParams = extra.ecmaFeatures.restParams; + + params = []; + options = { + paramSet: new StringMap() + }; + + for (i = 0, len = expressions.length; i < len; i += 1) { + param = expressions[i]; + if (param.type === astNodeTypes.Identifier) { + params.push(param); + validateParam(options, param, param.name); + } else if (param.type === astNodeTypes.ObjectExpression || param.type === astNodeTypes.ArrayExpression) { + reinterpretAsDestructuredParameter(options, param); + params.push(param); + } else if (param.type === astNodeTypes.SpreadElement) { + assert(i === len - 1, "It is guaranteed that SpreadElement is last element by parseExpression"); + if (param.argument.type !== astNodeTypes.Identifier) { + throwError({}, Messages.UnexpectedToken, "["); + } + + if (!allowRestParams) { + // can't get correct line/column here :( + throwError({}, Messages.UnexpectedToken, "."); + } + + reinterpretAsDestructuredParameter(options, param.argument); + param.type = astNodeTypes.RestElement; + params.push(param); + } else if (param.type === astNodeTypes.RestElement) { + params.push(param); + validateParam(options, param.argument, param.argument.name); + } else if (param.type === astNodeTypes.AssignmentExpression) { + + // TODO: Find a less hacky way of doing this + param.type = astNodeTypes.AssignmentPattern; + delete param.operator; + + params.push(param); + validateParam(options, param.left, param.left.name); + } else { + return null; + } + } + + if (options.message === Messages.StrictParamDupe) { + throwError( + strict ? options.stricted : options.firstRestricted, + options.message + ); + } + + return { + params: params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; +} + +function parseArrowFunctionExpression(options, marker) { + var previousStrict, body; + + expect("=>"); + previousStrict = strict; + + body = parseConciseBody(); + + if (strict && options.firstRestricted) { + throwError(options.firstRestricted, options.message); + } + if (strict && options.stricted) { + throwErrorTolerant(options.stricted, options.message); + } + + strict = previousStrict; + return markerApply(marker, astNodeFactory.createArrowFunctionExpression( + options.params, + body, + body.type !== astNodeTypes.BlockStatement + )); +} + +// 11.13 Assignment Operators + +// 12.14.5 AssignmentPattern + +function reinterpretAsAssignmentBindingPattern(expr) { + var i, len, property, element, + allowDestructuring = extra.ecmaFeatures.destructuring; + + if (!allowDestructuring) { + throwUnexpected(lex()); + } + + if (expr.type === astNodeTypes.ObjectExpression) { + expr.type = astNodeTypes.ObjectPattern; + for (i = 0, len = expr.properties.length; i < len; i += 1) { + property = expr.properties[i]; + if (property.kind !== "init") { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + reinterpretAsAssignmentBindingPattern(property.value); + } + } else if (expr.type === astNodeTypes.ArrayExpression) { + expr.type = astNodeTypes.ArrayPattern; + for (i = 0, len = expr.elements.length; i < len; i += 1) { + element = expr.elements[i]; + /* istanbul ignore else */ + if (element) { + reinterpretAsAssignmentBindingPattern(element); + } + } + } else if (expr.type === astNodeTypes.Identifier) { + if (syntax.isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + } else if (expr.type === astNodeTypes.SpreadElement) { + reinterpretAsAssignmentBindingPattern(expr.argument); + if (expr.argument.type === astNodeTypes.ObjectPattern) { + throwErrorTolerant({}, Messages.ObjectPatternAsSpread); + } + } else if (expr.type === "AssignmentExpression" && expr.operator === "=") { + expr.type = astNodeTypes.AssignmentPattern; + } else { + /* istanbul ignore else */ + if (expr.type !== astNodeTypes.MemberExpression && + expr.type !== astNodeTypes.CallExpression && + expr.type !== astNodeTypes.NewExpression && + expr.type !== astNodeTypes.AssignmentPattern + ) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + } +} + +// 13.2.3 BindingPattern + +function reinterpretAsDestructuredParameter(options, expr) { + var i, len, property, element, + allowDestructuring = extra.ecmaFeatures.destructuring; + + if (!allowDestructuring) { + throwUnexpected(lex()); + } + + if (expr.type === astNodeTypes.ObjectExpression) { + expr.type = astNodeTypes.ObjectPattern; + for (i = 0, len = expr.properties.length; i < len; i += 1) { + property = expr.properties[i]; + if (property.kind !== "init") { + throwErrorTolerant({}, Messages.InvalidLHSInFormalsList); + } + reinterpretAsDestructuredParameter(options, property.value); + } + } else if (expr.type === astNodeTypes.ArrayExpression) { + expr.type = astNodeTypes.ArrayPattern; + for (i = 0, len = expr.elements.length; i < len; i += 1) { + element = expr.elements[i]; + if (element) { + reinterpretAsDestructuredParameter(options, element); + } + } + } else if (expr.type === astNodeTypes.Identifier) { + validateParam(options, expr, expr.name); + } else if (expr.type === astNodeTypes.SpreadElement) { + // BindingRestElement only allows BindingIdentifier + if (expr.argument.type !== astNodeTypes.Identifier) { + throwErrorTolerant({}, Messages.InvalidLHSInFormalsList); + } + validateParam(options, expr.argument, expr.argument.name); + } else if (expr.type === astNodeTypes.AssignmentExpression && expr.operator === "=") { + expr.type = astNodeTypes.AssignmentPattern; + } else if (expr.type !== astNodeTypes.AssignmentPattern) { + throwError({}, Messages.InvalidLHSInFormalsList); + } +} + +function parseAssignmentExpression() { + var token, left, right, node, params, + marker, + startsWithParen = false, + oldParenthesisCount = state.parenthesisCount, + allowGenerators = extra.ecmaFeatures.generators; + + // Note that 'yield' is treated as a keyword in strict mode, but a + // contextual keyword (identifier) in non-strict mode, so we need + // to use matchKeyword and matchContextualKeyword appropriately. + if (allowGenerators && ((state.yieldAllowed && matchContextualKeyword("yield")) || (strict && matchKeyword("yield")))) { + return parseYieldExpression(); + } + + marker = markerCreate(); + + if (match("(")) { + token = lookahead2(); + if ((token.value === ")" && token.type === Token.Punctuator) || token.value === "...") { + params = parseParams(); + if (!match("=>")) { + throwUnexpected(lex()); + } + return parseArrowFunctionExpression(params, marker); + } + startsWithParen = true; + } + + // revert to the previous lookahead style object + token = lookahead; + node = left = parseConditionalExpression(); + + if (match("=>") && + (state.parenthesisCount === oldParenthesisCount || + state.parenthesisCount === (oldParenthesisCount + 1))) { + + if (node.type === astNodeTypes.Identifier) { + params = reinterpretAsCoverFormalsList([ node ]); + } else if (node.type === astNodeTypes.AssignmentExpression || + node.type === astNodeTypes.ArrayExpression || + node.type === astNodeTypes.ObjectExpression) { + if (!startsWithParen) { + throwUnexpected(lex()); + } + params = reinterpretAsCoverFormalsList([ node ]); + } else if (node.type === astNodeTypes.SequenceExpression) { + params = reinterpretAsCoverFormalsList(node.expressions); + } + + if (params) { + return parseArrowFunctionExpression(params, marker); + } + } + + if (matchAssign()) { + + // 11.13.1 + if (strict && left.type === astNodeTypes.Identifier && syntax.isRestrictedWord(left.name)) { + throwErrorTolerant(token, Messages.StrictLHSAssignment); + } + + // ES.next draf 11.13 Runtime Semantics step 1 + if (match("=") && (node.type === astNodeTypes.ObjectExpression || node.type === astNodeTypes.ArrayExpression)) { + reinterpretAsAssignmentBindingPattern(node); + } else if (!isLeftHandSide(node)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + + token = lex(); + right = parseAssignmentExpression(); + node = markerApply(marker, astNodeFactory.createAssignmentExpression(token.value, left, right)); + } + + return node; +} + +// 11.14 Comma Operator + +function parseExpression() { + var marker = markerCreate(), + expr = parseAssignmentExpression(), + expressions = [ expr ], + sequence, spreadFound; + + if (match(",")) { + while (index < length) { + if (!match(",")) { + break; + } + lex(); + expr = parseSpreadOrAssignmentExpression(); + expressions.push(expr); + + if (expr.type === astNodeTypes.SpreadElement) { + spreadFound = true; + if (!match(")")) { + throwError({}, Messages.ElementAfterSpreadElement); + } + break; + } + } + + sequence = markerApply(marker, astNodeFactory.createSequenceExpression(expressions)); + } + + if (spreadFound && lookahead2().value !== "=>") { + throwError({}, Messages.IllegalSpread); + } + + return sequence || expr; +} + +// 12.1 Block + +function parseStatementList() { + var list = [], + statement; + + while (index < length) { + if (match("}")) { + break; + } + statement = parseSourceElement(); + if (typeof statement === "undefined") { + break; + } + list.push(statement); + } + + return list; +} + +function parseBlock() { + var block, + marker = markerCreate(); + + expect("{"); + + block = parseStatementList(); + + expect("}"); + + return markerApply(marker, astNodeFactory.createBlockStatement(block)); +} + +// 12.2 Variable Statement + +function parseVariableIdentifier() { + var token, + marker = markerCreate(); + + token = lex(); + + if (token.type !== Token.Identifier) { + if (strict && token.type === Token.Keyword && syntax.isStrictModeReservedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictReservedWord); + } else { + throwUnexpected(token); + } + } + + return markerApply(marker, astNodeFactory.createIdentifier(token.value)); +} + +function parseVariableDeclaration(kind) { + var id, + marker = markerCreate(), + init = null; + if (match("{")) { + id = parseObjectInitialiser(); + reinterpretAsAssignmentBindingPattern(id); + } else if (match("[")) { + id = parseArrayInitialiser(); + reinterpretAsAssignmentBindingPattern(id); + } else { + /* istanbul ignore next */ + id = state.allowKeyword ? parseNonComputedProperty() : parseVariableIdentifier(); + // 12.2.1 + if (strict && syntax.isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } + } + + // TODO: Verify against feature flags + if (kind === "const") { + if (!match("=")) { + throwError({}, Messages.NoUnintializedConst); + } + expect("="); + init = parseAssignmentExpression(); + } else if (match("=")) { + lex(); + init = parseAssignmentExpression(); + } + + return markerApply(marker, astNodeFactory.createVariableDeclarator(id, init)); +} + +function parseVariableDeclarationList(kind) { + var list = []; + + do { + list.push(parseVariableDeclaration(kind)); + if (!match(",")) { + break; + } + lex(); + } while (index < length); + + return list; +} + +function parseVariableStatement() { + var declarations; + + expectKeyword("var"); + + declarations = parseVariableDeclarationList(); + + consumeSemicolon(); + + return astNodeFactory.createVariableDeclaration(declarations, "var"); +} + +// kind may be `const` or `let` +// Both are experimental and not in the specification yet. +// see http://wiki.ecmascript.org/doku.php?id=harmony:const +// and http://wiki.ecmascript.org/doku.php?id=harmony:let +function parseConstLetDeclaration(kind) { + var declarations, + marker = markerCreate(); + + expectKeyword(kind); + + declarations = parseVariableDeclarationList(kind); + + consumeSemicolon(); + + return markerApply(marker, astNodeFactory.createVariableDeclaration(declarations, kind)); +} + + +function parseRestElement() { + var param, + marker = markerCreate(); + + lex(); + + if (match("{")) { + throwError(lookahead, Messages.ObjectPatternAsRestParameter); + } + + param = parseVariableIdentifier(); + + if (match("=")) { + throwError(lookahead, Messages.DefaultRestParameter); + } + + if (!match(")")) { + throwError(lookahead, Messages.ParameterAfterRestParameter); + } + + return markerApply(marker, astNodeFactory.createRestElement(param)); +} + +// 12.3 Empty Statement + +function parseEmptyStatement() { + expect(";"); + return astNodeFactory.createEmptyStatement(); +} + +// 12.4 Expression Statement + +function parseExpressionStatement() { + var expr = parseExpression(); + consumeSemicolon(); + return astNodeFactory.createExpressionStatement(expr); +} + +// 12.5 If statement + +function parseIfStatement() { + var test, consequent, alternate; + + expectKeyword("if"); + + expect("("); + + test = parseExpression(); + + expect(")"); + + consequent = parseStatement(); + + if (matchKeyword("else")) { + lex(); + alternate = parseStatement(); + } else { + alternate = null; + } + + return astNodeFactory.createIfStatement(test, consequent, alternate); +} + +// 12.6 Iteration Statements + +function parseDoWhileStatement() { + var body, test, oldInIteration; + + expectKeyword("do"); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + expectKeyword("while"); + + expect("("); + + test = parseExpression(); + + expect(")"); + + if (match(";")) { + lex(); + } + + return astNodeFactory.createDoWhileStatement(test, body); +} + +function parseWhileStatement() { + var test, body, oldInIteration; + + expectKeyword("while"); + + expect("("); + + test = parseExpression(); + + expect(")"); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return astNodeFactory.createWhileStatement(test, body); +} + +function parseForVariableDeclaration() { + var token, declarations, + marker = markerCreate(); + + token = lex(); + declarations = parseVariableDeclarationList(); + + return markerApply(marker, astNodeFactory.createVariableDeclaration(declarations, token.value)); +} + +function parseForStatement(opts) { + var init, test, update, left, right, body, operator, oldInIteration; + var allowForOf = extra.ecmaFeatures.forOf, + allowBlockBindings = extra.ecmaFeatures.blockBindings; + + init = test = update = null; + + expectKeyword("for"); + + expect("("); + + if (match(";")) { + lex(); + } else { + + if (matchKeyword("var") || + (allowBlockBindings && (matchKeyword("let") || matchKeyword("const"))) + ) { + state.allowIn = false; + init = parseForVariableDeclaration(); + state.allowIn = true; + + if (init.declarations.length === 1) { + if (matchKeyword("in") || (allowForOf && matchContextualKeyword("of"))) { + operator = lookahead; + + // TODO: is "var" check here really needed? wasn"t in 1.2.2 + if (!((operator.value === "in" || init.kind !== "var") && init.declarations[0].init)) { + lex(); + left = init; + right = parseExpression(); + init = null; + } + } + } + + } else { + state.allowIn = false; + init = parseExpression(); + state.allowIn = true; + + if (allowForOf && matchContextualKeyword("of")) { + operator = lex(); + left = init; + right = parseExpression(); + init = null; + } else if (matchKeyword("in")) { + // LeftHandSideExpression + if (!isLeftHandSide(init)) { + throwErrorTolerant({}, Messages.InvalidLHSInForIn); + } + + operator = lex(); + left = init; + right = parseExpression(); + init = null; + } + } + + if (typeof left === "undefined") { + expect(";"); + } + } + + if (typeof left === "undefined") { + + if (!match(";")) { + test = parseExpression(); + } + expect(";"); + + if (!match(")")) { + update = parseExpression(); + } + } + + expect(")"); + + oldInIteration = state.inIteration; + state.inIteration = true; + + if (!(opts !== undefined && opts.ignoreBody)) { + body = parseStatement(); + } + + state.inIteration = oldInIteration; + + if (typeof left === "undefined") { + return astNodeFactory.createForStatement(init, test, update, body); + } + + if (extra.ecmaFeatures.forOf && operator.value === "of") { + return astNodeFactory.createForOfStatement(left, right, body); + } + + return astNodeFactory.createForInStatement(left, right, body); +} + +// 12.7 The continue statement + +function parseContinueStatement() { + var label = null; + + expectKeyword("continue"); + + // Optimize the most common form: "continue;". + if (source.charCodeAt(index) === 0x3B) { + lex(); + + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return astNodeFactory.createContinueStatement(null); + } + + if (peekLineTerminator()) { + if (!state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return astNodeFactory.createContinueStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + if (!state.labelSet.has(label.name)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !state.inIteration) { + throwError({}, Messages.IllegalContinue); + } + + return astNodeFactory.createContinueStatement(label); +} + +// 12.8 The break statement + +function parseBreakStatement() { + var label = null; + + expectKeyword("break"); + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(index) === 0x3B) { + lex(); + + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return astNodeFactory.createBreakStatement(null); + } + + if (peekLineTerminator()) { + if (!(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return astNodeFactory.createBreakStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + if (!state.labelSet.has(label.name)) { + throwError({}, Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !(state.inIteration || state.inSwitch)) { + throwError({}, Messages.IllegalBreak); + } + + return astNodeFactory.createBreakStatement(label); +} + +// 12.9 The return statement + +function parseReturnStatement() { + var argument = null; + + expectKeyword("return"); + + if (!state.inFunctionBody && !extra.ecmaFeatures.globalReturn) { + throwErrorTolerant({}, Messages.IllegalReturn); + } + + // "return" followed by a space and an identifier is very common. + if (source.charCodeAt(index) === 0x20) { + if (syntax.isIdentifierStart(source.charCodeAt(index + 1))) { + argument = parseExpression(); + consumeSemicolon(); + return astNodeFactory.createReturnStatement(argument); + } + } + + if (peekLineTerminator()) { + return astNodeFactory.createReturnStatement(null); + } + + if (!match(";")) { + if (!match("}") && lookahead.type !== Token.EOF) { + argument = parseExpression(); + } + } + + consumeSemicolon(); + + return astNodeFactory.createReturnStatement(argument); +} + +// 12.10 The with statement + +function parseWithStatement() { + var object, body; + + if (strict) { + // TODO(ikarienator): Should we update the test cases instead? + skipComment(); + throwErrorTolerant({}, Messages.StrictModeWith); + } + + expectKeyword("with"); + + expect("("); + + object = parseExpression(); + + expect(")"); + + body = parseStatement(); + + return astNodeFactory.createWithStatement(object, body); +} + +// 12.10 The swith statement + +function parseSwitchCase() { + var test, consequent = [], statement, + marker = markerCreate(); + + if (matchKeyword("default")) { + lex(); + test = null; + } else { + expectKeyword("case"); + test = parseExpression(); + } + expect(":"); + + while (index < length) { + if (match("}") || matchKeyword("default") || matchKeyword("case")) { + break; + } + statement = parseSourceElement(); + consequent.push(statement); + } + + return markerApply(marker, astNodeFactory.createSwitchCase(test, consequent)); +} + +function parseSwitchStatement() { + var discriminant, cases, clause, oldInSwitch, defaultFound; + + expectKeyword("switch"); + + expect("("); + + discriminant = parseExpression(); + + expect(")"); + + expect("{"); + + cases = []; + + if (match("}")) { + lex(); + return astNodeFactory.createSwitchStatement(discriminant, cases); + } + + oldInSwitch = state.inSwitch; + state.inSwitch = true; + defaultFound = false; + + while (index < length) { + if (match("}")) { + break; + } + clause = parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + throwError({}, Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + + state.inSwitch = oldInSwitch; + + expect("}"); + + return astNodeFactory.createSwitchStatement(discriminant, cases); +} + +// 12.13 The throw statement + +function parseThrowStatement() { + var argument; + + expectKeyword("throw"); + + if (peekLineTerminator()) { + throwError({}, Messages.NewlineAfterThrow); + } + + argument = parseExpression(); + + consumeSemicolon(); + + return astNodeFactory.createThrowStatement(argument); +} + +// 12.14 The try statement + +function parseCatchClause() { + var param, body, + marker = markerCreate(), + allowDestructuring = extra.ecmaFeatures.destructuring, + options = { + paramSet: new StringMap() + }; + + expectKeyword("catch"); + + expect("("); + if (match(")")) { + throwUnexpected(lookahead); + } + + if (match("[")) { + if (!allowDestructuring) { + throwUnexpected(lookahead); + } + param = parseArrayInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else if (match("{")) { + + if (!allowDestructuring) { + throwUnexpected(lookahead); + } + param = parseObjectInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else { + param = parseVariableIdentifier(); + } + + // 12.14.1 + if (strict && param.name && syntax.isRestrictedWord(param.name)) { + throwErrorTolerant({}, Messages.StrictCatchVariable); + } + + expect(")"); + body = parseBlock(); + return markerApply(marker, astNodeFactory.createCatchClause(param, body)); +} + +function parseTryStatement() { + var block, handler = null, finalizer = null; + + expectKeyword("try"); + + block = parseBlock(); + + if (matchKeyword("catch")) { + handler = parseCatchClause(); + } + + if (matchKeyword("finally")) { + lex(); + finalizer = parseBlock(); + } + + if (!handler && !finalizer) { + throwError({}, Messages.NoCatchOrFinally); + } + + return astNodeFactory.createTryStatement(block, handler, finalizer); +} + +// 12.15 The debugger statement + +function parseDebuggerStatement() { + expectKeyword("debugger"); + + consumeSemicolon(); + + return astNodeFactory.createDebuggerStatement(); +} + +// 12 Statements + +function parseStatement() { + var type = lookahead.type, + expr, + labeledBody, + marker; + + if (type === Token.EOF) { + throwUnexpected(lookahead); + } + + if (type === Token.Punctuator && lookahead.value === "{") { + return parseBlock(); + } + + marker = markerCreate(); + + if (type === Token.Punctuator) { + switch (lookahead.value) { + case ";": + return markerApply(marker, parseEmptyStatement()); + case "{": + return parseBlock(); + case "(": + return markerApply(marker, parseExpressionStatement()); + default: + break; + } + } + + marker = markerCreate(); + + if (type === Token.Keyword) { + switch (lookahead.value) { + case "break": + return markerApply(marker, parseBreakStatement()); + case "continue": + return markerApply(marker, parseContinueStatement()); + case "debugger": + return markerApply(marker, parseDebuggerStatement()); + case "do": + return markerApply(marker, parseDoWhileStatement()); + case "for": + return markerApply(marker, parseForStatement()); + case "function": + return markerApply(marker, parseFunctionDeclaration()); + case "if": + return markerApply(marker, parseIfStatement()); + case "return": + return markerApply(marker, parseReturnStatement()); + case "switch": + return markerApply(marker, parseSwitchStatement()); + case "throw": + return markerApply(marker, parseThrowStatement()); + case "try": + return markerApply(marker, parseTryStatement()); + case "var": + return markerApply(marker, parseVariableStatement()); + case "while": + return markerApply(marker, parseWhileStatement()); + case "with": + return markerApply(marker, parseWithStatement()); + default: + break; + } + } + + marker = markerCreate(); + expr = parseExpression(); + + // 12.12 Labelled Statements + if ((expr.type === astNodeTypes.Identifier) && match(":")) { + lex(); + + if (state.labelSet.has(expr.name)) { + throwError({}, Messages.Redeclaration, "Label", expr.name); + } + + state.labelSet.set(expr.name, true); + labeledBody = parseStatement(); + state.labelSet.delete(expr.name); + return markerApply(marker, astNodeFactory.createLabeledStatement(expr, labeledBody)); + } + + consumeSemicolon(); + + return markerApply(marker, astNodeFactory.createExpressionStatement(expr)); +} + +// 13 Function Definition + +// function parseConciseBody() { +// if (match("{")) { +// return parseFunctionSourceElements(); +// } +// return parseAssignmentExpression(); +// } + +function parseFunctionSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount, + marker = markerCreate(); + + expect("{"); + + while (index < length) { + if (lookahead.type !== Token.StringLiteral) { + break; + } + token = lookahead; + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== astNodeTypes.Literal) { + // this is not directive + break; + } + directive = source.slice(token.range[0] + 1, token.range[1] - 1); + if (directive === "use strict") { + strict = true; + + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + oldLabelSet = state.labelSet; + oldInIteration = state.inIteration; + oldInSwitch = state.inSwitch; + oldInFunctionBody = state.inFunctionBody; + oldParenthesisCount = state.parenthesizedCount; + + state.labelSet = new StringMap(); + state.inIteration = false; + state.inSwitch = false; + state.inFunctionBody = true; + + while (index < length) { + + if (match("}")) { + break; + } + + sourceElement = parseSourceElement(); + + if (typeof sourceElement === "undefined") { + break; + } + + sourceElements.push(sourceElement); + } + + expect("}"); + + state.labelSet = oldLabelSet; + state.inIteration = oldInIteration; + state.inSwitch = oldInSwitch; + state.inFunctionBody = oldInFunctionBody; + state.parenthesizedCount = oldParenthesisCount; + + return markerApply(marker, astNodeFactory.createBlockStatement(sourceElements)); +} + +function validateParam(options, param, name) { + + if (strict) { + if (syntax.isRestrictedWord(name)) { + options.stricted = param; + options.message = Messages.StrictParamName; + } + + if (options.paramSet.has(name)) { + options.stricted = param; + options.message = Messages.StrictParamDupe; + } + } else if (!options.firstRestricted) { + if (syntax.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamName; + } else if (syntax.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictReservedWord; + } else if (options.paramSet.has(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamDupe; + } + } + options.paramSet.set(name, true); +} + +function parseParam(options) { + var token, param, def, + allowRestParams = extra.ecmaFeatures.restParams, + allowDestructuring = extra.ecmaFeatures.destructuring, + allowDefaultParams = extra.ecmaFeatures.defaultParams, + marker = markerCreate(); + + token = lookahead; + if (token.value === "...") { + if (!allowRestParams) { + throwUnexpected(lookahead); + } + param = parseRestElement(); + validateParam(options, param.argument, param.argument.name); + options.params.push(param); + return false; + } + + if (match("[")) { + if (!allowDestructuring) { + throwUnexpected(lookahead); + } + param = parseArrayInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else if (match("{")) { + if (!allowDestructuring) { + throwUnexpected(lookahead); + } + param = parseObjectInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else { + param = parseVariableIdentifier(); + validateParam(options, token, token.value); + } + + if (match("=")) { + if (allowDefaultParams || allowDestructuring) { + lex(); + def = parseAssignmentExpression(); + ++options.defaultCount; + } else { + throwUnexpected(lookahead); + } + } + + if (def) { + options.params.push(markerApply( + marker, + astNodeFactory.createAssignmentPattern( + param, + def + ) + )); + } else { + options.params.push(param); + } + + return !match(")"); +} + + +function parseParams(firstRestricted) { + var options; + + options = { + params: [], + defaultCount: 0, + firstRestricted: firstRestricted + }; + + expect("("); + + if (!match(")")) { + options.paramSet = new StringMap(); + while (index < length) { + if (!parseParam(options)) { + break; + } + expect(","); + } + } + + expect(")"); + + return { + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; +} + +function parseFunctionDeclaration(identifierIsOptional) { + var id = null, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator, + marker = markerCreate(), + allowGenerators = extra.ecmaFeatures.generators; + + expectKeyword("function"); + + generator = false; + if (allowGenerators && match("*")) { + lex(); + generator = true; + } + + if (!identifierIsOptional || !match("(")) { + + token = lookahead; + + id = parseVariableIdentifier(); + + if (strict) { + if (syntax.isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (syntax.isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (syntax.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + tmp = parseParams(firstRestricted); + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = generator; + + body = parseFunctionSourceElements(); + + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && tmp.stricted) { + throwErrorTolerant(tmp.stricted, message); + } + strict = previousStrict; + state.yieldAllowed = previousYieldAllowed; + + return markerApply( + marker, + astNodeFactory.createFunctionDeclaration( + id, + tmp.params, + body, + generator, + false + ) + ); + } + +function parseFunctionExpression() { + var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator, + marker = markerCreate(), + allowGenerators = extra.ecmaFeatures.generators; + + expectKeyword("function"); + + generator = false; + + if (allowGenerators && match("*")) { + lex(); + generator = true; + } + + if (!match("(")) { + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (syntax.isRestrictedWord(token.value)) { + throwErrorTolerant(token, Messages.StrictFunctionName); + } + } else { + if (syntax.isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (syntax.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + tmp = parseParams(firstRestricted); + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + previousYieldAllowed = state.yieldAllowed; + state.yieldAllowed = generator; + + body = parseFunctionSourceElements(); + + if (strict && firstRestricted) { + throwError(firstRestricted, message); + } + if (strict && tmp.stricted) { + throwErrorTolerant(tmp.stricted, message); + } + strict = previousStrict; + state.yieldAllowed = previousYieldAllowed; + + return markerApply( + marker, + astNodeFactory.createFunctionExpression( + id, + tmp.params, + body, + generator, + false + ) + ); +} + +function parseYieldExpression() { + var yieldToken, delegateFlag, expr, marker = markerCreate(); + + yieldToken = lex(); + assert(yieldToken.value === "yield", "Called parseYieldExpression with non-yield lookahead."); + + if (!state.yieldAllowed) { + throwErrorTolerant({}, Messages.IllegalYield); + } + + delegateFlag = false; + if (match("*")) { + lex(); + delegateFlag = true; + } + + if (peekLineTerminator()) { + return markerApply(marker, astNodeFactory.createYieldExpression(null, delegateFlag)); + } + + if (!match(";") && !match(")")) { + if (!match("}") && lookahead.type !== Token.EOF) { + expr = parseAssignmentExpression(); + } + } + + return markerApply(marker, astNodeFactory.createYieldExpression(expr, delegateFlag)); +} + +// Modules grammar from: +// people.mozilla.org/~jorendorff/es6-draft.html + +function parseModuleSpecifier() { + var marker = markerCreate(), + specifier; + + if (lookahead.type !== Token.StringLiteral) { + throwError({}, Messages.InvalidModuleSpecifier); + } + specifier = astNodeFactory.createLiteralFromSource(lex(), source); + return markerApply(marker, specifier); +} + +function parseExportSpecifier() { + var exported, local, marker = markerCreate(); + if (matchKeyword("default")) { + lex(); + local = markerApply(marker, astNodeFactory.createIdentifier("default")); + // export {default} from "something"; + } else { + local = parseVariableIdentifier(); + } + if (matchContextualKeyword("as")) { + lex(); + exported = parseNonComputedProperty(); + } + return markerApply(marker, astNodeFactory.createExportSpecifier(local, exported)); +} + +function parseExportNamedDeclaration() { + var declaration = null, + isExportFromIdentifier, + src = null, specifiers = [], + marker = markerCreate(); + + expectKeyword("export"); + + // non-default export + if (lookahead.type === Token.Keyword) { + // covers: + // export var f = 1; + switch (lookahead.value) { + case "let": + case "const": + case "var": + case "class": + case "function": + declaration = parseSourceElement(); + return markerApply(marker, astNodeFactory.createExportNamedDeclaration(declaration, specifiers, null)); + default: + break; + } + } + + expect("{"); + if (!match("}")) { + do { + isExportFromIdentifier = isExportFromIdentifier || matchKeyword("default"); + specifiers.push(parseExportSpecifier()); + } while (match(",") && lex()); + } + expect("}"); + + if (matchContextualKeyword("from")) { + // covering: + // export {default} from "foo"; + // export {foo} from "foo"; + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + } else if (isExportFromIdentifier) { + // covering: + // export {default}; // missing fromClause + throwError({}, lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } else { + // cover + // export {foo}; + consumeSemicolon(); + } + return markerApply(marker, astNodeFactory.createExportNamedDeclaration(declaration, specifiers, src)); +} + +function parseExportDefaultDeclaration() { + var declaration = null, + expression = null, + possibleIdentifierToken, + allowClasses = extra.ecmaFeatures.classes, + marker = markerCreate(); + + // covers: + // export default ... + expectKeyword("export"); + expectKeyword("default"); + + if (matchKeyword("function") || matchKeyword("class")) { + possibleIdentifierToken = lookahead2(); + if (possibleIdentifierToken.type === Token.Identifier) { + // covers: + // export default function foo () {} + // export default class foo {} + declaration = parseSourceElement(); + return markerApply(marker, astNodeFactory.createExportDefaultDeclaration(declaration)); + } + // covers: + // export default function () {} + // export default class {} + if (lookahead.value === "function") { + declaration = parseFunctionDeclaration(true); + return markerApply(marker, astNodeFactory.createExportDefaultDeclaration(declaration)); + } else if (allowClasses && lookahead.value === "class") { + declaration = parseClassDeclaration(true); + return markerApply(marker, astNodeFactory.createExportDefaultDeclaration(declaration)); + } + } + + if (matchContextualKeyword("from")) { + throwError({}, Messages.UnexpectedToken, lookahead.value); + } + + // covers: + // export default {}; + // export default []; + // export default (1 + 2); + if (match("{")) { + expression = parseObjectInitialiser(); + } else if (match("[")) { + expression = parseArrayInitialiser(); + } else { + expression = parseAssignmentExpression(); + } + consumeSemicolon(); + return markerApply(marker, astNodeFactory.createExportDefaultDeclaration(expression)); +} + + +function parseExportAllDeclaration() { + var src, + marker = markerCreate(); + + // covers: + // export * from "foo"; + expectKeyword("export"); + expect("*"); + if (!matchContextualKeyword("from")) { + throwError({}, lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + + return markerApply(marker, astNodeFactory.createExportAllDeclaration(src)); +} + +function parseExportDeclaration() { + if (state.inFunctionBody) { + throwError({}, Messages.IllegalExportDeclaration); + } + var declarationType = lookahead2().value; + if (declarationType === "default") { + return parseExportDefaultDeclaration(); + } else if (declarationType === "*") { + return parseExportAllDeclaration(); + } else { + return parseExportNamedDeclaration(); + } +} + +function parseImportSpecifier() { + // import {} ...; + var local, imported, marker = markerCreate(); + + imported = parseNonComputedProperty(); + if (matchContextualKeyword("as")) { + lex(); + local = parseVariableIdentifier(); + } + + return markerApply(marker, astNodeFactory.createImportSpecifier(local, imported)); +} + +function parseNamedImports() { + var specifiers = []; + // {foo, bar as bas} + expect("{"); + if (!match("}")) { + do { + specifiers.push(parseImportSpecifier()); + } while (match(",") && lex()); + } + expect("}"); + return specifiers; +} + +function parseImportDefaultSpecifier() { + // import ...; + var local, marker = markerCreate(); + + local = parseNonComputedProperty(); + + return markerApply(marker, astNodeFactory.createImportDefaultSpecifier(local)); +} + +function parseImportNamespaceSpecifier() { + // import <* as foo> ...; + var local, marker = markerCreate(); + + expect("*"); + if (!matchContextualKeyword("as")) { + throwError({}, Messages.NoAsAfterImportNamespace); + } + lex(); + local = parseNonComputedProperty(); + + return markerApply(marker, astNodeFactory.createImportNamespaceSpecifier(local)); +} + +function parseImportDeclaration() { + var specifiers, src, marker = markerCreate(); + + if (state.inFunctionBody) { + throwError({}, Messages.IllegalImportDeclaration); + } + + expectKeyword("import"); + specifiers = []; + + if (lookahead.type === Token.StringLiteral) { + // covers: + // import "foo"; + src = parseModuleSpecifier(); + consumeSemicolon(); + return markerApply(marker, astNodeFactory.createImportDeclaration(specifiers, src)); + } + + if (!matchKeyword("default") && isIdentifierName(lookahead)) { + // covers: + // import foo + // import foo, ... + specifiers.push(parseImportDefaultSpecifier()); + if (match(",")) { + lex(); + } + } + if (match("*")) { + // covers: + // import foo, * as foo + // import * as foo + specifiers.push(parseImportNamespaceSpecifier()); + } else if (match("{")) { + // covers: + // import foo, {bar} + // import {bar} + specifiers = specifiers.concat(parseNamedImports()); + } + + if (!matchContextualKeyword("from")) { + throwError({}, lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + + return markerApply(marker, astNodeFactory.createImportDeclaration(specifiers, src)); +} + +// 14 Functions and classes + +// 14.1 Functions is defined above (13 in ES5) +// 14.2 Arrow Functions Definitions is defined in (7.3 assignments) + +// 14.3 Method Definitions +// 14.3.7 + +// 14.5 Class Definitions + +function parseClassBody() { + var hasConstructor = false, generator = false, + allowGenerators = extra.ecmaFeatures.generators, + token, isStatic, body = [], method, computed, key; + + var existingProps = {}, + topMarker = markerCreate(), + marker; + + existingProps.static = new StringMap(); + existingProps.prototype = new StringMap(); + + expect("{"); + + while (!match("}")) { + + // extra semicolons are fine + if (match(";")) { + lex(); + continue; + } + + token = lookahead; + isStatic = false; + generator = match("*"); + computed = match("["); + marker = markerCreate(); + + if (generator) { + if (!allowGenerators) { + throwUnexpected(lookahead); + } + lex(); + } + + key = parseObjectPropertyKey(); + + // static generator methods + if (key.name === "static" && match("*")) { + if (!allowGenerators) { + throwUnexpected(lookahead); + } + generator = true; + lex(); + } + + if (key.name === "static" && lookaheadPropertyName()) { + token = lookahead; + isStatic = true; + computed = match("["); + key = parseObjectPropertyKey(); + } + + if (generator) { + method = parseGeneratorProperty(key, marker); + } else { + method = tryParseMethodDefinition(token, key, computed, marker, generator); + } + + if (method) { + method.static = isStatic; + if (method.kind === "init") { + method.kind = "method"; + } + + if (!isStatic) { + + if (!method.computed && (method.key.name || (method.key.value && method.key.value.toString())) === "constructor") { + if (method.kind !== "method" || !method.method || method.value.generator) { + throwUnexpected(token, Messages.ConstructorSpecialMethod); + } + if (hasConstructor) { + throwUnexpected(token, Messages.DuplicateConstructor); + } else { + hasConstructor = true; + } + method.kind = "constructor"; + } + } else { + if (!method.computed && (method.key.name || method.key.value.toString()) === "prototype") { + throwUnexpected(token, Messages.StaticPrototype); + } + } + method.type = astNodeTypes.MethodDefinition; + delete method.method; + delete method.shorthand; + body.push(method); + } else { + throwUnexpected(lookahead); + } + } + + lex(); + return markerApply(topMarker, astNodeFactory.createClassBody(body)); +} + +function parseClassExpression() { + var id = null, superClass = null, marker = markerCreate(), + previousStrict = strict, classBody; + + // classes run in strict mode + strict = true; + + expectKeyword("class"); + + if (lookahead.type === Token.Identifier) { + id = parseVariableIdentifier(); + } + + if (matchKeyword("extends")) { + lex(); + superClass = parseLeftHandSideExpressionAllowCall(); + } + + classBody = parseClassBody(); + strict = previousStrict; + + return markerApply(marker, astNodeFactory.createClassExpression(id, superClass, classBody)); +} + +function parseClassDeclaration(identifierIsOptional) { + var id = null, superClass = null, marker = markerCreate(), + previousStrict = strict, classBody; + + // classes run in strict mode + strict = true; + + expectKeyword("class"); + + if (!identifierIsOptional || lookahead.type === Token.Identifier) { + id = parseVariableIdentifier(); + } + + if (matchKeyword("extends")) { + lex(); + superClass = parseLeftHandSideExpressionAllowCall(); + } + + classBody = parseClassBody(); + strict = previousStrict; + + return markerApply(marker, astNodeFactory.createClassDeclaration(id, superClass, classBody)); +} + +// 15 Program + +function parseSourceElement() { + + var allowClasses = extra.ecmaFeatures.classes, + allowModules = extra.ecmaFeatures.modules, + allowBlockBindings = extra.ecmaFeatures.blockBindings; + + if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { + case "export": + if (!allowModules) { + throwErrorTolerant({}, Messages.IllegalExportDeclaration); + } + return parseExportDeclaration(); + case "import": + if (!allowModules) { + throwErrorTolerant({}, Messages.IllegalImportDeclaration); + } + return parseImportDeclaration(); + case "function": + return parseFunctionDeclaration(); + case "class": + if (allowClasses) { + return parseClassDeclaration(); + } + break; + case "const": + case "let": + if (allowBlockBindings) { + return parseConstLetDeclaration(lookahead.value); + } + /* falls through */ + default: + return parseStatement(); + } + } + + if (lookahead.type !== Token.EOF) { + return parseStatement(); + } +} + +function parseSourceElements() { + var sourceElement, sourceElements = [], token, directive, firstRestricted; + + while (index < length) { + token = lookahead; + if (token.type !== Token.StringLiteral) { + break; + } + + sourceElement = parseSourceElement(); + sourceElements.push(sourceElement); + if (sourceElement.expression.type !== astNodeTypes.Literal) { + // this is not directive + break; + } + directive = source.slice(token.range[0] + 1, token.range[1] - 1); + if (directive === "use strict") { + strict = true; + if (firstRestricted) { + throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + while (index < length) { + sourceElement = parseSourceElement(); + /* istanbul ignore if */ + if (typeof sourceElement === "undefined") { + break; + } + sourceElements.push(sourceElement); + } + return sourceElements; +} + +function parseProgram() { + var body, + marker, + isModule = !!extra.ecmaFeatures.modules; + + skipComment(); + peek(); + marker = markerCreate(); + strict = isModule; + + body = parseSourceElements(); + return markerApply(marker, astNodeFactory.createProgram(body, isModule ? "module" : "script")); +} + +function filterTokenLocation() { + var i, entry, token, tokens = []; + + for (i = 0; i < extra.tokens.length; ++i) { + entry = extra.tokens[i]; + token = { + type: entry.type, + value: entry.value + }; + if (entry.regex) { + token.regex = { + pattern: entry.regex.pattern, + flags: entry.regex.flags + }; + } + if (extra.range) { + token.range = entry.range; + } + if (extra.loc) { + token.loc = entry.loc; + } + tokens.push(token); + } + + extra.tokens = tokens; +} + +//------------------------------------------------------------------------------ +// Tokenizer +//------------------------------------------------------------------------------ + +function tokenize(code, options) { + var toString, + tokens; + + toString = String; + if (typeof code !== "string" && !(code instanceof String)) { + code = toString(code); + } + + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + parenthesisCount: 0, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1, + yieldAllowed: false, + curlyStack: [], + curlyLastIndex: 0, + inJSXSpreadAttribute: false, + inJSXChild: false, + inJSXTag: false + }; + + extra = { + ecmaFeatures: defaultFeatures + }; + + // Options matching. + options = options || {}; + + // Of course we collect tokens here. + options.tokens = true; + extra.tokens = []; + extra.tokenize = true; + + // The following two fields are necessary to compute the Regex tokens. + extra.openParenToken = -1; + extra.openCurlyToken = -1; + + extra.range = (typeof options.range === "boolean") && options.range; + extra.loc = (typeof options.loc === "boolean") && options.loc; + + if (typeof options.comment === "boolean" && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === "boolean" && options.tolerant) { + extra.errors = []; + } + + // apply parsing flags + if (options.ecmaFeatures && typeof options.ecmaFeatures === "object") { + extra.ecmaFeatures = options.ecmaFeatures; + } + + try { + peek(); + if (lookahead.type === Token.EOF) { + return extra.tokens; + } + + lex(); + while (lookahead.type !== Token.EOF) { + try { + lex(); + } catch (lexError) { + if (extra.errors) { + extra.errors.push(lexError); + // We have to break on the first error + // to avoid infinite loops. + break; + } else { + throw lexError; + } + } + } + + filterTokenLocation(); + tokens = extra.tokens; + + if (typeof extra.comments !== "undefined") { + tokens.comments = extra.comments; + } + if (typeof extra.errors !== "undefined") { + tokens.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + return tokens; +} + +//------------------------------------------------------------------------------ +// Parser +//------------------------------------------------------------------------------ + +function parse(code, options) { + var program, toString; + + toString = String; + if (typeof code !== "string" && !(code instanceof String)) { + code = toString(code); + } + + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: new StringMap(), + parenthesisCount: 0, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1, + yieldAllowed: false, + curlyStack: [], + curlyLastIndex: 0, + inJSXSpreadAttribute: false, + inJSXChild: false, + inJSXTag: false + }; + + extra = { + ecmaFeatures: Object.create(defaultFeatures) + }; + + // for template strings + state.curlyStack = []; + + if (typeof options !== "undefined") { + extra.range = (typeof options.range === "boolean") && options.range; + extra.loc = (typeof options.loc === "boolean") && options.loc; + extra.attachComment = (typeof options.attachComment === "boolean") && options.attachComment; + + if (extra.loc && options.source !== null && options.source !== undefined) { + extra.source = toString(options.source); + } + + if (typeof options.tokens === "boolean" && options.tokens) { + extra.tokens = []; + } + if (typeof options.comment === "boolean" && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === "boolean" && options.tolerant) { + extra.errors = []; + } + if (extra.attachComment) { + extra.range = true; + extra.comments = []; + commentAttachment.reset(); + } + + if (options.sourceType === "module") { + extra.ecmaFeatures = { + arrowFunctions: true, + blockBindings: true, + regexUFlag: true, + regexYFlag: true, + templateStrings: true, + binaryLiterals: true, + octalLiterals: true, + unicodeCodePointEscapes: true, + superInFunctions: true, + defaultParams: true, + restParams: true, + forOf: true, + objectLiteralComputedProperties: true, + objectLiteralShorthandMethods: true, + objectLiteralShorthandProperties: true, + objectLiteralDuplicateProperties: true, + generators: true, + destructuring: true, + classes: true, + modules: true + }; + } + + // apply parsing flags after sourceType to allow overriding + if (options.ecmaFeatures && typeof options.ecmaFeatures === "object") { + + // if it's a module, augment the ecmaFeatures + if (options.sourceType === "module") { + Object.keys(options.ecmaFeatures).forEach(function(key) { + extra.ecmaFeatures[key] = options.ecmaFeatures[key]; + }); + } else { + extra.ecmaFeatures = options.ecmaFeatures; + } + } + + } + + try { + program = parseProgram(); + if (typeof extra.comments !== "undefined") { + program.comments = extra.comments; + } + if (typeof extra.tokens !== "undefined") { + filterTokenLocation(); + program.tokens = extra.tokens; + } + if (typeof extra.errors !== "undefined") { + program.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + + return program; +} + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +exports.version = require("./package.json").version; + +exports.tokenize = tokenize; + +exports.parse = parse; + +// Deep copy. +/* istanbul ignore next */ +exports.Syntax = (function () { + var name, types = {}; + + if (typeof Object.create === "function") { + types = Object.create(null); + } + + for (name in astNodeTypes) { + if (astNodeTypes.hasOwnProperty(name)) { + types[name] = astNodeTypes[name]; + } + } + + if (typeof Object.freeze === "function") { + Object.freeze(types); + } + + return types; +}()); diff --git a/tools/eslint/node_modules/espree/lib/ast-node-factory.js b/tools/eslint/node_modules/espree/lib/ast-node-factory.js new file mode 100644 index 00000000000000..56bdbcadbf9c40 --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/ast-node-factory.js @@ -0,0 +1,932 @@ +/** + * @fileoverview A factory for creating AST nodes + * @author Fred K. Schott + * @copyright 2014 Fred K. Schott. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var astNodeTypes = require("./ast-node-types"); + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + + /** + * Create an Array Expression ASTNode out of an array of elements + * @param {ASTNode[]} elements An array of ASTNode elements + * @returns {ASTNode} An ASTNode representing the entire array expression + */ + createArrayExpression: function(elements) { + return { + type: astNodeTypes.ArrayExpression, + elements: elements + }; + }, + + /** + * Create an Arrow Function Expression ASTNode + * @param {ASTNode} params The function arguments + * @param {ASTNode} body The function body + * @param {boolean} expression True if the arrow function is created via an expression. + * Always false for declarations, but kept here to be in sync with + * FunctionExpression objects. + * @returns {ASTNode} An ASTNode representing the entire arrow function expression + */ + createArrowFunctionExpression: function (params, body, expression) { + return { + type: astNodeTypes.ArrowFunctionExpression, + id: null, + params: params, + body: body, + generator: false, + expression: expression + }; + }, + + /** + * Create an ASTNode representation of an assignment expression + * @param {ASTNode} operator The assignment operator + * @param {ASTNode} left The left operand + * @param {ASTNode} right The right operand + * @returns {ASTNode} An ASTNode representing the entire assignment expression + */ + createAssignmentExpression: function(operator, left, right) { + return { + type: astNodeTypes.AssignmentExpression, + operator: operator, + left: left, + right: right + }; + }, + + /** + * Create an ASTNode representation of an assignment pattern (default parameters) + * @param {ASTNode} left The left operand + * @param {ASTNode} right The right operand + * @returns {ASTNode} An ASTNode representing the entire assignment pattern + */ + createAssignmentPattern: function(left, right) { + return { + type: astNodeTypes.AssignmentPattern, + left: left, + right: right + }; + }, + + /** + * Create an ASTNode representation of a binary expression + * @param {ASTNode} operator The assignment operator + * @param {ASTNode} left The left operand + * @param {ASTNode} right The right operand + * @returns {ASTNode} An ASTNode representing the entire binary expression + */ + createBinaryExpression: function(operator, left, right) { + var type = (operator === "||" || operator === "&&") ? astNodeTypes.LogicalExpression : + astNodeTypes.BinaryExpression; + return { + type: type, + operator: operator, + left: left, + right: right + }; + }, + + /** + * Create an ASTNode representation of a block statement + * @param {ASTNode} body The block statement body + * @returns {ASTNode} An ASTNode representing the entire block statement + */ + createBlockStatement: function(body) { + return { + type: astNodeTypes.BlockStatement, + body: body + }; + }, + + /** + * Create an ASTNode representation of a break statement + * @param {ASTNode} label The break statement label + * @returns {ASTNode} An ASTNode representing the break statement + */ + createBreakStatement: function(label) { + return { + type: astNodeTypes.BreakStatement, + label: label + }; + }, + + /** + * Create an ASTNode representation of a call expression + * @param {ASTNode} callee The function being called + * @param {ASTNode[]} args An array of ASTNodes representing the function call arguments + * @returns {ASTNode} An ASTNode representing the entire call expression + */ + createCallExpression: function(callee, args) { + return { + type: astNodeTypes.CallExpression, + callee: callee, + "arguments": args + }; + }, + + /** + * Create an ASTNode representation of a catch clause/block + * @param {ASTNode} param Any catch clause exeption/conditional parameter information + * @param {ASTNode} body The catch block body + * @returns {ASTNode} An ASTNode representing the entire catch clause + */ + createCatchClause: function(param, body) { + return { + type: astNodeTypes.CatchClause, + param: param, + body: body + }; + }, + + /** + * Creates an ASTNode representation of a class body. + * @param {ASTNode} body The node representing the body of the class. + * @returns {ASTNode} An ASTNode representing the class body. + */ + createClassBody: function(body) { + return { + type: astNodeTypes.ClassBody, + body: body + }; + }, + + createClassExpression: function(id, superClass, body) { + return { + type: astNodeTypes.ClassExpression, + id: id, + superClass: superClass, + body: body + }; + }, + + createClassDeclaration: function(id, superClass, body) { + return { + type: astNodeTypes.ClassDeclaration, + id: id, + superClass: superClass, + body: body + }; + }, + + createMethodDefinition: function(propertyType, kind, key, value, computed) { + return { + type: astNodeTypes.MethodDefinition, + key: key, + value: value, + kind: kind, + "static": propertyType === "static", + computed: computed + }; + }, + + /** + * Create an ASTNode representation of a conditional expression + * @param {ASTNode} test The conditional to evaluate + * @param {ASTNode} consequent The code to be run if the test returns true + * @param {ASTNode} alternate The code to be run if the test returns false + * @returns {ASTNode} An ASTNode representing the entire conditional expression + */ + createConditionalExpression: function(test, consequent, alternate) { + return { + type: astNodeTypes.ConditionalExpression, + test: test, + consequent: consequent, + alternate: alternate + }; + }, + + /** + * Create an ASTNode representation of a continue statement + * @param {?ASTNode} label The optional continue label (null if not set) + * @returns {ASTNode} An ASTNode representing the continue statement + */ + createContinueStatement: function(label) { + return { + type: astNodeTypes.ContinueStatement, + label: label + }; + }, + + /** + * Create an ASTNode representation of a debugger statement + * @returns {ASTNode} An ASTNode representing the debugger statement + */ + createDebuggerStatement: function() { + return { + type: astNodeTypes.DebuggerStatement + }; + }, + + /** + * Create an ASTNode representation of an empty statement + * @returns {ASTNode} An ASTNode representing an empty statement + */ + createEmptyStatement: function() { + return { + type: astNodeTypes.EmptyStatement + }; + }, + + /** + * Create an ASTNode representation of an expression statement + * @param {ASTNode} expression The expression + * @returns {ASTNode} An ASTNode representing an expression statement + */ + createExpressionStatement: function(expression) { + return { + type: astNodeTypes.ExpressionStatement, + expression: expression + }; + }, + + /** + * Create an ASTNode representation of a while statement + * @param {ASTNode} test The while conditional + * @param {ASTNode} body The while loop body + * @returns {ASTNode} An ASTNode representing a while statement + */ + createWhileStatement: function(test, body) { + return { + type: astNodeTypes.WhileStatement, + test: test, + body: body + }; + }, + + /** + * Create an ASTNode representation of a do..while statement + * @param {ASTNode} test The do..while conditional + * @param {ASTNode} body The do..while loop body + * @returns {ASTNode} An ASTNode representing a do..while statement + */ + createDoWhileStatement: function(test, body) { + return { + type: astNodeTypes.DoWhileStatement, + body: body, + test: test + }; + }, + + /** + * Create an ASTNode representation of a for statement + * @param {ASTNode} init The initialization expression + * @param {ASTNode} test The conditional test expression + * @param {ASTNode} update The update expression + * @param {ASTNode} body The statement body + * @returns {ASTNode} An ASTNode representing a for statement + */ + createForStatement: function(init, test, update, body) { + return { + type: astNodeTypes.ForStatement, + init: init, + test: test, + update: update, + body: body + }; + }, + + /** + * Create an ASTNode representation of a for..in statement + * @param {ASTNode} left The left-side variable for the property name + * @param {ASTNode} right The right-side object + * @param {ASTNode} body The statement body + * @returns {ASTNode} An ASTNode representing a for..in statement + */ + createForInStatement: function(left, right, body) { + return { + type: astNodeTypes.ForInStatement, + left: left, + right: right, + body: body, + each: false + }; + }, + + /** + * Create an ASTNode representation of a for..of statement + * @param {ASTNode} left The left-side variable for the property value + * @param {ASTNode} right The right-side object + * @param {ASTNode} body The statement body + * @returns {ASTNode} An ASTNode representing a for..of statement + */ + createForOfStatement: function(left, right, body) { + return { + type: astNodeTypes.ForOfStatement, + left: left, + right: right, + body: body + }; + }, + + /** + * Create an ASTNode representation of a function declaration + * @param {ASTNode} id The function name + * @param {ASTNode} params The function arguments + * @param {ASTNode} body The function body + * @param {boolean} generator True if the function is a generator, false if not. + * @param {boolean} expression True if the function is created via an expression. + * Always false for declarations, but kept here to be in sync with + * FunctionExpression objects. + * @returns {ASTNode} An ASTNode representing a function declaration + */ + createFunctionDeclaration: function (id, params, body, generator, expression) { + return { + type: astNodeTypes.FunctionDeclaration, + id: id, + params: params || [], + body: body, + generator: !!generator, + expression: !!expression + }; + }, + + /** + * Create an ASTNode representation of a function expression + * @param {ASTNode} id The function name + * @param {ASTNode} params The function arguments + * @param {ASTNode} body The function body + * @param {boolean} generator True if the function is a generator, false if not. + * @param {boolean} expression True if the function is created via an expression. + * @returns {ASTNode} An ASTNode representing a function declaration + */ + createFunctionExpression: function (id, params, body, generator, expression) { + return { + type: astNodeTypes.FunctionExpression, + id: id, + params: params || [], + body: body, + generator: !!generator, + expression: !!expression + }; + }, + + /** + * Create an ASTNode representation of an identifier + * @param {ASTNode} name The identifier name + * @returns {ASTNode} An ASTNode representing an identifier + */ + createIdentifier: function(name) { + return { + type: astNodeTypes.Identifier, + name: name + }; + }, + + /** + * Create an ASTNode representation of an if statement + * @param {ASTNode} test The if conditional expression + * @param {ASTNode} consequent The consequent if statement to run + * @param {ASTNode} alternate the "else" alternate statement + * @returns {ASTNode} An ASTNode representing an if statement + */ + createIfStatement: function(test, consequent, alternate) { + return { + type: astNodeTypes.IfStatement, + test: test, + consequent: consequent, + alternate: alternate + }; + }, + + /** + * Create an ASTNode representation of a labeled statement + * @param {ASTNode} label The statement label + * @param {ASTNode} body The labeled statement body + * @returns {ASTNode} An ASTNode representing a labeled statement + */ + createLabeledStatement: function(label, body) { + return { + type: astNodeTypes.LabeledStatement, + label: label, + body: body + }; + }, + + /** + * Create an ASTNode literal from the source code + * @param {ASTNode} token The ASTNode token + * @param {string} source The source code to get the literal from + * @returns {ASTNode} An ASTNode representing the new literal + */ + createLiteralFromSource: function(token, source) { + var node = { + type: astNodeTypes.Literal, + value: token.value, + raw: source.slice(token.range[0], token.range[1]) + }; + + // regular expressions have regex properties + if (token.regex) { + node.regex = token.regex; + } + + return node; + }, + + /** + * Create an ASTNode template element + * @param {Object} value Data on the element value + * @param {string} value.raw The raw template string + * @param {string} value.cooked The processed template string + * @param {boolean} tail True if this is the final element in a template string + * @returns {ASTNode} An ASTNode representing the template string element + */ + createTemplateElement: function(value, tail) { + return { + type: astNodeTypes.TemplateElement, + value: value, + tail: tail + }; + }, + + /** + * Create an ASTNode template literal + * @param {ASTNode[]} quasis An array of the template string elements + * @param {ASTNode[]} expressions An array of the template string expressions + * @returns {ASTNode} An ASTNode representing the template string + */ + createTemplateLiteral: function(quasis, expressions) { + return { + type: astNodeTypes.TemplateLiteral, + quasis: quasis, + expressions: expressions + }; + }, + + /** + * Create an ASTNode representation of a spread element + * @param {ASTNode} argument The array being spread + * @returns {ASTNode} An ASTNode representing a spread element + */ + createSpreadElement: function(argument) { + return { + type: astNodeTypes.SpreadElement, + argument: argument + }; + }, + + /** + * Create an ASTNode tagged template expression + * @param {ASTNode} tag The tag expression + * @param {ASTNode} quasi A TemplateLiteral ASTNode representing + * the template string itself. + * @returns {ASTNode} An ASTNode representing the tagged template + */ + createTaggedTemplateExpression: function(tag, quasi) { + return { + type: astNodeTypes.TaggedTemplateExpression, + tag: tag, + quasi: quasi + }; + }, + + /** + * Create an ASTNode representation of a member expression + * @param {string} accessor The member access method (bracket or period) + * @param {ASTNode} object The object being referenced + * @param {ASTNode} property The object-property being referenced + * @returns {ASTNode} An ASTNode representing a member expression + */ + createMemberExpression: function(accessor, object, property) { + return { + type: astNodeTypes.MemberExpression, + computed: accessor === "[", + object: object, + property: property + }; + }, + + /** + * Create an ASTNode representation of a new expression + * @param {ASTNode} callee The constructor for the new object type + * @param {ASTNode} args The arguments passed to the constructor + * @returns {ASTNode} An ASTNode representing a new expression + */ + createNewExpression: function(callee, args) { + return { + type: astNodeTypes.NewExpression, + callee: callee, + "arguments": args + }; + }, + + /** + * Create an ASTNode representation of a new object expression + * @param {ASTNode[]} properties An array of ASTNodes that represent all object + * properties and associated values + * @returns {ASTNode} An ASTNode representing a new object expression + */ + createObjectExpression: function(properties) { + return { + type: astNodeTypes.ObjectExpression, + properties: properties + }; + }, + + /** + * Create an ASTNode representation of a postfix expression + * @param {string} operator The postfix operator ("++", "--", etc.) + * @param {ASTNode} argument The operator argument + * @returns {ASTNode} An ASTNode representing a postfix expression + */ + createPostfixExpression: function(operator, argument) { + return { + type: astNodeTypes.UpdateExpression, + operator: operator, + argument: argument, + prefix: false + }; + }, + + /** + * Create an ASTNode representation of an entire program + * @param {ASTNode} body The program body + * @param {string} sourceType Either "module" or "script". + * @returns {ASTNode} An ASTNode representing an entire program + */ + createProgram: function(body, sourceType) { + return { + type: astNodeTypes.Program, + body: body, + sourceType: sourceType + }; + }, + + /** + * Create an ASTNode representation of an object property + * @param {string} kind The type of property represented ("get", "set", etc.) + * @param {ASTNode} key The property key + * @param {ASTNode} value The new property value + * @param {boolean} method True if the property is also a method (value is a function) + * @param {boolean} shorthand True if the property is shorthand + * @param {boolean} computed True if the property value has been computed + * @returns {ASTNode} An ASTNode representing an object property + */ + createProperty: function(kind, key, value, method, shorthand, computed) { + return { + type: astNodeTypes.Property, + key: key, + value: value, + kind: kind, + method: method, + shorthand: shorthand, + computed: computed + }; + }, + + /** + * Create an ASTNode representation of a rest element + * @param {ASTNode} argument The rest argument + * @returns {ASTNode} An ASTNode representing a rest element + */ + createRestElement: function (argument) { + return { + type: astNodeTypes.RestElement, + argument: argument + }; + }, + + /** + * Create an ASTNode representation of a return statement + * @param {?ASTNode} argument The return argument, null if no argument is provided + * @returns {ASTNode} An ASTNode representing a return statement + */ + createReturnStatement: function(argument) { + return { + type: astNodeTypes.ReturnStatement, + argument: argument + }; + }, + + /** + * Create an ASTNode representation of a sequence of expressions + * @param {ASTNode[]} expressions An array containing each expression, in order + * @returns {ASTNode} An ASTNode representing a sequence of expressions + */ + createSequenceExpression: function(expressions) { + return { + type: astNodeTypes.SequenceExpression, + expressions: expressions + }; + }, + + /** + * Create an ASTNode representation of super + * @returns {ASTNode} An ASTNode representing super + */ + createSuper: function() { + return { + type: astNodeTypes.Super + }; + }, + + /** + * Create an ASTNode representation of a switch case statement + * @param {ASTNode} test The case value to test against the switch value + * @param {ASTNode} consequent The consequent case statement + * @returns {ASTNode} An ASTNode representing a switch case + */ + createSwitchCase: function(test, consequent) { + return { + type: astNodeTypes.SwitchCase, + test: test, + consequent: consequent + }; + }, + + /** + * Create an ASTNode representation of a switch statement + * @param {ASTNode} discriminant An expression to test against each case value + * @param {ASTNode[]} cases An array of switch case statements + * @returns {ASTNode} An ASTNode representing a switch statement + */ + createSwitchStatement: function(discriminant, cases) { + return { + type: astNodeTypes.SwitchStatement, + discriminant: discriminant, + cases: cases + }; + }, + + /** + * Create an ASTNode representation of a this statement + * @returns {ASTNode} An ASTNode representing a this statement + */ + createThisExpression: function() { + return { + type: astNodeTypes.ThisExpression + }; + }, + + /** + * Create an ASTNode representation of a throw statement + * @param {ASTNode} argument The argument to throw + * @returns {ASTNode} An ASTNode representing a throw statement + */ + createThrowStatement: function(argument) { + return { + type: astNodeTypes.ThrowStatement, + argument: argument + }; + }, + + /** + * Create an ASTNode representation of a try statement + * @param {ASTNode} block The try block + * @param {ASTNode} handler A catch handler + * @param {?ASTNode} finalizer The final code block to run after the try/catch has run + * @returns {ASTNode} An ASTNode representing a try statement + */ + createTryStatement: function(block, handler, finalizer) { + return { + type: astNodeTypes.TryStatement, + block: block, + handler: handler, + finalizer: finalizer + }; + }, + + /** + * Create an ASTNode representation of a unary expression + * @param {string} operator The unary operator + * @param {ASTNode} argument The unary operand + * @returns {ASTNode} An ASTNode representing a unary expression + */ + createUnaryExpression: function(operator, argument) { + if (operator === "++" || operator === "--") { + return { + type: astNodeTypes.UpdateExpression, + operator: operator, + argument: argument, + prefix: true + }; + } + return { + type: astNodeTypes.UnaryExpression, + operator: operator, + argument: argument, + prefix: true + }; + }, + + /** + * Create an ASTNode representation of a variable declaration + * @param {ASTNode[]} declarations An array of variable declarations + * @param {string} kind The kind of variable created ("var", "let", etc.) + * @returns {ASTNode} An ASTNode representing a variable declaration + */ + createVariableDeclaration: function(declarations, kind) { + return { + type: astNodeTypes.VariableDeclaration, + declarations: declarations, + kind: kind + }; + }, + + /** + * Create an ASTNode representation of a variable declarator + * @param {ASTNode} id The variable ID + * @param {ASTNode} init The variable's initial value + * @returns {ASTNode} An ASTNode representing a variable declarator + */ + createVariableDeclarator: function(id, init) { + return { + type: astNodeTypes.VariableDeclarator, + id: id, + init: init + }; + }, + + /** + * Create an ASTNode representation of a with statement + * @param {ASTNode} object The with statement object expression + * @param {ASTNode} body The with statement body + * @returns {ASTNode} An ASTNode representing a with statement + */ + createWithStatement: function(object, body) { + return { + type: astNodeTypes.WithStatement, + object: object, + body: body + }; + }, + + createYieldExpression: function(argument, delegate) { + return { + type: astNodeTypes.YieldExpression, + argument: argument || null, + delegate: delegate + }; + }, + + createJSXAttribute: function(name, value) { + return { + type: astNodeTypes.JSXAttribute, + name: name, + value: value || null + }; + }, + + createJSXSpreadAttribute: function(argument) { + return { + type: astNodeTypes.JSXSpreadAttribute, + argument: argument + }; + }, + + createJSXIdentifier: function(name) { + return { + type: astNodeTypes.JSXIdentifier, + name: name + }; + }, + + createJSXNamespacedName: function(namespace, name) { + return { + type: astNodeTypes.JSXNamespacedName, + namespace: namespace, + name: name + }; + }, + + createJSXMemberExpression: function(object, property) { + return { + type: astNodeTypes.JSXMemberExpression, + object: object, + property: property + }; + }, + + createJSXElement: function(openingElement, closingElement, children) { + return { + type: astNodeTypes.JSXElement, + openingElement: openingElement, + closingElement: closingElement, + children: children + }; + }, + + createJSXEmptyExpression: function() { + return { + type: astNodeTypes.JSXEmptyExpression + }; + }, + + createJSXExpressionContainer: function(expression) { + return { + type: astNodeTypes.JSXExpressionContainer, + expression: expression + }; + }, + + createJSXOpeningElement: function(name, attributes, selfClosing) { + return { + type: astNodeTypes.JSXOpeningElement, + name: name, + selfClosing: selfClosing, + attributes: attributes + }; + }, + + createJSXClosingElement: function(name) { + return { + type: astNodeTypes.JSXClosingElement, + name: name + }; + }, + + createExportSpecifier: function(local, exported) { + return { + type: astNodeTypes.ExportSpecifier, + exported: exported || local, + local: local + }; + }, + + createImportDefaultSpecifier: function(local) { + return { + type: astNodeTypes.ImportDefaultSpecifier, + local: local + }; + }, + + createImportNamespaceSpecifier: function(local) { + return { + type: astNodeTypes.ImportNamespaceSpecifier, + local: local + }; + }, + + createExportNamedDeclaration: function(declaration, specifiers, source) { + return { + type: astNodeTypes.ExportNamedDeclaration, + declaration: declaration, + specifiers: specifiers, + source: source + }; + }, + + createExportDefaultDeclaration: function(declaration) { + return { + type: astNodeTypes.ExportDefaultDeclaration, + declaration: declaration + }; + }, + + createExportAllDeclaration: function(source) { + return { + type: astNodeTypes.ExportAllDeclaration, + source: source + }; + }, + + createImportSpecifier: function(local, imported) { + return { + type: astNodeTypes.ImportSpecifier, + local: local || imported, + imported: imported + }; + }, + + createImportDeclaration: function(specifiers, source) { + return { + type: astNodeTypes.ImportDeclaration, + specifiers: specifiers, + source: source + }; + } + +}; diff --git a/tools/eslint/node_modules/espree/lib/ast-node-types.js b/tools/eslint/node_modules/espree/lib/ast-node-types.js new file mode 100644 index 00000000000000..5d14b7f4437283 --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/ast-node-types.js @@ -0,0 +1,116 @@ +/** + * @fileoverview The AST node types produced by the parser. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + AssignmentExpression: "AssignmentExpression", + AssignmentPattern: "AssignmentPattern", + ArrayExpression: "ArrayExpression", + ArrayPattern: "ArrayPattern", + ArrowFunctionExpression: "ArrowFunctionExpression", + BlockStatement: "BlockStatement", + BinaryExpression: "BinaryExpression", + BreakStatement: "BreakStatement", + CallExpression: "CallExpression", + CatchClause: "CatchClause", + ClassBody: "ClassBody", + ClassDeclaration: "ClassDeclaration", + ClassExpression: "ClassExpression", + ConditionalExpression: "ConditionalExpression", + ContinueStatement: "ContinueStatement", + DoWhileStatement: "DoWhileStatement", + DebuggerStatement: "DebuggerStatement", + EmptyStatement: "EmptyStatement", + ExpressionStatement: "ExpressionStatement", + ForStatement: "ForStatement", + ForInStatement: "ForInStatement", + ForOfStatement: "ForOfStatement", + FunctionDeclaration: "FunctionDeclaration", + FunctionExpression: "FunctionExpression", + Identifier: "Identifier", + IfStatement: "IfStatement", + Literal: "Literal", + LabeledStatement: "LabeledStatement", + LogicalExpression: "LogicalExpression", + MemberExpression: "MemberExpression", + MethodDefinition: "MethodDefinition", + NewExpression: "NewExpression", + ObjectExpression: "ObjectExpression", + ObjectPattern: "ObjectPattern", + Program: "Program", + Property: "Property", + RestElement: "RestElement", + ReturnStatement: "ReturnStatement", + SequenceExpression: "SequenceExpression", + SpreadElement: "SpreadElement", + Super: "Super", + SwitchCase: "SwitchCase", + SwitchStatement: "SwitchStatement", + TaggedTemplateExpression: "TaggedTemplateExpression", + TemplateElement: "TemplateElement", + TemplateLiteral: "TemplateLiteral", + ThisExpression: "ThisExpression", + ThrowStatement: "ThrowStatement", + TryStatement: "TryStatement", + UnaryExpression: "UnaryExpression", + UpdateExpression: "UpdateExpression", + VariableDeclaration: "VariableDeclaration", + VariableDeclarator: "VariableDeclarator", + WhileStatement: "WhileStatement", + WithStatement: "WithStatement", + YieldExpression: "YieldExpression", + JSXIdentifier: "JSXIdentifier", + JSXNamespacedName: "JSXNamespacedName", + JSXMemberExpression: "JSXMemberExpression", + JSXEmptyExpression: "JSXEmptyExpression", + JSXExpressionContainer: "JSXExpressionContainer", + JSXElement: "JSXElement", + JSXClosingElement: "JSXClosingElement", + JSXOpeningElement: "JSXOpeningElement", + JSXAttribute: "JSXAttribute", + JSXSpreadAttribute: "JSXSpreadAttribute", + JSXText: "JSXText", + ExportDefaultDeclaration: "ExportDefaultDeclaration", + ExportNamedDeclaration: "ExportNamedDeclaration", + ExportAllDeclaration: "ExportAllDeclaration", + ExportSpecifier: "ExportSpecifier", + ImportDeclaration: "ImportDeclaration", + ImportSpecifier: "ImportSpecifier", + ImportDefaultSpecifier: "ImportDefaultSpecifier", + ImportNamespaceSpecifier: "ImportNamespaceSpecifier" +}; diff --git a/tools/eslint/node_modules/espree/lib/comment-attachment.js b/tools/eslint/node_modules/espree/lib/comment-attachment.js new file mode 100644 index 00000000000000..3618bb3bf08823 --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/comment-attachment.js @@ -0,0 +1,171 @@ +/** + * @fileoverview Attaches comments to the AST. + * @author Nicholas C. Zakas + * @copyright 2015 Nicholas C. Zakas. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var astNodeTypes = require("./ast-node-types"); + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +var extra = { + trailingComments: [], + leadingComments: [], + bottomRightStack: [] + }; + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + + reset: function() { + extra.trailingComments = []; + extra.leadingComments = []; + extra.bottomRightStack = []; + }, + + addComment: function(comment) { + extra.trailingComments.push(comment); + extra.leadingComments.push(comment); + }, + + processComment: function(node) { + var lastChild, + trailingComments, + i; + + if (node.type === astNodeTypes.Program) { + if (node.body.length > 0) { + return; + } + } + + if (extra.trailingComments.length > 0) { + + /* + * If the first comment in trailingComments comes after the + * current node, then we're good - all comments in the array will + * come after the node and so it's safe to add then as official + * trailingComments. + */ + if (extra.trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.trailingComments; + extra.trailingComments = []; + } else { + + /* + * Otherwise, if the first comment doesn't come after the + * current node, that means we have a mix of leading and trailing + * comments in the array and that leadingComments contains the + * same items as trailingComments. Reset trailingComments to + * zero items and we'll handle this by evaluating leadingComments + * later. + */ + extra.trailingComments.length = 0; + } + } else { + if (extra.bottomRightStack.length > 0 && + extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments && + extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) { + trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; + delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments; + } + } + + // Eating the stack. + while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) { + lastChild = extra.bottomRightStack.pop(); + } + + if (lastChild) { + if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = lastChild.leadingComments; + delete lastChild.leadingComments; + } + } else if (extra.leadingComments.length > 0) { + + if (extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { + node.leadingComments = extra.leadingComments; + extra.leadingComments = []; + } else { + + // https://github.com/eslint/espree/issues/2 + + /* + * In special cases, such as return (without a value) and + * debugger, all comments will end up as leadingComments and + * will otherwise be eliminated. This extra step runs when the + * bottomRightStack is empty and there are comments left + * in leadingComments. + * + * This loop figures out the stopping point between the actual + * leading and trailing comments by finding the location of the + * first comment that comes after the given node. + */ + for (i = 0; i < extra.leadingComments.length; i++) { + if (extra.leadingComments[i].range[1] > node.range[0]) { + break; + } + } + + /* + * Split the array based on the location of the first comment + * that comes after the node. Keep in mind that this could + * result in an empty array, and if so, the array must be + * deleted. + */ + node.leadingComments = extra.leadingComments.slice(0, i); + if (node.leadingComments.length === 0) { + delete node.leadingComments; + } + + /* + * Similarly, trailing comments are attached later. The variable + * must be reset to null if there are no trailing comments. + */ + trailingComments = extra.leadingComments.slice(i); + if (trailingComments.length === 0) { + trailingComments = null; + } + } + } + + if (trailingComments) { + node.trailingComments = trailingComments; + } + + extra.bottomRightStack.push(node); + } + +}; diff --git a/tools/eslint/node_modules/espree/lib/features.js b/tools/eslint/node_modules/espree/lib/features.js new file mode 100644 index 00000000000000..c33274a441b7d3 --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/features.js @@ -0,0 +1,111 @@ +/** + * @fileoverview The list of feature flags supported by the parser and their default + * settings. + * @author Nicholas C. Zakas + * @copyright 2015 Fred K. Schott. All rights reserved. + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + + // enable parsing of arrow functions + arrowFunctions: false, + + // enable parsing of let and const + blockBindings: true, + + // enable parsing of destructured arrays and objects + destructuring: false, + + // enable parsing of regex u flag + regexUFlag: false, + + // enable parsing of regex y flag + regexYFlag: false, + + // enable parsing of template strings + templateStrings: false, + + // enable parsing binary literals + binaryLiterals: false, + + // enable parsing ES6 octal literals + octalLiterals: false, + + // enable parsing unicode code point escape sequences + unicodeCodePointEscapes: true, + + // enable parsing of default parameters + defaultParams: false, + + // enable parsing of rest parameters + restParams: false, + + // enable parsing of for-of statements + forOf: false, + + // enable parsing computed object literal properties + objectLiteralComputedProperties: false, + + // enable parsing of shorthand object literal methods + objectLiteralShorthandMethods: false, + + // enable parsing of shorthand object literal properties + objectLiteralShorthandProperties: false, + + // Allow duplicate object literal properties (except '__proto__') + objectLiteralDuplicateProperties: false, + + // enable parsing of generators/yield + generators: false, + + // support the spread operator + spread: false, + + // enable super in functions + superInFunctions: false, + + // enable parsing of classes + classes: false, + + // enable parsing of modules + modules: false, + + // React JSX parsing + jsx: false, + + // allow return statement in global scope + globalReturn: false +}; diff --git a/tools/eslint/node_modules/espree/lib/messages.js b/tools/eslint/node_modules/espree/lib/messages.js new file mode 100644 index 00000000000000..b0f324f87d58bc --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/messages.js @@ -0,0 +1,99 @@ +/** + * @fileoverview Error messages returned by the parser. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +// error messages should be identical to V8 where possible +module.exports = { + UnexpectedToken: "Unexpected token %0", + UnexpectedNumber: "Unexpected number", + UnexpectedString: "Unexpected string", + UnexpectedIdentifier: "Unexpected identifier", + UnexpectedReserved: "Unexpected reserved word", + UnexpectedTemplate: "Unexpected quasi %0", + UnexpectedEOS: "Unexpected end of input", + NewlineAfterThrow: "Illegal newline after throw", + InvalidRegExp: "Invalid regular expression", + InvalidRegExpFlag: "Invalid regular expression flag", + UnterminatedRegExp: "Invalid regular expression: missing /", + InvalidLHSInAssignment: "Invalid left-hand side in assignment", + InvalidLHSInFormalsList: "Invalid left-hand side in formals list", + InvalidLHSInForIn: "Invalid left-hand side in for-in", + MultipleDefaultsInSwitch: "More than one default clause in switch statement", + NoCatchOrFinally: "Missing catch or finally after try", + NoUnintializedConst: "Const must be initialized", + UnknownLabel: "Undefined label '%0'", + Redeclaration: "%0 '%1' has already been declared", + IllegalContinue: "Illegal continue statement", + IllegalBreak: "Illegal break statement", + IllegalReturn: "Illegal return statement", + IllegalYield: "Illegal yield expression", + IllegalSpread: "Illegal spread element", + StrictModeWith: "Strict mode code may not include a with statement", + StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode", + StrictVarName: "Variable name may not be eval or arguments in strict mode", + StrictParamName: "Parameter name eval or arguments is not allowed in strict mode", + StrictParamDupe: "Strict mode function may not have duplicate parameter names", + TemplateOctalLiteral: "Octal literals are not allowed in template strings.", + ParameterAfterRestParameter: "Rest parameter must be last formal parameter", + DefaultRestParameter: "Rest parameter can not have a default value", + ElementAfterSpreadElement: "Spread must be the final element of an element list", + ObjectPatternAsRestParameter: "Invalid rest parameter", + ObjectPatternAsSpread: "Invalid spread argument", + StrictFunctionName: "Function name may not be eval or arguments in strict mode", + StrictOctalLiteral: "Octal literals are not allowed in strict mode.", + StrictDelete: "Delete of an unqualified identifier in strict mode.", + StrictDuplicateProperty: "Duplicate data property in object literal not allowed in strict mode", + DuplicatePrototypeProperty: "Duplicate '__proto__' property in object literal are not allowed", + ConstructorSpecialMethod: "Class constructor may not be an accessor", + DuplicateConstructor: "A class may only have one constructor", + StaticPrototype: "Classes may not have static property named prototype", + AccessorDataProperty: "Object literal may not have data and accessor property with the same name", + AccessorGetSet: "Object literal may not have multiple get/set accessors with the same name", + StrictLHSAssignment: "Assignment to eval or arguments is not allowed in strict mode", + StrictLHSPostfix: "Postfix increment/decrement may not have eval or arguments operand in strict mode", + StrictLHSPrefix: "Prefix increment/decrement may not have eval or arguments operand in strict mode", + StrictReservedWord: "Use of future reserved word in strict mode", + InvalidJSXAttributeValue: "JSX value should be either an expression or a quoted JSX text", + ExpectedJSXClosingTag: "Expected corresponding JSX closing tag for %0", + AdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag", + MissingFromClause: "Missing from clause", + NoAsAfterImportNamespace: "Missing as after import *", + InvalidModuleSpecifier: "Invalid module specifier", + IllegalImportDeclaration: "Illegal import declaration", + IllegalExportDeclaration: "Illegal export declaration" +}; diff --git a/tools/eslint/node_modules/espree/lib/string-map.js b/tools/eslint/node_modules/espree/lib/string-map.js new file mode 100644 index 00000000000000..97c87032f25c45 --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/string-map.js @@ -0,0 +1,55 @@ +/** + * @fileoverview A simple map that helps avoid collisions on the Object prototype. + * @author Jamund Ferguson + * @copyright 2015 Jamund Ferguson. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +function StringMap() { + this.$data = {}; +} + +StringMap.prototype.get = function (key) { + key = "$" + key; + return this.$data[key]; +}; + +StringMap.prototype.set = function (key, value) { + key = "$" + key; + this.$data[key] = value; + return this; +}; + +StringMap.prototype.has = function (key) { + key = "$" + key; + return Object.prototype.hasOwnProperty.call(this.$data, key); +}; + +StringMap.prototype.delete = function (key) { + key = "$" + key; + return delete this.$data[key]; +}; + +module.exports = StringMap; diff --git a/tools/eslint/node_modules/espree/lib/syntax.js b/tools/eslint/node_modules/espree/lib/syntax.js new file mode 100644 index 00000000000000..7cad1afc898020 --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/syntax.js @@ -0,0 +1,187 @@ +/** + * @fileoverview Various syntax/pattern checks for parsing. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * @copyright 2012-2013 Mathias Bynens + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// See also tools/generate-identifier-regex.js. +var Regex = { + NonAsciiIdentifierStart: new RegExp("[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]"), + NonAsciiIdentifierPart: new RegExp("[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]"), + LeadingZeros: new RegExp("^0+(?!$)") +}; + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + + Regex: Regex, + + isDecimalDigit: function(ch) { + return (ch >= 48 && ch <= 57); // 0..9 + }, + + isHexDigit: function(ch) { + return "0123456789abcdefABCDEF".indexOf(ch) >= 0; + }, + + isOctalDigit: function(ch) { + return "01234567".indexOf(ch) >= 0; + }, + + // 7.2 White Space + + isWhiteSpace: function(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); + }, + + // 7.3 Line Terminators + + isLineTerminator: function(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + }, + + // 7.6 Identifier Names and Identifiers + + isIdentifierStart: function(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); + }, + + isIdentifierPart: function(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch >= 0x30 && ch <= 0x39) || // 0..9 + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + }, + + // 7.6.1.2 Future Reserved Words + + isFutureReservedWord: function(id) { + switch (id) { + case "class": + case "enum": + case "export": + case "extends": + case "import": + case "super": + return true; + default: + return false; + } + }, + + isStrictModeReservedWord: function(id) { + switch (id) { + case "implements": + case "interface": + case "package": + case "private": + case "protected": + case "public": + case "static": + case "yield": + case "let": + return true; + default: + return false; + } + }, + + isRestrictedWord: function(id) { + return id === "eval" || id === "arguments"; + }, + + // 7.6.1.1 Keywords + + isKeyword: function(id, strict, ecmaFeatures) { + + if (strict && this.isStrictModeReservedWord(id)) { + return true; + } + + // "const" is specialized as Keyword in V8. + // "yield" and "let" are for compatiblity with SpiderMonkey and ES.next. + // Some others are from future reserved words. + + switch (id.length) { + case 2: + return (id === "if") || (id === "in") || (id === "do"); + case 3: + return (id === "var") || (id === "for") || (id === "new") || + (id === "try") || (id === "let"); + case 4: + return (id === "this") || (id === "else") || (id === "case") || + (id === "void") || (id === "with") || (id === "enum"); + case 5: + return (id === "while") || (id === "break") || (id === "catch") || + (id === "throw") || (id === "const") || (!ecmaFeatures.generators && id === "yield") || + (id === "class") || (id === "super"); + case 6: + return (id === "return") || (id === "typeof") || (id === "delete") || + (id === "switch") || (id === "export") || (id === "import"); + case 7: + return (id === "default") || (id === "finally") || (id === "extends"); + case 8: + return (id === "function") || (id === "continue") || (id === "debugger"); + case 10: + return (id === "instanceof"); + default: + return false; + } + }, + + isJSXIdentifierStart: function(ch) { + // exclude backslash (\) + return (ch !== 92) && this.isIdentifierStart(ch); + }, + + isJSXIdentifierPart: function(ch) { + // exclude backslash (\) and add hyphen (-) + return (ch !== 92) && (ch === 45 || this.isIdentifierPart(ch)); + } + + +}; diff --git a/tools/eslint/node_modules/espree/lib/token-info.js b/tools/eslint/node_modules/espree/lib/token-info.js new file mode 100644 index 00000000000000..ea7676477ccc7f --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/token-info.js @@ -0,0 +1,90 @@ +/** + * @fileoverview Contains token information. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * @copyright 2013 Thaddee Tyl + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +var Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8, + RegularExpression: 9, + Template: 10, + JSXIdentifier: 11, + JSXText: 12 +}; + +var TokenName = {}; +TokenName[Token.BooleanLiteral] = "Boolean"; +TokenName[Token.EOF] = ""; +TokenName[Token.Identifier] = "Identifier"; +TokenName[Token.Keyword] = "Keyword"; +TokenName[Token.NullLiteral] = "Null"; +TokenName[Token.NumericLiteral] = "Numeric"; +TokenName[Token.Punctuator] = "Punctuator"; +TokenName[Token.StringLiteral] = "String"; +TokenName[Token.RegularExpression] = "RegularExpression"; +TokenName[Token.Template] = "Template"; +TokenName[Token.JSXIdentifier] = "JSXIdentifier"; +TokenName[Token.JSXText] = "JSXText"; + +// A function following one of those tokens is an expression. +var FnExprTokens = ["(", "{", "[", "in", "typeof", "instanceof", "new", + "return", "case", "delete", "throw", "void", + // assignment operators + "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", + "&=", "|=", "^=", ",", + // binary/unary operators + "+", "-", "*", "/", "%", "++", "--", "<<", ">>", ">>>", "&", + "|", "^", "!", "~", "&&", "||", "?", ":", "===", "==", ">=", + "<=", "<", ">", "!=", "!=="]; + + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + Token: Token, + TokenName: TokenName, + FnExprTokens: FnExprTokens +}; diff --git a/tools/eslint/node_modules/espree/lib/xhtml-entities.js b/tools/eslint/node_modules/espree/lib/xhtml-entities.js new file mode 100644 index 00000000000000..1ceda1ecab937d --- /dev/null +++ b/tools/eslint/node_modules/espree/lib/xhtml-entities.js @@ -0,0 +1,293 @@ +/** + * @fileoverview The list of XHTML entities that are valid in JSX. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +// None! + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +module.exports = { + quot: "\u0022", + amp: "&", + apos: "\u0027", + lt: "<", + gt: ">", + nbsp: "\u00A0", + iexcl: "\u00A1", + cent: "\u00A2", + pound: "\u00A3", + curren: "\u00A4", + yen: "\u00A5", + brvbar: "\u00A6", + sect: "\u00A7", + uml: "\u00A8", + copy: "\u00A9", + ordf: "\u00AA", + laquo: "\u00AB", + not: "\u00AC", + shy: "\u00AD", + reg: "\u00AE", + macr: "\u00AF", + deg: "\u00B0", + plusmn: "\u00B1", + sup2: "\u00B2", + sup3: "\u00B3", + acute: "\u00B4", + micro: "\u00B5", + para: "\u00B6", + middot: "\u00B7", + cedil: "\u00B8", + sup1: "\u00B9", + ordm: "\u00BA", + raquo: "\u00BB", + frac14: "\u00BC", + frac12: "\u00BD", + frac34: "\u00BE", + iquest: "\u00BF", + Agrave: "\u00C0", + Aacute: "\u00C1", + Acirc: "\u00C2", + Atilde: "\u00C3", + Auml: "\u00C4", + Aring: "\u00C5", + AElig: "\u00C6", + Ccedil: "\u00C7", + Egrave: "\u00C8", + Eacute: "\u00C9", + Ecirc: "\u00CA", + Euml: "\u00CB", + Igrave: "\u00CC", + Iacute: "\u00CD", + Icirc: "\u00CE", + Iuml: "\u00CF", + ETH: "\u00D0", + Ntilde: "\u00D1", + Ograve: "\u00D2", + Oacute: "\u00D3", + Ocirc: "\u00D4", + Otilde: "\u00D5", + Ouml: "\u00D6", + times: "\u00D7", + Oslash: "\u00D8", + Ugrave: "\u00D9", + Uacute: "\u00DA", + Ucirc: "\u00DB", + Uuml: "\u00DC", + Yacute: "\u00DD", + THORN: "\u00DE", + szlig: "\u00DF", + agrave: "\u00E0", + aacute: "\u00E1", + acirc: "\u00E2", + atilde: "\u00E3", + auml: "\u00E4", + aring: "\u00E5", + aelig: "\u00E6", + ccedil: "\u00E7", + egrave: "\u00E8", + eacute: "\u00E9", + ecirc: "\u00EA", + euml: "\u00EB", + igrave: "\u00EC", + iacute: "\u00ED", + icirc: "\u00EE", + iuml: "\u00EF", + eth: "\u00F0", + ntilde: "\u00F1", + ograve: "\u00F2", + oacute: "\u00F3", + ocirc: "\u00F4", + otilde: "\u00F5", + ouml: "\u00F6", + divide: "\u00F7", + oslash: "\u00F8", + ugrave: "\u00F9", + uacute: "\u00FA", + ucirc: "\u00FB", + uuml: "\u00FC", + yacute: "\u00FD", + thorn: "\u00FE", + yuml: "\u00FF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + "int": "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; diff --git a/tools/eslint/node_modules/espree/package.json b/tools/eslint/node_modules/espree/package.json new file mode 100644 index 00000000000000..4fb253a4018566 --- /dev/null +++ b/tools/eslint/node_modules/espree/package.json @@ -0,0 +1,108 @@ +{ + "name": "espree", + "description": "An actively-maintained fork of Esprima, the ECMAScript parsing infrastructure for multipurpose analysis", + "author": { + "name": "Nicholas C. Zakas", + "email": "nicholas+npm@nczconsulting.com" + }, + "homepage": "https://github.com/eslint/espree", + "main": "espree.js", + "bin": { + "esparse": "./bin/esparse.js", + "esvalidate": "./bin/esvalidate.js" + }, + "version": "2.0.2", + "files": [ + "bin", + "lib", + "test/run.js", + "test/runner.js", + "test/test.js", + "test/compat.js", + "test/reflect.js", + "espree.js" + ], + "engines": { + "node": ">=0.10.0" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/eslint/espree.git" + }, + "bugs": { + "url": "http://github.com/eslint/espree.git" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/nzakas/espree/raw/master/LICENSE" + } + ], + "devDependencies": { + "browserify": "^7.0.0", + "chai": "^1.10.0", + "complexity-report": "~0.6.1", + "dateformat": "^1.0.11", + "eslint": "^0.9.2", + "esprima": "git://github.com/jquery/esprima.git", + "esprima-fb": "^8001.2001.0-dev-harmony-fb", + "istanbul": "~0.2.6", + "json-diff": "~0.3.1", + "leche": "^1.0.1", + "mocha": "^2.0.1", + "npm-license": "^0.2.3", + "optimist": "~0.6.0", + "regenerate": "~0.5.4", + "semver": "^4.1.1", + "shelljs": "^0.3.0", + "shelljs-nodecli": "^0.1.1", + "unicode-6.3.0": "~0.1.0" + }, + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax" + ], + "scripts": { + "generate-regex": "node tools/generate-identifier-regex.js", + "test": "npm run-script lint && node Makefile.js test && node test/run.js", + "lint": "node Makefile.js lint", + "patch": "node Makefile.js patch", + "minor": "node Makefile.js minor", + "major": "node Makefile.js major", + "browserify": "node Makefile.js browserify", + "coverage": "npm run-script analyze-coverage && npm run-script check-coverage", + "analyze-coverage": "node node_modules/istanbul/lib/cli.js cover test/runner.js", + "check-coverage": "node node_modules/istanbul/lib/cli.js check-coverage --statement 99 --branch 99 --function 99", + "complexity": "npm run-script analyze-complexity && npm run-script check-complexity", + "analyze-complexity": "node tools/list-complexity.js", + "check-complexity": "node node_modules/complexity-report/src/cli.js --maxcc 14 --silent -l -w espree.js", + "benchmark": "node test/benchmarks.js", + "benchmark-quick": "node test/benchmarks.js quick" + }, + "dependencies": {}, + "gitHead": "71b433bf1b3f570452b987a06c5db615d11225e6", + "_id": "espree@2.0.2", + "_shasum": "adaefd803ad501779e2063b357549ae3366fd14c", + "_from": "espree@>=2.0.1 <3.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + }, + "maintainers": [ + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + } + ], + "dist": { + "shasum": "adaefd803ad501779e2063b357549ae3366fd14c", + "tarball": "http://registry.npmjs.org/espree/-/espree-2.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/espree/-/espree-2.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/espree/test/compat.js b/tools/eslint/node_modules/espree/test/compat.js new file mode 100644 index 00000000000000..abd623aa254cf4 --- /dev/null +++ b/tools/eslint/node_modules/espree/test/compat.js @@ -0,0 +1,255 @@ +/* + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint node: true */ +/*global document: true, window:true, espree: true, testReflect: true */ + +var runTests; + +function getContext(espree, reportCase, reportFailure) { + 'use strict'; + + var Reflect, Pattern; + + // Maps Mozilla Reflect object to our espree parser. + Reflect = { + parse: function (code) { + var result; + + reportCase(code); + + try { + result = espree.parse(code); + } catch (error) { + result = error; + } + + return result; + } + }; + + // This is used by Reflect test suite to match a syntax tree. + Pattern = function (obj) { + var pattern; + + // Poor man's deep object cloning. + pattern = JSON.parse(JSON.stringify(obj)); + + // Special handling for regular expression literal since we need to + // convert it to a string literal, otherwise it will be decoded + // as object "{}" and the regular expression would be lost. + if (obj.type && obj.type === 'Literal') { + if (obj.value instanceof RegExp) { + pattern = { + type: obj.type, + value: obj.value.toString() + }; + } + } + + // Special handling for branch statement because SpiderMonkey + // prefers to put the 'alternate' property before 'consequent'. + if (obj.type && obj.type === 'IfStatement') { + pattern = { + type: pattern.type, + test: pattern.test, + consequent: pattern.consequent, + alternate: pattern.alternate + }; + } + + // Special handling for do while statement because SpiderMonkey + // prefers to put the 'test' property before 'body'. + if (obj.type && obj.type === 'DoWhileStatement') { + pattern = { + type: pattern.type, + body: pattern.body, + test: pattern.test + }; + } + + // Remove special properties on Property node + if (obj.type && obj.type === 'Property') { + pattern = { + type: pattern.type, + key: pattern.key, + value: pattern.value, + kind: pattern.kind + }; + } + + function adjustRegexLiteralAndRaw(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } else if (key === 'raw' && typeof value === "string") { + // Ignore Espree-specific 'raw' property. + return undefined; + } else if (key === 'regex' && typeof value === "object") { + // Ignore Espree-specific 'regex' property. + return undefined; + } + return value; + } + + + if (obj.type && (obj.type === 'Program')) { + pattern.assert = function (tree) { + var actual, expected; + actual = JSON.stringify(tree, adjustRegexLiteralAndRaw, 4); + expected = JSON.stringify(obj, null, 4); + + if (expected !== actual) { + reportFailure(expected, actual); + } + }; + } + + return pattern; + }; + + return { + Reflect: Reflect, + Pattern: Pattern + }; +} + +if (typeof window !== 'undefined') { + // Run all tests in a browser environment. + runTests = function () { + 'use strict'; + + var total = 0, + failures = 0; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function reportCase(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + total += 1; + } + + function reportFailure(expected, actual) { + var report, e; + + failures += 1; + + report = document.getElementById('report'); + + e = document.createElement('p'); + setText(e, 'Expected'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'expected'); + setText(e, expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'actual'); + setText(e, actual); + report.appendChild(e); + } + + setText(document.getElementById('version'), espree.version); + + window.setTimeout(function () { + var tick, context = getContext(espree, reportCase, reportFailure); + + tick = new Date(); + testReflect(context.Reflect, context.Pattern); + tick = (new Date()) - tick; + + if (failures > 0) { + document.getElementById('status').className = 'alert-box alert'; + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms'); + } else { + document.getElementById('status').className = 'alert-box success'; + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms'); + } + }, 11); + }; +} else { + (function (global) { + 'use strict'; + var espree = require('../espree'), + tick, + total = 0, + failures = [], + header, + current, + context; + + function reportCase(code) { + total += 1; + current = code; + } + + function reportFailure(expected, actual) { + failures.push({ + source: current, + expected: expected.toString(), + actual: actual.toString() + }); + } + + context = getContext(espree, reportCase, reportFailure); + + tick = new Date(); + require('./reflect').testReflect(context.Reflect, context.Pattern); + tick = (new Date()) - tick; + + header = total + ' tests. ' + failures.length + ' failures. ' + + tick + ' ms'; + if (failures.length) { + console.error(header); + failures.forEach(function (failure) { + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual); + }); + } else { + console.log(header); + } + process.exit(failures.length === 0 ? 0 : 1); + }(this)); +} +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/espree/test/reflect.js b/tools/eslint/node_modules/espree/test/reflect.js new file mode 100644 index 00000000000000..a4740fbb751fbd --- /dev/null +++ b/tools/eslint/node_modules/espree/test/reflect.js @@ -0,0 +1,422 @@ +// This is modified from Mozilla Reflect.parse test suite (the file is located +// at js/src/tests/js1_8_5/extensions/reflect-parse.js in the source tree). +// +// Some notable changes: +// * Removed unsupported features (destructuring, let, comprehensions...). +// * Removed tests for E4X (ECMAScript for XML). +// * Removed everything related to builder. +// * Enclosed every 'Pattern' construct with a scope. +// * Tweaked some expected tree to remove generator field. +// * Removed the test for bug 632030 and bug 632024. + +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/licenses/publicdomain/ + */ + +(function (exports) { + +function testReflect(Reflect, Pattern) { + +function program(elts) { return Pattern({ type: "Program", body: elts }) } +function exprStmt(expr) { return Pattern({ type: "ExpressionStatement", expression: expr }) } +function throwStmt(expr) { return Pattern({ type: "ThrowStatement", argument: expr }) } +function returnStmt(expr) { return Pattern({ type: "ReturnStatement", argument: expr }) } +function yieldExpr(expr) { return Pattern({ type: "YieldExpression", argument: expr }) } +function lit(val) { return Pattern({ type: "Literal", value: val }) } +var thisExpr = Pattern({ type: "ThisExpression" }); +function funDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration", + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function genFunDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration", + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function declarator(id, init) { return Pattern({ type: "VariableDeclarator", id: id, init: init }) } +function varDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "var" }) } +function letDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "let" }) } +function constDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "const" }) } +function ident(name) { return Pattern({ type: "Identifier", name: name }) } +function dotExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: false, object: obj, property: id }) } +function memExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: true, object: obj, property: id }) } +function forStmt(init, test, update, body) { return Pattern({ type: "ForStatement", init: init, test: test, update: update, body: body }) } +function forInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: false }) } +function forEachInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: true }) } +function breakStmt(lab) { return Pattern({ type: "BreakStatement", label: lab }) } +function continueStmt(lab) { return Pattern({ type: "ContinueStatement", label: lab }) } +function blockStmt(body) { return Pattern({ type: "BlockStatement", body: body }) } +var emptyStmt = Pattern({ type: "EmptyStatement" }); +function ifStmt(test, cons, alt) { return Pattern({ type: "IfStatement", test: test, alternate: alt, consequent: cons }) } +function labStmt(lab, stmt) { return Pattern({ type: "LabeledStatement", label: lab, body: stmt }) } +function withStmt(obj, stmt) { return Pattern({ type: "WithStatement", object: obj, body: stmt }) } +function whileStmt(test, stmt) { return Pattern({ type: "WhileStatement", test: test, body: stmt }) } +function doStmt(stmt, test) { return Pattern({ type: "DoWhileStatement", test: test, body: stmt }) } +function switchStmt(disc, cases) { return Pattern({ type: "SwitchStatement", discriminant: disc, cases: cases }) } +function caseClause(test, stmts) { return Pattern({ type: "SwitchCase", test: test, consequent: stmts }) } +function defaultClause(stmts) { return Pattern({ type: "SwitchCase", test: null, consequent: stmts }) } +function catchClause(id, guard, body) { if (guard) { return Pattern({ type: "GuardedCatchClause", param: id, guard: guard, body: body }) } else { return Pattern({ type: "CatchClause", param: id, body: body }) } } +function tryStmt(body, guarded, catches, fin) { return Pattern({ type: "TryStatement", block: body, guardedHandlers: guarded, handlers: catches, handler: (catches.length > 0) ? catches[0] : null, finalizer: fin }) } +function letStmt(head, body) { return Pattern({ type: "LetStatement", head: head, body: body }) } +function funExpr(id, args, body, gen) { return Pattern({ type: "FunctionExpression", + id: id, + params: args, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function genFunExpr(id, args, body) { return Pattern({ type: "FunctionExpression", + id: id, + params: args, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } + +function unExpr(op, arg) { return Pattern({ type: "UnaryExpression", operator: op, argument: arg, prefix: true }) } +function binExpr(op, left, right) { return Pattern({ type: "BinaryExpression", operator: op, left: left, right: right }) } +function aExpr(op, left, right) { return Pattern({ type: "AssignmentExpression", operator: op, left: left, right: right }) } +function updExpr(op, arg, prefix) { return Pattern({ type: "UpdateExpression", operator: op, argument: arg, prefix: prefix }) } +function logExpr(op, left, right) { return Pattern({ type: "LogicalExpression", operator: op, left: left, right: right }) } + +function condExpr(test, cons, alt) { return Pattern({ type: "ConditionalExpression", test: test, consequent: cons, alternate: alt }) } +function seqExpr(exprs) { return Pattern({ type: "SequenceExpression", expressions: exprs }) } +function newExpr(callee, args) { return Pattern({ type: "NewExpression", callee: callee, arguments: args }) } +function callExpr(callee, args) { return Pattern({ type: "CallExpression", callee: callee, arguments: args }) } +function arrExpr(elts) { return Pattern({ type: "ArrayExpression", elements: elts }) } +function objExpr(elts) { return Pattern({ type: "ObjectExpression", properties: elts }) } +function objProp(key, value, kind) { return Pattern({ type: "Property", key: key, value: value, kind: kind }) } + +function arrPatt(elts) { return Pattern({ type: "ArrayPattern", elements: elts }) } +function objPatt(elts) { return Pattern({ type: "ObjectPattern", properties: elts }) } + +function localSrc(src) { return "(function(){ " + src + " })" } +function localPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([patt])))]) } +function blockSrc(src) { return "(function(){ { " + src + " } })" } +function blockPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([blockStmt([patt])])))]) } + +function assertBlockStmt(src, patt) { + blockPatt(patt).assert(Reflect.parse(blockSrc(src))); +} + +function assertBlockExpr(src, patt) { + assertBlockStmt(src, exprStmt(patt)); +} + +function assertBlockDecl(src, patt, builder) { + blockPatt(patt).assert(Reflect.parse(blockSrc(src), {builder: builder})); +} + +function assertLocalStmt(src, patt) { + localPatt(patt).assert(Reflect.parse(localSrc(src))); +} + +function assertLocalExpr(src, patt) { + assertLocalStmt(src, exprStmt(patt)); +} + +function assertLocalDecl(src, patt) { + localPatt(patt).assert(Reflect.parse(localSrc(src))); +} + +function assertGlobalStmt(src, patt, builder) { + program([patt]).assert(Reflect.parse(src, {builder: builder})); +} + +function assertGlobalExpr(src, patt, builder) { + program([exprStmt(patt)]).assert(Reflect.parse(src, {builder: builder})); + //assertStmt(src, exprStmt(patt)); +} + +function assertGlobalDecl(src, patt) { + program([patt]).assert(Reflect.parse(src)); +} + +function assertProg(src, patt) { + program(patt).assert(Reflect.parse(src)); +} + +function assertStmt(src, patt) { + assertLocalStmt(src, patt); + assertGlobalStmt(src, patt); + assertBlockStmt(src, patt); +} + +function assertExpr(src, patt) { + assertLocalExpr(src, patt); + assertGlobalExpr(src, patt); + assertBlockExpr(src, patt); +} + +function assertDecl(src, patt) { + assertLocalDecl(src, patt); + assertGlobalDecl(src, patt); + assertBlockDecl(src, patt); +} + +function assertError(src, errorType) { + try { + Reflect.parse(src); + } catch (e) { + return; + } + throw new Error("expected " + errorType.name + " for " + uneval(src)); +} + + +// general tests + +// NB: These are useful but for now jit-test doesn't do I/O reliably. + +//program(_).assert(Reflect.parse(snarf('data/flapjax.txt'))); +//program(_).assert(Reflect.parse(snarf('data/jquery-1.4.2.txt'))); +//program(_).assert(Reflect.parse(snarf('data/prototype.js'))); +//program(_).assert(Reflect.parse(snarf('data/dojo.js.uncompressed.js'))); +//program(_).assert(Reflect.parse(snarf('data/mootools-1.2.4-core-nc.js'))); + + +// declarations + +assertDecl("var x = 1, y = 2, z = 3", + varDecl([declarator(ident("x"), lit(1)), + declarator(ident("y"), lit(2)), + declarator(ident("z"), lit(3))])); +assertDecl("var x, y, z", + varDecl([declarator(ident("x"), null), + declarator(ident("y"), null), + declarator(ident("z"), null)])); +assertDecl("function foo() { }", + funDecl(ident("foo"), [], blockStmt([]))); +assertDecl("function foo() { return 42 }", + funDecl(ident("foo"), [], blockStmt([returnStmt(lit(42))]))); + + +// Bug 591437: rebound args have their defs turned into uses +assertDecl("function f(a) { function a() { } }", + funDecl(ident("f"), [ident("a")], blockStmt([funDecl(ident("a"), [], blockStmt([]))]))); +assertDecl("function f(a,b,c) { function b() { } }", + funDecl(ident("f"), [ident("a"),ident("b"),ident("c")], blockStmt([funDecl(ident("b"), [], blockStmt([]))]))); + +// expressions + +assertExpr("true", lit(true)); +assertExpr("false", lit(false)); +assertExpr("42", lit(42)); +assertExpr("(/asdf/)", lit(/asdf/)); +assertExpr("this", thisExpr); +assertExpr("foo", ident("foo")); +assertExpr("foo.bar", dotExpr(ident("foo"), ident("bar"))); +assertExpr("foo[bar]", memExpr(ident("foo"), ident("bar"))); +assertExpr("(function(){})", funExpr(null, [], blockStmt([]))); +assertExpr("(function f() {})", funExpr(ident("f"), [], blockStmt([]))); +assertExpr("(function f(x,y,z) {})", funExpr(ident("f"), [ident("x"),ident("y"),ident("z")], blockStmt([]))); +assertExpr("(++x)", updExpr("++", ident("x"), true)); +assertExpr("(x++)", updExpr("++", ident("x"), false)); +assertExpr("(+x)", unExpr("+", ident("x"))); +assertExpr("(-x)", unExpr("-", ident("x"))); +assertExpr("(!x)", unExpr("!", ident("x"))); +assertExpr("(~x)", unExpr("~", ident("x"))); +assertExpr("(delete x)", unExpr("delete", ident("x"))); +assertExpr("(typeof x)", unExpr("typeof", ident("x"))); +assertExpr("(void x)", unExpr("void", ident("x"))); +assertExpr("(x == y)", binExpr("==", ident("x"), ident("y"))); +assertExpr("(x != y)", binExpr("!=", ident("x"), ident("y"))); +assertExpr("(x === y)", binExpr("===", ident("x"), ident("y"))); +assertExpr("(x !== y)", binExpr("!==", ident("x"), ident("y"))); +assertExpr("(x < y)", binExpr("<", ident("x"), ident("y"))); +assertExpr("(x <= y)", binExpr("<=", ident("x"), ident("y"))); +assertExpr("(x > y)", binExpr(">", ident("x"), ident("y"))); +assertExpr("(x >= y)", binExpr(">=", ident("x"), ident("y"))); +assertExpr("(x << y)", binExpr("<<", ident("x"), ident("y"))); +assertExpr("(x >> y)", binExpr(">>", ident("x"), ident("y"))); +assertExpr("(x >>> y)", binExpr(">>>", ident("x"), ident("y"))); +assertExpr("(x + y)", binExpr("+", ident("x"), ident("y"))); +assertExpr("(w + x + y + z)", binExpr("+", binExpr("+", binExpr("+", ident("w"), ident("x")), ident("y")), ident("z"))); +assertExpr("(x - y)", binExpr("-", ident("x"), ident("y"))); +assertExpr("(w - x - y - z)", binExpr("-", binExpr("-", binExpr("-", ident("w"), ident("x")), ident("y")), ident("z"))); +assertExpr("(x * y)", binExpr("*", ident("x"), ident("y"))); +assertExpr("(x / y)", binExpr("/", ident("x"), ident("y"))); +assertExpr("(x % y)", binExpr("%", ident("x"), ident("y"))); +assertExpr("(x | y)", binExpr("|", ident("x"), ident("y"))); +assertExpr("(x ^ y)", binExpr("^", ident("x"), ident("y"))); +assertExpr("(x & y)", binExpr("&", ident("x"), ident("y"))); +assertExpr("(x in y)", binExpr("in", ident("x"), ident("y"))); +assertExpr("(x instanceof y)", binExpr("instanceof", ident("x"), ident("y"))); +assertExpr("(x = y)", aExpr("=", ident("x"), ident("y"))); +assertExpr("(x += y)", aExpr("+=", ident("x"), ident("y"))); +assertExpr("(x -= y)", aExpr("-=", ident("x"), ident("y"))); +assertExpr("(x *= y)", aExpr("*=", ident("x"), ident("y"))); +assertExpr("(x /= y)", aExpr("/=", ident("x"), ident("y"))); +assertExpr("(x %= y)", aExpr("%=", ident("x"), ident("y"))); +assertExpr("(x <<= y)", aExpr("<<=", ident("x"), ident("y"))); +assertExpr("(x >>= y)", aExpr(">>=", ident("x"), ident("y"))); +assertExpr("(x >>>= y)", aExpr(">>>=", ident("x"), ident("y"))); +assertExpr("(x |= y)", aExpr("|=", ident("x"), ident("y"))); +assertExpr("(x ^= y)", aExpr("^=", ident("x"), ident("y"))); +assertExpr("(x &= y)", aExpr("&=", ident("x"), ident("y"))); +assertExpr("(x || y)", logExpr("||", ident("x"), ident("y"))); +assertExpr("(x && y)", logExpr("&&", ident("x"), ident("y"))); +assertExpr("(w || x || y || z)", logExpr("||", logExpr("||", logExpr("||", ident("w"), ident("x")), ident("y")), ident("z"))) +assertExpr("(x ? y : z)", condExpr(ident("x"), ident("y"), ident("z"))); +assertExpr("(x,y)", seqExpr([ident("x"),ident("y")])) +assertExpr("(x,y,z)", seqExpr([ident("x"),ident("y"),ident("z")])) +assertExpr("(a,b,c,d,e,f,g)", seqExpr([ident("a"),ident("b"),ident("c"),ident("d"),ident("e"),ident("f"),ident("g")])); +assertExpr("(new Object)", newExpr(ident("Object"), [])); +assertExpr("(new Object())", newExpr(ident("Object"), [])); +assertExpr("(new Object(42))", newExpr(ident("Object"), [lit(42)])); +assertExpr("(new Object(1,2,3))", newExpr(ident("Object"), [lit(1),lit(2),lit(3)])); +assertExpr("(String())", callExpr(ident("String"), [])); +assertExpr("(String(42))", callExpr(ident("String"), [lit(42)])); +assertExpr("(String(1,2,3))", callExpr(ident("String"), [lit(1),lit(2),lit(3)])); +assertExpr("[]", arrExpr([])); +assertExpr("[1]", arrExpr([lit(1)])); +assertExpr("[1,2]", arrExpr([lit(1),lit(2)])); +assertExpr("[1,2,3]", arrExpr([lit(1),lit(2),lit(3)])); +assertExpr("[1,,2,3]", arrExpr([lit(1),,lit(2),lit(3)])); +assertExpr("[1,,,2,3]", arrExpr([lit(1),,,lit(2),lit(3)])); +assertExpr("[1,,,2,,3]", arrExpr([lit(1),,,lit(2),,lit(3)])); +assertExpr("[1,,,2,,,3]", arrExpr([lit(1),,,lit(2),,,lit(3)])); +assertExpr("[,1,2,3]", arrExpr([,lit(1),lit(2),lit(3)])); +assertExpr("[,,1,2,3]", arrExpr([,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3]", arrExpr([,,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3,]", arrExpr([,,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined])); +assertExpr("[,,,1,2,3,,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined,undefined])); +assertExpr("[,,,,,]", arrExpr([undefined,undefined,undefined,undefined,undefined])); +assertExpr("({})", objExpr([])); +assertExpr("({x:1})", objExpr([objProp(ident("x"), lit(1), "init")])); +assertExpr("({x:1, y:2})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(ident("y"), lit(2), "init")])); +assertExpr("({x:1, y:2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(ident("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({x:1, 'y':2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({'x':1, 'y':2, z:3})", objExpr([objProp(lit("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({'x':1, 'y':2, 3:3})", objExpr([objProp(lit("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(lit(3), lit(3), "init") ])); + +// Bug 571617: eliminate constant-folding +assertExpr("2 + 3", binExpr("+", lit(2), lit(3))); + +// Bug 632026: constant-folding +assertExpr("typeof(0?0:a)", unExpr("typeof", condExpr(lit(0), lit(0), ident("a")))); + +// Bug 632056: constant-folding +program([exprStmt(ident("f")), + ifStmt(lit(1), + funDecl(ident("f"), [], blockStmt([])), + null)]).assert(Reflect.parse("f; if (1) function f(){}")); + +// statements + +assertStmt("throw 42", throwStmt(lit(42))); +assertStmt("for (;;) break", forStmt(null, null, null, breakStmt(null))); +assertStmt("for (x; y; z) break", forStmt(ident("x"), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (var x; y; z) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (var x = 42; y; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (x; ; z) break", forStmt(ident("x"), null, ident("z"), breakStmt(null))); +assertStmt("for (var x; ; z) break", forStmt(varDecl([declarator(ident("x"), null)]), null, ident("z"), breakStmt(null))); +assertStmt("for (var x = 42; ; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), null, ident("z"), breakStmt(null))); +assertStmt("for (x; y; ) break", forStmt(ident("x"), ident("y"), null, breakStmt(null))); +assertStmt("for (var x; y; ) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), null, breakStmt(null))); +assertStmt("for (var x = 42; y; ) break", forStmt(varDecl([declarator(ident("x"),lit(42))]), ident("y"), null, breakStmt(null))); +assertStmt("for (var x in y) break", forInStmt(varDecl([declarator(ident("x"),null)]), ident("y"), breakStmt(null))); +assertStmt("for (x in y) break", forInStmt(ident("x"), ident("y"), breakStmt(null))); +assertStmt("{ }", blockStmt([])); +assertStmt("{ throw 1; throw 2; throw 3; }", blockStmt([ throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))])); +assertStmt(";", emptyStmt); +assertStmt("if (foo) throw 42;", ifStmt(ident("foo"), throwStmt(lit(42)), null)); +assertStmt("if (foo) throw 42; else true;", ifStmt(ident("foo"), throwStmt(lit(42)), exprStmt(lit(true)))); +assertStmt("if (foo) { throw 1; throw 2; throw 3; }", + ifStmt(ident("foo"), + blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]), + null)); +assertStmt("if (foo) { throw 1; throw 2; throw 3; } else true;", + ifStmt(ident("foo"), + blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]), + exprStmt(lit(true)))); +assertStmt("foo: for(;;) break foo;", labStmt(ident("foo"), forStmt(null, null, null, breakStmt(ident("foo"))))); +assertStmt("foo: for(;;) continue foo;", labStmt(ident("foo"), forStmt(null, null, null, continueStmt(ident("foo"))))); +assertStmt("with (obj) { }", withStmt(ident("obj"), blockStmt([]))); +assertStmt("with (obj) { obj; }", withStmt(ident("obj"), blockStmt([exprStmt(ident("obj"))]))); +assertStmt("while (foo) { }", whileStmt(ident("foo"), blockStmt([]))); +assertStmt("while (foo) { foo; }", whileStmt(ident("foo"), blockStmt([exprStmt(ident("foo"))]))); +assertStmt("do { } while (foo);", doStmt(blockStmt([]), ident("foo"))); +assertStmt("do { foo; } while (foo)", doStmt(blockStmt([exprStmt(ident("foo"))]), ident("foo"))); +assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; }", + switchStmt(ident("foo"), + [ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]), + caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]), + defaultClause([ exprStmt(lit(3)) ]) ])); +assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; case 42: 42; }", + switchStmt(ident("foo"), + [ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]), + caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]), + defaultClause([ exprStmt(lit(3)) ]), + caseClause(lit(42), [ exprStmt(lit(42)) ]) ])); +assertStmt("try { } catch (e) { }", + tryStmt(blockStmt([]), + [], + [ catchClause(ident("e"), null, blockStmt([])) ], + null)); +assertStmt("try { } catch (e) { } finally { }", + tryStmt(blockStmt([]), + [], + [ catchClause(ident("e"), null, blockStmt([])) ], + blockStmt([]))); +assertStmt("try { } finally { }", + tryStmt(blockStmt([]), + [], + [], + blockStmt([]))); + +// redeclarations (TOK_NAME nodes with lexdef) + +assertStmt("function f() { function g() { } function g() { } }", + funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])), + funDecl(ident("g"), [], blockStmt([]))]))); + +assertStmt("function f() { function g() { } function g() { return 42 } }", + funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])), + funDecl(ident("g"), [], blockStmt([returnStmt(lit(42))]))]))); + +assertStmt("function f() { var x = 42; var x = 43; }", + funDecl(ident("f"), [], blockStmt([varDecl([declarator(ident("x"),lit(42))]), + varDecl([declarator(ident("x"),lit(43))])]))); + +// getters and setters + + assertExpr("({ get x() { return 42 } })", + objExpr([ objProp(ident("x"), + funExpr(null, [], blockStmt([returnStmt(lit(42))])), + "get" ) ])); + assertExpr("({ set x(v) { return 42 } })", + objExpr([ objProp(ident("x"), + funExpr(null, [ident("v")], blockStmt([returnStmt(lit(42))])), + "set" ) ])); + +} + +exports.testReflect = testReflect; + +}(typeof exports === 'undefined' ? this : exports)); diff --git a/tools/eslint/node_modules/espree/test/run.js b/tools/eslint/node_modules/espree/test/run.js new file mode 100644 index 00000000000000..bd303e058e40fb --- /dev/null +++ b/tools/eslint/node_modules/espree/test/run.js @@ -0,0 +1,68 @@ +/* + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint node:true */ + +(function () { + 'use strict'; + + var child = require('child_process'), + nodejs = '"' + process.execPath + '"', + ret = 0, + suites, + index; + + suites = [ + 'runner', + // TODO: Figure out what to do about this test...remove? + // 'compat', + 'parselibs' + ]; + + function nextTest() { + var suite = suites[index]; + + if (index < suites.length) { + child.exec(nodejs + ' ./test/' + suite + '.js', function (err, stdout, stderr) { + if (stdout) { + process.stdout.write(suite + ': ' + stdout); + } + if (stderr) { + process.stderr.write(suite + ': ' + stderr); + } + if (err) { + ret = err.code; + } + index += 1; + nextTest(); + }); + } else { + process.exit(ret); + } + } + + index = 0; + nextTest(); +}()); diff --git a/tools/eslint/node_modules/espree/test/runner.js b/tools/eslint/node_modules/espree/test/runner.js new file mode 100644 index 00000000000000..a29f29e1b407b3 --- /dev/null +++ b/tools/eslint/node_modules/espree/test/runner.js @@ -0,0 +1,492 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Yusuke Suzuki + Copyright (C) 2011 Arpad Borsos + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint browser:true node:true */ +/*global espree:true, testFixture:true */ + +var runTests; + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + 'use strict'; + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +function NotMatchingError(expected, actual) { + 'use strict'; + Error.call(this, 'Expected '); + this.expected = expected; + this.actual = actual; +} +NotMatchingError.prototype = new Error(); + +function errorToObject(e) { + 'use strict'; + var msg = e.toString(); + + // Opera 9.64 produces an non-standard string in toString(). + if (msg.substr(0, 6) !== 'Error:') { + if (typeof e.message === 'string') { + msg = 'Error: ' + e.message; + } + } + + return { + index: e.index, + lineNumber: e.lineNumber, + column: e.column, + message: msg + }; +} + +function sortedObject(o) { + if (o === null) { + return o; + } + if (o instanceof Array) { + return o.map(sortedObject); + } + if (typeof o !== 'object') { + return o; + } + if (o instanceof RegExp) { + return o; + } + var keys = Object.keys(o); + var result = { + range: undefined, + loc: undefined + }; + keys.forEach(function (key) { + if (o.hasOwnProperty(key)){ + result[key] = sortedObject(o[key]); + } + }); + return result; +} + +function hasAttachedComment(syntax) { + var key; + for (key in syntax) { + if (key === 'leadingComments' || key === 'trailingComments') { + return true; + } + if (typeof syntax[key] === 'object' && syntax[key] !== null) { + if (hasAttachedComment(syntax[key])) { + return true; + } + } + } + return false; +} + +function testParse(espree, code, syntax) { + 'use strict'; + var expected, tree, actual, options, StringObject, i, len, err; + + // alias, so that JSLint does not complain. + StringObject = String; + + options = { + comment: (typeof syntax.comments !== 'undefined'), + range: true, + loc: true, + tokens: (typeof syntax.tokens !== 'undefined'), + raw: true, + tolerant: (typeof syntax.errors !== 'undefined'), + source: null + }; + + if (options.comment) { + options.attachComment = hasAttachedComment(syntax); + } + + if (typeof syntax.tokens !== 'undefined') { + if (syntax.tokens.length > 0) { + options.range = (typeof syntax.tokens[0].range !== 'undefined'); + options.loc = (typeof syntax.tokens[0].loc !== 'undefined'); + } + } + + if (typeof syntax.comments !== 'undefined') { + if (syntax.comments.length > 0) { + options.range = (typeof syntax.comments[0].range !== 'undefined'); + options.loc = (typeof syntax.comments[0].loc !== 'undefined'); + } + } + + if (options.loc) { + options.source = syntax.loc.source; + } + + syntax = sortedObject(syntax); + expected = JSON.stringify(syntax, null, 4); + try { + // Some variations of the options. + tree = espree.parse(code, { tolerant: options.tolerant }); + tree = espree.parse(code, { tolerant: options.tolerant, range: true }); + tree = espree.parse(code, { tolerant: options.tolerant, loc: true }); + + tree = espree.parse(code, options); + tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0]; + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + tree = sortedObject(tree); + actual = JSON.stringify(tree, adjustRegexLiteral, 4); + + // Only to ensure that there is no error when using string object. + espree.parse(new StringObject(code), options); + + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } + + function filter(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return (key === 'loc' || key === 'range') ? undefined : value; + } + + if (options.tolerant) { + return; + } + + + // Check again without any location info. + options.range = false; + options.loc = false; + syntax = sortedObject(syntax); + expected = JSON.stringify(syntax, filter, 4); + try { + tree = espree.parse(code, options); + tree = (options.comment || options.tokens) ? tree : tree.body[0]; + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + tree = sortedObject(tree); + actual = JSON.stringify(tree, filter, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function testTokenize(espree, code, tokens) { + 'use strict'; + var options, expected, actual, tree; + + options = { + comment: true, + tolerant: true, + loc: true, + range: true + }; + + expected = JSON.stringify(tokens, null, 4); + + try { + tree = espree.tokenize(code, options); + actual = JSON.stringify(tree, null, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function testError(espree, code, exception) { + 'use strict'; + var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize; + + // Different parsing options should give the same error. + options = [ + {}, + { comment: true }, + { raw: true }, + { raw: true, comment: true } + ]; + + // If handleInvalidRegexFlag is true, an invalid flag in a regular expression + // will throw an exception. In some old version V8, this is not the case + // and hence handleInvalidRegexFlag is false. + handleInvalidRegexFlag = false; + try { + 'test'.match(new RegExp('[a-z]', 'x')); + } catch (e) { + handleInvalidRegexFlag = true; + } + + exception.description = exception.message.replace(/Error: Line [0-9]+: /, ''); + + if (exception.tokenize) { + tokenize = true; + exception.tokenize = undefined; + } + expected = JSON.stringify(exception); + + for (i = 0; i < options.length; i += 1) { + + try { + if (tokenize) { + espree.tokenize(code, options[i]) + } else { + espree.parse(code, options[i]); + } + } catch (e) { + err = errorToObject(e); + err.description = e.description; + actual = JSON.stringify(err); + } + + if (expected !== actual) { + + // Compensate for old V8 which does not handle invalid flag. + if (exception.message.indexOf('Invalid regular expression') > 0) { + if (typeof actual === 'undefined' && !handleInvalidRegexFlag) { + return; + } + } + + throw new NotMatchingError(expected, actual); + } + + } +} + +function testAPI(espree, code, result) { + 'use strict'; + var expected, res, actual; + + expected = JSON.stringify(result.result, null, 4); + try { + if (typeof result.property !== 'undefined') { + res = espree[result.property]; + } else { + res = espree[result.call].apply(espree, result.args); + } + actual = JSON.stringify(res, adjustRegexLiteral, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function runTest(espree, code, result) { + 'use strict'; + if (result.hasOwnProperty('lineNumber')) { + testError(espree, code, result); + } else if (result.hasOwnProperty('result')) { + testAPI(espree, code, result); + } else if (result instanceof Array) { + testTokenize(espree, code, result); + } else { + testParse(espree, code, result); + } +} + +if (typeof window !== 'undefined') { + // Run all tests in a browser environment. + runTests = function () { + 'use strict'; + var total = 0, + failures = 0, + category, + fixture, + source, + tick, + expected, + index, + len; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function startCategory(category) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('h4'); + setText(e, category); + report.appendChild(e); + } + + function reportSuccess(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + } + + function reportFailure(code, expected, actual) { + var report, e; + + report = document.getElementById('report'); + + e = document.createElement('p'); + setText(e, 'Code:'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Expected'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'expected'); + setText(e, expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'actual'); + setText(e, actual); + report.appendChild(e); + } + + setText(document.getElementById('version'), espree.version); + + tick = new Date(); + for (category in testFixture) { + if (testFixture.hasOwnProperty(category)) { + startCategory(category); + fixture = testFixture[category]; + for (source in fixture) { + if (fixture.hasOwnProperty(source)) { + expected = fixture[source]; + total += 1; + try { + runTest(espree, source, expected); + reportSuccess(source, JSON.stringify(expected, null, 4)); + } catch (e) { + failures += 1; + reportFailure(source, e.expected, e.actual); + } + } + } + } + } + tick = (new Date()) - tick; + + if (failures > 0) { + document.getElementById('status').className = 'alert-box alert'; + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms.'); + } else { + document.getElementById('status').className = 'alert-box success'; + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms.'); + } + }; +} else { + (function () { + 'use strict'; + + var espree = require('../espree'), + diff = require('json-diff').diffString, + total = 0, + failures = [], + tick = new Date(), + expected, + header, + testFixture = require("./test"); + + Object.keys(testFixture).forEach(function (category) { + Object.keys(testFixture[category]).forEach(function (source) { + total += 1; + expected = testFixture[category][source]; + try { + runTest(espree, source, expected); + } catch (e) { + e.source = source; + failures.push(e); + } + }); + }); + tick = (new Date()) - tick; + + header = total + ' tests. ' + failures.length + ' failures. ' + + tick + ' ms'; + if (failures.length) { + console.error(header); + failures.forEach(function (failure) { + try { + var expectedObject = JSON.parse(failure.expected); + var actualObject = JSON.parse(failure.actual); + + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual + '\nDiff:\n' + + diff(expectedObject, actualObject)); + } catch (ex) { + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual); + } + }); + } else { + console.log(header); + } + process.exit(failures.length === 0 ? 0 : 1); + }()); +} diff --git a/tools/eslint/node_modules/espree/test/test.js b/tools/eslint/node_modules/espree/test/test.js new file mode 100644 index 00000000000000..93193c7ea5d0e0 --- /dev/null +++ b/tools/eslint/node_modules/espree/test/test.js @@ -0,0 +1,34 @@ +/** + * @fileoverview Tests for parsing/tokenization. + * @author Nicholas C. Zakas + * @copyright 2014 Nicholas C. Zakas. All rights reserved. + */ + +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +var shelljs = require("shelljs"), + fs = require("fs"), + path = require("path"); + +//------------------------------------------------------------------------------ +// Processing +//------------------------------------------------------------------------------ + +var files = shelljs.find("./tests/fixtures/ast"); + +files.filter(function(filename) { + return path.extname(filename) === ".json"; +}).forEach(function(filename) { + var basename = path.basename(filename, ".json"); + exports[basename] = JSON.parse(fs.readFileSync(filename, "utf8"), function(key, value) { + + // JSON can't represent undefined, so we use a special value + if (value === "espree@undefined") { + return undefined; + } else { + return value; + } + }); +}); diff --git a/tools/eslint/node_modules/estraverse-fb/.npmignore b/tools/eslint/node_modules/estraverse-fb/.npmignore new file mode 100644 index 00000000000000..da23d0d4bab050 --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/.npmignore @@ -0,0 +1,25 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Deployed apps should consider commenting this line out: +# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git +node_modules diff --git a/tools/eslint/node_modules/estraverse-fb/.travis.yml b/tools/eslint/node_modules/estraverse-fb/.travis.yml new file mode 100644 index 00000000000000..ffb9f710ac283a --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/.travis.yml @@ -0,0 +1,2 @@ +language: node_js +node_js: '0.10' diff --git a/tools/eslint/node_modules/estraverse-fb/LICENSE b/tools/eslint/node_modules/estraverse-fb/LICENSE new file mode 100644 index 00000000000000..54530b38082641 --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ingvar Stepanyan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/tools/eslint/node_modules/estraverse-fb/README.md b/tools/eslint/node_modules/estraverse-fb/README.md new file mode 100644 index 00000000000000..20b02966b871d0 --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/README.md @@ -0,0 +1,34 @@ +estraverse-fb +============= +[![Build Status](https://travis-ci.org/RReverser/estraverse-fb.svg?branch=master)](https://travis-ci.org/RReverser/estraverse-fb) + +Drop-in for estraverse that enables traversal over React's JSX and Flow nodes using monkey-patching technique. + +You can use estraverse-fb in two possible ways: + +* by default, you just require it and it injects needed keys into your installed version of estraverse (it's installed automatically if you don't have it yet): + ```javascript + var estraverse = require('estraverse-fb'); + /* same as: + require('estraverse-fb'); + var estraverse = require('estraverse'); + */ + + estraverse.traverse(ast, { + enter: ..., + leave: ... + }); + ``` + +* alternatively, you can use it manually for selected traversals: + ```javascript + var jsxKeys = require('estraverse-fb/keys'); + + estraverse.traverse(ast, { + enter: ..., + leave: ..., + keys: jsxKeys + }) +``` + +Check out [estraverse page](https://github.com/Constellation/estraverse) for detailed usage. diff --git a/tools/eslint/node_modules/estraverse-fb/estraverse-fb.js b/tools/eslint/node_modules/estraverse-fb/estraverse-fb.js new file mode 100644 index 00000000000000..795ec40e62a2ae --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/estraverse-fb.js @@ -0,0 +1,13 @@ +var estraverse = module.exports = require('estraverse'); + +var VisitorKeys = require('./keys'); + +for (var nodeType in VisitorKeys) { + estraverse.Syntax[nodeType] = nodeType; + + var keys = VisitorKeys[nodeType]; + + if (keys) { + estraverse.VisitorKeys[nodeType] = keys; + } +} \ No newline at end of file diff --git a/tools/eslint/node_modules/estraverse-fb/keys.js b/tools/eslint/node_modules/estraverse-fb/keys.js new file mode 100644 index 00000000000000..47df04a58ba37d --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/keys.js @@ -0,0 +1,57 @@ +var unprefixedKeys = { + Identifier: [], + NamespacedName: ['namespace', 'name'], + MemberExpression: ['object', 'property'], + EmptyExpression: [], + ExpressionContainer: ['expression'], + Element: ['openingElement', 'closingElement', 'children'], + ClosingElement: ['name'], + OpeningElement: ['name', 'attributes'], + Attribute: ['name', 'value'], + Text: null, + SpreadAttribute: ['argument'] +}; + +var flowKeys = { + Type: [], + AnyTypeAnnotation: [], + VoidTypeAnnotation: [], + NumberTypeAnnotation: [], + StringTypeAnnotation: [], + StringLiteralTypeAnnotation: ["value", "raw"], + BooleanTypeAnnotation: [], + TypeAnnotation: ["typeAnnotation"], + NullableTypeAnnotation: ["typeAnnotation"], + FunctionTypeAnnotation: ["params", "returnType", "rest", "typeParameters"], + FunctionTypeParam: ["name", "typeAnnotation", "optional"], + ObjectTypeAnnotation: ["properties"], + ObjectTypeProperty: ["key", "value", "optional"], + ObjectTypeIndexer: ["id", "key", "value"], + ObjectTypeCallProperty: ["value"], + QualifiedTypeIdentifier: ["qualification", "id"], + GenericTypeAnnotation: ["id", "typeParameters"], + MemberTypeAnnotation: ["object", "property"], + UnionTypeAnnotation: ["types"], + IntersectionTypeAnnotation: ["types"], + TypeofTypeAnnotation: ["argument"], + TypeParameterDeclaration: ["params"], + TypeParameterInstantiation: ["params"], + ClassProperty: ["key", "typeAnnotation"], + ClassImplements: [], + InterfaceDeclaration: ["id", "body", "extends"], + InterfaceExtends: ["id"], + TypeAlias: ["id", "typeParameters", "right"], + TupleTypeAnnotation: ["types"], + DeclareVariable: ["id"], + DeclareFunction: ["id"], + DeclareClass: ["id"], + DeclareModule: ["id", "body"] +}; + +for (var key in unprefixedKeys) { + exports['XJS' + key] = exports['JSX' + key] = unprefixedKeys[key]; +} + +for (var key in flowKeys) { + exports[key] = flowKeys[key]; +} \ No newline at end of file diff --git a/tools/eslint/node_modules/estraverse-fb/package.json b/tools/eslint/node_modules/estraverse-fb/package.json new file mode 100644 index 00000000000000..c96ec2f456d784 --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/package.json @@ -0,0 +1,60 @@ +{ + "name": "estraverse-fb", + "version": "1.3.1", + "description": "Drop-in for estraverse that enables traversal over React's JSX nodes.", + "main": "estraverse-fb.js", + "repository": { + "type": "git", + "url": "git+https://github.com/RReverser/estraverse-fb.git" + }, + "keywords": [ + "traverse", + "ast", + "react", + "jsx" + ], + "author": { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "url": "https://github.com/RReverser" + }, + "license": "MIT", + "scripts": { + "test": "mocha" + }, + "peerDependencies": { + "estraverse": "*" + }, + "devDependencies": { + "chai": "^1.9.1", + "esprima-fb": "^8001.1001.0-dev-harmony-fb", + "estraverse": "^1.7.0", + "mocha": "^1.20.0" + }, + "gitHead": "776d565d897ad91e20efedd926972c7ab0c7221e", + "bugs": { + "url": "https://github.com/RReverser/estraverse-fb/issues" + }, + "homepage": "https://github.com/RReverser/estraverse-fb", + "_id": "estraverse-fb@1.3.1", + "_shasum": "160e75a80e605b08ce894bcce2fe3e429abf92bf", + "_from": "estraverse-fb@>=1.3.1 <2.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "rreverser", + "email": "me@rreverser.com" + }, + "maintainers": [ + { + "name": "rreverser", + "email": "me@rreverser.com" + } + ], + "dist": { + "shasum": "160e75a80e605b08ce894bcce2fe3e429abf92bf", + "tarball": "http://registry.npmjs.org/estraverse-fb/-/estraverse-fb-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/estraverse-fb/-/estraverse-fb-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/estraverse-fb/test.js b/tools/eslint/node_modules/estraverse-fb/test.js new file mode 100644 index 00000000000000..e0fca88a01689a --- /dev/null +++ b/tools/eslint/node_modules/estraverse-fb/test.js @@ -0,0 +1,116 @@ +var assert = require('chai').assert; +var parse = require('esprima-fb').parse; +var originalKeys = require('./keys'); + +describe('works', function () { + var code = ['class MyClass{', + 'x: number;', + 'y: number;', + 'constructor(x: number, y: number){', + 'this.x = x;', + 'this.y = y;', + '}', + 'render(){', + 'return !{}', + '}', + '}'].join('\n'); + + var ast = parse(code); + + var expectedKeys = [ + 'ClassProperty', + 'TypeAnnotation', + 'NumberTypeAnnotation', + 'ClassProperty', + 'TypeAnnotation', + 'NumberTypeAnnotation', + 'XJSElement', + 'XJSOpeningElement', + 'XJSNamespacedName', + 'XJSIdentifier', + 'XJSIdentifier', + 'XJSAttribute', + 'XJSIdentifier', + 'XJSAttribute', + 'XJSIdentifier', + 'XJSExpressionContainer', + 'XJSSpreadAttribute', + 'XJSClosingElement', + 'XJSNamespacedName', + 'XJSIdentifier', + 'XJSIdentifier', + 'XJSElement', + 'XJSOpeningElement', + 'XJSMemberExpression', + 'XJSIdentifier', + 'XJSIdentifier', + 'XJSClosingElement', + 'XJSMemberExpression', + 'XJSIdentifier', + 'XJSIdentifier', + 'XJSExpressionContainer', + 'XJSEmptyExpression' + ]; + + beforeEach(function () { + for (var key in require.cache) { + delete require.cache[key]; + } + }); + + it('directly from dependency', function () { + var traverse = require('./').traverse; + var actualKeys = []; + var actualTypeKeys = []; + + traverse(ast, { + enter: function (node) { + if (originalKeys[node.type] != null) { + actualKeys.push(node.type); + } + } + }); + + assert.deepEqual(actualKeys, expectedKeys); + }); + + it('in injected mode', function () { + require('./'); + var traverse = require('estraverse').traverse; + var actualKeys = []; + + traverse(ast, { + enter: function (node) { + if (originalKeys[node.type] != null) { + actualKeys.push(node.type); + } + } + }); + + assert.deepEqual(actualKeys, expectedKeys); + }); + + it('in single-pass mode', function () { + var traverse = require('estraverse').traverse; + var keys = require('./keys'); + + var actualKeys = []; + + traverse(ast, { + enter: function (node) { + if (originalKeys[node.type] != null) { + actualKeys.push(node.type); + } + }, + keys: keys + }); + + assert.throws(function () { + traverse(ast, { + enter: function () {} + }); + }); + + assert.deepEqual(actualKeys, expectedKeys); + }); +}); diff --git a/tools/eslint/node_modules/estraverse/.jshintrc b/tools/eslint/node_modules/estraverse/.jshintrc new file mode 100644 index 00000000000000..f642dae7683b81 --- /dev/null +++ b/tools/eslint/node_modules/estraverse/.jshintrc @@ -0,0 +1,16 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "eqnull": true, + "latedef": true, + "noarg": true, + "noempty": true, + "quotmark": "single", + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "node": true +} diff --git a/tools/eslint/node_modules/estraverse/LICENSE.BSD b/tools/eslint/node_modules/estraverse/LICENSE.BSD new file mode 100644 index 00000000000000..3e580c355a96e5 --- /dev/null +++ b/tools/eslint/node_modules/estraverse/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/estraverse/README.md b/tools/eslint/node_modules/estraverse/README.md new file mode 100644 index 00000000000000..4242c513309e9a --- /dev/null +++ b/tools/eslint/node_modules/estraverse/README.md @@ -0,0 +1,124 @@ +### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.png)](http://travis-ci.org/estools/estraverse) + +Estraverse ([estraverse](http://github.com/estools/estraverse)) is +[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +traversal functions from [esmangle project](http://github.com/estools/esmangle). + +### Documentation + +You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). + +### Example Usage + +The following code will output all variables declared at the root of a file. + +```javascript +estraverse.traverse(ast, { + enter: function (node, parent) { + if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') + return estraverse.VisitorOption.Skip; + }, + leave: function (node, parent) { + if (node.type == 'VariableDeclarator') + console.log(node.id.name); + } +}); +``` + +We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. + +```javascript +estraverse.traverse(ast, { + enter: function (node) { + this.break(); + } +}); +``` + +And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. + +```javascript +result = estraverse.replace(tree, { + enter: function (node) { + // Replace it with replaced. + if (node.type === 'Literal') + return replaced; + } +}); +``` + +By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. + +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Extending the exising traversing rules. + keys: { + // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] + TestExpression: ['argument'] + } +}); +``` + +By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. +```javascript +// This tree contains a user-defined `TestExpression` node. +var tree = { + type: 'TestExpression', + + // This 'argument' is the property containing the other **node**. + argument: { + type: 'Literal', + value: 20 + }, + + // This 'extended' is the property not containing the other **node**. + extended: true +}; +estraverse.traverse(tree, { + enter: function (node) { }, + + // Iterating the child **nodes** of unknown nodes. + fallback: 'iteration' +}); +``` + +### License + +Copyright (C) 2012-2013 [Yusuke Suzuki](http://github.com/Constellation) + (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/estraverse/estraverse.js b/tools/eslint/node_modules/estraverse/estraverse.js new file mode 100644 index 00000000000000..abc52ce501225a --- /dev/null +++ b/tools/eslint/node_modules/estraverse/estraverse.js @@ -0,0 +1,839 @@ +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + + var Syntax, + isArray, + VisitorOption, + VisitorKeys, + objectCreate, + objectKeys, + BREAK, + SKIP, + REMOVE; + + function ignoreJSHintError() { } + + isArray = Array.isArray; + if (!isArray) { + isArray = function isArray(array) { + return Object.prototype.toString.call(array) === '[object Array]'; + }; + } + + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } + + function shallowCopy(obj) { + var ret = {}, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + ignoreJSHintError(shallowCopy); + + // based on LLVM libc++ upper_bound / lower_bound + // MIT License + + function upperBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } + + function lowerBound(array, func) { + var diff, len, i, current; + + len = array.length; + i = 0; + + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + i = current + 1; + len -= diff + 1; + } else { + len = diff; + } + } + return i; + } + ignoreJSHintError(lowerBound); + + objectCreate = Object.create || (function () { + function F() { } + + return function (o) { + F.prototype = o; + return new F(); + }; + })(); + + objectKeys = Object.keys || function (o) { + var keys = [], key; + for (key in o) { + keys.push(key); + } + return keys; + }; + + function extend(to, from) { + var keys = objectKeys(from), key, i, len; + for (i = 0, len = keys.length; i < len; i += 1) { + key = keys[i]; + to[key] = from[key]; + } + return to; + } + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'], + FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; + + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; + + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; + + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + + Reference.prototype.remove = function remove() { + if (isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; + + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } + + function Controller() { } + + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; + + function addToPath(result, path) { + if (isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } + + // root node + if (!this.__current.path) { + return null; + } + + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; + + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; + + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; + + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + + return result; + }; + + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; + + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; + + result = undefined; + + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + + return result; + }; + + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; + + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; + + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; + + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = visitor.fallback === 'iteration'; + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = extend(objectCreate(this.__keys), visitor.keys); + } + }; + + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + ret = this.__execute(visitor.leave, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + + if (element.node) { + + ret = this.__execute(visitor.enter, element); + + if (this.__state === BREAK || ret === BREAK) { + return; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || ret === SKIP) { + continue; + } + + node = element.node; + nodeType = element.wrap || node.type; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = objectKeys(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; + + Controller.prototype.replace = function replace(root, visitor) { + function removeElem(element) { + var i, + key, + nextElem, + parent; + + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; + + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } + + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + + this.__initialize(root, visitor); + + sentinel = {}; + + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; + + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); + + while (worklist.length) { + element = worklist.pop(); + + if (element === sentinel) { + element = leavelist.pop(); + + target = this.__execute(visitor.leave, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + + target = this.__execute(visitor.enter, element); + + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } + + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + + // node may be null + node = element.node; + if (!node) { + continue; + } + + worklist.push(sentinel); + leavelist.push(element); + + if (this.__state === SKIP || target === SKIP) { + continue; + } + + nodeType = element.wrap || node.type; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = objectKeys(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } + + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } + + if (isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + + return outer.root; + }; + + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } + + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } + + function extendCommentRange(comment, tokens) { + var target; + + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + + comment.extendedRange = [comment.range[0], comment.range[1]]; + + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } + + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } + + return comment; + } + + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; + + if (!tree.range) { + throw new Error('attachComments needs range information'); + } + + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } + + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } + + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } + + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = require('./package.json').version; + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/estraverse/gulpfile.js b/tools/eslint/node_modules/estraverse/gulpfile.js new file mode 100644 index 00000000000000..8772bbcca542a8 --- /dev/null +++ b/tools/eslint/node_modules/estraverse/gulpfile.js @@ -0,0 +1,70 @@ +/* + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +'use strict'; + +var gulp = require('gulp'), + git = require('gulp-git'), + bump = require('gulp-bump'), + filter = require('gulp-filter'), + tagVersion = require('gulp-tag-version'); + +var TEST = [ 'test/*.js' ]; +var POWERED = [ 'powered-test/*.js' ]; +var SOURCE = [ 'src/**/*.js' ]; + +/** + * Bumping version number and tagging the repository with it. + * Please read http://semver.org/ + * + * You can use the commands + * + * gulp patch # makes v0.1.0 -> v0.1.1 + * gulp feature # makes v0.1.1 -> v0.2.0 + * gulp release # makes v0.2.1 -> v1.0.0 + * + * To bump the version numbers accordingly after you did a patch, + * introduced a feature or made a backwards-incompatible release. + */ + +function inc(importance) { + // get all the files to bump version in + return gulp.src(['./package.json']) + // bump the version number in those files + .pipe(bump({type: importance})) + // save it back to filesystem + .pipe(gulp.dest('./')) + // commit the changed version number + .pipe(git.commit('Bumps package version')) + // read only one file to get the version number + .pipe(filter('package.json')) + // **tag it in the repository** + .pipe(tagVersion({ + prefix: '' + })); +} + +gulp.task('patch', [ ], function () { return inc('patch'); }) +gulp.task('minor', [ ], function () { return inc('minor'); }) +gulp.task('major', [ ], function () { return inc('major'); }) diff --git a/tools/eslint/node_modules/estraverse/package.json b/tools/eslint/node_modules/estraverse/package.json new file mode 100644 index 00000000000000..73d905f97d4462 --- /dev/null +++ b/tools/eslint/node_modules/estraverse/package.json @@ -0,0 +1,62 @@ +{ + "name": "estraverse", + "description": "ECMAScript JS AST traversal functions", + "homepage": "https://github.com/estools/estraverse", + "main": "estraverse.js", + "version": "2.0.0", + "engines": { + "node": ">=0.10.0" + }, + "maintainers": [ + { + "name": "constellation", + "email": "utatane.tea@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/estools/estraverse.git" + }, + "devDependencies": { + "chai": "^2.1.1", + "coffee-script": "^1.8.0", + "espree": "^1.11.0", + "gulp": "^3.8.10", + "gulp-bump": "^0.2.2", + "gulp-filter": "^2.0.0", + "gulp-git": "^1.0.1", + "gulp-tag-version": "^1.2.1", + "jshint": "^2.5.6", + "mocha": "^2.1.0" + }, + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/estools/estraverse/raw/master/LICENSE.BSD" + } + ], + "scripts": { + "test": "npm run-script lint && npm run-script unit-test", + "lint": "jshint estraverse.js", + "unit-test": "mocha --compilers coffee:coffee-script/register" + }, + "gitHead": "d8bc726f126817cc03c7a4e751528edb19db0ffb", + "bugs": { + "url": "https://github.com/estools/estraverse/issues" + }, + "_id": "estraverse@2.0.0", + "_shasum": "5ae46963243600206674ccb24a09e16674fcdca1", + "_from": "estraverse@>=2.0.0 <3.0.0", + "_npmVersion": "2.0.0-alpha-5", + "_npmUser": { + "name": "constellation", + "email": "utatane.tea@gmail.com" + }, + "dist": { + "shasum": "5ae46963243600206674ccb24a09e16674fcdca1", + "tarball": "http://registry.npmjs.org/estraverse/-/estraverse-2.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/estraverse/-/estraverse-2.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/globals/globals.json b/tools/eslint/node_modules/globals/globals.json new file mode 100644 index 00000000000000..14f69c313d221d --- /dev/null +++ b/tools/eslint/node_modules/globals/globals.json @@ -0,0 +1,749 @@ +{ + "builtin": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "System": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "nonstandard": { + "escape": false, + "unescape": false + }, + "browser": { + "addEventListener": false, + "alert": false, + "applicationCache": false, + "atob": false, + "Audio": false, + "AudioProcessingEvent": false, + "BeforeUnloadEvent": false, + "Blob": false, + "blur": false, + "btoa": false, + "cancelAnimationFrame": false, + "CanvasGradient": false, + "CanvasPattern": false, + "CanvasRenderingContext2D": false, + "clearInterval": false, + "clearTimeout": false, + "close": false, + "closed": false, + "CloseEvent": false, + "Comment": false, + "CompositionEvent": false, + "confirm": false, + "console": false, + "crypto": false, + "CSS": false, + "CustomEvent": false, + "DataView": false, + "Debug": false, + "defaultStatus": false, + "devicePixelRatio": false, + "dispatchEvent": false, + "document": false, + "Document": false, + "DocumentFragment": false, + "DOMParser": false, + "DragEvent": false, + "Element": false, + "ElementTimeControl": false, + "ErrorEvent": false, + "event": false, + "Event": false, + "FileReader": false, + "fetch": false, + "find": false, + "focus": false, + "FocusEvent": false, + "FormData": false, + "frameElement": false, + "frames": false, + "GamepadEvent": false, + "getComputedStyle": false, + "getSelection": false, + "HashChangeEvent": false, + "Headers": false, + "history": false, + "HTMLAnchorElement": false, + "HTMLBaseElement": false, + "HTMLBlockquoteElement": false, + "HTMLBodyElement": false, + "HTMLBRElement": false, + "HTMLButtonElement": false, + "HTMLCanvasElement": false, + "HTMLDirectoryElement": false, + "HTMLDivElement": false, + "HTMLDListElement": false, + "HTMLElement": false, + "HTMLFieldSetElement": false, + "HTMLFontElement": false, + "HTMLFormElement": false, + "HTMLFrameElement": false, + "HTMLFrameSetElement": false, + "HTMLHeadElement": false, + "HTMLHeadingElement": false, + "HTMLHRElement": false, + "HTMLHtmlElement": false, + "HTMLIFrameElement": false, + "HTMLImageElement": false, + "HTMLInputElement": false, + "HTMLIsIndexElement": false, + "HTMLLabelElement": false, + "HTMLLayerElement": false, + "HTMLLegendElement": false, + "HTMLLIElement": false, + "HTMLLinkElement": false, + "HTMLMapElement": false, + "HTMLMenuElement": false, + "HTMLMetaElement": false, + "HTMLModElement": false, + "HTMLObjectElement": false, + "HTMLOListElement": false, + "HTMLOptGroupElement": false, + "HTMLOptionElement": false, + "HTMLParagraphElement": false, + "HTMLParamElement": false, + "HTMLPreElement": false, + "HTMLQuoteElement": false, + "HTMLScriptElement": false, + "HTMLSelectElement": false, + "HTMLStyleElement": false, + "HTMLTableCaptionElement": false, + "HTMLTableCellElement": false, + "HTMLTableColElement": false, + "HTMLTableElement": false, + "HTMLTableRowElement": false, + "HTMLTableSectionElement": false, + "HTMLTextAreaElement": false, + "HTMLTitleElement": false, + "HTMLUListElement": false, + "HTMLVideoElement": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBEnvironment": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "Image": false, + "indexedDB": false, + "innerHeight": false, + "innerWidth": false, + "InputEvent": false, + "Intl": false, + "KeyboardEvent": false, + "length": false, + "localStorage": false, + "location": false, + "matchMedia": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "MouseEvent": false, + "moveBy": false, + "moveTo": false, + "MutationObserver": false, + "name": false, + "navigator": false, + "Node": false, + "NodeFilter": false, + "NodeList": false, + "Notification": false, + "OfflineAudioCompletionEvent": false, + "onbeforeunload": true, + "onblur": true, + "onerror": true, + "onfocus": true, + "onload": true, + "onresize": true, + "onunload": true, + "open": false, + "openDatabase": false, + "opener": false, + "opera": false, + "Option": false, + "outerHeight": false, + "outerWidth": false, + "PageTransitionEvent": false, + "pageXOffset": false, + "pageYOffset": false, + "parent": false, + "PopStateEvent": false, + "postMessage": false, + "print": false, + "ProgressEvent": false, + "prompt": false, + "Range": false, + "Request": false, + "Response": false, + "removeEventListener": false, + "requestAnimationFrame": false, + "resizeBy": false, + "resizeTo": false, + "screen": false, + "screenX": false, + "screenY": false, + "scroll": false, + "scrollbars": false, + "scrollBy": false, + "scrollTo": false, + "scrollX": false, + "scrollY": false, + "self": false, + "sessionStorage": false, + "setInterval": false, + "setTimeout": false, + "SharedWorker": false, + "showModalDialog": false, + "status": false, + "stop": false, + "StorageEvent": false, + "SVGAElement": false, + "SVGAltGlyphDefElement": false, + "SVGAltGlyphElement": false, + "SVGAltGlyphItemElement": false, + "SVGAngle": false, + "SVGAnimateColorElement": false, + "SVGAnimatedAngle": false, + "SVGAnimatedBoolean": false, + "SVGAnimatedEnumeration": false, + "SVGAnimatedInteger": false, + "SVGAnimatedLength": false, + "SVGAnimatedLengthList": false, + "SVGAnimatedNumber": false, + "SVGAnimatedNumberList": false, + "SVGAnimatedPathData": false, + "SVGAnimatedPoints": false, + "SVGAnimatedPreserveAspectRatio": false, + "SVGAnimatedRect": false, + "SVGAnimatedString": false, + "SVGAnimatedTransformList": false, + "SVGAnimateElement": false, + "SVGAnimateMotionElement": false, + "SVGAnimateTransformElement": false, + "SVGAnimationElement": false, + "SVGCircleElement": false, + "SVGClipPathElement": false, + "SVGColor": false, + "SVGColorProfileElement": false, + "SVGColorProfileRule": false, + "SVGComponentTransferFunctionElement": false, + "SVGCSSRule": false, + "SVGCursorElement": false, + "SVGDefsElement": false, + "SVGDescElement": false, + "SVGDocument": false, + "SVGElement": false, + "SVGElementInstance": false, + "SVGElementInstanceList": false, + "SVGEllipseElement": false, + "SVGEvent": false, + "SVGExternalResourcesRequired": false, + "SVGFEBlendElement": false, + "SVGFEColorMatrixElement": false, + "SVGFEComponentTransferElement": false, + "SVGFECompositeElement": false, + "SVGFEConvolveMatrixElement": false, + "SVGFEDiffuseLightingElement": false, + "SVGFEDisplacementMapElement": false, + "SVGFEDistantLightElement": false, + "SVGFEFloodElement": false, + "SVGFEFuncAElement": false, + "SVGFEFuncBElement": false, + "SVGFEFuncGElement": false, + "SVGFEFuncRElement": false, + "SVGFEGaussianBlurElement": false, + "SVGFEImageElement": false, + "SVGFEMergeElement": false, + "SVGFEMergeNodeElement": false, + "SVGFEMorphologyElement": false, + "SVGFEOffsetElement": false, + "SVGFEPointLightElement": false, + "SVGFESpecularLightingElement": false, + "SVGFESpotLightElement": false, + "SVGFETileElement": false, + "SVGFETurbulenceElement": false, + "SVGFilterElement": false, + "SVGFilterPrimitiveStandardAttributes": false, + "SVGFitToViewBox": false, + "SVGFontElement": false, + "SVGFontFaceElement": false, + "SVGFontFaceFormatElement": false, + "SVGFontFaceNameElement": false, + "SVGFontFaceSrcElement": false, + "SVGFontFaceUriElement": false, + "SVGForeignObjectElement": false, + "SVGGElement": false, + "SVGGlyphElement": false, + "SVGGlyphRefElement": false, + "SVGGradientElement": false, + "SVGHKernElement": false, + "SVGICCColor": false, + "SVGImageElement": false, + "SVGLangSpace": false, + "SVGLength": false, + "SVGLengthList": false, + "SVGLinearGradientElement": false, + "SVGLineElement": false, + "SVGLocatable": false, + "SVGMarkerElement": false, + "SVGMaskElement": false, + "SVGMatrix": false, + "SVGMetadataElement": false, + "SVGMissingGlyphElement": false, + "SVGMPathElement": false, + "SVGNumber": false, + "SVGNumberList": false, + "SVGPaint": false, + "SVGPathElement": false, + "SVGPathSeg": false, + "SVGPathSegArcAbs": false, + "SVGPathSegArcRel": false, + "SVGPathSegClosePath": false, + "SVGPathSegCurvetoCubicAbs": false, + "SVGPathSegCurvetoCubicRel": false, + "SVGPathSegCurvetoCubicSmoothAbs": false, + "SVGPathSegCurvetoCubicSmoothRel": false, + "SVGPathSegCurvetoQuadraticAbs": false, + "SVGPathSegCurvetoQuadraticRel": false, + "SVGPathSegCurvetoQuadraticSmoothAbs": false, + "SVGPathSegCurvetoQuadraticSmoothRel": false, + "SVGPathSegLinetoAbs": false, + "SVGPathSegLinetoHorizontalAbs": false, + "SVGPathSegLinetoHorizontalRel": false, + "SVGPathSegLinetoRel": false, + "SVGPathSegLinetoVerticalAbs": false, + "SVGPathSegLinetoVerticalRel": false, + "SVGPathSegList": false, + "SVGPathSegMovetoAbs": false, + "SVGPathSegMovetoRel": false, + "SVGPatternElement": false, + "SVGPoint": false, + "SVGPointList": false, + "SVGPolygonElement": false, + "SVGPolylineElement": false, + "SVGPreserveAspectRatio": false, + "SVGRadialGradientElement": false, + "SVGRect": false, + "SVGRectElement": false, + "SVGRenderingIntent": false, + "SVGScriptElement": false, + "SVGSetElement": false, + "SVGStopElement": false, + "SVGStringList": false, + "SVGStylable": false, + "SVGStyleElement": false, + "SVGSVGElement": false, + "SVGSwitchElement": false, + "SVGSymbolElement": false, + "SVGTests": false, + "SVGTextContentElement": false, + "SVGTextElement": false, + "SVGTextPathElement": false, + "SVGTextPositioningElement": false, + "SVGTitleElement": false, + "SVGTransform": false, + "SVGTransformable": false, + "SVGTransformList": false, + "SVGTRefElement": false, + "SVGTSpanElement": false, + "SVGUnitTypes": false, + "SVGURIReference": false, + "SVGUseElement": false, + "SVGViewElement": false, + "SVGViewSpec": false, + "SVGVKernElement": false, + "SVGZoomAndPan": false, + "Text": false, + "TextDecoder": false, + "TextEncoder": false, + "TimeEvent": false, + "top": false, + "TouchEvent": false, + "UIEvent": false, + "URL": false, + "WebGLActiveInfo": false, + "WebGLBuffer": false, + "WebGLContextEvent": false, + "WebGLFramebuffer": false, + "WebGLProgram": false, + "WebGLRenderbuffer": false, + "WebGLRenderingContext": false, + "WebGLShader": false, + "WebGLShaderPrecisionFormat": false, + "WebGLTexture": false, + "WebGLUniformLocation": false, + "WebSocket": false, + "WheelEvent": false, + "window": false, + "Window": false, + "Worker": false, + "XDomainRequest": false, + "XMLHttpRequest": false, + "XMLSerializer": false, + "XPathEvaluator": false, + "XPathException": false, + "XPathExpression": false, + "XPathNamespace": false, + "XPathNSResolver": false, + "XPathResult": false + }, + "worker": { + "importScripts": true, + "postMessage": true, + "self": true + }, + "node": { + "__dirname": false, + "__filename": false, + "arguments": false, + "Buffer": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "console": false, + "DataView": false, + "exports": true, + "GLOBAL": false, + "global": false, + "module": false, + "process": false, + "require": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false + }, + "amd": { + "define": false, + "require": false + }, + "mocha": { + "after": false, + "afterEach": false, + "before": false, + "beforeEach": false, + "context": false, + "describe": false, + "it": false, + "setup": false, + "specify": false, + "suite": false, + "suiteSetup": false, + "suiteTeardown": false, + "teardown": false, + "test": false, + "xcontext": false, + "xdescribe": false, + "xit": false, + "xspecify": false + }, + "jasmine": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "fail": false, + "fdescribe": false, + "fit": false, + "it": false, + "jasmine": false, + "pending": false, + "runs": false, + "spyOn": false, + "waits": false, + "waitsFor": false, + "xdescribe": false, + "xit": false + }, + "qunit": { + "asyncTest": false, + "deepEqual": false, + "equal": false, + "expect": false, + "module": false, + "notDeepEqual": false, + "notEqual": false, + "notPropEqual": false, + "notStrictEqual": false, + "ok": false, + "propEqual": false, + "QUnit": false, + "raises": false, + "start": false, + "stop": false, + "strictEqual": false, + "test": false, + "throws": false + }, + "phantomjs": { + "console": true, + "exports": true, + "phantom": true, + "require": true, + "WebPage": true + }, + "couch": { + "emit": false, + "exports": false, + "getRow": false, + "log": false, + "module": false, + "provides": false, + "require": false, + "respond": false, + "send": false, + "start": false, + "sum": false + }, + "rhino": { + "defineClass": false, + "deserialize": false, + "gc": false, + "help": false, + "importClass": false, + "importPackage": false, + "java": false, + "load": false, + "loadClass": false, + "Packages": false, + "print": false, + "quit": false, + "readFile": false, + "readUrl": false, + "runCommand": false, + "seal": false, + "serialize": false, + "spawn": false, + "sync": false, + "toint32": false, + "version": false + }, + "wsh": { + "ActiveXObject": true, + "Enumerator": true, + "GetObject": true, + "ScriptEngine": true, + "ScriptEngineBuildVersion": true, + "ScriptEngineMajorVersion": true, + "ScriptEngineMinorVersion": true, + "VBArray": true, + "WScript": true, + "WSH": true, + "XDomainRequest": true + }, + "jquery": { + "$": false, + "jQuery": false + }, + "yui": { + "Y": false, + "YUI": false, + "YUI_config": false + }, + "shelljs": { + "cat": false, + "cd": false, + "chmod": false, + "config": false, + "cp": false, + "dirs": false, + "echo": false, + "env": false, + "error": false, + "exec": false, + "exit": false, + "find": false, + "grep": false, + "ls": false, + "mkdir": false, + "mv": false, + "popd": false, + "pushd": false, + "pwd": false, + "rm": false, + "sed": false, + "target": false, + "tempdir": false, + "test": false, + "which": false + }, + "prototypejs": { + "$": false, + "$$": false, + "$A": false, + "$break": false, + "$continue": false, + "$F": false, + "$H": false, + "$R": false, + "$w": false, + "Abstract": false, + "Ajax": false, + "Autocompleter": false, + "Builder": false, + "Class": false, + "Control": false, + "Draggable": false, + "Draggables": false, + "Droppables": false, + "Effect": false, + "Element": false, + "Enumerable": false, + "Event": false, + "Field": false, + "Form": false, + "Hash": false, + "Insertion": false, + "ObjectRange": false, + "PeriodicalExecuter": false, + "Position": false, + "Prototype": false, + "Scriptaculous": false, + "Selector": false, + "Sortable": false, + "SortableObserver": false, + "Sound": false, + "Template": false, + "Toggle": false, + "Try": false + }, + "meteor": { + "$": false, + "_": false, + "Accounts": false, + "App": false, + "Assets": false, + "Blaze": false, + "check": false, + "Cordova": false, + "DDP": false, + "DDPServer": false, + "Deps": false, + "EJSON": false, + "Email": false, + "HTTP": false, + "Log": false, + "Match": false, + "Meteor": false, + "Mongo": false, + "MongoInternals": false, + "Npm": false, + "Package": false, + "Plugin": false, + "process": false, + "Random": false, + "ReactiveDict": false, + "ReactiveVar": false, + "Router": false, + "Session": false, + "share": false, + "Spacebars": false, + "Template": false, + "Tinytest": false, + "Tracker": false, + "UI": false, + "Utils": false, + "WebApp": false, + "WebAppInternals": false + }, + "mongo": { + "_isWindows": false, + "_rand": false, + "BulkWriteResult": false, + "cat": false, + "cd": false, + "connect": false, + "db": false, + "getHostName": false, + "getMemInfo": false, + "hostname": false, + "listFiles": false, + "load": false, + "ls": false, + "md5sumFile": false, + "mkdir": false, + "Mongo": false, + "ObjectId": false, + "PlanCache": false, + "pwd": false, + "quit": false, + "removeFile": false, + "rs": false, + "sh": false, + "UUID": false, + "version": false, + "WriteResult": false + }, + "applescript": { + "$": false, + "Application": false, + "Automation": false, + "console": false, + "delay": false, + "Library": false, + "ObjC": false, + "ObjectSpecifier": false, + "Path": false, + "Progress": false, + "Ref": false + } +} diff --git a/tools/eslint/node_modules/globals/index.js b/tools/eslint/node_modules/globals/index.js new file mode 100644 index 00000000000000..a02ef2485f059b --- /dev/null +++ b/tools/eslint/node_modules/globals/index.js @@ -0,0 +1 @@ +module.exports = require('./globals.json'); diff --git a/tools/eslint/node_modules/globals/license b/tools/eslint/node_modules/globals/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/globals/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/globals/package.json b/tools/eslint/node_modules/globals/package.json new file mode 100644 index 00000000000000..292823c7b314c5 --- /dev/null +++ b/tools/eslint/node_modules/globals/package.json @@ -0,0 +1,73 @@ +{ + "name": "globals", + "version": "6.4.1", + "description": "Global identifiers from different JavaScript environments", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/globals.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js", + "globals.json" + ], + "keywords": [ + "globals", + "global", + "identifiers", + "variables", + "vars", + "jshint", + "eslint", + "environments" + ], + "devDependencies": { + "mocha": "*" + }, + "gitHead": "c8e9f2aba0eaea2a732452667a386178ddd6bcb7", + "bugs": { + "url": "https://github.com/sindresorhus/globals/issues" + }, + "homepage": "https://github.com/sindresorhus/globals", + "_id": "globals@6.4.1", + "_shasum": "8498032b3b6d1cc81eebc5f79690d8fe29fabf4f", + "_from": "globals@>=6.1.0 <7.0.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + }, + { + "name": "lo1tuma", + "email": "schreck.mathias@gmail.com" + } + ], + "dist": { + "shasum": "8498032b3b6d1cc81eebc5f79690d8fe29fabf4f", + "tarball": "http://registry.npmjs.org/globals/-/globals-6.4.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/globals/-/globals-6.4.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/globals/readme.md b/tools/eslint/node_modules/globals/readme.md new file mode 100644 index 00000000000000..dc23c97f35433c --- /dev/null +++ b/tools/eslint/node_modules/globals/readme.md @@ -0,0 +1,39 @@ +# globals [![Build Status](https://travis-ci.org/sindresorhus/globals.svg?branch=master)](https://travis-ci.org/sindresorhus/globals) + +> Global identifiers from different JavaScript environments + +Extracted from [JSHint](https://github.com/jshint/jshint/blob/master/src/vars.js) and [ESLint](https://github.com/nzakas/eslint/blob/master/conf/environments.json) and merged. + +It's just a [JSON file](globals.json), so use it in whatever environment you like. + + +## Install + +``` +$ npm install --save globals +``` + + +## Usage + +```js +var globals = require('globals'); + +console.log(globals.browser); +/* +{ + addEventListener: false, + applicationCache: false, + ArrayBuffer: false, + atob: false, + ... +} +*/ +``` + +Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/js-yaml/CHANGELOG.md b/tools/eslint/node_modules/js-yaml/CHANGELOG.md new file mode 100644 index 00000000000000..4cddf198842d44 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/CHANGELOG.md @@ -0,0 +1,292 @@ +3.3.0 / 2015-04-26 +------------------ + +- Significantly improved long strings formatting in dumper, thanks to @isaacs. +- Strip BOM if exists. + + +3.2.7 / 2015-02-19 +------------------ + +- Maintenance release. +- Updated dependencies. +- HISTORY.md -> CHANGELOG.md + + +3.2.6 / 2015-02-07 +------------------ + +- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). +- Fixed demo dates dump (#113, thanks to @Hypercubed). + + +3.2.5 / 2014-12-28 +------------------ + +- Fixed resolving of all built-in types on empty nodes. +- Fixed invalid warning on empty lines within quoted scalars and flow collections. +- Fixed bug: Tag on an empty node didn't resolve in some cases. + + +3.2.4 / 2014-12-19 +------------------ + +- Fixed resolving of !!null tag on an empty node. + + +3.2.3 / 2014-11-08 +------------------ + +- Implemented dumping of objects with circular and cross references. +- Partially fixed aliasing of constructed objects. (see issue #141 for details) + + +3.2.2 / 2014-09-07 +------------------ + +- Fixed infinite loop on unindented block scalars. +- Rewritten base64 encode/decode in binary type, to keep code licence clear. + + +3.2.1 / 2014-08-24 +------------------ + +- Nothig new. Just fix npm publish error. + + +3.2.0 / 2014-08-24 +------------------ + +- Added input piping support to CLI. +- Fixed typo, that could cause hand on initial indent (#139). + + +3.1.0 / 2014-07-07 +------------------ + +- 1.5x-2x speed boost. +- Removed deprecated `require('xxx.yml')` support. +- Significant code cleanup and refactoring. +- Internal API changed. If you used custom types - see updated examples. + Others are not affected. +- Even if the input string has no trailing line break character, + it will be parsed as if it has one. +- Added benchmark scripts. +- Moved bower files to /dist folder +- Bugfixes. + + +3.0.2 / 2014-02-27 +------------------ + +- Fixed bug: "constructor" string parsed as `null`. + + +3.0.1 / 2013-12-22 +------------------ + +- Fixed parsing of literal scalars. (issue #108) +- Prevented adding unnecessary spaces in object dumps. (issue #68) +- Fixed dumping of objects with very long (> 1024 in length) keys. + + +3.0.0 / 2013-12-16 +------------------ + +- Refactored code. Changed API for custom types. +- Removed output colors in CLI, dump json by default. +- Removed big dependencies from browser version (esprima, buffer) + - load `esprima` manually, if !!js/function needed + - !!bin now returns Array in browser +- AMD support. +- Don't quote dumped strings because of `-` & `?` (if not first char). +- __Deprecated__ loading yaml files via `require()`, as not recommended + behaviour for node. + + +2.1.3 / 2013-10-16 +------------------ + +- Fix wrong loading of empty block scalars. + + +2.1.2 / 2013-10-07 +------------------ + +- Fix unwanted line breaks in folded scalars. + + +2.1.1 / 2013-10-02 +------------------ + +- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 +- Fixed reader bug in JSON-like sequences/mappings. + + +2.1.0 / 2013-06-05 +------------------ + +- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), + JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). +- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` + and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`. +- Bug fix: export `NIL` constant from the public interface. +- Add `skipInvalid` dumper option. +- Use `safeLoad` for `require` extension. + + +2.0.5 / 2013-04-26 +------------------ + +- Close security issue in !!js/function constructor. + Big thanks to @nealpoole for security audit. + + +2.0.4 / 2013-04-08 +------------------ + +- Updated .npmignore to reduce package size + + +2.0.3 / 2013-02-26 +------------------ + +- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) + + +2.0.2 / 2013-02-15 +------------------ + +- Fixed input validation: tabs are printable characters. + + +2.0.1 / 2013-02-09 +------------------ + +- Fixed error, when options not passed to function cass + + +2.0.0 / 2013-02-09 +------------------ + +- Full rewrite. New architecture. Fast one-stage parsing. +- Changed custom types API. +- Added YAML dumper. + + +1.0.3 / 2012-11-05 +------------------ + +- Fixed utf-8 files loading. + + +1.0.2 / 2012-08-02 +------------------ + +- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. +- Fix timstamps incorectly parsed in local time when no time part specified. + + +1.0.1 / 2012-07-07 +------------------ + +- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. +- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. + + +1.0.0 / 2012-07-01 +------------------ + +- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. + Fixes #42. +- `require(filename)` now returns a single document and throws an Error if + file contains more than one document. +- CLI was merged back from js-yaml.bin + + +0.3.7 / 2012-02-28 +------------------ + +- Fix export of `addConstructor()`. Closes #39. + + +0.3.6 / 2012-02-22 +------------------ + +- Removed AMD parts - too buggy to use. Need help to rewrite from scratch +- Removed YUI compressor warning (renamed `double` variable). Closes #40. + + +0.3.5 / 2012-01-10 +------------------ + +- Workagound for .npmignore fuckup under windows. Thanks to airportyh. + + +0.3.4 / 2011-12-24 +------------------ + +- Fixes str[] for oldIEs support. +- Adds better has change support for browserified demo. +- improves compact output of Error. Closes #33. + + +0.3.3 / 2011-12-20 +------------------ + +- jsyaml executable moved to separate module. +- adds `compact` stringification of Errors. + + +0.3.2 / 2011-12-16 +------------------ + +- Fixes ug with block style scalars. Closes #26. +- All sources are passing JSLint now. +- Fixes bug in Safari. Closes #28. +- Fixes bug in Opers. Closes #29. +- Improves browser support. Closes #20. +- Added jsyaml executable. +- Added !!js/function support. Closes #12. + + +0.3.1 / 2011-11-18 +------------------ + +- Added AMD support for browserified version. +- Wrapped browserified js-yaml into closure. +- Fixed the resolvement of non-specific tags. Closes #17. +- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol. +- Added !!js/regexp and !!js/undefined types. Partially solves #12. +- Fixed !!set mapping. +- Fixed month parse in dates. Closes #19. + + +0.3.0 / 2011-11-09 +------------------ + +- Removed JS.Class dependency. Closes #3. +- Added browserified version. Closes #13. +- Added live demo of browserified version. +- Ported some of the PyYAML tests. See #14. +- Fixed timestamp bug when fraction was given. + + +0.2.2 / 2011-11-06 +------------------ + +- Fixed crash on docs without ---. Closes #8. +- Fixed miltiline string parse +- Fixed tests/comments for using array as key + + +0.2.1 / 2011-11-02 +------------------ + +- Fixed short file read (<4k). Closes #9. + + +0.2.0 / 2011-11-02 +------------------ + +- First public release diff --git a/tools/eslint/node_modules/js-yaml/LICENSE b/tools/eslint/node_modules/js-yaml/LICENSE new file mode 100644 index 00000000000000..09d3a29e93d123 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2011-2015 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/js-yaml/README.md b/tools/eslint/node_modules/js-yaml/README.md new file mode 100644 index 00000000000000..c181df1645eb21 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/README.md @@ -0,0 +1,288 @@ +JS-YAML - YAML 1.2 parser and serializer for JavaScript +======================================================= + +[![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) +[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) + +[Online Demo](http://nodeca.github.com/js-yaml/) + + +This is an implementation of [YAML](http://yaml.org/), a human friendly data +serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was +completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. + + +Installation +------------ + +### YAML module for node.js + +``` +npm install js-yaml +``` + + +### CLI executable + +If you want to inspect your YAML files from CLI, install js-yaml globally: + +``` +npm install -g js-yaml +``` + +#### Usage + +``` +usage: js-yaml [-h] [-v] [-c] [-t] file + +Positional arguments: + file File with YAML document(s) + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -c, --compact Display errors in compact mode + -t, --trace Show stack trace on error +``` + + +### Bundled YAML library for browsers + +``` html + + + + +``` + +Browser support was done mostly for online demo. If you find any errors - feel +free to send pull requests with fixes. Also note, that IE and other old browsers +needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. + +Notes: + +1. We have no resourses to support browserified version. Don't expect it to be + well tested. Don't expect fast fixes if something goes wrong there. +2. `!!js/function` in browser bundle will not work by default. If you really need + it - load `esprima` parser first (via amd or directly). +3. `!!bin` in browser will return `Array`, because browsers do not support + node.js `Buffer` and adding Buffer shims is completely useless on practice. + + +API +--- + +Here we cover the most 'useful' methods. If you need advanced details (creating +your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and +[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more +info. + +``` javascript +yaml = require('js-yaml'); +fs = require('fs'); + +// Get document, or throw exception on error +try { + var doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); + console.log(doc); +} catch (e) { + console.log(e); +} +``` + + +### safeLoad (string [ , options ]) + +**Recommended loading way.** Parses `string` as single YAML document. Returns a JavaScript +object or throws `YAMLException` on error. By default, does not support regexps, +functions and undefined. This method is safe for untrusted data. + +options: + +- `filename` _(default: null)_ - string to be used as a file path in + error/warning messages. +- `onWarning` _(default: null)_ - function to call on warning messages. + Loader will throw on warnings if this function is not provided. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. + - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: + http://www.yaml.org/spec/1.2/spec.html#id2802346 + - `JSON_SCHEMA` - all JSON-supported types: + http://www.yaml.org/spec/1.2/spec.html#id2803231 + - `CORE_SCHEMA` - same as `JSON_SCHEMA`: + http://www.yaml.org/spec/1.2/spec.html#id2804923 + - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones + (`!!js/undefined`, `!!js/regexp` and `!!js/function`): + http://yaml.org/type/ + - `DEFAULT_FULL_SCHEMA` - all supported YAML types. + +NOTE: This function **does not** understand multi-document sources, it throws +exception on those. + +NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. +So, JSON schema is not as strict as defined in the YAML specification. +It allows numbers in any notaion, use `Null` and `NULL` as `null`, etc. +Core schema also has no such restrictions. It allows binary notation for integers. + + +### load (string [ , options ]) + +**Use with care with untrusted sources**. The same as `safeLoad()` but uses +`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: +`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources you +must additionally validate object structure, to avoid injections: + +``` javascript +var untrusted_code = '"toString": ! "function (){very_evil_thing();}"'; + +// I'm just converting that string, what could possibly go wrong? +require('js-yaml').load(untrusted_code) + '' +``` + + +### safeLoadAll (string, iterator [ , options ]) + +Same as `safeLoad()`, but understands multi-document sources and apply +`iterator` to each document. + +``` javascript +var yaml = require('js-yaml'); + +yaml.safeLoadAll(data, function (doc) { + console.log(doc); +}); +``` + + +### loadAll (string, iterator [ , options ]) + +Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. + + +### safeDump (object [ , options ]) + +Serializes `object` as YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will +throw exception if you try to dump regexps or functions. However, you can +disable exceptions by `skipInvalid` option. + +options: + +- `indent` _(default: 2)_ - indentation width to use (in spaces). +- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function + in the safe schema) and skip pairs and single values with such types. +- `flowLevel` (default: -1) - specifies level of nesting, when to switch from + block to flow style for collections. -1 means block style everwhere +- `styles` - "tag" => "style" map. Each tag may have own set of styles. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. + +styles: + +``` none +!!null + "canonical" => "~" + +!!int + "binary" => "0b1", "0b101010", "0b1110001111010" + "octal" => "01", "052", "016172" + "decimal" => "1", "42", "7290" + "hexadecimal" => "0x1", "0x2A", "0x1C7A" + +!!null, !!bool, !!float + "lowercase" => "null", "true", "false", ".nan", '.inf' + "uppercase" => "NULL", "TRUE", "FALSE", ".NAN", '.INF' + "camelcase" => "Null", "True", "False", ".NaN", '.Inf' +``` + +By default, !!int uses `decimal`, and !!null, !!bool, !!float use `lowercase`. + + + +### dump (object [ , options ]) + +Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). + + +Supported YAML types +-------------------- + +The list of standard YAML tags and corresponding JavaScipt types. See also +[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and +[YAML types repository](http://yaml.org/type/). + +``` +!!null '' # null +!!bool 'yes' # bool +!!int '3...' # number +!!float '3.14...' # number +!!binary '...base64...' # buffer +!!timestamp 'YYYY-...' # date +!!omap [ ... ] # array of key-value pairs +!!pairs [ ... ] # array or array pairs +!!set { ... } # array of objects with given keys and null values +!!str '...' # string +!!seq [ ... ] # array +!!map { ... } # object +``` + +**JavaScript-specific tags** + +``` +!!js/regexp /pattern/gim # RegExp +!!js/undefined '' # Undefined +!!js/function 'function () {...}' # Function +``` + +Caveats +------- + +Note, that you use arrays or objects as key in JS-YAML. JS do not allows objects +or array as keys, and stringifies (by calling .toString method) them at the +moment of adding them. + +``` yaml +--- +? [ foo, bar ] +: - baz +? { foo: bar } +: - baz + - baz +``` + +``` javascript +{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } +``` + +Also, reading of properties on implicit block mapping keys is not supported yet. +So, the following YAML document cannot be loaded. + +``` yaml +&anchor foo: + foo: bar + *anchor: duplicate key + baz: bat + *anchor: duplicate key +``` + + +Breaking changes in 2.x.x -> 3.x.x +---------------------------------- + +If your have not used __custom__ tags or loader classes and not loaded yaml +files via `require()` - no changes needed. Just upgrade library. + +In other case, you should: + +1. Replace all occurences of `require('xxxx.yml')` by `fs.readFileSync()` + + `yaml.safeLoad()`. +2. rewrite your custom tags constructors and custom loader + classes, to conform new API. See + [examples](https://github.com/nodeca/js-yaml/tree/master/examples) and + [wiki](https://github.com/nodeca/js-yaml/wiki) for details. + + +License +------- + +View the [LICENSE](https://github.com/nodeca/js-yaml/blob/master/LICENSE) file +(MIT). diff --git a/tools/eslint/node_modules/js-yaml/bin/js-yaml.js b/tools/eslint/node_modules/js-yaml/bin/js-yaml.js new file mode 100755 index 00000000000000..e6029d64ce23eb --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/bin/js-yaml.js @@ -0,0 +1,142 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +// stdlib +var fs = require('fs'); + + +// 3rd-party +var argparse = require('argparse'); + + +// internal +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + version: require('../package.json').version, + addHelp: true +}); + + +cli.addArgument([ '-c', '--compact' ], { + help: 'Display errors in compact mode', + action: 'storeTrue' +}); + + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.addArgument([ '-j', '--to-json' ], { + help: argparse.Const.SUPPRESS, + dest: 'json', + action: 'storeTrue' +}); + + +cli.addArgument([ '-t', '--trace' ], { + help: 'Show stack trace on error', + action: 'storeTrue' +}); + +cli.addArgument([ 'file' ], { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + defaultValue: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parseArgs(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (error) { + if (error instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (0 === output.length) { + output = null; + } else if (1 === output.length) { + output = output[0]; + } + } catch (error) { + if (options.trace && error.stack) { + console.error(error.stack); + } else { + console.error(error.toString(options.compact)); + } + + process.exit(1); + } + } else { + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + } + + if (isYaml) { + console.log(JSON.stringify(output, null, ' ')); + } else { + console.log(yaml.dump(output)); + } + + process.exit(0); +}); diff --git a/tools/eslint/node_modules/js-yaml/bower.json b/tools/eslint/node_modules/js-yaml/bower.json new file mode 100644 index 00000000000000..010912f10f9d55 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/bower.json @@ -0,0 +1,23 @@ + +{ + "name": "js-yaml", + "main": "dist/js-yaml.js", + "homepage": "https://github.com/nodeca/js-yaml", + "authors": [ "Dervus Grim ", + "Vitaly Puzrin ", + "Aleksey V Zapparov ", + "Martin Grenfell " ], + "description": "YAML 1.2 parser and serializer", + "keywords": ["yaml", "parser", "serializer", "pyyaml"], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "benchmark", + "bower_components", + "test", + "Makefile", + "index*", + "package.json" + ] +} diff --git a/tools/eslint/node_modules/js-yaml/dist/js-yaml.js b/tools/eslint/node_modules/js-yaml/dist/js-yaml.js new file mode 100644 index 00000000000000..f917fea9940ac3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/dist/js-yaml.js @@ -0,0 +1,3947 @@ +/* js-yaml 3.3.0 https://github.com/nodeca/js-yaml */!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.jsyaml=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (null === map) { + return {}; + } + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if ('!!' === tag.slice(0, 2)) { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + + type = schema.compiledTypeMap[tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + if (line.length && line !== '\n') { + result += ind; + } + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +function StringBuilder(source) { + this.source = source; + this.result = ''; + this.checkpoint = 0; +} + +StringBuilder.prototype.takeUpTo = function (position) { + var er; + + if (position < this.checkpoint) { + er = new Error('position should be > checkpoint'); + er.position = position; + er.checkpoint = this.checkpoint; + throw er; + } + + this.result += this.source.slice(this.checkpoint, position); + this.checkpoint = position; + return this; +}; + +StringBuilder.prototype.escapeChar = function () { + var character, esc; + + character = this.source.charCodeAt(this.checkpoint); + esc = ESCAPE_SEQUENCES[character] || encodeHex(character); + this.result += esc; + this.checkpoint += 1; + + return this; +}; + +StringBuilder.prototype.finish = function () { + if (this.source.length > this.checkpoint) { + this.takeUpTo(this.source.length); + } +}; + +function writeScalar(state, object, level) { + var simple, first, spaceWrap, folded, literal, single, double, + sawLineFeed, linePosition, longestLine, indent, max, character, + position, escapeSeq, hexEsc, previous, lineLength, modifier, + trailingLineBreaks, result; + + if (0 === object.length) { + state.dump = "''"; + return; + } + + if (-1 !== DEPRECATED_BOOLEANS_SYNTAX.indexOf(object)) { + state.dump = "'" + object + "'"; + return; + } + + simple = true; + first = object.length ? object.charCodeAt(0) : 0; + spaceWrap = (CHAR_SPACE === first || + CHAR_SPACE === object.charCodeAt(object.length - 1)); + + // Simplified check for restricted first characters + // http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29 + if (CHAR_MINUS === first || + CHAR_QUESTION === first || + CHAR_COMMERCIAL_AT === first || + CHAR_GRAVE_ACCENT === first) { + simple = false; + } + + // can only use > and | if not wrapped in spaces. + if (spaceWrap) { + simple = false; + folded = false; + literal = false; + } else { + folded = true; + literal = true; + } + + single = true; + double = new StringBuilder(object); + + sawLineFeed = false; + linePosition = 0; + longestLine = 0; + + indent = state.indent * level; + max = 80; + if (indent < 40) { + max -= indent; + } else { + max = 40; + } + + for (position = 0; position < object.length; position++) { + character = object.charCodeAt(position); + if (simple) { + // Characters that can never appear in the simple scalar + if (!simpleChar(character)) { + simple = false; + } else { + // Still simple. If we make it all the way through like + // this, then we can just dump the string as-is. + continue; + } + } + + if (single && character === CHAR_SINGLE_QUOTE) { + single = false; + } + + escapeSeq = ESCAPE_SEQUENCES[character]; + hexEsc = needsHexEscape(character); + + if (!escapeSeq && !hexEsc) { + continue; + } + + if (character !== CHAR_LINE_FEED && + character !== CHAR_DOUBLE_QUOTE && + character !== CHAR_SINGLE_QUOTE) { + folded = false; + literal = false; + } else if (character === CHAR_LINE_FEED) { + sawLineFeed = true; + single = false; + if (position > 0) { + previous = object.charCodeAt(position - 1); + if (previous === CHAR_SPACE) { + literal = false; + folded = false; + } + } + if (folded) { + lineLength = position - linePosition; + linePosition = position; + if (lineLength > longestLine) { + longestLine = lineLength; + } + } + } + + if (character !== CHAR_DOUBLE_QUOTE) { + single = false; + } + + double.takeUpTo(position); + double.escapeChar(); + } + + if (simple && testImplicitResolving(state, object)) { + simple = false; + } + + modifier = ''; + if (folded || literal) { + trailingLineBreaks = 0; + if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) { + trailingLineBreaks += 1; + if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) { + trailingLineBreaks += 1; + } + } + + if (trailingLineBreaks === 0) { + modifier = '-'; + } else if (trailingLineBreaks === 2) { + modifier = '+'; + } + } + + if (literal && longestLine < max) { + folded = false; + } + + // If it's literally one line, then don't bother with the literal. + // We may still want to do a fold, though, if it's a super long line. + if (!sawLineFeed) { + literal = false; + } + + if (simple) { + state.dump = object; + } else if (single) { + state.dump = '\'' + object + '\''; + } else if (folded) { + result = fold(object, max); + state.dump = '>' + modifier + '\n' + indentString(result, indent); + } else if (literal) { + if (!modifier) { + object = object.replace(/\n$/, ''); + } + state.dump = '|' + modifier + '\n' + indentString(object, indent); + } else if (double) { + double.finish(); + state.dump = '"' + double.result + '"'; + } else { + throw new Error('Failed to dump scalar value'); + } + + return; +} + +// The `trailing` var is a regexp match of any trailing `\n` characters. +// +// There are three cases we care about: +// +// 1. One trailing `\n` on the string. Just use `|` or `>`. +// This is the assumed default. (trailing = null) +// 2. No trailing `\n` on the string. Use `|-` or `>-` to "chomp" the end. +// 3. More than one trailing `\n` on the string. Use `|+` or `>+`. +// +// In the case of `>+`, these line breaks are *not* doubled (like the line +// breaks within the string), so it's important to only end with the exact +// same number as we started. +function fold(object, max) { + var result = '', + position = 0, + length = object.length, + trailing = /\n+$/.exec(object), + newLine; + + if (trailing) { + length = trailing.index + 1; + } + + while (position < length) { + newLine = object.indexOf('\n', position); + if (newLine > length || newLine === -1) { + if (result) { + result += '\n\n'; + } + result += foldLine(object.slice(position, length), max); + position = length; + } else { + if (result) { + result += '\n\n'; + } + result += foldLine(object.slice(position, newLine), max); + position = newLine + 1; + } + } + if (trailing && trailing[0] !== '\n') { + result += trailing[0]; + } + + return result; +} + +function foldLine(line, max) { + if (line === '') { + return line; + } + + var foldRe = /[^\s] [^\s]/g, + result = '', + prevMatch = 0, + foldStart = 0, + match = foldRe.exec(line), + index, + foldEnd, + folded; + + while (match) { + index = match.index; + + // when we cross the max len, if the previous match would've + // been ok, use that one, and carry on. If there was no previous + // match on this fold section, then just have a long line. + if (index - foldStart > max) { + if (prevMatch !== foldStart) { + foldEnd = prevMatch; + } else { + foldEnd = index; + } + + if (result) { + result += '\n'; + } + folded = line.slice(foldStart, foldEnd); + result += folded; + foldStart = foldEnd + 1; + } + prevMatch = index + 1; + match = foldRe.exec(line); + } + + if (result) { + result += '\n'; + } + + // if we end up with one last word at the end, then the last bit might + // be slightly bigger than we wanted, because we exited out of the loop. + if (foldStart !== prevMatch && line.length - foldStart > max) { + result += line.slice(foldStart, prevMatch) + '\n' + + line.slice(prevMatch + 1); + } else { + result += line.slice(foldStart); + } + + return result; +} + +// Returns true if character can be found in a simple scalar +function simpleChar(character) { + return CHAR_TAB !== character && + CHAR_LINE_FEED !== character && + CHAR_CARRIAGE_RETURN !== character && + CHAR_COMMA !== character && + CHAR_LEFT_SQUARE_BRACKET !== character && + CHAR_RIGHT_SQUARE_BRACKET !== character && + CHAR_LEFT_CURLY_BRACKET !== character && + CHAR_RIGHT_CURLY_BRACKET !== character && + CHAR_SHARP !== character && + CHAR_AMPERSAND !== character && + CHAR_ASTERISK !== character && + CHAR_EXCLAMATION !== character && + CHAR_VERTICAL_LINE !== character && + CHAR_GREATER_THAN !== character && + CHAR_SINGLE_QUOTE !== character && + CHAR_DOUBLE_QUOTE !== character && + CHAR_PERCENT !== character && + CHAR_COLON !== character && + !ESCAPE_SEQUENCES[character] && + !needsHexEscape(character); +} + +// Returns true if the character code needs to be escaped. +function needsHexEscape(character) { + return !((0x00020 <= character && character <= 0x00007E) || + (0x00085 === character) || + (0x000A0 <= character && character <= 0x00D7FF) || + (0x0E000 <= character && character <= 0x00FFFD) || + (0x10000 <= character && character <= 0x10FFFF)); +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (0 !== index) { + _result += ', '; + } + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || 0 !== index) { + _result += generateNextLine(state, level); + } + _result += '- ' + state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (0 !== index) { + pairBuffer += ', '; + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) { + pairBuffer += '? '; + } + + pairBuffer += state.dump + ': '; + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || 0 !== index) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (null !== state.tag && '?' !== state.tag) || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || (('object' === typeof object) && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if ('[object Function]' === _toString.call(type.represent)) { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (0 > state.flowLevel || state.flowLevel > level); + } + + if ((null !== state.tag && '?' !== state.tag) || (2 !== state.indent && level > 0)) { + compact = false; + } + + var objectOrArray = '[object Object]' === type || '[object Array]' === type, + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if ('[object Object]' === type) { + if (block && (0 !== Object.keys(state.dump).length)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if ('[object Array]' === type) { + if (block && (0 !== state.dump.length)) { + writeBlockSequence(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if ('[object String]' === type) { + if ('?' !== state.tag) { + writeScalar(state, state.dump, level); + } + } else { + if (state.skipInvalid) { + return false; + } + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (null !== state.tag && '?' !== state.tag) { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var type = _toString.call(object), + objectKeyList, + index, + length; + + if (null !== object && 'object' === typeof object) { + index = objects.indexOf(object); + if (-1 !== index) { + if (-1 === duplicatesIndexes.indexOf(index)) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) { + return state.dump + '\n'; + } + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; + +},{"./common":3,"./exception":5,"./schema/default_full":10,"./schema/default_safe":11}],5:[function(require,module,exports){ +'use strict'; + + +function YAMLException(reason, mark) { + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = this.toString(false); +} + + +YAMLException.prototype.toString = function toString(compact) { + var result; + + result = 'JS-YAML: ' + (this.reason || '(unknown reason)'); + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; + +},{}],6:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uD800-\uDFFF\uFFFE\uFFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return 0x2C/* , */ === c || + 0x5B/* [ */ === c || + 0x5D/* ] */ === c || + 0x7B/* { */ === c || + 0x7D/* } */ === c; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode(((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + var error = generateError(state, message); + + if (state.onWarning) { + state.onWarning.call(null, error); + } else { + throw error; + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (null !== state.version) { + throwError(state, 'duplication of %YAML directive'); + } + + if (1 !== args.length) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (null === match) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (1 !== major) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (1 !== minor && 2 !== minor) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (2 !== args.length) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; + _position < _length; + _position += 1) { + _character = _result.charCodeAt(_position); + if (!(0x09 === _character || + 0x20 <= _character && _character <= 0x10FFFF)) { + throwError(state, 'expected valid JSON character'); + } + } + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + } + } +} + +function storeMappingPair(state, _result, keyTag, keyNode, valueNode) { + var index, quantity; + + keyNode = String(keyNode); + + if (null === _result) { + _result = {}; + } + + if ('tag:yaml.org,2002:merge' === keyTag) { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index]); + } + } else { + mergeMappings(state, _result, valueNode); + } + } else { + _result[keyNode] = valueNode; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (0x0A/* LF */ === ch) { + state.position++; + } else if (0x0D/* CR */ === ch) { + state.position++; + if (0x0A/* LF */ === state.input.charCodeAt(state.position)) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (0 !== ch) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && 0x23/* # */ === ch) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && 0 !== ch); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (0x20/* Space */ === ch) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (-1 !== checkIndent && 0 !== lineBreaks && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((0x2D/* - */ === ch || 0x2E/* . */ === ch) && + state.input.charCodeAt(_position + 1) === ch && + state.input.charCodeAt(_position + 2) === ch) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (1 === count) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + 0x23/* # */ === ch || + 0x26/* & */ === ch || + 0x2A/* * */ === ch || + 0x21/* ! */ === ch || + 0x7C/* | */ === ch || + 0x3E/* > */ === ch || + 0x27/* ' */ === ch || + 0x22/* " */ === ch || + 0x25/* % */ === ch || + 0x40/* @ */ === ch || + 0x60/* ` */ === ch) { + return false; + } + + if (0x3F/* ? */ === ch || 0x2D/* - */ === ch) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (0 !== ch) { + if (0x3A/* : */ === ch) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (0x23/* # */ === ch) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (0x27/* ' */ !== ch) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while (0 !== (ch = state.input.charCodeAt(state.position))) { + if (0x27/* ' */ === ch) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (0x27/* ' */ === ch) { + captureStart = captureEnd = state.position; + state.position++; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, tmpEsc, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x22/* " */ !== ch) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while (0 !== (ch = state.input.charCodeAt(state.position))) { + if (0x22/* " */ === ch) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (0x5C/* \ */ === ch) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (0 !== ch) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (0x3F/* ? */ === ch) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && 0x3A/* : */ === ch) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (0x2C/* , */ === ch) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (0 !== ch) { + ch = state.input.charCodeAt(++state.position); + + if (0x2B/* + */ === ch || 0x2D/* - */ === ch) { + if (CHOMPING_CLIP === chomping) { + chomping = (0x2B/* + */ === ch) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (0x23/* # */ === ch) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (0 !== ch)); + } + } + + while (0 !== ch) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (0x20/* Space */ === ch)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (detectedIndent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + state.result += common.repeat('\n', emptyLines + 1); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (0 === emptyLines) { + if (detectedIndent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else if (detectedIndent) { + // If current line isn't the first one - count line break from the last content line. + state.result += common.repeat('\n', emptyLines + 1); + } else { + // In case of the first content line - count only empty lines. + } + + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (0 !== ch)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (0 !== ch) { + + if (0x2D/* - */ !== ch) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (0 !== ch)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (0 !== ch) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((0x3F/* ? */ === ch || 0x3A/* : */ === ch) && is_WS_OR_EOL(following)) { + + if (0x3F/* ? */ === ch) { + if (atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (0x3A/* : */ === ch) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, valueNode); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (0 !== ch)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x21/* ! */ !== ch) { + return false; + } + + if (null !== state.tag) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (0x3C/* < */ === ch) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (0x21/* ! */ === ch) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (0 !== ch && 0x3E/* > */ !== ch); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (0 !== ch && !is_WS_OR_EOL(ch)) { + + if (0x21/* ! */ === ch) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if ('!' === tagHandle) { + state.tag = '!' + tagName; + + } else if ('!!' === tagHandle) { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x26/* & */ !== ch) { + return false; + } + + if (null !== state.anchor) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + len = state.length, + input = state.input, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x2A/* * */ !== ch) { + return false; + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!state.anchorMap.hasOwnProperty(alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (1 === indentStatus) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (1 === indentStatus || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (1 === indentStatus) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (null !== state.tag || null !== state.anchor) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (null === state.tag) { + state.tag = '?'; + } + } + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (0 === indentStatus) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (null !== state.tag && '!' !== state.tag) { + if ('?' === state.tag) { + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; + typeIndex < typeQuantity; + typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only assigned to plain scalars. So, it isn't + // needed to check for 'kind' conformity. + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (null !== state.anchor) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap, state.tag)) { + type = state.typeMap[state.tag]; + + if (null !== state.result && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (null !== state.anchor) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwWarning(state, 'unknown tag !<' + state.tag + '>'); + } + } + + return null !== state.tag || null !== state.anchor || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while (0 !== (ch = state.input.charCodeAt(state.position))) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || 0x25/* % */ !== ch) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (0 !== ch) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (0x23/* # */ === ch) { + do { ch = state.input.charCodeAt(++state.position); } + while (0 !== ch && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) { + break; + } + + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (0 !== ch) { + readLineBreak(state); + } + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (0 === state.lineIndent && + 0x2D/* - */ === state.input.charCodeAt(state.position) && + 0x2D/* - */ === state.input.charCodeAt(state.position + 1) && + 0x2D/* - */ === state.input.charCodeAt(state.position + 2)) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (0x2E/* . */ === state.input.charCodeAt(state.position)) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (0x0A/* LF */ !== input.charCodeAt(input.length - 1) && + 0x0D/* CR */ !== input.charCodeAt(input.length - 1)) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + if (PATTERN_NON_PRINTABLE.test(state.input)) { + throwError(state, 'the stream contains non-printable characters'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (0x20/* Space */ === state.input.charCodeAt(state.position)) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + var documents = loadDocuments(input, options), index, length; + + for (index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options), index, length; + + if (0 === documents.length) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (1 === documents.length) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, output, options) { + loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; + +},{"./common":3,"./exception":5,"./mark":7,"./schema/default_full":10,"./schema/default_safe":11}],7:[function(require,module,exports){ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) { + return null; + } + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1))) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end))) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; + +},{"./common":3}],8:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return -1 === exclude.indexOf(index); + }); +} + + +function compileMap(/* lists... */) { + var result = {}, index, length; + + function collectType(type) { + result[type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && 'scalar' !== type.loadKind) { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; + +},{"./common":3,"./exception":5,"./type":14}],9:[function(require,module,exports){ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); + +},{"../schema":8,"./json":13}],10:[function(require,module,exports){ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); + +},{"../schema":8,"../type/js/function":19,"../type/js/regexp":20,"../type/js/undefined":21,"./default_safe":11}],11:[function(require,module,exports){ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); + +},{"../schema":8,"../type/binary":15,"../type/merge":23,"../type/omap":25,"../type/pairs":26,"../type/set":28,"../type/timestamp":30,"./core":9}],12:[function(require,module,exports){ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); + +},{"../schema":8,"../type/map":22,"../type/seq":27,"../type/str":29}],13:[function(require,module,exports){ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); + +},{"../schema":8,"../type/bool":16,"../type/float":17,"../type/int":18,"../type/null":24,"./failsafe":12}],14:[function(require,module,exports){ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (null !== map) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (-1 === TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (-1 === YAML_NODE_KINDS.indexOf(this.kind)) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + +},{"./exception":5}],15:[function(require,module,exports){ +'use strict'; + +/*eslint-disable no-bitwise*/ + +// A trick for browserified version. +// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined +var NodeBuffer = require('buffer').Buffer; +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (null === data) { + return false; + } + + var code, idx, bitlen = 0, len = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) { continue; } + + // Fail on illegal characters + if (code < 0) { return false; } + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var code, idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + return new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +},{"../type":14,"buffer":1}],16:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (null === data) { + return false; + } + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return '[object Boolean]' === Object.prototype.toString.call(object); +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":14}],17:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + '^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' + + '|\\.[0-9_]+(?:[eE][-+][0-9]+)?' + + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + '|[-+]?\\.(?:inf|Inf|INF)' + + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (null === data) { + return false; + } + + var value, sign, base, digits; + + if (!YAML_FLOAT_PATTERN.test(data)) { + return false; + } + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = '-' === value[0] ? -1 : 1; + digits = []; + + if (0 <= '+-'.indexOf(value[0])) { + value = value.slice(1); + } + + if ('.inf' === value) { + return (1 === sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if ('.nan' === value) { + return NaN; + + } else if (0 <= value.indexOf(':')) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + +function representYamlFloat(object, style) { + if (isNaN(object)) { + switch (style) { + case 'lowercase': + return '.nan'; + case 'uppercase': + return '.NAN'; + case 'camelcase': + return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': + return '.inf'; + case 'uppercase': + return '.INF'; + case 'camelcase': + return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': + return '-.inf'; + case 'uppercase': + return '-.INF'; + case 'camelcase': + return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + return object.toString(10); +} + +function isFloat(object) { + return ('[object Number]' === Object.prototype.toString.call(object)) && + (0 !== object % 1 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +},{"../common":3,"../type":14}],18:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (null === data) { + return false; + } + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) { return false; } + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) { return true; } + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (ch !== '0' && ch !== '1') { + return false; + } + hasDigits = true; + } + return hasDigits; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (!isHexCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + return hasDigits; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (!isOctCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + return hasDigits; + } + + // base 10 (except 0) or base 60 + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (ch === ':') { break; } + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + if (!hasDigits) { return false; } + + // if !base60 - done; + if (ch !== ':') { return true; } + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') { sign = -1; } + value = value.slice(1); + ch = value[0]; + } + + if ('0' === value) { + return 0; + } + + if (ch === '0') { + if (value[1] === 'b') { + return sign * parseInt(value.slice(2), 2); + } + if (value[1] === 'x') { + return sign * parseInt(value, 16); + } + return sign * parseInt(value, 8); + + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return ('[object Number]' === Object.prototype.toString.call(object)) && + (0 === object % 1 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (object) { return '0b' + object.toString(2); }, + octal: function (object) { return '0' + object.toString(8); }, + decimal: function (object) { return object.toString(10); }, + hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +},{"../common":3,"../type":14}],19:[function(require,module,exports){ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + esprima = require('esprima'); +} catch (_) { + /*global window */ + if (typeof window !== 'undefined') { esprima = window.esprima; } +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (null === data) { + return false; + } + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if ('Program' !== ast.type || + 1 !== ast.body.length || + 'ExpressionStatement' !== ast.body[0].type || + 'FunctionExpression' !== ast.body[0].expression.type) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if ('Program' !== ast.type || + 1 !== ast.body.length || + 'ExpressionStatement' !== ast.body[0].type || + 'FunctionExpression' !== ast.body[0].expression.type) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return '[object Function]' === Object.prototype.toString.call(object); +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); + +},{"../../type":14,"esprima":"esprima"}],20:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (null === data) { + return false; + } + + if (0 === data.length) { + return false; + } + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if ('/' === regexp[0]) { + if (tail) { + modifiers = tail[1]; + } + + if (modifiers.length > 3) { return false; } + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') { return false; } + + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + try { + var dummy = new RegExp(regexp, modifiers); + return true; + } catch (error) { + return false; + } +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if ('/' === regexp[0]) { + if (tail) { + modifiers = tail[1]; + } + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) { + result += 'g'; + } + + if (object.multiline) { + result += 'm'; + } + + if (object.ignoreCase) { + result += 'i'; + } + + return result; +} + +function isRegExp(object) { + return '[object RegExp]' === Object.prototype.toString.call(object); +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + +},{"../../type":14}],21:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return 'undefined' === typeof object; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); + +},{"../../type":14}],22:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return null !== data ? data : {}; } +}); + +},{"../type":14}],23:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return '<<' === data || null === data; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +},{"../type":14}],24:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (null === data) { + return true; + } + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return null === object; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":14}],25:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (null === data) { + return true; + } + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if ('[object Object]' !== _toString.call(pair)) { + return false; + } + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) { + pairHasKey = true; + } else { + return false; + } + } + } + + if (!pairHasKey) { + return false; + } + + if (-1 === objectKeys.indexOf(pairKey)) { + objectKeys.push(pairKey); + } else { + return false; + } + } + + return true; +} + +function constructYamlOmap(data) { + return null !== data ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +},{"../type":14}],26:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (null === data) { + return true; + } + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if ('[object Object]' !== _toString.call(pair)) { + return false; + } + + keys = Object.keys(pair); + + if (1 !== keys.length) { + return false; + } + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (null === data) { + return []; + } + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +},{"../type":14}],27:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return null !== data ? data : []; } +}); + +},{"../type":14}],28:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (null === data) { + return true; + } + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (null !== object[key]) { + return false; + } + } + } + + return true; +} + +function constructYamlSet(data) { + return null !== data ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +},{"../type":14}],29:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return null !== data ? data : ''; } +}); + +},{"../type":14}],30:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?)?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (null === data) { + return false; + } + + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (null === match) { + return false; + } + + return true; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (null === match) { + throw new Error('Date resolve error'); + } + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if ('-' === match[9]) { + delta = -delta; + } + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) { + date.setTime(date.getTime() - delta); + } + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +},{"../type":14}],"/":[function(require,module,exports){ +'use strict'; + + +var yaml = require('./lib/js-yaml.js'); + + +module.exports = yaml; + +},{"./lib/js-yaml.js":2}]},{},[])("/") +}); \ No newline at end of file diff --git a/tools/eslint/node_modules/js-yaml/examples/custom_types.js b/tools/eslint/node_modules/js-yaml/examples/custom_types.js new file mode 100644 index 00000000000000..02d8754fad1ef4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/examples/custom_types.js @@ -0,0 +1,103 @@ +'use strict'; + +/*eslint-disable no-console*/ + +var fs = require('fs'); +var path = require('path'); +var util = require('util'); +var yaml = require('../lib/js-yaml'); + + +// Let's define a couple of classes. + +function Point(x, y, z) { + this.klass = 'Point'; + this.x = x; + this.y = y; + this.z = z; +} + + +function Space(height, width, points) { + if (points) { + if (!points.every(function (point) { return point instanceof Point; })) { + throw new Error('A non-Point inside a points array!'); + } + } + + this.klass = 'Space'; + this.height = height; + this.width = width; + this.points = points; +} + + +// Then define YAML types to load and dump our Point/Space objects. + +var PointYamlType = new yaml.Type('!point', { + // Loader must parse sequence nodes only for this type (i.e. arrays in JS terminology). + // Other available kinds are 'scalar' (string) and 'mapping' (object). + // http://www.yaml.org/spec/1.2/spec.html#kind// + kind: 'sequence', + + // Loader must check if the input object is suitable for this type. + resolve: function (data) { + // `data` may be either: + // - Null in case of an "empty node" (http://www.yaml.org/spec/1.2/spec.html#id2786563) + // - Array since we specified `kind` to 'sequence' + return data !== null && data.length === 3; + }, + + // If a node is resolved, use it to create a Point instance. + construct: function (data) { + return new Point(data[0], data[1], data[2]); + }, + + // Dumper must process instances of Point by rules of this YAML type. + instanceOf: Point, + + // Dumper must represent Point objects as three-element sequence in YAML. + represent: function (point) { + return [ point.x, point.y, point.z ]; + } +}); + + +var SpaceYamlType = new yaml.Type('!space', { + kind: 'mapping', + construct: function (data) { + data = data || {}; // in case of empty node + return new Space(data.height || 0, data.width || 0, data.points || []); + }, + instanceOf: Space + // `represent` is omitted here. So, Space objects will be dumped as is. + // That is regular mapping with three key-value pairs but with !space tag. +}); + + +// After our types are defined, it's time to join them into a schema. + +var SPACE_SCHEMA = yaml.Schema.create([ SpaceYamlType, PointYamlType ]); + + +// And read a document using that schema. + +fs.readFile(path.join(__dirname, 'custom_types.yml'), 'utf8', function (error, data) { + var loaded; + + if (!error) { + loaded = yaml.load(data, { schema: SPACE_SCHEMA }); + console.log(util.inspect(loaded, false, 20, true)); + } else { + console.error(error.stack || error.message || String(error)); + } +}); + + +// There are some exports to play with this example interactively. + +module.exports.Point = Point; +module.exports.Space = Space; +module.exports.PointYamlType = PointYamlType; +module.exports.SpaceYamlType = SpaceYamlType; +module.exports.SPACE_SCHEMA = SPACE_SCHEMA; diff --git a/tools/eslint/node_modules/js-yaml/examples/custom_types.yml b/tools/eslint/node_modules/js-yaml/examples/custom_types.yml new file mode 100644 index 00000000000000..f10d4e25a414da --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/examples/custom_types.yml @@ -0,0 +1,18 @@ +subject: Custom types in JS-YAML +spaces: +- !space + height: 1000 + width: 1000 + points: + - !point [ 10, 43, 23 ] + - !point [ 165, 0, 50 ] + - !point [ 100, 100, 100 ] + +- !space + height: 64 + width: 128 + points: + - !point [ 12, 43, 0 ] + - !point [ 1, 4, 90 ] + +- !space # An empty space diff --git a/tools/eslint/node_modules/js-yaml/examples/dumper.js b/tools/eslint/node_modules/js-yaml/examples/dumper.js new file mode 100644 index 00000000000000..d237949530f6dd --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/examples/dumper.js @@ -0,0 +1,32 @@ +'use strict'; + +/*eslint-disable no-console*/ + +var yaml = require('../lib/js-yaml'); +var object = require('./dumper.json'); + + +console.log(yaml.dump(object, { + flowLevel: 3, + styles: { + '!!int' : 'hexadecimal', + '!!null' : 'camelcase' + } +})); + + +// Output: +//============================================================================== +// name: Wizzard +// level: 0x11 +// sanity: Null +// inventory: +// - name: Hat +// features: [magic, pointed] +// traits: {} +// - name: Staff +// features: [] +// traits: {damage: 0xA} +// - name: Cloak +// features: [old] +// traits: {defence: 0x0, comfort: 0x3} diff --git a/tools/eslint/node_modules/js-yaml/examples/dumper.json b/tools/eslint/node_modules/js-yaml/examples/dumper.json new file mode 100644 index 00000000000000..9f54c053e51720 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/examples/dumper.json @@ -0,0 +1,22 @@ +{ + "name" : "Wizzard", + "level" : 17, + "sanity" : null, + "inventory" : [ + { + "name" : "Hat", + "features" : [ "magic", "pointed" ], + "traits" : {} + }, + { + "name" : "Staff", + "features" : [], + "traits" : { "damage" : 10 } + }, + { + "name" : "Cloak", + "features" : [ "old" ], + "traits" : { "defence" : 0, "comfort" : 3 } + } + ] +} diff --git a/tools/eslint/node_modules/js-yaml/examples/sample_document.js b/tools/eslint/node_modules/js-yaml/examples/sample_document.js new file mode 100644 index 00000000000000..3204fa50f94243 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/examples/sample_document.js @@ -0,0 +1,19 @@ +'use strict'; + +/*eslint-disable no-console*/ + +var fs = require('fs'); +var path = require('path'); +var util = require('util'); +var yaml = require('../lib/js-yaml'); + + +try { + var filename = path.join(__dirname, 'sample_document.yml'), + contents = fs.readFileSync(filename, 'utf8'), + data = yaml.load(contents); + + console.log(util.inspect(data, false, 10, true)); +} catch (err) { + console.log(err.stack || String(err)); +} diff --git a/tools/eslint/node_modules/js-yaml/examples/sample_document.yml b/tools/eslint/node_modules/js-yaml/examples/sample_document.yml new file mode 100644 index 00000000000000..4479ee9c0783cf --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/examples/sample_document.yml @@ -0,0 +1,197 @@ +--- +# Collection Types ############################################################# +################################################################################ + +# http://yaml.org/type/map.html -----------------------------------------------# + +map: + # Unordered set of key: value pairs. + Block style: !!map + Clark : Evans + Ingy : döt Net + Oren : Ben-Kiki + Flow style: !!map { Clark: Evans, Ingy: döt Net, Oren: Ben-Kiki } + +# http://yaml.org/type/omap.html ----------------------------------------------# + +omap: + # Explicitly typed ordered map (dictionary). + Bestiary: !!omap + - aardvark: African pig-like ant eater. Ugly. + - anteater: South-American ant eater. Two species. + - anaconda: South-American constrictor snake. Scaly. + # Etc. + # Flow style + Numbers: !!omap [ one: 1, two: 2, three : 3 ] + +# http://yaml.org/type/pairs.html ---------------------------------------------# + +pairs: + # Explicitly typed pairs. + Block tasks: !!pairs + - meeting: with team. + - meeting: with boss. + - break: lunch. + - meeting: with client. + Flow tasks: !!pairs [ meeting: with team, meeting: with boss ] + +# http://yaml.org/type/set.html -----------------------------------------------# + +set: + # Explicitly typed set. + baseball players: !!set + ? Mark McGwire + ? Sammy Sosa + ? Ken Griffey + # Flow style + baseball teams: !!set { Boston Red Sox, Detroit Tigers, New York Yankees } + +# http://yaml.org/type/seq.html -----------------------------------------------# + +seq: + # Ordered sequence of nodes + Block style: !!seq + - Mercury # Rotates - no light/dark sides. + - Venus # Deadliest. Aptly named. + - Earth # Mostly dirt. + - Mars # Seems empty. + - Jupiter # The king. + - Saturn # Pretty. + - Uranus # Where the sun hardly shines. + - Neptune # Boring. No rings. + - Pluto # You call this a planet? + Flow style: !!seq [ Mercury, Venus, Earth, Mars, # Rocks + Jupiter, Saturn, Uranus, Neptune, # Gas + Pluto ] # Overrated + + +# Scalar Types ################################################################# +################################################################################ + +# http://yaml.org/type/binary.html --------------------------------------------# + +binary: + canonical: !!binary "\ + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\ + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\ + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=" + generic: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + description: + The binary value above is a tiny arrow encoded as a gif image. + +# http://yaml.org/type/bool.html ----------------------------------------------# + +bool: + - true + - True + - TRUE + - false + - False + - FALSE + +# http://yaml.org/type/float.html ---------------------------------------------# + +float: + canonical: 6.8523015e+5 + exponentioal: 685.230_15e+03 + fixed: 685_230.15 + sexagesimal: 190:20:30.15 + negative infinity: -.inf + not a number: .NaN + +# http://yaml.org/type/int.html -----------------------------------------------# + +int: + canonical: 685230 + decimal: +685_230 + octal: 02472256 + hexadecimal: 0x_0A_74_AE + binary: 0b1010_0111_0100_1010_1110 + sexagesimal: 190:20:30 + +# http://yaml.org/type/merge.html ---------------------------------------------# + +merge: + - &CENTER { x: 1, y: 2 } + - &LEFT { x: 0, y: 2 } + - &BIG { r: 10 } + - &SMALL { r: 1 } + + # All the following maps are equal: + + - # Explicit keys + x: 1 + y: 2 + r: 10 + label: nothing + + - # Merge one map + << : *CENTER + r: 10 + label: center + + - # Merge multiple maps + << : [ *CENTER, *BIG ] + label: center/big + + - # Override + << : [ *BIG, *LEFT, *SMALL ] + x: 1 + label: big/left/small + +# http://yaml.org/type/null.html ----------------------------------------------# + +null: + # This mapping has four keys, + # one has a value. + empty: + canonical: ~ + english: null + ~: null key + # This sequence has five + # entries, two have values. + sparse: + - ~ + - 2nd entry + - + - 4th entry + - Null + +# http://yaml.org/type/str.html -----------------------------------------------# + +string: abcd + +# http://yaml.org/type/timestamp.html -----------------------------------------# + +timestamp: + canonical: 2001-12-15T02:59:43.1Z + valid iso8601: 2001-12-14t21:59:43.10-05:00 + space separated: 2001-12-14 21:59:43.10 -5 + no time zone (Z): 2001-12-15 2:59:43.10 + date (00:00:00Z): 2002-12-14 + + +# JavaScript Specific Types #################################################### +################################################################################ + +# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp + +regexp: + simple: !!js/regexp foobar + modifiers: !!js/regexp /foobar/mi + +# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined + +undefined: !!js/undefined ~ + +# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function + +function: !!js/function > + function foobar() { + return 'Wow! JS-YAML Rocks!'; + } diff --git a/tools/eslint/node_modules/js-yaml/index.js b/tools/eslint/node_modules/js-yaml/index.js new file mode 100644 index 00000000000000..13744352448b84 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/index.js @@ -0,0 +1,7 @@ +'use strict'; + + +var yaml = require('./lib/js-yaml.js'); + + +module.exports = yaml; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml.js new file mode 100644 index 00000000000000..842104eca3be9e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml.js @@ -0,0 +1,39 @@ +'use strict'; + + +var loader = require('./js-yaml/loader'); +var dumper = require('./js-yaml/dumper'); + + +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; +} + + +module.exports.Type = require('./js-yaml/type'); +module.exports.Schema = require('./js-yaml/schema'); +module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe'); +module.exports.JSON_SCHEMA = require('./js-yaml/schema/json'); +module.exports.CORE_SCHEMA = require('./js-yaml/schema/core'); +module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe'); +module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full'); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.safeLoad = loader.safeLoad; +module.exports.safeLoadAll = loader.safeLoadAll; +module.exports.dump = dumper.dump; +module.exports.safeDump = dumper.safeDump; +module.exports.YAMLException = require('./js-yaml/exception'); + +// Deprecared schema names from JS-YAML 2.0.x +module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe'); +module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe'); +module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full'); + +// Deprecated functions from JS-YAML 1.x.x +module.exports.scan = deprecated('scan'); +module.exports.parse = deprecated('parse'); +module.exports.compose = deprecated('compose'); +module.exports.addConstructor = deprecated('addConstructor'); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/common.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/common.js new file mode 100644 index 00000000000000..197eb248a05a51 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/common.js @@ -0,0 +1,61 @@ +'use strict'; + + +function isNothing(subject) { + return (typeof subject === 'undefined') || (null === subject); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (null !== subject); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) { + return sequence; + } else if (isNothing(sequence)) { + return []; + } + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (0 === number) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/dumper.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/dumper.js new file mode 100644 index 00000000000000..1fc09ba39ce6c4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/dumper.js @@ -0,0 +1,829 @@ +'use strict'; + +/*eslint-disable no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (null === map) { + return {}; + } + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if ('!!' === tag.slice(0, 2)) { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + + type = schema.compiledTypeMap[tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + if (line.length && line !== '\n') { + result += ind; + } + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +function StringBuilder(source) { + this.source = source; + this.result = ''; + this.checkpoint = 0; +} + +StringBuilder.prototype.takeUpTo = function (position) { + var er; + + if (position < this.checkpoint) { + er = new Error('position should be > checkpoint'); + er.position = position; + er.checkpoint = this.checkpoint; + throw er; + } + + this.result += this.source.slice(this.checkpoint, position); + this.checkpoint = position; + return this; +}; + +StringBuilder.prototype.escapeChar = function () { + var character, esc; + + character = this.source.charCodeAt(this.checkpoint); + esc = ESCAPE_SEQUENCES[character] || encodeHex(character); + this.result += esc; + this.checkpoint += 1; + + return this; +}; + +StringBuilder.prototype.finish = function () { + if (this.source.length > this.checkpoint) { + this.takeUpTo(this.source.length); + } +}; + +function writeScalar(state, object, level) { + var simple, first, spaceWrap, folded, literal, single, double, + sawLineFeed, linePosition, longestLine, indent, max, character, + position, escapeSeq, hexEsc, previous, lineLength, modifier, + trailingLineBreaks, result; + + if (0 === object.length) { + state.dump = "''"; + return; + } + + if (-1 !== DEPRECATED_BOOLEANS_SYNTAX.indexOf(object)) { + state.dump = "'" + object + "'"; + return; + } + + simple = true; + first = object.length ? object.charCodeAt(0) : 0; + spaceWrap = (CHAR_SPACE === first || + CHAR_SPACE === object.charCodeAt(object.length - 1)); + + // Simplified check for restricted first characters + // http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29 + if (CHAR_MINUS === first || + CHAR_QUESTION === first || + CHAR_COMMERCIAL_AT === first || + CHAR_GRAVE_ACCENT === first) { + simple = false; + } + + // can only use > and | if not wrapped in spaces. + if (spaceWrap) { + simple = false; + folded = false; + literal = false; + } else { + folded = true; + literal = true; + } + + single = true; + double = new StringBuilder(object); + + sawLineFeed = false; + linePosition = 0; + longestLine = 0; + + indent = state.indent * level; + max = 80; + if (indent < 40) { + max -= indent; + } else { + max = 40; + } + + for (position = 0; position < object.length; position++) { + character = object.charCodeAt(position); + if (simple) { + // Characters that can never appear in the simple scalar + if (!simpleChar(character)) { + simple = false; + } else { + // Still simple. If we make it all the way through like + // this, then we can just dump the string as-is. + continue; + } + } + + if (single && character === CHAR_SINGLE_QUOTE) { + single = false; + } + + escapeSeq = ESCAPE_SEQUENCES[character]; + hexEsc = needsHexEscape(character); + + if (!escapeSeq && !hexEsc) { + continue; + } + + if (character !== CHAR_LINE_FEED && + character !== CHAR_DOUBLE_QUOTE && + character !== CHAR_SINGLE_QUOTE) { + folded = false; + literal = false; + } else if (character === CHAR_LINE_FEED) { + sawLineFeed = true; + single = false; + if (position > 0) { + previous = object.charCodeAt(position - 1); + if (previous === CHAR_SPACE) { + literal = false; + folded = false; + } + } + if (folded) { + lineLength = position - linePosition; + linePosition = position; + if (lineLength > longestLine) { + longestLine = lineLength; + } + } + } + + if (character !== CHAR_DOUBLE_QUOTE) { + single = false; + } + + double.takeUpTo(position); + double.escapeChar(); + } + + if (simple && testImplicitResolving(state, object)) { + simple = false; + } + + modifier = ''; + if (folded || literal) { + trailingLineBreaks = 0; + if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) { + trailingLineBreaks += 1; + if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) { + trailingLineBreaks += 1; + } + } + + if (trailingLineBreaks === 0) { + modifier = '-'; + } else if (trailingLineBreaks === 2) { + modifier = '+'; + } + } + + if (literal && longestLine < max) { + folded = false; + } + + // If it's literally one line, then don't bother with the literal. + // We may still want to do a fold, though, if it's a super long line. + if (!sawLineFeed) { + literal = false; + } + + if (simple) { + state.dump = object; + } else if (single) { + state.dump = '\'' + object + '\''; + } else if (folded) { + result = fold(object, max); + state.dump = '>' + modifier + '\n' + indentString(result, indent); + } else if (literal) { + if (!modifier) { + object = object.replace(/\n$/, ''); + } + state.dump = '|' + modifier + '\n' + indentString(object, indent); + } else if (double) { + double.finish(); + state.dump = '"' + double.result + '"'; + } else { + throw new Error('Failed to dump scalar value'); + } + + return; +} + +// The `trailing` var is a regexp match of any trailing `\n` characters. +// +// There are three cases we care about: +// +// 1. One trailing `\n` on the string. Just use `|` or `>`. +// This is the assumed default. (trailing = null) +// 2. No trailing `\n` on the string. Use `|-` or `>-` to "chomp" the end. +// 3. More than one trailing `\n` on the string. Use `|+` or `>+`. +// +// In the case of `>+`, these line breaks are *not* doubled (like the line +// breaks within the string), so it's important to only end with the exact +// same number as we started. +function fold(object, max) { + var result = '', + position = 0, + length = object.length, + trailing = /\n+$/.exec(object), + newLine; + + if (trailing) { + length = trailing.index + 1; + } + + while (position < length) { + newLine = object.indexOf('\n', position); + if (newLine > length || newLine === -1) { + if (result) { + result += '\n\n'; + } + result += foldLine(object.slice(position, length), max); + position = length; + } else { + if (result) { + result += '\n\n'; + } + result += foldLine(object.slice(position, newLine), max); + position = newLine + 1; + } + } + if (trailing && trailing[0] !== '\n') { + result += trailing[0]; + } + + return result; +} + +function foldLine(line, max) { + if (line === '') { + return line; + } + + var foldRe = /[^\s] [^\s]/g, + result = '', + prevMatch = 0, + foldStart = 0, + match = foldRe.exec(line), + index, + foldEnd, + folded; + + while (match) { + index = match.index; + + // when we cross the max len, if the previous match would've + // been ok, use that one, and carry on. If there was no previous + // match on this fold section, then just have a long line. + if (index - foldStart > max) { + if (prevMatch !== foldStart) { + foldEnd = prevMatch; + } else { + foldEnd = index; + } + + if (result) { + result += '\n'; + } + folded = line.slice(foldStart, foldEnd); + result += folded; + foldStart = foldEnd + 1; + } + prevMatch = index + 1; + match = foldRe.exec(line); + } + + if (result) { + result += '\n'; + } + + // if we end up with one last word at the end, then the last bit might + // be slightly bigger than we wanted, because we exited out of the loop. + if (foldStart !== prevMatch && line.length - foldStart > max) { + result += line.slice(foldStart, prevMatch) + '\n' + + line.slice(prevMatch + 1); + } else { + result += line.slice(foldStart); + } + + return result; +} + +// Returns true if character can be found in a simple scalar +function simpleChar(character) { + return CHAR_TAB !== character && + CHAR_LINE_FEED !== character && + CHAR_CARRIAGE_RETURN !== character && + CHAR_COMMA !== character && + CHAR_LEFT_SQUARE_BRACKET !== character && + CHAR_RIGHT_SQUARE_BRACKET !== character && + CHAR_LEFT_CURLY_BRACKET !== character && + CHAR_RIGHT_CURLY_BRACKET !== character && + CHAR_SHARP !== character && + CHAR_AMPERSAND !== character && + CHAR_ASTERISK !== character && + CHAR_EXCLAMATION !== character && + CHAR_VERTICAL_LINE !== character && + CHAR_GREATER_THAN !== character && + CHAR_SINGLE_QUOTE !== character && + CHAR_DOUBLE_QUOTE !== character && + CHAR_PERCENT !== character && + CHAR_COLON !== character && + !ESCAPE_SEQUENCES[character] && + !needsHexEscape(character); +} + +// Returns true if the character code needs to be escaped. +function needsHexEscape(character) { + return !((0x00020 <= character && character <= 0x00007E) || + (0x00085 === character) || + (0x000A0 <= character && character <= 0x00D7FF) || + (0x0E000 <= character && character <= 0x00FFFD) || + (0x10000 <= character && character <= 0x10FFFF)); +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (0 !== index) { + _result += ', '; + } + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || 0 !== index) { + _result += generateNextLine(state, level); + } + _result += '- ' + state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (0 !== index) { + pairBuffer += ', '; + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) { + pairBuffer += '? '; + } + + pairBuffer += state.dump + ': '; + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || 0 !== index) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (null !== state.tag && '?' !== state.tag) || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || (('object' === typeof object) && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if ('[object Function]' === _toString.call(type.represent)) { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (0 > state.flowLevel || state.flowLevel > level); + } + + if ((null !== state.tag && '?' !== state.tag) || (2 !== state.indent && level > 0)) { + compact = false; + } + + var objectOrArray = '[object Object]' === type || '[object Array]' === type, + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if ('[object Object]' === type) { + if (block && (0 !== Object.keys(state.dump).length)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if ('[object Array]' === type) { + if (block && (0 !== state.dump.length)) { + writeBlockSequence(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if ('[object String]' === type) { + if ('?' !== state.tag) { + writeScalar(state, state.dump, level); + } + } else { + if (state.skipInvalid) { + return false; + } + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (null !== state.tag && '?' !== state.tag) { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var type = _toString.call(object), + objectKeyList, + index, + length; + + if (null !== object && 'object' === typeof object) { + index = objects.indexOf(object); + if (-1 !== index) { + if (-1 === duplicatesIndexes.indexOf(index)) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) { + return state.dump + '\n'; + } + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/exception.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/exception.js new file mode 100644 index 00000000000000..479ba88791de26 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/exception.js @@ -0,0 +1,25 @@ +'use strict'; + + +function YAMLException(reason, mark) { + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = this.toString(false); +} + + +YAMLException.prototype.toString = function toString(compact) { + var result; + + result = 'JS-YAML: ' + (this.reason || '(unknown reason)'); + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/loader.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/loader.js new file mode 100644 index 00000000000000..af1b99b35223c0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/loader.js @@ -0,0 +1,1586 @@ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uD800-\uDFFF\uFFFE\uFFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return 0x2C/* , */ === c || + 0x5B/* [ */ === c || + 0x5D/* ] */ === c || + 0x7B/* { */ === c || + 0x7D/* } */ === c; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode(((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + var error = generateError(state, message); + + if (state.onWarning) { + state.onWarning.call(null, error); + } else { + throw error; + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (null !== state.version) { + throwError(state, 'duplication of %YAML directive'); + } + + if (1 !== args.length) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (null === match) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (1 !== major) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (1 !== minor && 2 !== minor) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (2 !== args.length) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; + _position < _length; + _position += 1) { + _character = _result.charCodeAt(_position); + if (!(0x09 === _character || + 0x20 <= _character && _character <= 0x10FFFF)) { + throwError(state, 'expected valid JSON character'); + } + } + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + } + } +} + +function storeMappingPair(state, _result, keyTag, keyNode, valueNode) { + var index, quantity; + + keyNode = String(keyNode); + + if (null === _result) { + _result = {}; + } + + if ('tag:yaml.org,2002:merge' === keyTag) { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index]); + } + } else { + mergeMappings(state, _result, valueNode); + } + } else { + _result[keyNode] = valueNode; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (0x0A/* LF */ === ch) { + state.position++; + } else if (0x0D/* CR */ === ch) { + state.position++; + if (0x0A/* LF */ === state.input.charCodeAt(state.position)) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (0 !== ch) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && 0x23/* # */ === ch) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && 0 !== ch); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (0x20/* Space */ === ch) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (-1 !== checkIndent && 0 !== lineBreaks && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((0x2D/* - */ === ch || 0x2E/* . */ === ch) && + state.input.charCodeAt(_position + 1) === ch && + state.input.charCodeAt(_position + 2) === ch) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (1 === count) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + 0x23/* # */ === ch || + 0x26/* & */ === ch || + 0x2A/* * */ === ch || + 0x21/* ! */ === ch || + 0x7C/* | */ === ch || + 0x3E/* > */ === ch || + 0x27/* ' */ === ch || + 0x22/* " */ === ch || + 0x25/* % */ === ch || + 0x40/* @ */ === ch || + 0x60/* ` */ === ch) { + return false; + } + + if (0x3F/* ? */ === ch || 0x2D/* - */ === ch) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (0 !== ch) { + if (0x3A/* : */ === ch) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (0x23/* # */ === ch) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (0x27/* ' */ !== ch) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while (0 !== (ch = state.input.charCodeAt(state.position))) { + if (0x27/* ' */ === ch) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (0x27/* ' */ === ch) { + captureStart = captureEnd = state.position; + state.position++; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, tmpEsc, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x22/* " */ !== ch) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while (0 !== (ch = state.input.charCodeAt(state.position))) { + if (0x22/* " */ === ch) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (0x5C/* \ */ === ch) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (0 !== ch) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (0x3F/* ? */ === ch) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && 0x3A/* : */ === ch) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (0x2C/* , */ === ch) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (0 !== ch) { + ch = state.input.charCodeAt(++state.position); + + if (0x2B/* + */ === ch || 0x2D/* - */ === ch) { + if (CHOMPING_CLIP === chomping) { + chomping = (0x2B/* + */ === ch) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (0x23/* # */ === ch) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (0 !== ch)); + } + } + + while (0 !== ch) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (0x20/* Space */ === ch)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (detectedIndent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + state.result += common.repeat('\n', emptyLines + 1); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (0 === emptyLines) { + if (detectedIndent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else if (detectedIndent) { + // If current line isn't the first one - count line break from the last content line. + state.result += common.repeat('\n', emptyLines + 1); + } else { + // In case of the first content line - count only empty lines. + } + + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (0 !== ch)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (0 !== ch) { + + if (0x2D/* - */ !== ch) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (0 !== ch)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (0 !== ch) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((0x3F/* ? */ === ch || 0x3A/* : */ === ch) && is_WS_OR_EOL(following)) { + + if (0x3F/* ? */ === ch) { + if (atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (0x3A/* : */ === ch) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, valueNode); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (0 !== ch)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x21/* ! */ !== ch) { + return false; + } + + if (null !== state.tag) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (0x3C/* < */ === ch) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (0x21/* ! */ === ch) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (0 !== ch && 0x3E/* > */ !== ch); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (0 !== ch && !is_WS_OR_EOL(ch)) { + + if (0x21/* ! */ === ch) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if ('!' === tagHandle) { + state.tag = '!' + tagName; + + } else if ('!!' === tagHandle) { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x26/* & */ !== ch) { + return false; + } + + if (null !== state.anchor) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + len = state.length, + input = state.input, + ch; + + ch = state.input.charCodeAt(state.position); + + if (0x2A/* * */ !== ch) { + return false; + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!state.anchorMap.hasOwnProperty(alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (1 === indentStatus) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (1 === indentStatus || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (1 === indentStatus) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (null !== state.tag || null !== state.anchor) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (null === state.tag) { + state.tag = '?'; + } + } + + if (null !== state.anchor) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (0 === indentStatus) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (null !== state.tag && '!' !== state.tag) { + if ('?' === state.tag) { + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; + typeIndex < typeQuantity; + typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only assigned to plain scalars. So, it isn't + // needed to check for 'kind' conformity. + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (null !== state.anchor) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap, state.tag)) { + type = state.typeMap[state.tag]; + + if (null !== state.result && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (null !== state.anchor) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwWarning(state, 'unknown tag !<' + state.tag + '>'); + } + } + + return null !== state.tag || null !== state.anchor || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while (0 !== (ch = state.input.charCodeAt(state.position))) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || 0x25/* % */ !== ch) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (0 !== ch) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (0x23/* # */ === ch) { + do { ch = state.input.charCodeAt(++state.position); } + while (0 !== ch && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) { + break; + } + + _position = state.position; + + while (0 !== ch && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (0 !== ch) { + readLineBreak(state); + } + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (0 === state.lineIndent && + 0x2D/* - */ === state.input.charCodeAt(state.position) && + 0x2D/* - */ === state.input.charCodeAt(state.position + 1) && + 0x2D/* - */ === state.input.charCodeAt(state.position + 2)) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (0x2E/* . */ === state.input.charCodeAt(state.position)) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (0x0A/* LF */ !== input.charCodeAt(input.length - 1) && + 0x0D/* CR */ !== input.charCodeAt(input.length - 1)) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + if (PATTERN_NON_PRINTABLE.test(state.input)) { + throwError(state, 'the stream contains non-printable characters'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (0x20/* Space */ === state.input.charCodeAt(state.position)) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + var documents = loadDocuments(input, options), index, length; + + for (index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options), index, length; + + if (0 === documents.length) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (1 === documents.length) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, output, options) { + loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/mark.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/mark.js new file mode 100644 index 00000000000000..bfe279ba52c3a9 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/mark.js @@ -0,0 +1,78 @@ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) { + return null; + } + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1))) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end))) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema.js new file mode 100644 index 00000000000000..984e2904f3b2a1 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema.js @@ -0,0 +1,104 @@ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return -1 === exclude.indexOf(index); + }); +} + + +function compileMap(/* lists... */) { + var result = {}, index, length; + + function collectType(type) { + result[type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && 'scalar' !== type.loadKind) { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/core.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/core.js new file mode 100644 index 00000000000000..206daab56c0586 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/core.js @@ -0,0 +1,18 @@ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/default_full.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/default_full.js new file mode 100644 index 00000000000000..a55ef42accdaf9 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/default_full.js @@ -0,0 +1,25 @@ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js new file mode 100644 index 00000000000000..11d89bbfbba45e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js @@ -0,0 +1,28 @@ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js new file mode 100644 index 00000000000000..b7a33eb7a1ccea --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js @@ -0,0 +1,17 @@ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/json.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/json.js new file mode 100644 index 00000000000000..5be3dbf805bc5d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/schema/json.js @@ -0,0 +1,25 @@ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type.js new file mode 100644 index 00000000000000..5e3176cebef887 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type.js @@ -0,0 +1,61 @@ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (null !== map) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (-1 === TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (-1 === YAML_NODE_KINDS.indexOf(this.kind)) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/binary.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/binary.js new file mode 100644 index 00000000000000..122155c75bdab2 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/binary.js @@ -0,0 +1,134 @@ +'use strict'; + +/*eslint-disable no-bitwise*/ + +// A trick for browserified version. +// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined +var NodeBuffer = require('buffer').Buffer; +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (null === data) { + return false; + } + + var code, idx, bitlen = 0, len = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) { continue; } + + // Fail on illegal characters + if (code < 0) { return false; } + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var code, idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + return new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/bool.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/bool.js new file mode 100644 index 00000000000000..5c2a304d8a46d8 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/bool.js @@ -0,0 +1,37 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (null === data) { + return false; + } + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return '[object Boolean]' === Object.prototype.toString.call(object); +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/float.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/float.js new file mode 100644 index 00000000000000..67c9c21f247a8d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/float.js @@ -0,0 +1,108 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + '^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' + + '|\\.[0-9_]+(?:[eE][-+][0-9]+)?' + + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + '|[-+]?\\.(?:inf|Inf|INF)' + + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (null === data) { + return false; + } + + var value, sign, base, digits; + + if (!YAML_FLOAT_PATTERN.test(data)) { + return false; + } + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = '-' === value[0] ? -1 : 1; + digits = []; + + if (0 <= '+-'.indexOf(value[0])) { + value = value.slice(1); + } + + if ('.inf' === value) { + return (1 === sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if ('.nan' === value) { + return NaN; + + } else if (0 <= value.indexOf(':')) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + +function representYamlFloat(object, style) { + if (isNaN(object)) { + switch (style) { + case 'lowercase': + return '.nan'; + case 'uppercase': + return '.NAN'; + case 'camelcase': + return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': + return '.inf'; + case 'uppercase': + return '.INF'; + case 'camelcase': + return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': + return '-.inf'; + case 'uppercase': + return '-.INF'; + case 'camelcase': + return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + return object.toString(10); +} + +function isFloat(object) { + return ('[object Number]' === Object.prototype.toString.call(object)) && + (0 !== object % 1 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/int.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/int.js new file mode 100644 index 00000000000000..800f10608ad1d3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/int.js @@ -0,0 +1,183 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (null === data) { + return false; + } + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) { return false; } + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) { return true; } + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (ch !== '0' && ch !== '1') { + return false; + } + hasDigits = true; + } + return hasDigits; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (!isHexCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + return hasDigits; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (!isOctCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + return hasDigits; + } + + // base 10 (except 0) or base 60 + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') { continue; } + if (ch === ':') { break; } + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + if (!hasDigits) { return false; } + + // if !base60 - done; + if (ch !== ':') { return true; } + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') { sign = -1; } + value = value.slice(1); + ch = value[0]; + } + + if ('0' === value) { + return 0; + } + + if (ch === '0') { + if (value[1] === 'b') { + return sign * parseInt(value.slice(2), 2); + } + if (value[1] === 'x') { + return sign * parseInt(value, 16); + } + return sign * parseInt(value, 8); + + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return ('[object Number]' === Object.prototype.toString.call(object)) && + (0 === object % 1 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (object) { return '0b' + object.toString(2); }, + octal: function (object) { return '0' + object.toString(8); }, + decimal: function (object) { return object.toString(10); }, + hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/function.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/function.js new file mode 100644 index 00000000000000..4061c43ad11714 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/function.js @@ -0,0 +1,86 @@ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + esprima = require('esprima'); +} catch (_) { + /*global window */ + if (typeof window !== 'undefined') { esprima = window.esprima; } +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (null === data) { + return false; + } + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if ('Program' !== ast.type || + 1 !== ast.body.length || + 'ExpressionStatement' !== ast.body[0].type || + 'FunctionExpression' !== ast.body[0].expression.type) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if ('Program' !== ast.type || + 1 !== ast.body.length || + 'ExpressionStatement' !== ast.body[0].type || + 'FunctionExpression' !== ast.body[0].expression.type) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return '[object Function]' === Object.prototype.toString.call(object); +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js new file mode 100644 index 00000000000000..07ef5218ed91f0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js @@ -0,0 +1,84 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (null === data) { + return false; + } + + if (0 === data.length) { + return false; + } + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if ('/' === regexp[0]) { + if (tail) { + modifiers = tail[1]; + } + + if (modifiers.length > 3) { return false; } + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') { return false; } + + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + try { + var dummy = new RegExp(regexp, modifiers); + return true; + } catch (error) { + return false; + } +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if ('/' === regexp[0]) { + if (tail) { + modifiers = tail[1]; + } + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) { + result += 'g'; + } + + if (object.multiline) { + result += 'm'; + } + + if (object.ignoreCase) { + result += 'i'; + } + + return result; +} + +function isRegExp(object) { + return '[object RegExp]' === Object.prototype.toString.call(object); +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js new file mode 100644 index 00000000000000..562753c2b51113 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js @@ -0,0 +1,28 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return 'undefined' === typeof object; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/map.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/map.js new file mode 100644 index 00000000000000..dab9838c254c58 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/map.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return null !== data ? data : {}; } +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/merge.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/merge.js new file mode 100644 index 00000000000000..29fa382707b931 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/merge.js @@ -0,0 +1,12 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return '<<' === data || null === data; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/null.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/null.js new file mode 100644 index 00000000000000..3474055698f5dd --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/null.js @@ -0,0 +1,36 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (null === data) { + return true; + } + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return null === object; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/omap.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/omap.js new file mode 100644 index 00000000000000..f956459a0d6ae4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/omap.js @@ -0,0 +1,56 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (null === data) { + return true; + } + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if ('[object Object]' !== _toString.call(pair)) { + return false; + } + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) { + pairHasKey = true; + } else { + return false; + } + } + } + + if (!pairHasKey) { + return false; + } + + if (-1 === objectKeys.indexOf(pairKey)) { + objectKeys.push(pairKey); + } else { + return false; + } + } + + return true; +} + +function constructYamlOmap(data) { + return null !== data ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/pairs.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/pairs.js new file mode 100644 index 00000000000000..02a0af6bc11dc6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/pairs.js @@ -0,0 +1,61 @@ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (null === data) { + return true; + } + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if ('[object Object]' !== _toString.call(pair)) { + return false; + } + + keys = Object.keys(pair); + + if (1 !== keys.length) { + return false; + } + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (null === data) { + return []; + } + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/seq.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/seq.js new file mode 100644 index 00000000000000..5b860a2639c4b6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/seq.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return null !== data ? data : []; } +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/set.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/set.js new file mode 100644 index 00000000000000..64d29e9b68c2ed --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/set.js @@ -0,0 +1,33 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (null === data) { + return true; + } + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (null !== object[key]) { + return false; + } + } + } + + return true; +} + +function constructYamlSet(data) { + return null !== data ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/str.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/str.js new file mode 100644 index 00000000000000..8b5284fe9bcbe0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/str.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return null !== data ? data : ''; } +}); diff --git a/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/timestamp.js b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/timestamp.js new file mode 100644 index 00000000000000..dc8cf15a06f424 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/lib/js-yaml/type/timestamp.js @@ -0,0 +1,98 @@ +'use strict'; + +var Type = require('../type'); + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?)?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (null === data) { + return false; + } + + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (null === match) { + return false; + } + + return true; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (null === match) { + throw new Error('Date resolve error'); + } + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if ('-' === match[9]) { + delta = -delta; + } + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) { + date.setTime(date.getTime() - delta); + } + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/.bin/esparse b/tools/eslint/node_modules/js-yaml/node_modules/.bin/esparse new file mode 100755 index 00000000000000..560366695a1e37 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/.bin/esparse @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true rhino:true */ + +var fs, esprima, fname, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); +} else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } +}); + +if (typeof fname !== 'string') { + console.log('Error: no input file.'); + process.exit(1); +} + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +try { + content = fs.readFileSync(fname, 'utf-8'); + syntax = esprima.parse(content, options); + console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/.bin/esvalidate b/tools/eslint/node_modules/js-yaml/node_modules/.bin/esvalidate new file mode 100755 index 00000000000000..dddd8a2ada461a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/.bin/esvalidate @@ -0,0 +1,199 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true plusplus:true node:true rhino:true */ +/*global phantom:true */ + +var fs, system, esprima, options, fnames, count; + +if (typeof esprima === 'undefined') { + // PhantomJS can only require() relative files + if (typeof phantom === 'object') { + fs = require('fs'); + system = require('system'); + esprima = require('./esprima'); + } else if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); + } else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } + } +} + +// Shims to Node.js objects when running under PhantomJS 1.7+. +if (typeof phantom === 'object') { + fs.readFileSync = fs.read; + process = { + argv: [].slice.call(system.args), + exit: phantom.exit + }; + process.argv.unshift('phantomjs'); +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else { + fnames.push(entry); + } +}); + +if (fnames.length === 0) { + console.log('Error: no input file.'); + process.exit(1); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; +fnames.forEach(function (fname) { + var content, timestamp, syntax, name; + try { + content = fs.readFileSync(fname, 'utf-8'); + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = esprima.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log('Error: ' + e.message); + } + } +}); + +if (options.format === 'junit') { + console.log(''); +} + +if (count > 0) { + process.exit(1); +} + +if (count === 0 && typeof phantom === 'object') { + process.exit(0); +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/CHANGELOG.md b/tools/eslint/node_modules/js-yaml/node_modules/argparse/CHANGELOG.md new file mode 100644 index 00000000000000..661e75d76511b6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/CHANGELOG.md @@ -0,0 +1,136 @@ +1.0.2 / 2015-03-22 +------------------ + +* Relaxed lodash version dependency. + + +1.0.1 / 2015-02-20 +------------------ + +* Changed dependencies to be compatible with ancient nodejs. + + +1.0.0 / 2015-02-19 +------------------ + +* Maintenance release. +* Replaced `underscore` with `lodash`. +* Bumped version to 1.0.0 to better reflect semver meaning. +* HISTORY.md -> CHANGELOG.md + + +0.1.16 / 2013-12-01 +------------------- + +* Maintenance release. Updated dependencies and docs. + + +0.1.15 / 2013-05-13 +------------------- + +* Fixed #55, @trebor89 + + +0.1.14 / 2013-05-12 +------------------- + +* Fixed #62, @maxtaco + + +0.1.13 / 2013-04-08 +------------------- + +* Added `.npmignore` to reduce package size + + +0.1.12 / 2013-02-10 +------------------- + +* Fixed conflictHandler (#46), @hpaulj + + +0.1.11 / 2013-02-07 +------------------- + +* Multiple bugfixes, @hpaulj +* Added 70+ tests (ported from python), @hpaulj +* Added conflictHandler, @applepicke +* Added fromfilePrefixChar, @hpaulj + + +0.1.10 / 2012-12-30 +------------------- + +* Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) + support, thanks to @hpaulj +* Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj + + +0.1.9 / 2012-12-27 +------------------ + +* Fixed option dest interferens with other options (issue #23), thanks to @hpaulj +* Fixed default value behavior with `*` positionals, thanks to @hpaulj +* Improve `getDefault()` behavior, thanks to @hpaulj +* Imrove negative argument parsing, thanks to @hpaulj + + +0.1.8 / 2012-12-01 +------------------ + +* Fixed parser parents (issue #19), thanks to @hpaulj +* Fixed negative argument parse (issue #20), thanks to @hpaulj + + +0.1.7 / 2012-10-14 +------------------ + +* Fixed 'choices' argument parse (issue #16) +* Fixed stderr output (issue #15) + + +0.1.6 / 2012-09-09 +------------------ + +* Fixed check for conflict of options (thanks to @tomxtobin) + + +0.1.5 / 2012-09-03 +------------------ + +* Fix parser #setDefaults method (thanks to @tomxtobin) + + +0.1.4 / 2012-07-30 +------------------ + +* Fixed pseudo-argument support (thanks to @CGamesPlay) +* Fixed addHelp default (should be true), if not set (thanks to @benblank) + + +0.1.3 / 2012-06-27 +------------------ + +* Fixed formatter api name: Formatter -> HelpFormatter + + +0.1.2 / 2012-05-29 +------------------ + +* Added basic tests +* Removed excess whitespace in help +* Fixed error reporting, when parcer with subcommands + called with empty arguments + + +0.1.1 / 2012-05-23 +------------------ + +* Fixed line wrapping in help formatter +* Added better error reporting on invalid arguments + + +0.1.0 / 2012-05-16 +------------------ + +* First release. diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/LICENSE b/tools/eslint/node_modules/js-yaml/node_modules/argparse/LICENSE new file mode 100644 index 00000000000000..1afdae5584056a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2012 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/README.md b/tools/eslint/node_modules/js-yaml/node_modules/argparse/README.md new file mode 100644 index 00000000000000..72e4261688e8d2 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/README.md @@ -0,0 +1,243 @@ +argparse +======== + +[![Build Status](https://secure.travis-ci.org/nodeca/argparse.png?branch=master)](http://travis-ci.org/nodeca/argparse) +[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) + +CLI arguments parser for node.js. Javascript port of python's +[argparse](http://docs.python.org/dev/library/argparse.html) module +(original version 3.2). That's a full port, except some very rare options, +recorded in issue tracker. + +**NB. Difference with original.** + +- Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). +- Use `defaultValue` instead of `default`. + + +Example +======= + +test.js file: + +```javascript +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp:true, + description: 'Argparse example' +}); +parser.addArgument( + [ '-f', '--foo' ], + { + help: 'foo bar' + } +); +parser.addArgument( + [ '-b', '--bar' ], + { + help: 'bar foo' + } +); +var args = parser.parseArgs(); +console.dir(args); +``` + +Display help: + +``` +$ ./test.js -h +usage: example.js [-h] [-v] [-f FOO] [-b BAR] + +Argparse example + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -f FOO, --foo FOO foo bar + -b BAR, --bar BAR bar foo +``` + +Parse arguments: + +``` +$ ./test.js -f=3 --bar=4 +{ foo: '3', bar: '4' } +``` + +More [examples](https://github.com/nodeca/argparse/tree/master/examples). + + +ArgumentParser objects +====================== + +``` +new ArgumentParser({paramters hash}); +``` + +Creates a new ArgumentParser object. + +**Supported params:** + +- ```description``` - Text to display before the argument help. +- ```epilog``` - Text to display after the argument help. +- ```addHelp``` - Add a -h/–help option to the parser. (default: true) +- ```argumentDefault``` - Set the global default value for arguments. (default: null) +- ```parents``` - A list of ArgumentParser objects whose arguments should also be included. +- ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) +- ```formatterClass``` - A class for customizing the help output. +- ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) +- ```usage``` - The string describing the program usage (default: generated) +- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. + +**Not supportied yet** + +- ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. + + +Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) + + +addArgument() method +==================== + +``` +ArgumentParser.addArgument([names or flags], {options}) +``` + +Defines how a single command-line argument should be parsed. + +- ```name or flags``` - Either a name or a list of option strings, e.g. foo or -f, --foo. + +Options: + +- ```action``` - The basic type of action to be taken when this argument is encountered at the command line. +- ```nargs```- The number of command-line arguments that should be consumed. +- ```constant``` - A constant value required by some action and nargs selections. +- ```defaultValue``` - The value produced if the argument is absent from the command line. +- ```type``` - The type to which the command-line argument should be converted. +- ```choices``` - A container of the allowable values for the argument. +- ```required``` - Whether or not the command-line option may be omitted (optionals only). +- ```help``` - A brief description of what the argument does. +- ```metavar``` - A name for the argument in usage messages. +- ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). + +Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) + + +Action (some details) +================ + +ArgumentParser objects associate command-line arguments with actions. +These actions can do just about anything with the command-line arguments associated +with them, though most actions simply add an attribute to the object returned by +parseArgs(). The action keyword argument specifies how the command-line arguments +should be handled. The supported actions are: + +- ```store``` - Just stores the argument’s value. This is the default action. +- ```storeConst``` - Stores value, specified by the const keyword argument. + (Note that the const keyword argument defaults to the rather unhelpful None.) + The 'storeConst' action is most commonly used with optional arguments, that + specify some sort of flag. +- ```storeTrue``` and ```storeFalse``` - Stores values True and False + respectively. These are special cases of 'storeConst'. +- ```append``` - Stores a list, and appends each argument value to the list. + This is useful to allow an option to be specified multiple times. +- ```appendConst``` - Stores a list, and appends value, specified by the + const keyword argument to the list. (Note, that the const keyword argument defaults + is None.) The 'appendConst' action is typically used when multiple arguments need + to store constants to the same list. +- ```count``` - Counts the number of times a keyword argument occurs. For example, + used for increasing verbosity levels. +- ```help``` - Prints a complete help message for all the options in the current + parser and then exits. By default a help action is automatically added to the parser. + See ArgumentParser for details of how the output is created. +- ```version``` - Prints version information and exit. Expects a `version=` + keyword argument in the addArgument() call. + +Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) + + +Sub-commands +============ + +ArgumentParser.addSubparsers() + +Many programs split their functionality into a number of sub-commands, for +example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, +and `svn commit`. Splitting up functionality this way can be a particularly good +idea when a program performs several different functions which require different +kinds of command-line arguments. `ArgumentParser` supports creation of such +sub-commands with `addSubparsers()` method. The `addSubparsers()` method is +normally called with no arguments and returns an special action object. +This object has a single method `addParser()`, which takes a command name and +any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object +that can be modified as usual. + +Example: + +sub_commands.js +```javascript +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp:true, + description: 'Argparse examples: sub-commands', +}); + +var subparsers = parser.addSubparsers({ + title:'subcommands', + dest:"subcommand_name" +}); + +var bar = subparsers.addParser('c1', {addHelp:true}); +bar.addArgument( + [ '-f', '--foo' ], + { + action: 'store', + help: 'foo3 bar3' + } +); +var bar = subparsers.addParser( + 'c2', + {aliases:['co'], addHelp:true} +); +bar.addArgument( + [ '-b', '--bar' ], + { + action: 'store', + type: 'int', + help: 'foo3 bar3' + } +); + +var args = parser.parseArgs(); +console.dir(args); + +``` + +Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) + + +Contributors +============ + +- [Eugene Shkuropat](https://github.com/shkuropat) +- [Paul Jacobson](https://github.com/hpaulj) + +[others](https://github.com/nodeca/argparse/graphs/contributors) + +License +======= + +Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). +Released under the MIT license. See +[LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. + + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/arguments.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/arguments.js new file mode 100755 index 00000000000000..5b090fa2e1185a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/arguments.js @@ -0,0 +1,36 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: arguments' +}); +parser.addArgument( + [ '-f', '--foo' ], + { + help: 'foo bar' + } +); +parser.addArgument( + [ '-b', '--bar' ], + { + help: 'bar foo' + } +); + + +parser.printHelp(); +console.log('-----------'); + +var args; +args = parser.parseArgs('-f 1 -b2'.split(' ')); +console.dir(args); +console.log('-----------'); +args = parser.parseArgs('-f=3 --bar=4'.split(' ')); +console.dir(args); +console.log('-----------'); +args = parser.parseArgs('--foo 5 --bar 6'.split(' ')); +console.dir(args); +console.log('-----------'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/choice.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/choice.js new file mode 100755 index 00000000000000..2616fa4d75275e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/choice.js @@ -0,0 +1,22 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: choice' +}); + +parser.addArgument(['foo'], {choices: 'abc'}); + +parser.printHelp(); +console.log('-----------'); + +var args; +args = parser.parseArgs(['c']); +console.dir(args); +console.log('-----------'); +parser.parseArgs(['X']); +console.dir(args); + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/constants.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/constants.js new file mode 100755 index 00000000000000..172a4f3d4f62c0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/constants.js @@ -0,0 +1,59 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: constant' +}); + +parser.addArgument( + [ '-a'], + { + action: 'storeConst', + dest: 'answer', + help: 'store constant', + constant: 42 + } +); +parser.addArgument( + [ '--str' ], + { + action: 'appendConst', + dest: 'types', + help: 'append constant "str" to types', + constant: 'str' + } +); +parser.addArgument( + [ '--int' ], + { + action: 'appendConst', + dest: 'types', + help: 'append constant "int" to types', + constant: 'int' + } +); + +parser.addArgument( + [ '--true' ], + { + action: 'storeTrue', + help: 'store true constant' + } +); +parser.addArgument( + [ '--false' ], + { + action: 'storeFalse', + help: 'store false constant' + } +); + +parser.printHelp(); +console.log('-----------'); + +var args; +args = parser.parseArgs('-a --str --int --true'.split(' ')); +console.dir(args); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/help.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/help.js new file mode 100755 index 00000000000000..7eb955534fe29c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/help.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: help', + epilog: 'help epilog', + prog: 'help_example_prog', + usage: 'Usage %(prog)s ' +}); +parser.printHelp(); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/nargs.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/nargs.js new file mode 100755 index 00000000000000..74f376beba4a4c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/nargs.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: nargs' +}); +parser.addArgument( + [ '-f', '--foo' ], + { + help: 'foo bar', + nargs: 1 + } +); +parser.addArgument( + [ '-b', '--bar' ], + { + help: 'bar foo', + nargs: '*' + } +); + +parser.printHelp(); +console.log('-----------'); + +var args; +args = parser.parseArgs('--foo a --bar c d'.split(' ')); +console.dir(args); +console.log('-----------'); +args = parser.parseArgs('--bar b c f --foo a'.split(' ')); +console.dir(args); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/parents.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/parents.js new file mode 100755 index 00000000000000..dfe896868bd0f6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/parents.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; + +var args; +var parent_parser = new ArgumentParser({ addHelp: false }); +// note addHelp:false to prevent duplication of the -h option +parent_parser.addArgument( + ['--parent'], + { type: 'int', description: 'parent' } +); + +var foo_parser = new ArgumentParser({ + parents: [ parent_parser ], + description: 'child1' +}); +foo_parser.addArgument(['foo']); +args = foo_parser.parseArgs(['--parent', '2', 'XXX']); +console.log(args); + +var bar_parser = new ArgumentParser({ + parents: [ parent_parser ], + description: 'child2' +}); +bar_parser.addArgument(['--bar']); +args = bar_parser.parseArgs(['--bar', 'YYY']); +console.log(args); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/prefix_chars.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/prefix_chars.js new file mode 100755 index 00000000000000..430d5e182346d9 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/prefix_chars.js @@ -0,0 +1,23 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: prefix_chars', + prefixChars: '-+' +}); +parser.addArgument(['+f', '++foo']); +parser.addArgument(['++bar'], {action: 'storeTrue'}); + +parser.printHelp(); +console.log('-----------'); + +var args; +args = parser.parseArgs(['+f', '1']); +console.dir(args); +args = parser.parseArgs(['++bar']); +console.dir(args); +args = parser.parseArgs(['++foo', '2', '++bar']); +console.dir(args); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/sub_commands.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/sub_commands.js new file mode 100755 index 00000000000000..df9c494440bee0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/sub_commands.js @@ -0,0 +1,49 @@ +#!/usr/bin/env node +'use strict'; + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: sub-commands' +}); + +var subparsers = parser.addSubparsers({ + title: 'subcommands', + dest: "subcommand_name" +}); + +var bar = subparsers.addParser('c1', {addHelp: true, help: 'c1 help'}); +bar.addArgument( + [ '-f', '--foo' ], + { + action: 'store', + help: 'foo3 bar3' + } +); +var bar = subparsers.addParser( + 'c2', + {aliases: ['co'], addHelp: true, help: 'c2 help'} +); +bar.addArgument( + [ '-b', '--bar' ], + { + action: 'store', + type: 'int', + help: 'foo3 bar3' + } +); +parser.printHelp(); +console.log('-----------'); + +var args; +args = parser.parseArgs('c1 -f 2'.split(' ')); +console.dir(args); +console.log('-----------'); +args = parser.parseArgs('c2 -b 1'.split(' ')); +console.dir(args); +console.log('-----------'); +args = parser.parseArgs('co -b 1'.split(' ')); +console.dir(args); +console.log('-----------'); +parser.parseArgs(['c1', '-h']); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/sum.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/sum.js new file mode 100755 index 00000000000000..4532800a50d31f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/sum.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node + +'use strict'; + + +var ArgumentParser = require('../lib/argparse').ArgumentParser; +var parser = new ArgumentParser({ description: 'Process some integers.' }); + + +function sum(arr) { + return arr.reduce(function (a, b) { + return a + b; + }, 0); +} +function max(arr) { + return Math.max.apply(Math, arr); +} + + +parser.addArgument(['integers'], { + metavar: 'N', + type: 'int', + nargs: '+', + help: 'an integer for the accumulator' +}); +parser.addArgument(['--sum'], { + dest: 'accumulate', + action: 'storeConst', + constant: sum, + defaultValue: max, + help: 'sum the integers (default: find the max)' +}); + +var args = parser.parseArgs('--sum 1 2 -1'.split(' ')); +console.log(args.accumulate(args.integers)); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/testformatters.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/testformatters.js new file mode 100644 index 00000000000000..1c03cdc8435c81 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/examples/testformatters.js @@ -0,0 +1,270 @@ +'use strict'; + +var a, group, parser, helptext; + +var assert = require('assert'); + + +var print = function () { + return console.log.apply(console, arguments); + }; +// print = function () {}; + +var argparse = require('argparse'); + +print("TEST argparse.ArgumentDefaultsHelpFormatter"); + +parser = new argparse.ArgumentParser({ + debug: true, + formatterClass: argparse.ArgumentDefaultsHelpFormatter, + description: 'description' +}); + +parser.addArgument(['--foo'], { + help: 'foo help - oh and by the way, %(defaultValue)s' +}); + +parser.addArgument(['--bar'], { + action: 'storeTrue', + help: 'bar help' +}); + +parser.addArgument(['spam'], { + help: 'spam help' +}); + +parser.addArgument(['badger'], { + nargs: '?', + defaultValue: 'wooden', + help: 'badger help' +}); + +group = parser.addArgumentGroup({ + title: 'title', + description: 'group description' +}); + +group.addArgument(['--baz'], { + type: 'int', + defaultValue: 42, + help: 'baz help' +}); + +helptext = parser.formatHelp(); +print(helptext); +// test selected clips +assert(helptext.match(/badger help \(default: wooden\)/)); +assert(helptext.match(/foo help - oh and by the way, null/)); +assert(helptext.match(/bar help \(default: false\)/)); +assert(helptext.match(/title:\n {2}group description/)); // test indent +assert(helptext.match(/baz help \(default: 42\)/im)); + +/* +usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger] + +description + +positional arguments: + spam spam help + badger badger help (default: wooden) + +optional arguments: + -h, --help show this help message and exit + --foo FOO foo help - oh and by the way, null + --bar bar help (default: false) + +title: + group description + + --baz BAZ baz help (default: 42) +*/ + +print("TEST argparse.RawDescriptionHelpFormatter"); + +parser = new argparse.ArgumentParser({ + debug: true, + prog: 'PROG', + formatterClass: argparse.RawDescriptionHelpFormatter, + description: 'Keep the formatting\n' + + ' exactly as it is written\n' + + '\n' + + 'here\n' +}); + +a = parser.addArgument(['--foo'], { + help: ' foo help should not\n' + + ' retain this odd formatting' +}); + +parser.addArgument(['spam'], { + 'help': 'spam help' +}); + +group = parser.addArgumentGroup({ + title: 'title', + description: ' This text\n' + + ' should be indented\n' + + ' exactly like it is here\n' +}); + +group.addArgument(['--bar'], { + help: 'bar help' +}); + +helptext = parser.formatHelp(); +print(helptext); +// test selected clips +assert(helptext.match(parser.description)); +assert.equal(helptext.match(a.help), null); +assert(helptext.match(/foo help should not retain this odd formatting/)); + +/* +class TestHelpRawDescription(HelpTestCase): + """Test the RawTextHelpFormatter""" +.... + +usage: PROG [-h] [--foo FOO] [--bar BAR] spam + +Keep the formatting + exactly as it is written + +here + +positional arguments: + spam spam help + +optional arguments: + -h, --help show this help message and exit + --foo FOO foo help should not retain this odd formatting + +title: + This text + should be indented + exactly like it is here + + --bar BAR bar help +*/ + + +print("TEST argparse.RawTextHelpFormatter"); + +parser = new argparse.ArgumentParser({ + debug: true, + prog: 'PROG', + formatterClass: argparse.RawTextHelpFormatter, + description: 'Keep the formatting\n' + + ' exactly as it is written\n' + + '\n' + + 'here\n' +}); + +parser.addArgument(['--baz'], { + help: ' baz help should also\n' + + 'appear as given here' +}); + +a = parser.addArgument(['--foo'], { + help: ' foo help should also\n' + + 'appear as given here' +}); + +parser.addArgument(['spam'], { + 'help': 'spam help' +}); + +group = parser.addArgumentGroup({ + title: 'title', + description: ' This text\n' + + ' should be indented\n' + + ' exactly like it is here\n' +}); + +group.addArgument(['--bar'], { + help: 'bar help' +}); + +helptext = parser.formatHelp(); +print(helptext); +// test selected clips +assert(helptext.match(parser.description)); +assert(helptext.match(/( {14})appear as given here/gm)); + +/* +class TestHelpRawText(HelpTestCase): + """Test the RawTextHelpFormatter""" + +usage: PROG [-h] [--foo FOO] [--bar BAR] spam + +Keep the formatting + exactly as it is written + +here + +positional arguments: + spam spam help + +optional arguments: + -h, --help show this help message and exit + --foo FOO foo help should also + appear as given here + +title: + This text + should be indented + exactly like it is here + + --bar BAR bar help +*/ + + +print("TEST metavar as a tuple"); + +parser = new argparse.ArgumentParser({ + prog: 'PROG' +}); + +parser.addArgument(['-w'], { + help: 'w', + nargs: '+', + metavar: ['W1', 'W2'] +}); + +parser.addArgument(['-x'], { + help: 'x', + nargs: '*', + metavar: ['X1', 'X2'] +}); + +parser.addArgument(['-y'], { + help: 'y', + nargs: 3, + metavar: ['Y1', 'Y2', 'Y3'] +}); + +parser.addArgument(['-z'], { + help: 'z', + nargs: '?', + metavar: ['Z1'] +}); + +helptext = parser.formatHelp(); +print(helptext); +var ustring = 'PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] [-z [Z1]]'; +ustring = ustring.replace(/\[/g, '\\[').replace(/\]/g, '\\]'); +// print(ustring) +assert(helptext.match(new RegExp(ustring))); + +/* +class TestHelpTupleMetavar(HelpTestCase): + """Test specifying metavar as a tuple""" + +usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] [-z [Z1]] + +optional arguments: + -h, --help show this help message and exit + -w W1 [W2 ...] w + -x [X1 [X2 ...]] x + -y Y1 Y2 Y3 y + -z [Z1] z +*/ + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/index.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/index.js new file mode 100644 index 00000000000000..3b6eea0138b844 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/argparse'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action.js new file mode 100644 index 00000000000000..6f7e9a56ccc667 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action.js @@ -0,0 +1,146 @@ +/** + * class Action + * + * Base class for all actions + * Do not call in your code, use this class only for inherits your own action + * + * Information about how to convert command line strings to Javascript objects. + * Action objects are used by an ArgumentParser to represent the information + * needed to parse a single argument from one or more strings from the command + * line. The keyword arguments to the Action constructor are also all attributes + * of Action instances. + * + * #####Alowed keywords: + * + * - `store` + * - `storeConstant` + * - `storeTrue` + * - `storeFalse` + * - `append` + * - `appendConstant` + * - `count` + * - `help` + * - `version` + * + * Information about action options see [[Action.new]] + * + * See also [original guide](http://docs.python.org/dev/library/argparse.html#action) + * + **/ + +'use strict'; + + +// Constants +var $$ = require('./const'); + + +/** + * new Action(options) + * + * Base class for all actions. Used only for inherits + * + * + * ##### Options: + * + * - `optionStrings` A list of command-line option strings for the action. + * - `dest` Attribute to hold the created object(s) + * - `nargs` The number of command-line arguments that should be consumed. + * By default, one argument will be consumed and a single value will be + * produced. + * - `constant` Default value for an action with no value. + * - `defaultValue` The value to be produced if the option is not specified. + * - `type` Cast to 'string'|'int'|'float'|'complex'|function (string). If + * None, 'string'. + * - `choices` The choices available. + * - `required` True if the action must always be specified at the command + * line. + * - `help` The help describing the argument. + * - `metavar` The name to be used for the option's argument with the help + * string. If None, the 'dest' value will be used as the name. + * + * ##### nargs supported values: + * + * - `N` (an integer) consumes N arguments (and produces a list) + * - `?` consumes zero or one arguments + * - `*` consumes zero or more arguments (and produces a list) + * - `+` consumes one or more arguments (and produces a list) + * + * Note: that the difference between the default and nargs=1 is that with the + * default, a single value will be produced, while with nargs=1, a list + * containing a single value will be produced. + **/ +var Action = module.exports = function Action(options) { + options = options || {}; + this.optionStrings = options.optionStrings || []; + this.dest = options.dest; + this.nargs = options.nargs !== undefined ? options.nargs : null; + this.constant = options.constant !== undefined ? options.constant : null; + this.defaultValue = options.defaultValue; + this.type = options.type !== undefined ? options.type : null; + this.choices = options.choices !== undefined ? options.choices : null; + this.required = options.required !== undefined ? options.required: false; + this.help = options.help !== undefined ? options.help : null; + this.metavar = options.metavar !== undefined ? options.metavar : null; + + if (!(this.optionStrings instanceof Array)) { + throw new Error('optionStrings should be an array'); + } + if (this.required !== undefined && typeof(this.required) !== 'boolean') { + throw new Error('required should be a boolean'); + } +}; + +/** + * Action#getName -> String + * + * Tells action name + **/ +Action.prototype.getName = function () { + if (this.optionStrings.length > 0) { + return this.optionStrings.join('/'); + } else if (this.metavar !== null && this.metavar !== $$.SUPPRESS) { + return this.metavar; + } else if (this.dest !== undefined && this.dest !== $$.SUPPRESS) { + return this.dest; + } + return null; +}; + +/** + * Action#isOptional -> Boolean + * + * Return true if optional + **/ +Action.prototype.isOptional = function () { + return !this.isPositional(); +}; + +/** + * Action#isPositional -> Boolean + * + * Return true if positional + **/ +Action.prototype.isPositional = function () { + return (this.optionStrings.length === 0); +}; + +/** + * Action#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Should be implemented in inherited classes + * + * ##### Example + * + * ActionCount.prototype.call = function (parser, namespace, values, optionString) { + * namespace.set(this.dest, (namespace[this.dest] || 0) + 1); + * }; + * + **/ +Action.prototype.call = function () { + throw new Error('.call() not defined');// Not Implemented error +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/append.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/append.js new file mode 100644 index 00000000000000..48c6dbe30de5d6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/append.js @@ -0,0 +1,55 @@ +/*:nodoc:* + * class ActionAppend + * + * This action stores a list, and appends each argument value to the list. + * This is useful to allow an option to be specified multiple times. + * This class inherided from [[Action]] + * + **/ + +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// Constants +var $$ = require('../const'); + +/*:nodoc:* + * new ActionAppend(options) + * - options (object): options hash see [[Action.new]] + * + * Note: options.nargs should be optional for constants + * and more then zero for other + **/ +var ActionAppend = module.exports = function ActionAppend(options) { + options = options || {}; + if (this.nargs <= 0) { + throw new Error('nargs for append actions must be > 0; if arg ' + + 'strings are not supplying the value to append, ' + + 'the append const action may be more appropriate'); + } + if (!!this.constant && this.nargs !== $$.OPTIONAL) { + throw new Error('nargs must be OPTIONAL to supply const'); + } + Action.call(this, options); +}; +util.inherits(ActionAppend, Action); + +/*:nodoc:* + * ActionAppend#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionAppend.prototype.call = function (parser, namespace, values) { + var items = [].concat(namespace[this.dest] || []); // or _.clone + items.push(values); + namespace.set(this.dest, items); +}; + + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/append/constant.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/append/constant.js new file mode 100644 index 00000000000000..90747abbf61115 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/append/constant.js @@ -0,0 +1,47 @@ +/*:nodoc:* + * class ActionAppendConstant + * + * This stores a list, and appends the value specified by + * the const keyword argument to the list. + * (Note that the const keyword argument defaults to null.) + * The 'appendConst' action is typically useful when multiple + * arguments need to store constants to the same list. + * + * This class inherited from [[Action]] + **/ + +'use strict'; + +var util = require('util'); + +var Action = require('../../action'); + +/*:nodoc:* + * new ActionAppendConstant(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionAppendConstant = module.exports = function ActionAppendConstant(options) { + options = options || {}; + options.nargs = 0; + if (options.constant === undefined) { + throw new Error('constant option is required for appendAction'); + } + Action.call(this, options); +}; +util.inherits(ActionAppendConstant, Action); + +/*:nodoc:* + * ActionAppendConstant#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionAppendConstant.prototype.call = function (parser, namespace) { + var items = [].concat(namespace[this.dest] || []); + items.push(this.constant); + namespace.set(this.dest, items); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/count.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/count.js new file mode 100644 index 00000000000000..d6a5899d07ef24 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/count.js @@ -0,0 +1,40 @@ +/*:nodoc:* + * class ActionCount + * + * This counts the number of times a keyword argument occurs. + * For example, this is useful for increasing verbosity levels + * + * This class inherided from [[Action]] + * + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +/*:nodoc:* + * new ActionCount(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionCount = module.exports = function ActionCount(options) { + options = options || {}; + options.nargs = 0; + + Action.call(this, options); +}; +util.inherits(ActionCount, Action); + +/*:nodoc:* + * ActionCount#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionCount.prototype.call = function (parser, namespace) { + namespace.set(this.dest, (namespace[this.dest] || 0) + 1); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/help.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/help.js new file mode 100644 index 00000000000000..7f7b4e2d21219b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/help.js @@ -0,0 +1,48 @@ +/*:nodoc:* + * class ActionHelp + * + * Support action for printing help + * This class inherided from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// Constants +var $$ = require('../const'); + +/*:nodoc:* + * new ActionHelp(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionHelp = module.exports = function ActionHelp(options) { + options = options || {}; + if (options.defaultValue !== null) { + options.defaultValue = options.defaultValue; + } + else { + options.defaultValue = $$.SUPPRESS; + } + options.dest = (options.dest !== null ? options.dest: $$.SUPPRESS); + options.nargs = 0; + Action.call(this, options); + +}; +util.inherits(ActionHelp, Action); + +/*:nodoc:* + * ActionHelp#call(parser, namespace, values, optionString) + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Print help and exit + **/ +ActionHelp.prototype.call = function (parser) { + parser.printHelp(); + parser.exit(); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store.js new file mode 100644 index 00000000000000..8ebc9748b6914c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store.js @@ -0,0 +1,50 @@ +/*:nodoc:* + * class ActionStore + * + * This action just stores the argument’s value. This is the default action. + * + * This class inherited from [[Action]] + * + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// Constants +var $$ = require('../const'); + + +/*:nodoc:* + * new ActionStore(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStore = module.exports = function ActionStore(options) { + options = options || {}; + if (this.nargs <= 0) { + throw new Error('nargs for store actions must be > 0; if you ' + + 'have nothing to store, actions such as store ' + + 'true or store const may be more appropriate'); + + } + if (this.constant !== undefined && this.nargs !== $$.OPTIONAL) { + throw new Error('nargs must be OPTIONAL to supply const'); + } + Action.call(this, options); +}; +util.inherits(ActionStore, Action); + +/*:nodoc:* + * ActionStore#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionStore.prototype.call = function (parser, namespace, values) { + namespace.set(this.dest, values); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/constant.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/constant.js new file mode 100644 index 00000000000000..8410fcf784c64e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/constant.js @@ -0,0 +1,43 @@ +/*:nodoc:* + * class ActionStoreConstant + * + * This action stores the value specified by the const keyword argument. + * (Note that the const keyword argument defaults to the rather unhelpful null.) + * The 'store_const' action is most commonly used with optional + * arguments that specify some sort of flag. + * + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../../action'); + +/*:nodoc:* + * new ActionStoreConstant(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStoreConstant = module.exports = function ActionStoreConstant(options) { + options = options || {}; + options.nargs = 0; + if (options.constant === undefined) { + throw new Error('constant option is required for storeAction'); + } + Action.call(this, options); +}; +util.inherits(ActionStoreConstant, Action); + +/*:nodoc:* + * ActionStoreConstant#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Save result in namespace object + **/ +ActionStoreConstant.prototype.call = function (parser, namespace) { + namespace.set(this.dest, this.constant); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/false.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/false.js new file mode 100644 index 00000000000000..66417bf6d8f0e2 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/false.js @@ -0,0 +1,27 @@ +/*:nodoc:* + * class ActionStoreFalse + * + * This action store the values False respectively. + * This is special cases of 'storeConst' + * + * This class inherited from [[Action]] + **/ + +'use strict'; + +var util = require('util'); + +var ActionStoreConstant = require('./constant'); + +/*:nodoc:* + * new ActionStoreFalse(options) + * - options (object): hash of options see [[Action.new]] + * + **/ +var ActionStoreFalse = module.exports = function ActionStoreFalse(options) { + options = options || {}; + options.constant = false; + options.defaultValue = options.defaultValue !== null ? options.defaultValue: true; + ActionStoreConstant.call(this, options); +}; +util.inherits(ActionStoreFalse, ActionStoreConstant); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/true.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/true.js new file mode 100644 index 00000000000000..43ec7086f629c0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/store/true.js @@ -0,0 +1,26 @@ +/*:nodoc:* + * class ActionStoreTrue + * + * This action store the values True respectively. + * This isspecial cases of 'storeConst' + * + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var ActionStoreConstant = require('./constant'); + +/*:nodoc:* + * new ActionStoreTrue(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionStoreTrue = module.exports = function ActionStoreTrue(options) { + options = options || {}; + options.constant = true; + options.defaultValue = options.defaultValue !== null ? options.defaultValue: false; + ActionStoreConstant.call(this, options); +}; +util.inherits(ActionStoreTrue, ActionStoreConstant); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/subparsers.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/subparsers.js new file mode 100644 index 00000000000000..257714d40e0e3f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/subparsers.js @@ -0,0 +1,148 @@ +/** internal + * class ActionSubparsers + * + * Support the creation of such sub-commands with the addSubparsers() + * + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); +var format = require('util').format; +var _ = require('lodash'); + + +var Action = require('../action'); + +// Constants +var $$ = require('../const'); + +// Errors +var argumentErrorHelper = require('../argument/error'); + + +/*:nodoc:* + * new ChoicesPseudoAction(name, help) + * + * Create pseudo action for correct help text + * + **/ +var ChoicesPseudoAction = function (name, help) { + var options = { + optionStrings: [], + dest: name, + help: help + }; + + Action.call(this, options); +}; +util.inherits(ChoicesPseudoAction, Action); + +/** + * new ActionSubparsers(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionSubparsers = module.exports = function ActionSubparsers(options) { + options = options || {}; + options.dest = options.dest || $$.SUPPRESS; + options.nargs = $$.PARSER; + + this.debug = (options.debug === true); + + this._progPrefix = options.prog; + this._parserClass = options.parserClass; + this._nameParserMap = {}; + this._choicesActions = []; + + options.choices = this._nameParserMap; + Action.call(this, options); +}; +util.inherits(ActionSubparsers, Action); + +/*:nodoc:* + * ActionSubparsers#addParser(name, options) -> ArgumentParser + * - name (string): sub-command name + * - options (object): see [[ArgumentParser.new]] + * + * Note: + * addParser supports an additional aliases option, + * which allows multiple strings to refer to the same subparser. + * This example, like svn, aliases co as a shorthand for checkout + * + **/ +ActionSubparsers.prototype.addParser = function (name, options) { + var parser; + + var self = this; + + options = options || {}; + + options.debug = (this.debug === true); + + // set program from the existing prefix + if (!options.prog) { + options.prog = this._progPrefix + ' ' + name; + } + + var aliases = options.aliases || []; + + // create a pseudo-action to hold the choice help + if (!!options.help || _.isString(options.help)) { + var help = options.help; + delete options.help; + + var choiceAction = new ChoicesPseudoAction(name, help); + this._choicesActions.push(choiceAction); + } + + // create the parser and add it to the map + parser = new this._parserClass(options); + this._nameParserMap[name] = parser; + + // make parser available under aliases also + aliases.forEach(function (alias) { + self._nameParserMap[alias] = parser; + }); + + return parser; +}; + +ActionSubparsers.prototype._getSubactions = function () { + return this._choicesActions; +}; + +/*:nodoc:* + * ActionSubparsers#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Call the action. Parse input aguments + **/ +ActionSubparsers.prototype.call = function (parser, namespace, values) { + var parserName = values[0]; + var argStrings = values.slice(1); + + // set the parser name if requested + if (this.dest !== $$.SUPPRESS) { + namespace[this.dest] = parserName; + } + + // select the parser + if (!!this._nameParserMap[parserName]) { + parser = this._nameParserMap[parserName]; + } else { + throw argumentErrorHelper(format( + 'Unknown parser "%s" (choices: [%s]).', + parserName, + _.keys(this._nameParserMap).join(', ') + )); + } + + // parse all the remaining options into the namespace + parser.parseArgs(argStrings, namespace); +}; + + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/version.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/version.js new file mode 100644 index 00000000000000..a17877c0bacc3c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action/version.js @@ -0,0 +1,50 @@ +/*:nodoc:* + * class ActionVersion + * + * Support action for printing program version + * This class inherited from [[Action]] + **/ +'use strict'; + +var util = require('util'); + +var Action = require('../action'); + +// +// Constants +// +var $$ = require('../const'); + +/*:nodoc:* + * new ActionVersion(options) + * - options (object): options hash see [[Action.new]] + * + **/ +var ActionVersion = module.exports = function ActionVersion(options) { + options = options || {}; + options.defaultValue = (!!options.defaultValue ? options.defaultValue: $$.SUPPRESS); + options.dest = (options.dest || $$.SUPPRESS); + options.nargs = 0; + this.version = options.version; + Action.call(this, options); +}; +util.inherits(ActionVersion, Action); + +/*:nodoc:* + * ActionVersion#call(parser, namespace, values, optionString) -> Void + * - parser (ArgumentParser): current parser + * - namespace (Namespace): namespace for output data + * - values (Array): parsed values + * - optionString (Array): input option string(not parsed) + * + * Print version and exit + **/ +ActionVersion.prototype.call = function (parser) { + var version = this.version || parser.version; + var formatter = parser._getFormatter(); + formatter.addText(version); + parser.exit(0, formatter.formatHelp()); +}; + + + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action_container.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action_container.js new file mode 100644 index 00000000000000..043ead410f6295 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/action_container.js @@ -0,0 +1,479 @@ +/** internal + * class ActionContainer + * + * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] + **/ + +'use strict'; + +var format = require('util').format; +var _ = require('lodash'); + +// Constants +var $$ = require('./const'); + +//Actions +var ActionHelp = require('./action/help'); +var ActionAppend = require('./action/append'); +var ActionAppendConstant = require('./action/append/constant'); +var ActionCount = require('./action/count'); +var ActionStore = require('./action/store'); +var ActionStoreConstant = require('./action/store/constant'); +var ActionStoreTrue = require('./action/store/true'); +var ActionStoreFalse = require('./action/store/false'); +var ActionVersion = require('./action/version'); +var ActionSubparsers = require('./action/subparsers'); + +// Errors +var argumentErrorHelper = require('./argument/error'); + + + +/** + * new ActionContainer(options) + * + * Action container. Parent for [[ArgumentParser]] and [[ArgumentGroup]] + * + * ##### Options: + * + * - `description` -- A description of what the program does + * - `prefixChars` -- Characters that prefix optional arguments + * - `argumentDefault` -- The default value for all arguments + * - `conflictHandler` -- The conflict handler to use for duplicate arguments + **/ +var ActionContainer = module.exports = function ActionContainer(options) { + options = options || {}; + + this.description = options.description; + this.argumentDefault = options.argumentDefault; + this.prefixChars = options.prefixChars || ''; + this.conflictHandler = options.conflictHandler; + + // set up registries + this._registries = {}; + + // register actions + this.register('action', null, ActionStore); + this.register('action', 'store', ActionStore); + this.register('action', 'storeConst', ActionStoreConstant); + this.register('action', 'storeTrue', ActionStoreTrue); + this.register('action', 'storeFalse', ActionStoreFalse); + this.register('action', 'append', ActionAppend); + this.register('action', 'appendConst', ActionAppendConstant); + this.register('action', 'count', ActionCount); + this.register('action', 'help', ActionHelp); + this.register('action', 'version', ActionVersion); + this.register('action', 'parsers', ActionSubparsers); + + // raise an exception if the conflict handler is invalid + this._getHandler(); + + // action storage + this._actions = []; + this._optionStringActions = {}; + + // groups + this._actionGroups = []; + this._mutuallyExclusiveGroups = []; + + // defaults storage + this._defaults = {}; + + // determines whether an "option" looks like a negative number + // -1, -1.5 -5e+4 + this._regexpNegativeNumber = new RegExp('^[-]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'); + + // whether or not there are any optionals that look like negative + // numbers -- uses a list so it can be shared and edited + this._hasNegativeNumberOptionals = []; +}; + +// Groups must be required, then ActionContainer already defined +var ArgumentGroup = require('./argument/group'); +var MutuallyExclusiveGroup = require('./argument/exclusive'); + +// +// Registration methods +// + +/** + * ActionContainer#register(registryName, value, object) -> Void + * - registryName (String) : object type action|type + * - value (string) : keyword + * - object (Object|Function) : handler + * + * Register handlers + **/ +ActionContainer.prototype.register = function (registryName, value, object) { + this._registries[registryName] = this._registries[registryName] || {}; + this._registries[registryName][value] = object; +}; + +ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) { + if (3 > arguments.length) { + defaultValue = null; + } + return this._registries[registryName][value] || defaultValue; +}; + +// +// Namespace default accessor methods +// + +/** + * ActionContainer#setDefaults(options) -> Void + * - options (object):hash of options see [[Action.new]] + * + * Set defaults + **/ +ActionContainer.prototype.setDefaults = function (options) { + options = options || {}; + for (var property in options) { + this._defaults[property] = options[property]; + } + + // if these defaults match any existing arguments, replace the previous + // default on the object with the new one + this._actions.forEach(function (action) { + if (action.dest in options) { + action.defaultValue = options[action.dest]; + } + }); +}; + +/** + * ActionContainer#getDefault(dest) -> Mixed + * - dest (string): action destination + * + * Return action default value + **/ +ActionContainer.prototype.getDefault = function (dest) { + var result = (_.has(this._defaults, dest)) ? this._defaults[dest] : null; + + this._actions.forEach(function (action) { + if (action.dest === dest && _.has(action, 'defaultValue')) { + result = action.defaultValue; + } + }); + + return result; +}; +// +// Adding argument actions +// + +/** + * ActionContainer#addArgument(args, options) -> Object + * - args (Array): array of argument keys + * - options (Object): action objects see [[Action.new]] + * + * #### Examples + * - addArgument([-f, --foo], {action:'store', defaultValue=1, ...}) + * - addArgument(['bar'], action: 'store', nargs:1, ...}) + **/ +ActionContainer.prototype.addArgument = function (args, options) { + args = args; + options = options || {}; + + if (!_.isArray(args)) { + throw new TypeError('addArgument first argument should be an array'); + } + if (!_.isObject(options) || _.isArray(options)) { + throw new TypeError('addArgument second argument should be a hash'); + } + + // if no positional args are supplied or only one is supplied and + // it doesn't look like an option string, parse a positional argument + if (!args || args.length === 1 && this.prefixChars.indexOf(args[0][0]) < 0) { + if (args && !!options.dest) { + throw new Error('dest supplied twice for positional argument'); + } + options = this._getPositional(args, options); + + // otherwise, we're adding an optional argument + } else { + options = this._getOptional(args, options); + } + + // if no default was supplied, use the parser-level default + if (_.isUndefined(options.defaultValue)) { + var dest = options.dest; + if (_.has(this._defaults, dest)) { + options.defaultValue = this._defaults[dest]; + } else if (!_.isUndefined(this.argumentDefault)) { + options.defaultValue = this.argumentDefault; + } + } + + // create the action object, and add it to the parser + var ActionClass = this._popActionClass(options); + if (! _.isFunction(ActionClass)) { + throw new Error(format('Unknown action "%s".', ActionClass)); + } + var action = new ActionClass(options); + + // throw an error if the action type is not callable + var typeFunction = this._registryGet('type', action.type, action.type); + if (!_.isFunction(typeFunction)) { + throw new Error(format('"%s" is not callable', typeFunction)); + } + + return this._addAction(action); +}; + +/** + * ActionContainer#addArgumentGroup(options) -> ArgumentGroup + * - options (Object): hash of options see [[ArgumentGroup.new]] + * + * Create new arguments groups + **/ +ActionContainer.prototype.addArgumentGroup = function (options) { + var group = new ArgumentGroup(this, options); + this._actionGroups.push(group); + return group; +}; + +/** + * ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup + * - options (Object): {required: false} + * + * Create new mutual exclusive groups + **/ +ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) { + var group = new MutuallyExclusiveGroup(this, options); + this._mutuallyExclusiveGroups.push(group); + return group; +}; + +ActionContainer.prototype._addAction = function (action) { + var self = this; + + // resolve any conflicts + this._checkConflict(action); + + // add to actions list + this._actions.push(action); + action.container = this; + + // index the action by any option strings it has + action.optionStrings.forEach(function (optionString) { + self._optionStringActions[optionString] = action; + }); + + // set the flag if any option strings look like negative numbers + action.optionStrings.forEach(function (optionString) { + if (optionString.match(self._regexpNegativeNumber)) { + if (!_.any(self._hasNegativeNumberOptionals)) { + self._hasNegativeNumberOptionals.push(true); + } + } + }); + + // return the created action + return action; +}; + +ActionContainer.prototype._removeAction = function (action) { + var actionIndex = this._actions.indexOf(action); + if (actionIndex >= 0) { + this._actions.splice(actionIndex, 1); + } +}; + +ActionContainer.prototype._addContainerActions = function (container) { + // collect groups by titles + var titleGroupMap = {}; + this._actionGroups.forEach(function (group) { + if (titleGroupMap[group.title]) { + throw new Error(format('Cannot merge actions - two groups are named "%s".', group.title)); + } + titleGroupMap[group.title] = group; + }); + + // map each action to its group + var groupMap = {}; + function actionHash(action) { + // unique (hopefully?) string suitable as dictionary key + return action.getName(); + } + container._actionGroups.forEach(function (group) { + // if a group with the title exists, use that, otherwise + // create a new group matching the container's group + if (!titleGroupMap[group.title]) { + titleGroupMap[group.title] = this.addArgumentGroup({ + title: group.title, + description: group.description + }); + } + + // map the actions to their new group + group._groupActions.forEach(function (action) { + groupMap[actionHash(action)] = titleGroupMap[group.title]; + }); + }, this); + + // add container's mutually exclusive groups + // NOTE: if add_mutually_exclusive_group ever gains title= and + // description= then this code will need to be expanded as above + var mutexGroup; + container._mutuallyExclusiveGroups.forEach(function (group) { + mutexGroup = this.addMutuallyExclusiveGroup({ + required: group.required + }); + // map the actions to their new mutex group + group._groupActions.forEach(function (action) { + groupMap[actionHash(action)] = mutexGroup; + }); + }, this); // forEach takes a 'this' argument + + // add all actions to this container or their group + container._actions.forEach(function (action) { + var key = actionHash(action); + if (!!groupMap[key]) { + groupMap[key]._addAction(action); + } + else + { + this._addAction(action); + } + }); +}; + +ActionContainer.prototype._getPositional = function (dest, options) { + if (_.isArray(dest)) { + dest = _.first(dest); + } + // make sure required is not specified + if (options.required) { + throw new Error('"required" is an invalid argument for positionals.'); + } + + // mark positional arguments as required if at least one is + // always required + if (options.nargs !== $$.OPTIONAL && options.nargs !== $$.ZERO_OR_MORE) { + options.required = true; + } + if (options.nargs === $$.ZERO_OR_MORE && options.defaultValue === undefined) { + options.required = true; + } + + // return the keyword arguments with no option strings + options.dest = dest; + options.optionStrings = []; + return options; +}; + +ActionContainer.prototype._getOptional = function (args, options) { + var prefixChars = this.prefixChars; + var optionStrings = []; + var optionStringsLong = []; + + // determine short and long option strings + args.forEach(function (optionString) { + // error on strings that don't start with an appropriate prefix + if (prefixChars.indexOf(optionString[0]) < 0) { + throw new Error(format('Invalid option string "%s": must start with a "%s".', + optionString, + prefixChars + )); + } + + // strings starting with two prefix characters are long options + optionStrings.push(optionString); + if (optionString.length > 1 && prefixChars.indexOf(optionString[1]) >= 0) { + optionStringsLong.push(optionString); + } + }); + + // infer dest, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' + var dest = options.dest || null; + delete options.dest; + + if (!dest) { + var optionStringDest = optionStringsLong.length ? optionStringsLong[0] :optionStrings[0]; + dest = _.trim(optionStringDest, this.prefixChars); + + if (dest.length === 0) { + throw new Error( + format('dest= is required for options like "%s"', optionStrings.join(', ')) + ); + } + dest = dest.replace(/-/g, '_'); + } + + // return the updated keyword arguments + options.dest = dest; + options.optionStrings = optionStrings; + + return options; +}; + +ActionContainer.prototype._popActionClass = function (options, defaultValue) { + defaultValue = defaultValue || null; + + var action = (options.action || defaultValue); + delete options.action; + + var actionClass = this._registryGet('action', action, action); + return actionClass; +}; + +ActionContainer.prototype._getHandler = function () { + var handlerString = this.conflictHandler; + var handlerFuncName = "_handleConflict" + _.capitalize(handlerString); + var func = this[handlerFuncName]; + if (typeof func === 'undefined') { + var msg = "invalid conflict resolution value: " + handlerString; + throw new Error(msg); + } else { + return func; + } +}; + +ActionContainer.prototype._checkConflict = function (action) { + var optionStringActions = this._optionStringActions; + var conflictOptionals = []; + + // find all options that conflict with this option + // collect pairs, the string, and an existing action that it conflicts with + action.optionStrings.forEach(function (optionString) { + var conflOptional = optionStringActions[optionString]; + if (typeof conflOptional !== 'undefined') { + conflictOptionals.push([optionString, conflOptional]); + } + }); + + if (conflictOptionals.length > 0) { + var conflictHandler = this._getHandler(); + conflictHandler.call(this, action, conflictOptionals); + } +}; + +ActionContainer.prototype._handleConflictError = function (action, conflOptionals) { + var conflicts = _.map(conflOptionals, function (pair) {return pair[0]; }); + conflicts = conflicts.join(', '); + throw argumentErrorHelper( + action, + format('Conflicting option string(s): %s', conflicts) + ); +}; + +ActionContainer.prototype._handleConflictResolve = function (action, conflOptionals) { + // remove all conflicting options + var self = this; + conflOptionals.forEach(function (pair) { + var optionString = pair[0]; + var conflictingAction = pair[1]; + // remove the conflicting option string + var i = conflictingAction.optionStrings.indexOf(optionString); + if (i >= 0) { + conflictingAction.optionStrings.splice(i, 1); + } + delete self._optionStringActions[optionString]; + // if the option now has no option string, remove it from the + // container holding it + if (conflictingAction.optionStrings.length === 0) { + conflictingAction.container._removeAction(conflictingAction); + } + }); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argparse.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argparse.js new file mode 100644 index 00000000000000..f2a2c51d9a8917 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argparse.js @@ -0,0 +1,14 @@ +'use strict'; + +module.exports.ArgumentParser = require('./argument_parser.js'); +module.exports.Namespace = require('./namespace'); +module.exports.Action = require('./action'); +module.exports.HelpFormatter = require('./help/formatter.js'); +module.exports.Const = require('./const.js'); + +module.exports.ArgumentDefaultsHelpFormatter = + require('./help/added_formatters.js').ArgumentDefaultsHelpFormatter; +module.exports.RawDescriptionHelpFormatter = + require('./help/added_formatters.js').RawDescriptionHelpFormatter; +module.exports.RawTextHelpFormatter = + require('./help/added_formatters.js').RawTextHelpFormatter; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/error.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/error.js new file mode 100644 index 00000000000000..c8a02a08b8fbaf --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/error.js @@ -0,0 +1,50 @@ +'use strict'; + + +var format = require('util').format; + + +var ERR_CODE = 'ARGError'; + +/*:nodoc:* + * argumentError(argument, message) -> TypeError + * - argument (Object): action with broken argument + * - message (String): error message + * + * Error format helper. An error from creating or using an argument + * (optional or positional). The string value of this exception + * is the message, augmented with information + * about the argument that caused it. + * + * #####Example + * + * var argumentErrorHelper = require('./argument/error'); + * if (conflictOptionals.length > 0) { + * throw argumentErrorHelper( + * action, + * format('Conflicting option string(s): %s', conflictOptionals.join(', ')) + * ); + * } + * + **/ +module.exports = function (argument, message) { + var argumentName = null; + var errMessage; + var err; + + if (argument.getName) { + argumentName = argument.getName(); + } else { + argumentName = '' + argument; + } + + if (!argumentName) { + errMessage = message; + } else { + errMessage = format('argument "%s": %s', argumentName, message); + } + + err = new TypeError(errMessage); + err.code = ERR_CODE; + return err; +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/exclusive.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/exclusive.js new file mode 100644 index 00000000000000..8287e00d0464f3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/exclusive.js @@ -0,0 +1,54 @@ +/** internal + * class MutuallyExclusiveGroup + * + * Group arguments. + * By default, ArgumentParser groups command-line arguments + * into “positional arguments” and “optional arguments” + * when displaying help messages. When there is a better + * conceptual grouping of arguments than this default one, + * appropriate groups can be created using the addArgumentGroup() method + * + * This class inherited from [[ArgumentContainer]] + **/ +'use strict'; + +var util = require('util'); + +var ArgumentGroup = require('./group'); + +/** + * new MutuallyExclusiveGroup(container, options) + * - container (object): main container + * - options (object): options.required -> true/false + * + * `required` could be an argument itself, but making it a property of + * the options argument is more consistent with the JS adaptation of the Python) + **/ +var MutuallyExclusiveGroup = module.exports = function MutuallyExclusiveGroup(container, options) { + var required; + options = options || {}; + required = options.required || false; + ArgumentGroup.call(this, container); + this.required = required; + +}; +util.inherits(MutuallyExclusiveGroup, ArgumentGroup); + + +MutuallyExclusiveGroup.prototype._addAction = function (action) { + var msg; + if (action.required) { + msg = 'mutually exclusive arguments must be optional'; + throw new Error(msg); + } + action = this._container._addAction(action); + this._groupActions.push(action); + return action; +}; + + +MutuallyExclusiveGroup.prototype._removeAction = function (action) { + this._container._removeAction(action); + this._groupActions.remove(action); +}; + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/group.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/group.js new file mode 100644 index 00000000000000..58b271f2fec8d0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument/group.js @@ -0,0 +1,75 @@ +/** internal + * class ArgumentGroup + * + * Group arguments. + * By default, ArgumentParser groups command-line arguments + * into “positional arguments” and “optional arguments” + * when displaying help messages. When there is a better + * conceptual grouping of arguments than this default one, + * appropriate groups can be created using the addArgumentGroup() method + * + * This class inherited from [[ArgumentContainer]] + **/ +'use strict'; + +var util = require('util'); + +var ActionContainer = require('../action_container'); + + +/** + * new ArgumentGroup(container, options) + * - container (object): main container + * - options (object): hash of group options + * + * #### options + * - **prefixChars** group name prefix + * - **argumentDefault** default argument value + * - **title** group title + * - **description** group description + * + **/ +var ArgumentGroup = module.exports = function ArgumentGroup(container, options) { + + options = options || {}; + + // add any missing keyword arguments by checking the container + options.conflictHandler = (options.conflictHandler || container.conflictHandler); + options.prefixChars = (options.prefixChars || container.prefixChars); + options.argumentDefault = (options.argumentDefault || container.argumentDefault); + + ActionContainer.call(this, options); + + // group attributes + this.title = options.title; + this._groupActions = []; + + // share most attributes with the container + this._container = container; + this._registries = container._registries; + this._actions = container._actions; + this._optionStringActions = container._optionStringActions; + this._defaults = container._defaults; + this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals; + this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups; +}; +util.inherits(ArgumentGroup, ActionContainer); + + +ArgumentGroup.prototype._addAction = function (action) { + // Parent add action + action = ActionContainer.prototype._addAction.call(this, action); + this._groupActions.push(action); + return action; +}; + + +ArgumentGroup.prototype._removeAction = function (action) { + // Parent remove action + ActionContainer.prototype._removeAction.call(this, action); + var actionIndex = this._groupActions.indexOf(action); + if (actionIndex >= 0) { + this._groupActions.splice(actionIndex, 1); + } +}; + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument_parser.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument_parser.js new file mode 100644 index 00000000000000..2b4cee395eb8f3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/argument_parser.js @@ -0,0 +1,1168 @@ +/** + * class ArgumentParser + * + * Object for parsing command line strings into js objects. + * + * Inherited from [[ActionContainer]] + **/ +'use strict'; + +var util = require('util'); +var format = require('util').format; +var Path = require('path'); + +var _ = require('lodash'); +var sprintf = require('sprintf-js').sprintf; + +// Constants +var $$ = require('./const'); + +var ActionContainer = require('./action_container'); + +// Errors +var argumentErrorHelper = require('./argument/error'); + +var HelpFormatter = require('./help/formatter'); + +var Namespace = require('./namespace'); + + +/** + * new ArgumentParser(options) + * + * Create a new ArgumentParser object. + * + * ##### Options: + * - `prog` The name of the program (default: Path.basename(process.argv[1])) + * - `usage` A usage message (default: auto-generated from arguments) + * - `description` A description of what the program does + * - `epilog` Text following the argument descriptions + * - `parents` Parsers whose arguments should be copied into this one + * - `formatterClass` HelpFormatter class for printing help messages + * - `prefixChars` Characters that prefix optional arguments + * - `fromfilePrefixChars` Characters that prefix files containing additional arguments + * - `argumentDefault` The default value for all arguments + * - `addHelp` Add a -h/-help option + * - `conflictHandler` Specifies how to handle conflicting argument names + * - `debug` Enable debug mode. Argument errors throw exception in + * debug mode and process.exit in normal. Used for development and + * testing (default: false) + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#argumentparser-objects + **/ +var ArgumentParser = module.exports = function ArgumentParser(options) { + var self = this; + options = options || {}; + + options.description = (options.description || null); + options.argumentDefault = (options.argumentDefault || null); + options.prefixChars = (options.prefixChars || '-'); + options.conflictHandler = (options.conflictHandler || 'error'); + ActionContainer.call(this, options); + + options.addHelp = (options.addHelp === undefined || !!options.addHelp); + options.parents = (options.parents || []); + // default program name + options.prog = (options.prog || Path.basename(process.argv[1])); + this.prog = options.prog; + this.usage = options.usage; + this.epilog = options.epilog; + this.version = options.version; + + this.debug = (options.debug === true); + + this.formatterClass = (options.formatterClass || HelpFormatter); + this.fromfilePrefixChars = options.fromfilePrefixChars || null; + this._positionals = this.addArgumentGroup({title: 'Positional arguments'}); + this._optionals = this.addArgumentGroup({title: 'Optional arguments'}); + this._subparsers = null; + + // register types + var FUNCTION_IDENTITY = function (o) { + return o; + }; + this.register('type', 'auto', FUNCTION_IDENTITY); + this.register('type', null, FUNCTION_IDENTITY); + this.register('type', 'int', function (x) { + var result = parseInt(x, 10); + if (isNaN(result)) { + throw new Error(x + ' is not a valid integer.'); + } + return result; + }); + this.register('type', 'float', function (x) { + var result = parseFloat(x); + if (isNaN(result)) { + throw new Error(x + ' is not a valid float.'); + } + return result; + }); + this.register('type', 'string', function (x) { + return '' + x; + }); + + // add help and version arguments if necessary + var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0]; + if (options.addHelp) { + this.addArgument( + [defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help'], + { + action: 'help', + defaultValue: $$.SUPPRESS, + help: 'Show this help message and exit.' + } + ); + } + if (this.version !== undefined) { + this.addArgument( + [defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version'], + { + action: 'version', + version: this.version, + defaultValue: $$.SUPPRESS, + help: "Show program's version number and exit." + } + ); + } + + // add parent arguments and defaults + options.parents.forEach(function (parent) { + self._addContainerActions(parent); + if (parent._defaults !== undefined) { + for (var defaultKey in parent._defaults) { + if (parent._defaults.hasOwnProperty(defaultKey)) { + self._defaults[defaultKey] = parent._defaults[defaultKey]; + } + } + } + }); + +}; +util.inherits(ArgumentParser, ActionContainer); + +/** + * ArgumentParser#addSubparsers(options) -> [[ActionSubparsers]] + * - options (object): hash of options see [[ActionSubparsers.new]] + * + * See also [subcommands][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#sub-commands + **/ +ArgumentParser.prototype.addSubparsers = function (options) { + if (!!this._subparsers) { + this.error('Cannot have multiple subparser arguments.'); + } + + options = options || {}; + options.debug = (this.debug === true); + options.optionStrings = []; + options.parserClass = (options.parserClass || ArgumentParser); + + + if (!!options.title || !!options.description) { + + this._subparsers = this.addArgumentGroup({ + title: (options.title || 'subcommands'), + description: options.description + }); + delete options.title; + delete options.description; + + } else { + this._subparsers = this._positionals; + } + + // prog defaults to the usage message of this parser, skipping + // optional arguments and with no "usage:" prefix + if (!options.prog) { + var formatter = this._getFormatter(); + var positionals = this._getPositionalActions(); + var groups = this._mutuallyExclusiveGroups; + formatter.addUsage(this.usage, positionals, groups, ''); + options.prog = _.trim(formatter.formatHelp()); + } + + // create the parsers action and add it to the positionals list + var ParsersClass = this._popActionClass(options, 'parsers'); + var action = new ParsersClass(options); + this._subparsers._addAction(action); + + // return the created parsers action + return action; +}; + +ArgumentParser.prototype._addAction = function (action) { + if (action.isOptional()) { + this._optionals._addAction(action); + } else { + this._positionals._addAction(action); + } + return action; +}; + +ArgumentParser.prototype._getOptionalActions = function () { + return this._actions.filter(function (action) { + return action.isOptional(); + }); +}; + +ArgumentParser.prototype._getPositionalActions = function () { + return this._actions.filter(function (action) { + return action.isPositional(); + }); +}; + + +/** + * ArgumentParser#parseArgs(args, namespace) -> Namespace|Object + * - args (array): input elements + * - namespace (Namespace|Object): result object + * + * Parsed args and throws error if some arguments are not recognized + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#the-parse-args-method + **/ +ArgumentParser.prototype.parseArgs = function (args, namespace) { + var argv; + var result = this.parseKnownArgs(args, namespace); + + args = result[0]; + argv = result[1]; + if (argv && argv.length > 0) { + this.error( + format('Unrecognized arguments: %s.', argv.join(' ')) + ); + } + return args; +}; + +/** + * ArgumentParser#parseKnownArgs(args, namespace) -> array + * - args (array): input options + * - namespace (Namespace|Object): result object + * + * Parse known arguments and return tuple of result object + * and unknown args + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#partial-parsing + **/ +ArgumentParser.prototype.parseKnownArgs = function (args, namespace) { + var self = this; + + // args default to the system args + args = args || process.argv.slice(2); + + // default Namespace built from parser defaults + namespace = namespace || new Namespace(); + + self._actions.forEach(function (action) { + if (action.dest !== $$.SUPPRESS) { + if (!_.has(namespace, action.dest)) { + if (action.defaultValue !== $$.SUPPRESS) { + var defaultValue = action.defaultValue; + if (_.isString(action.defaultValue)) { + defaultValue = self._getValue(action, defaultValue); + } + namespace[action.dest] = defaultValue; + } + } + } + }); + + _.keys(self._defaults).forEach(function (dest) { + namespace[dest] = self._defaults[dest]; + }); + + // parse the arguments and exit if there are any errors + try { + var res = this._parseKnownArgs(args, namespace); + + namespace = res[0]; + args = res[1]; + if (_.has(namespace, $$._UNRECOGNIZED_ARGS_ATTR)) { + args = _.union(args, namespace[$$._UNRECOGNIZED_ARGS_ATTR]); + delete namespace[$$._UNRECOGNIZED_ARGS_ATTR]; + } + return [namespace, args]; + } catch (e) { + this.error(e); + } +}; + +ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) { + var self = this; + + var extras = []; + + // replace arg strings that are file references + if (this.fromfilePrefixChars !== null) { + argStrings = this._readArgsFromFiles(argStrings); + } + // map all mutually exclusive arguments to the other arguments + // they can't occur with + // Python has 'conflicts = action_conflicts.setdefault(mutex_action, [])' + // though I can't conceive of a way in which an action could be a member + // of two different mutually exclusive groups. + + function actionHash(action) { + // some sort of hashable key for this action + // action itself cannot be a key in actionConflicts + // I think getName() (join of optionStrings) is unique enough + return action.getName(); + } + + var conflicts, key; + var actionConflicts = {}; + + this._mutuallyExclusiveGroups.forEach(function (mutexGroup) { + mutexGroup._groupActions.forEach(function (mutexAction, i, groupActions) { + key = actionHash(mutexAction); + if (!_.has(actionConflicts, key)) { + actionConflicts[key] = []; + } + conflicts = actionConflicts[key]; + conflicts.push.apply(conflicts, groupActions.slice(0, i)); + conflicts.push.apply(conflicts, groupActions.slice(i + 1)); + }); + }); + + // find all option indices, and determine the arg_string_pattern + // which has an 'O' if there is an option at an index, + // an 'A' if there is an argument, or a '-' if there is a '--' + var optionStringIndices = {}; + + var argStringPatternParts = []; + + argStrings.forEach(function (argString, argStringIndex) { + if (argString === '--') { + argStringPatternParts.push('-'); + while (argStringIndex < argStrings.length) { + argStringPatternParts.push('A'); + argStringIndex++; + } + } + // otherwise, add the arg to the arg strings + // and note the index if it was an option + else { + var pattern; + var optionTuple = self._parseOptional(argString); + if (!optionTuple) { + pattern = 'A'; + } + else { + optionStringIndices[argStringIndex] = optionTuple; + pattern = 'O'; + } + argStringPatternParts.push(pattern); + } + }); + var argStringsPattern = argStringPatternParts.join(''); + + var seenActions = []; + var seenNonDefaultActions = []; + + + function takeAction(action, argumentStrings, optionString) { + seenActions.push(action); + var argumentValues = self._getValues(action, argumentStrings); + + // error if this argument is not allowed with other previously + // seen arguments, assuming that actions that use the default + // value don't really count as "present" + if (argumentValues !== action.defaultValue) { + seenNonDefaultActions.push(action); + if (!!actionConflicts[actionHash(action)]) { + actionConflicts[actionHash(action)].forEach(function (actionConflict) { + if (seenNonDefaultActions.indexOf(actionConflict) >= 0) { + throw argumentErrorHelper( + action, + format('Not allowed with argument "%s".', actionConflict.getName()) + ); + } + }); + } + } + + if (argumentValues !== $$.SUPPRESS) { + action.call(self, namespace, argumentValues, optionString); + } + } + + function consumeOptional(startIndex) { + // get the optional identified at this index + var optionTuple = optionStringIndices[startIndex]; + var action = optionTuple[0]; + var optionString = optionTuple[1]; + var explicitArg = optionTuple[2]; + + // identify additional optionals in the same arg string + // (e.g. -xyz is the same as -x -y -z if no args are required) + var actionTuples = []; + + var args, argCount, start, stop; + + while (true) { + if (!action) { + extras.push(argStrings[startIndex]); + return startIndex + 1; + } + if (!!explicitArg) { + argCount = self._matchArgument(action, 'A'); + + // if the action is a single-dash option and takes no + // arguments, try to parse more single-dash options out + // of the tail of the option string + var chars = self.prefixChars; + if (argCount === 0 && chars.indexOf(optionString[1]) < 0) { + actionTuples.push([action, [], optionString]); + optionString = optionString[0] + explicitArg[0]; + var newExplicitArg = explicitArg.slice(1) || null; + var optionalsMap = self._optionStringActions; + + if (_.keys(optionalsMap).indexOf(optionString) >= 0) { + action = optionalsMap[optionString]; + explicitArg = newExplicitArg; + } + else { + var msg = 'ignored explicit argument %r'; + throw argumentErrorHelper(action, msg); + } + } + // if the action expect exactly one argument, we've + // successfully matched the option; exit the loop + else if (argCount === 1) { + stop = startIndex + 1; + args = [explicitArg]; + actionTuples.push([action, args, optionString]); + break; + } + // error if a double-dash option did not use the + // explicit argument + else { + var message = 'ignored explicit argument %r'; + throw argumentErrorHelper(action, sprintf(message, explicitArg)); + } + } + // if there is no explicit argument, try to match the + // optional's string arguments with the following strings + // if successful, exit the loop + else { + + start = startIndex + 1; + var selectedPatterns = argStringsPattern.substr(start); + + argCount = self._matchArgument(action, selectedPatterns); + stop = start + argCount; + + + args = argStrings.slice(start, stop); + + actionTuples.push([action, args, optionString]); + break; + } + + } + + // add the Optional to the list and return the index at which + // the Optional's string args stopped + if (actionTuples.length < 1) { + throw new Error('length should be > 0'); + } + for (var i = 0; i < actionTuples.length; i++) { + takeAction.apply(self, actionTuples[i]); + } + return stop; + } + + // the list of Positionals left to be parsed; this is modified + // by consume_positionals() + var positionals = self._getPositionalActions(); + + function consumePositionals(startIndex) { + // match as many Positionals as possible + var selectedPattern = argStringsPattern.substr(startIndex); + var argCounts = self._matchArgumentsPartial(positionals, selectedPattern); + + // slice off the appropriate arg strings for each Positional + // and add the Positional and its args to the list + _.zip(positionals, argCounts).forEach(function (item) { + var action = item[0]; + var argCount = item[1]; + if (argCount === undefined) { + return; + } + var args = argStrings.slice(startIndex, startIndex + argCount); + + startIndex += argCount; + takeAction(action, args); + }); + + // slice off the Positionals that we just parsed and return the + // index at which the Positionals' string args stopped + positionals = positionals.slice(argCounts.length); + return startIndex; + } + + // consume Positionals and Optionals alternately, until we have + // passed the last option string + var startIndex = 0; + var position; + + var maxOptionStringIndex = -1; + + Object.keys(optionStringIndices).forEach(function (position) { + maxOptionStringIndex = Math.max(maxOptionStringIndex, parseInt(position, 10)); + }); + + var positionalsEndIndex, nextOptionStringIndex; + + while (startIndex <= maxOptionStringIndex) { + // consume any Positionals preceding the next option + nextOptionStringIndex = null; + for (position in optionStringIndices) { + if (!optionStringIndices.hasOwnProperty(position)) { continue; } + + position = parseInt(position, 10); + if (position >= startIndex) { + if (nextOptionStringIndex !== null) { + nextOptionStringIndex = Math.min(nextOptionStringIndex, position); + } + else { + nextOptionStringIndex = position; + } + } + } + + if (startIndex !== nextOptionStringIndex) { + positionalsEndIndex = consumePositionals(startIndex); + // only try to parse the next optional if we didn't consume + // the option string during the positionals parsing + if (positionalsEndIndex > startIndex) { + startIndex = positionalsEndIndex; + continue; + } + else { + startIndex = positionalsEndIndex; + } + } + + // if we consumed all the positionals we could and we're not + // at the index of an option string, there were extra arguments + if (!optionStringIndices[startIndex]) { + var strings = argStrings.slice(startIndex, nextOptionStringIndex); + extras = extras.concat(strings); + startIndex = nextOptionStringIndex; + } + // consume the next optional and any arguments for it + startIndex = consumeOptional(startIndex); + } + + // consume any positionals following the last Optional + var stopIndex = consumePositionals(startIndex); + + // if we didn't consume all the argument strings, there were extras + extras = extras.concat(argStrings.slice(stopIndex)); + + // if we didn't use all the Positional objects, there were too few + // arg strings supplied. + if (positionals.length > 0) { + self.error('too few arguments'); + } + + // make sure all required actions were present + self._actions.forEach(function (action) { + if (action.required) { + if (_.indexOf(seenActions, action) < 0) { + self.error(format('Argument "%s" is required', action.getName())); + } + } + }); + + // make sure all required groups have one option present + var actionUsed = false; + self._mutuallyExclusiveGroups.forEach(function (group) { + if (group.required) { + actionUsed = _.any(group._groupActions, function (action) { + return _.contains(seenNonDefaultActions, action); + }); + + // if no actions were used, report the error + if (!actionUsed) { + var names = []; + group._groupActions.forEach(function (action) { + if (action.help !== $$.SUPPRESS) { + names.push(action.getName()); + } + }); + names = names.join(' '); + var msg = 'one of the arguments ' + names + ' is required'; + self.error(msg); + } + } + }); + + // return the updated namespace and the extra arguments + return [namespace, extras]; +}; + +ArgumentParser.prototype._readArgsFromFiles = function (argStrings) { + // expand arguments referencing files + var _this = this; + var fs = require('fs'); + var newArgStrings = []; + argStrings.forEach(function (argString) { + if (_this.fromfilePrefixChars.indexOf(argString[0]) < 0) { + // for regular arguments, just add them back into the list + newArgStrings.push(argString); + } else { + // replace arguments referencing files with the file content + try { + var argstrs = []; + var filename = argString.slice(1); + var content = fs.readFileSync(filename, 'utf8'); + content = content.trim().split('\n'); + content.forEach(function (argLine) { + _this.convertArgLineToArgs(argLine).forEach(function (arg) { + argstrs.push(arg); + }); + argstrs = _this._readArgsFromFiles(argstrs); + }); + newArgStrings.push.apply(newArgStrings, argstrs); + } catch (error) { + return _this.error(error.message); + } + } + }); + return newArgStrings; +}; + +ArgumentParser.prototype.convertArgLineToArgs = function (argLine) { + return [argLine]; +}; + +ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) { + + // match the pattern for this action to the arg strings + var regexpNargs = new RegExp('^' + this._getNargsPattern(action)); + var matches = regexpArgStrings.match(regexpNargs); + var message; + + // throw an exception if we weren't able to find a match + if (!matches) { + switch (action.nargs) { + case undefined: + case null: + message = 'Expected one argument.'; + break; + case $$.OPTIONAL: + message = 'Expected at most one argument.'; + break; + case $$.ONE_OR_MORE: + message = 'Expected at least one argument.'; + break; + default: + message = 'Expected %s argument(s)'; + } + + throw argumentErrorHelper( + action, + format(message, action.nargs) + ); + } + // return the number of arguments matched + return matches[1].length; +}; + +ArgumentParser.prototype._matchArgumentsPartial = function (actions, regexpArgStrings) { + // progressively shorten the actions list by slicing off the + // final actions until we find a match + var self = this; + var result = []; + var actionSlice, pattern, matches; + var i, j; + + var getLength = function (string) { + return string.length; + }; + + for (i = actions.length; i > 0; i--) { + pattern = ''; + actionSlice = actions.slice(0, i); + for (j = 0; j < actionSlice.length; j++) { + pattern += self._getNargsPattern(actionSlice[j]); + } + + pattern = new RegExp('^' + pattern); + matches = regexpArgStrings.match(pattern); + + if (matches && matches.length > 0) { + // need only groups + matches = matches.splice(1); + result = result.concat(matches.map(getLength)); + break; + } + } + + // return the list of arg string counts + return result; +}; + +ArgumentParser.prototype._parseOptional = function (argString) { + var action, optionString, argExplicit, optionTuples; + + // if it's an empty string, it was meant to be a positional + if (!argString) { + return null; + } + + // if it doesn't start with a prefix, it was meant to be positional + if (this.prefixChars.indexOf(argString[0]) < 0) { + return null; + } + + // if the option string is present in the parser, return the action + if (!!this._optionStringActions[argString]) { + return [this._optionStringActions[argString], argString, null]; + } + + // if it's just a single character, it was meant to be positional + if (argString.length === 1) { + return null; + } + + // if the option string before the "=" is present, return the action + if (argString.indexOf('=') >= 0) { + var argStringSplit = argString.split('='); + optionString = argStringSplit[0]; + argExplicit = argStringSplit[1]; + + if (!!this._optionStringActions[optionString]) { + action = this._optionStringActions[optionString]; + return [action, optionString, argExplicit]; + } + } + + // search through all possible prefixes of the option string + // and all actions in the parser for possible interpretations + optionTuples = this._getOptionTuples(argString); + + // if multiple actions match, the option string was ambiguous + if (optionTuples.length > 1) { + var optionStrings = optionTuples.map(function (optionTuple) { + return optionTuple[1]; + }); + this.error(format( + 'Ambiguous option: "%s" could match %s.', + argString, optionStrings.join(', ') + )); + // if exactly one action matched, this segmentation is good, + // so return the parsed action + } else if (optionTuples.length === 1) { + return optionTuples[0]; + } + + // if it was not found as an option, but it looks like a negative + // number, it was meant to be positional + // unless there are negative-number-like options + if (argString.match(this._regexpNegativeNumber)) { + if (!_.any(this._hasNegativeNumberOptionals)) { + return null; + } + } + // if it contains a space, it was meant to be a positional + if (argString.search(' ') >= 0) { + return null; + } + + // it was meant to be an optional but there is no such option + // in this parser (though it might be a valid option in a subparser) + return [null, argString, null]; +}; + +ArgumentParser.prototype._getOptionTuples = function (optionString) { + var result = []; + var chars = this.prefixChars; + var optionPrefix; + var argExplicit; + var action; + var actionOptionString; + + // option strings starting with two prefix characters are only split at + // the '=' + if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) >= 0) { + if (optionString.indexOf('=') >= 0) { + var optionStringSplit = optionString.split('=', 1); + + optionPrefix = optionStringSplit[0]; + argExplicit = optionStringSplit[1]; + } else { + optionPrefix = optionString; + argExplicit = null; + } + + for (actionOptionString in this._optionStringActions) { + if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { + action = this._optionStringActions[actionOptionString]; + result.push([action, actionOptionString, argExplicit]); + } + } + + // single character options can be concatenated with their arguments + // but multiple character options always have to have their argument + // separate + } else if (chars.indexOf(optionString[0]) >= 0 && chars.indexOf(optionString[1]) < 0) { + optionPrefix = optionString; + argExplicit = null; + var optionPrefixShort = optionString.substr(0, 2); + var argExplicitShort = optionString.substr(2); + + for (actionOptionString in this._optionStringActions) { + action = this._optionStringActions[actionOptionString]; + if (actionOptionString === optionPrefixShort) { + result.push([action, actionOptionString, argExplicitShort]); + } else if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) { + result.push([action, actionOptionString, argExplicit]); + } + } + + // shouldn't ever get here + } else { + throw new Error(format('Unexpected option string: %s.', optionString)); + } + // return the collected option tuples + return result; +}; + +ArgumentParser.prototype._getNargsPattern = function (action) { + // in all examples below, we have to allow for '--' args + // which are represented as '-' in the pattern + var regexpNargs; + + switch (action.nargs) { + // the default (null) is assumed to be a single argument + case undefined: + case null: + regexpNargs = '(-*A-*)'; + break; + // allow zero or more arguments + case $$.OPTIONAL: + regexpNargs = '(-*A?-*)'; + break; + // allow zero or more arguments + case $$.ZERO_OR_MORE: + regexpNargs = '(-*[A-]*)'; + break; + // allow one or more arguments + case $$.ONE_OR_MORE: + regexpNargs = '(-*A[A-]*)'; + break; + // allow any number of options or arguments + case $$.REMAINDER: + regexpNargs = '([-AO]*)'; + break; + // allow one argument followed by any number of options or arguments + case $$.PARSER: + regexpNargs = '(-*A[-AO]*)'; + break; + // all others should be integers + default: + regexpNargs = '(-*' + _.repeat('-*A', action.nargs) + '-*)'; + } + + // if this is an optional action, -- is not allowed + if (action.isOptional()) { + regexpNargs = regexpNargs.replace(/-\*/g, ''); + regexpNargs = regexpNargs.replace(/-/g, ''); + } + + // return the pattern + return regexpNargs; +}; + +// +// Value conversion methods +// + +ArgumentParser.prototype._getValues = function (action, argStrings) { + var self = this; + + // for everything but PARSER args, strip out '--' + if (action.nargs !== $$.PARSER && action.nargs !== $$.REMAINDER) { + argStrings = argStrings.filter(function (arrayElement) { + return arrayElement !== '--'; + }); + } + + var value, argString; + + // optional argument produces a default when not present + if (argStrings.length === 0 && action.nargs === $$.OPTIONAL) { + + value = (action.isOptional()) ? action.constant: action.defaultValue; + + if (typeof(value) === 'string') { + value = this._getValue(action, value); + this._checkValue(action, value); + } + + // when nargs='*' on a positional, if there were no command-line + // args, use the default if it is anything other than None + } else if (argStrings.length === 0 && action.nargs === $$.ZERO_OR_MORE && + action.optionStrings.length === 0) { + + value = (action.defaultValue || argStrings); + this._checkValue(action, value); + + // single argument or optional argument produces a single value + } else if (argStrings.length === 1 && + (!action.nargs || action.nargs === $$.OPTIONAL)) { + + argString = argStrings[0]; + value = this._getValue(action, argString); + this._checkValue(action, value); + + // REMAINDER arguments convert all values, checking none + } else if (action.nargs === $$.REMAINDER) { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + + // PARSER arguments convert all values, but check only the first + } else if (action.nargs === $$.PARSER) { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + this._checkValue(action, value[0]); + + // all other types of nargs produce a list + } else { + value = argStrings.map(function (v) { + return self._getValue(action, v); + }); + value.forEach(function (v) { + self._checkValue(action, v); + }); + } + + // return the converted value + return value; +}; + +ArgumentParser.prototype._getValue = function (action, argString) { + var result; + + var typeFunction = this._registryGet('type', action.type, action.type); + if (!_.isFunction(typeFunction)) { + var message = format('%s is not callable', typeFunction); + throw argumentErrorHelper(action, message); + } + + // convert the value to the appropriate type + try { + result = typeFunction(argString); + + // ArgumentTypeErrors indicate errors + // If action.type is not a registered string, it is a function + // Try to deduce its name for inclusion in the error message + // Failing that, include the error message it raised. + } catch (e) { + var name = null; + if (_.isString(action.type)) { + name = action.type; + } else { + name = action.type.name || action.type.displayName || ''; + } + var msg = format('Invalid %s value: %s', name, argString); + if (name === '') {msg += '\n' + e.message; } + throw argumentErrorHelper(action, msg); + } + // return the converted value + return result; +}; + +ArgumentParser.prototype._checkValue = function (action, value) { + // converted value must be one of the choices (if specified) + var choices = action.choices; + if (!!choices) { + // choise for argument can by array or string + if ((_.isString(choices) || _.isArray(choices)) && + choices.indexOf(value) !== -1) { + return; + } + // choise for subparsers can by only hash + if (_.isObject(choices) && !_.isArray(choices) && choices[value]) { + return; + } + + if (_.isString(choices)) { + choices = choices.split('').join(', '); + } + else if (_.isArray(choices)) { + choices = choices.join(', '); + } + else { + choices = _.keys(choices).join(', '); + } + var message = format('Invalid choice: %s (choose from [%s])', value, choices); + throw argumentErrorHelper(action, message); + } +}; + +// +// Help formatting methods +// + +/** + * ArgumentParser#formatUsage -> string + * + * Return usage string + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.formatUsage = function () { + var formatter = this._getFormatter(); + formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); + return formatter.formatHelp(); +}; + +/** + * ArgumentParser#formatHelp -> string + * + * Return help + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.formatHelp = function () { + var formatter = this._getFormatter(); + + // usage + formatter.addUsage(this.usage, this._actions, this._mutuallyExclusiveGroups); + + // description + formatter.addText(this.description); + + // positionals, optionals and user-defined groups + this._actionGroups.forEach(function (actionGroup) { + formatter.startSection(actionGroup.title); + formatter.addText(actionGroup.description); + formatter.addArguments(actionGroup._groupActions); + formatter.endSection(); + }); + + // epilog + formatter.addText(this.epilog); + + // determine help from format above + return formatter.formatHelp(); +}; + +ArgumentParser.prototype._getFormatter = function () { + var FormatterClass = this.formatterClass; + var formatter = new FormatterClass({prog: this.prog}); + return formatter; +}; + +// +// Print functions +// + +/** + * ArgumentParser#printUsage() -> Void + * + * Print usage + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.printUsage = function () { + this._printMessage(this.formatUsage()); +}; + +/** + * ArgumentParser#printHelp() -> Void + * + * Print help + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#printing-help + **/ +ArgumentParser.prototype.printHelp = function () { + this._printMessage(this.formatHelp()); +}; + +ArgumentParser.prototype._printMessage = function (message, stream) { + if (!stream) { + stream = process.stdout; + } + if (message) { + stream.write('' + message); + } +}; + +// +// Exit functions +// + +/** + * ArgumentParser#exit(status=0, message) -> Void + * - status (int): exit status + * - message (string): message + * + * Print message in stderr/stdout and exit program + **/ +ArgumentParser.prototype.exit = function (status, message) { + if (!!message) { + if (status === 0) { + this._printMessage(message); + } + else { + this._printMessage(message, process.stderr); + } + } + + process.exit(status); +}; + +/** + * ArgumentParser#error(message) -> Void + * - err (Error|string): message + * + * Error method Prints a usage message incorporating the message to stderr and + * exits. If you override this in a subclass, + * it should not return -- it should + * either exit or throw an exception. + * + **/ +ArgumentParser.prototype.error = function (err) { + var message; + if (err instanceof Error) { + if (this.debug === true) { + throw err; + } + message = err.message; + } + else { + message = err; + } + var msg = format('%s: error: %s', this.prog, message) + $$.EOL; + + if (this.debug === true) { + throw new Error(msg); + } + + this.printUsage(process.stderr); + + return this.exit(2, msg); +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/const.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/const.js new file mode 100644 index 00000000000000..de831ba4e93fc7 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/const.js @@ -0,0 +1,18 @@ +// +// Constants +// +module.exports.EOL = '\n'; + +module.exports.SUPPRESS = '==SUPPRESS=='; + +module.exports.OPTIONAL = '?'; + +module.exports.ZERO_OR_MORE = '*'; + +module.exports.ONE_OR_MORE = '+'; + +module.exports.PARSER = 'A...'; + +module.exports.REMAINDER = '...'; + +module.exports._UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/help/added_formatters.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/help/added_formatters.js new file mode 100644 index 00000000000000..3c99c4a1fc1826 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/help/added_formatters.js @@ -0,0 +1,88 @@ +'use strict'; + +var util = require('util'); +var _ = require('lodash'); + + +// Constants +var $$ = require('../const'); + +var HelpFormatter = require('./formatter.js'); + +/** + * new RawDescriptionHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) + * + * Help message formatter which adds default values to argument help. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +var ArgumentDefaultsHelpFormatter = function ArgumentDefaultsHelpFormatter(options) { + HelpFormatter.call(this, options); +}; + +util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter); + +ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) { + var help = action.help; + if (action.help.indexOf('%(defaultValue)s') === -1) { + if (action.defaultValue !== $$.SUPPRESS) { + var defaulting_nargs = [$$.OPTIONAL, $$.ZERO_OR_MORE]; + if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) { + help += ' (default: %(defaultValue)s)'; + } + } + } + return help; +}; + +module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter; + +/** + * new RawDescriptionHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...}) + * + * Help message formatter which retains any formatting in descriptions. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +var RawDescriptionHelpFormatter = function RawDescriptionHelpFormatter(options) { + HelpFormatter.call(this, options); +}; + +util.inherits(RawDescriptionHelpFormatter, HelpFormatter); + +RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) { + var lines = text.split('\n'); + lines = lines.map(function (line) { + return _.trimRight(indent + line); + }); + return lines.join('\n'); +}; +module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter; + +/** + * new RawTextHelpFormatter(options) + * new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...}) + * + * Help message formatter which retains formatting of all help text. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + **/ + +var RawTextHelpFormatter = function RawTextHelpFormatter(options) { + RawDescriptionHelpFormatter.call(this, options); +}; + +util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter); + +RawTextHelpFormatter.prototype._splitLines = function (text) { + return text.split('\n'); +}; + +module.exports.RawTextHelpFormatter = RawTextHelpFormatter; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/help/formatter.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/help/formatter.js new file mode 100644 index 00000000000000..e050728e3ea162 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/help/formatter.js @@ -0,0 +1,798 @@ +/** + * class HelpFormatter + * + * Formatter for generating usage messages and argument help strings. Only the + * name of this class is considered a public API. All the methods provided by + * the class are considered an implementation detail. + * + * Do not call in your code, use this class only for inherits your own forvatter + * + * ToDo add [additonal formatters][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#formatter-class + **/ +'use strict'; + +var _ = require('lodash'); +var sprintf = require('sprintf-js').sprintf; + +// Constants +var $$ = require('../const'); + + +/*:nodoc:* internal + * new Support(parent, heding) + * - parent (object): parent section + * - heading (string): header string + * + **/ +function Section(parent, heading) { + this._parent = parent; + this._heading = heading; + this._items = []; +} + +/*:nodoc:* internal + * Section#addItem(callback) -> Void + * - callback (array): tuple with function and args + * + * Add function for single element + **/ +Section.prototype.addItem = function (callback) { + this._items.push(callback); +}; + +/*:nodoc:* internal + * Section#formatHelp(formatter) -> string + * - formatter (HelpFormatter): current formatter + * + * Form help section string + * + **/ +Section.prototype.formatHelp = function (formatter) { + var itemHelp, heading; + + // format the indented section + if (!!this._parent) { + formatter._indent(); + } + + itemHelp = this._items.map(function (item) { + var obj, func, args; + + obj = formatter; + func = item[0]; + args = item[1]; + return func.apply(obj, args); + }); + itemHelp = formatter._joinParts(itemHelp); + + if (!!this._parent) { + formatter._dedent(); + } + + // return nothing if the section was empty + if (!itemHelp) { + return ''; + } + + // add the heading if the section was non-empty + heading = ''; + if (!!this._heading && this._heading !== $$.SUPPRESS) { + var currentIndent = formatter.currentIndent; + heading = _.repeat(' ', currentIndent) + this._heading + ':' + $$.EOL; + } + + // join the section-initialize newline, the heading and the help + return formatter._joinParts([$$.EOL, heading, itemHelp, $$.EOL]); +}; + +/** + * new HelpFormatter(options) + * + * #### Options: + * - `prog`: program name + * - `indentIncriment`: indent step, default value 2 + * - `maxHelpPosition`: max help position, default value = 24 + * - `width`: line width + * + **/ +var HelpFormatter = module.exports = function HelpFormatter(options) { + options = options || {}; + + this._prog = options.prog; + + this._maxHelpPosition = options.maxHelpPosition || 24; + this._width = (options.width || ((process.env.COLUMNS || 80) - 2)); + + this._currentIndent = 0; + this._indentIncriment = options.indentIncriment || 2; + this._level = 0; + this._actionMaxLength = 0; + + this._rootSection = new Section(null); + this._currentSection = this._rootSection; + + this._whitespaceMatcher = new RegExp('\\s+', 'g'); + this._longBreakMatcher = new RegExp($$.EOL + $$.EOL + $$.EOL + '+', 'g'); +}; + +HelpFormatter.prototype._indent = function () { + this._currentIndent += this._indentIncriment; + this._level += 1; +}; + +HelpFormatter.prototype._dedent = function () { + this._currentIndent -= this._indentIncriment; + this._level -= 1; + if (this._currentIndent < 0) { + throw new Error('Indent decreased below 0.'); + } +}; + +HelpFormatter.prototype._addItem = function (func, args) { + this._currentSection.addItem([func, args]); +}; + +// +// Message building methods +// + +/** + * HelpFormatter#startSection(heading) -> Void + * - heading (string): header string + * + * Start new help section + * + * See alse [code example][1] + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.startSection = function (heading) { + this._indent(); + var section = new Section(this._currentSection, heading); + var func = section.formatHelp.bind(section); + this._addItem(func, [this]); + this._currentSection = section; +}; + +/** + * HelpFormatter#endSection -> Void + * + * End help section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + **/ +HelpFormatter.prototype.endSection = function () { + this._currentSection = this._currentSection._parent; + this._dedent(); +}; + +/** + * HelpFormatter#addText(text) -> Void + * - text (string): plain text + * + * Add plain text into current section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.addText = function (text) { + if (!!text && text !== $$.SUPPRESS) { + this._addItem(this._formatText, [text]); + } +}; + +/** + * HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void + * - usage (string): usage text + * - actions (array): actions list + * - groups (array): groups list + * - prefix (string): usage prefix + * + * Add usage data into current section + * + * ##### Example + * + * formatter.addUsage(this.usage, this._actions, []); + * return formatter.formatHelp(); + * + **/ +HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) { + if (usage !== $$.SUPPRESS) { + this._addItem(this._formatUsage, [usage, actions, groups, prefix]); + } +}; + +/** + * HelpFormatter#addArgument(action) -> Void + * - action (object): action + * + * Add argument into current section + * + * Single variant of [[HelpFormatter#addArguments]] + **/ +HelpFormatter.prototype.addArgument = function (action) { + if (action.help !== $$.SUPPRESS) { + var self = this; + + // find all invocations + var invocations = [this._formatActionInvocation(action)]; + var invocationLength = invocations[0].length; + + var actionLength; + + if (!!action._getSubactions) { + this._indent(); + action._getSubactions().forEach(function (subaction) { + + var invocationNew = self._formatActionInvocation(subaction); + invocations.push(invocationNew); + invocationLength = Math.max(invocationLength, invocationNew.length); + + }); + this._dedent(); + } + + // update the maximum item length + actionLength = invocationLength + this._currentIndent; + this._actionMaxLength = Math.max(this._actionMaxLength, actionLength); + + // add the item to the list + this._addItem(this._formatAction, [action]); + } +}; + +/** + * HelpFormatter#addArguments(actions) -> Void + * - actions (array): actions list + * + * Mass add arguments into current section + * + * ##### Example + * + * formatter.startSection(actionGroup.title); + * formatter.addText(actionGroup.description); + * formatter.addArguments(actionGroup._groupActions); + * formatter.endSection(); + * + **/ +HelpFormatter.prototype.addArguments = function (actions) { + var self = this; + actions.forEach(function (action) { + self.addArgument(action); + }); +}; + +// +// Help-formatting methods +// + +/** + * HelpFormatter#formatHelp -> string + * + * Format help + * + * ##### Example + * + * formatter.addText(this.epilog); + * return formatter.formatHelp(); + * + **/ +HelpFormatter.prototype.formatHelp = function () { + var help = this._rootSection.formatHelp(this); + if (help) { + help = help.replace(this._longBreakMatcher, $$.EOL + $$.EOL); + help = _.trim(help, $$.EOL) + $$.EOL; + } + return help; +}; + +HelpFormatter.prototype._joinParts = function (partStrings) { + return partStrings.filter(function (part) { + return (!!part && part !== $$.SUPPRESS); + }).join(''); +}; + +HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) { + if (!prefix && !_.isString(prefix)) { + prefix = 'usage: '; + } + + actions = actions || []; + groups = groups || []; + + + // if usage is specified, use that + if (usage) { + usage = sprintf(usage, {prog: this._prog}); + + // if no optionals or positionals are available, usage is just prog + } else if (!usage && actions.length === 0) { + usage = this._prog; + + // if optionals and positionals are available, calculate usage + } else if (!usage) { + var prog = this._prog; + var optionals = []; + var positionals = []; + var actionUsage; + var textWidth; + + // split optionals from positionals + actions.forEach(function (action) { + if (action.isOptional()) { + optionals.push(action); + } else { + positionals.push(action); + } + }); + + // build full usage string + actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups); + usage = [prog, actionUsage].join(' '); + + // wrap the usage parts if it's too long + textWidth = this._width - this._currentIndent; + if ((prefix.length + usage.length) > textWidth) { + + // break usage into wrappable parts + var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g'); + var optionalUsage = this._formatActionsUsage(optionals, groups); + var positionalUsage = this._formatActionsUsage(positionals, groups); + + + var optionalParts = optionalUsage.match(regexpPart); + var positionalParts = positionalUsage.match(regexpPart) || []; + + if (optionalParts.join(' ') !== optionalUsage) { + throw new Error('assert "optionalParts.join(\' \') === optionalUsage"'); + } + if (positionalParts.join(' ') !== positionalUsage) { + throw new Error('assert "positionalParts.join(\' \') === positionalUsage"'); + } + + // helper for wrapping lines + var _getLines = function (parts, indent, prefix) { + var lines = []; + var line = []; + + var lineLength = !!prefix ? prefix.length - 1: indent.length - 1; + + parts.forEach(function (part) { + if (lineLength + 1 + part.length > textWidth) { + lines.push(indent + line.join(' ')); + line = []; + lineLength = indent.length - 1; + } + line.push(part); + lineLength += part.length + 1; + }); + + if (line) { + lines.push(indent + line.join(' ')); + } + if (prefix) { + lines[0] = lines[0].substr(indent.length); + } + return lines; + }; + + var lines, indent, parts; + // if prog is short, follow it with optionals or positionals + if (prefix.length + prog.length <= 0.75 * textWidth) { + indent = _.repeat(' ', (prefix.length + prog.length + 1)); + if (optionalParts) { + lines = [].concat( + _getLines([prog].concat(optionalParts), indent, prefix), + _getLines(positionalParts, indent) + ); + } else if (positionalParts) { + lines = _getLines([prog].concat(positionalParts), indent, prefix); + } else { + lines = [prog]; + } + + // if prog is long, put it on its own line + } else { + indent = _.repeat(' ', prefix.length); + parts = optionalParts + positionalParts; + lines = _getLines(parts, indent); + if (lines.length > 1) { + lines = [].concat( + _getLines(optionalParts, indent), + _getLines(positionalParts, indent) + ); + } + lines = [prog] + lines; + } + // join lines into usage + usage = lines.join($$.EOL); + } + } + + // prefix with 'usage:' + return prefix + usage + $$.EOL + $$.EOL; +}; + +HelpFormatter.prototype._formatActionsUsage = function (actions, groups) { + // find group indices and identify actions in groups + var groupActions = []; + var inserts = []; + var self = this; + + groups.forEach(function (group) { + var end; + var i; + + var start = actions.indexOf(group._groupActions[0]); + if (start >= 0) { + end = start + group._groupActions.length; + + //if (actions.slice(start, end) === group._groupActions) { + if (_.isEqual(actions.slice(start, end), group._groupActions)) { + group._groupActions.forEach(function (action) { + groupActions.push(action); + }); + + if (!group.required) { + if (!!inserts[start]) { + inserts[start] += ' ['; + } + else { + inserts[start] = '['; + } + inserts[end] = ']'; + } else { + if (!!inserts[start]) { + inserts[start] += ' ('; + } + else { + inserts[start] = '('; + } + inserts[end] = ')'; + } + for (i = start + 1; i < end; i += 1) { + inserts[i] = '|'; + } + } + } + }); + + // collect all actions format strings + var parts = []; + + actions.forEach(function (action, actionIndex) { + var part; + var optionString; + var argsDefault; + var argsString; + + // suppressed arguments are marked with None + // remove | separators for suppressed arguments + if (action.help === $$.SUPPRESS) { + parts.push(null); + if (inserts[actionIndex] === '|') { + inserts.splice(actionIndex, actionIndex); + } else if (inserts[actionIndex + 1] === '|') { + inserts.splice(actionIndex + 1, actionIndex + 1); + } + + // produce all arg strings + } else if (!action.isOptional()) { + part = self._formatArgs(action, action.dest); + + // if it's in a group, strip the outer [] + if (groupActions.indexOf(action) >= 0) { + if (part[0] === '[' && part[part.length - 1] === ']') { + part = part.slice(1, -1); + } + } + // add the action string to the list + parts.push(part); + + // produce the first way to invoke the option in brackets + } else { + optionString = action.optionStrings[0]; + + // if the Optional doesn't take a value, format is: -s or --long + if (action.nargs === 0) { + part = '' + optionString; + + // if the Optional takes a value, format is: -s ARGS or --long ARGS + } else { + argsDefault = action.dest.toUpperCase(); + argsString = self._formatArgs(action, argsDefault); + part = optionString + ' ' + argsString; + } + // make it look optional if it's not required or in a group + if (!action.required && groupActions.indexOf(action) < 0) { + part = '[' + part + ']'; + } + // add the action string to the list + parts.push(part); + } + }); + + // insert things at the necessary indices + for (var i = inserts.length - 1; i >= 0; --i) { + if (inserts[i] !== null) { + parts.splice(i, 0, inserts[i]); + } + } + + // join all the action items with spaces + var text = parts.filter(function (part) { + return !!part; + }).join(' '); + + // clean up separators for mutually exclusive groups + text = text.replace(/([\[(]) /g, '$1'); // remove spaces + text = text.replace(/ ([\])])/g, '$1'); + text = text.replace(/\[ *\]/g, ''); // remove empty groups + text = text.replace(/\( *\)/g, ''); + text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups + + text = _.trim(text); + + // return the text + return text; +}; + +HelpFormatter.prototype._formatText = function (text) { + text = sprintf(text, {prog: this._prog}); + var textWidth = this._width - this._currentIndent; + var indentIncriment = _.repeat(' ', this._currentIndent); + return this._fillText(text, textWidth, indentIncriment) + $$.EOL + $$.EOL; +}; + +HelpFormatter.prototype._formatAction = function (action) { + var self = this; + + var helpText; + var helpLines; + var parts; + var indentFirst; + + // determine the required width and the entry label + var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition); + var helpWidth = this._width - helpPosition; + var actionWidth = helpPosition - this._currentIndent - 2; + var actionHeader = this._formatActionInvocation(action); + + // no help; start on same line and add a final newline + if (!action.help) { + actionHeader = _.repeat(' ', this._currentIndent) + actionHeader + $$.EOL; + + // short action name; start on the same line and pad two spaces + } else if (actionHeader.length <= actionWidth) { + actionHeader = _.repeat(' ', this._currentIndent) + + actionHeader + + ' ' + + _.repeat(' ', actionWidth - actionHeader.length); + indentFirst = 0; + + // long action name; start on the next line + } else { + actionHeader = _.repeat(' ', this._currentIndent) + actionHeader + $$.EOL; + indentFirst = helpPosition; + } + + // collect the pieces of the action help + parts = [actionHeader]; + + // if there was help for the action, add lines of help text + if (!!action.help) { + helpText = this._expandHelp(action); + helpLines = this._splitLines(helpText, helpWidth); + parts.push(_.repeat(' ', indentFirst) + helpLines[0] + $$.EOL); + helpLines.slice(1).forEach(function (line) { + parts.push(_.repeat(' ', helpPosition) + line + $$.EOL); + }); + + // or add a newline if the description doesn't end with one + } else if (actionHeader.charAt(actionHeader.length - 1) !== $$.EOL) { + parts.push($$.EOL); + } + // if there are any sub-actions, add their help as well + if (!!action._getSubactions) { + this._indent(); + action._getSubactions().forEach(function (subaction) { + parts.push(self._formatAction(subaction)); + }); + this._dedent(); + } + // return a single string + return this._joinParts(parts); +}; + +HelpFormatter.prototype._formatActionInvocation = function (action) { + if (!action.isOptional()) { + var format_func = this._metavarFormatter(action, action.dest); + var metavars = format_func(1); + return metavars[0]; + } else { + var parts = []; + var argsDefault; + var argsString; + + // if the Optional doesn't take a value, format is: -s, --long + if (action.nargs === 0) { + parts = parts.concat(action.optionStrings); + + // if the Optional takes a value, format is: -s ARGS, --long ARGS + } else { + argsDefault = action.dest.toUpperCase(); + argsString = this._formatArgs(action, argsDefault); + action.optionStrings.forEach(function (optionString) { + parts.push(optionString + ' ' + argsString); + }); + } + return parts.join(', '); + } +}; + +HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) { + var result; + + if (!!action.metavar || action.metavar === '') { + result = action.metavar; + } else if (!!action.choices) { + var choices = action.choices; + + if (_.isString(choices)) { + choices = choices.split('').join(', '); + } else if (_.isArray(choices)) { + choices = choices.join(','); + } + else + { + choices = _.keys(choices).join(','); + } + result = '{' + choices + '}'; + } else { + result = metavarDefault; + } + + return function (size) { + if (Array.isArray(result)) { + return result; + } else { + var metavars = []; + for (var i = 0; i < size; i += 1) { + metavars.push(result); + } + return metavars; + } + }; +}; + +HelpFormatter.prototype._formatArgs = function (action, metavarDefault) { + var result; + var metavars; + + var buildMetavar = this._metavarFormatter(action, metavarDefault); + + switch (action.nargs) { + case undefined: + case null: + metavars = buildMetavar(1); + result = '' + metavars[0]; + break; + case $$.OPTIONAL: + metavars = buildMetavar(1); + result = '[' + metavars[0] + ']'; + break; + case $$.ZERO_OR_MORE: + metavars = buildMetavar(2); + result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]'; + break; + case $$.ONE_OR_MORE: + metavars = buildMetavar(2); + result = '' + metavars[0] + ' [' + metavars[1] + ' ...]'; + break; + case $$.REMAINDER: + result = '...'; + break; + case $$.PARSER: + metavars = buildMetavar(1); + result = metavars[0] + ' ...'; + break; + default: + metavars = buildMetavar(action.nargs); + result = metavars.join(' '); + } + return result; +}; + +HelpFormatter.prototype._expandHelp = function (action) { + var params = { prog: this._prog }; + + Object.keys(action).forEach(function (actionProperty) { + var actionValue = action[actionProperty]; + + if (actionValue !== $$.SUPPRESS) { + params[actionProperty] = actionValue; + } + }); + + if (!!params.choices) { + if (_.isString(params.choices)) { + params.choices = params.choices.split('').join(', '); + } + else if (_.isArray(params.choices)) { + params.choices = params.choices.join(', '); + } + else { + params.choices = _.keys(params.choices).join(', '); + } + } + + return sprintf(this._getHelpString(action), params); +}; + +HelpFormatter.prototype._splitLines = function (text, width) { + var lines = []; + var delimiters = [" ", ".", ",", "!", "?"]; + var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$'); + + text = text.replace(/[\n\|\t]/g, ' '); + + text = _.trim(text); + text = text.replace(this._whitespaceMatcher, ' '); + + // Wraps the single paragraph in text (a string) so every line + // is at most width characters long. + text.split($$.EOL).forEach(function (line) { + if (width >= line.length) { + lines.push(line); + return; + } + + var wrapStart = 0; + var wrapEnd = width; + var delimiterIndex = 0; + while (wrapEnd <= line.length) { + if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) { + delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index; + wrapEnd = wrapStart + delimiterIndex + 1; + } + lines.push(line.substring(wrapStart, wrapEnd)); + wrapStart = wrapEnd; + wrapEnd += width; + } + if (wrapStart < line.length) { + lines.push(line.substring(wrapStart, wrapEnd)); + } + }); + + return lines; +}; + +HelpFormatter.prototype._fillText = function (text, width, indent) { + var lines = this._splitLines(text, width); + lines = lines.map(function (line) { + return indent + line; + }); + return lines.join($$.EOL); +}; + +HelpFormatter.prototype._getHelpString = function (action) { + return action.help; +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/namespace.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/namespace.js new file mode 100644 index 00000000000000..2f1f8f4daa32fb --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/lib/namespace.js @@ -0,0 +1,77 @@ +/** + * class Namespace + * + * Simple object for storing attributes. Implements equality by attribute names + * and values, and provides a simple string representation. + * + * See also [original guide][1] + * + * [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object + **/ +'use strict'; + +var _ = require('lodash'); + +/** + * new Namespace(options) + * - options(object): predefined propertis for result object + * + **/ +var Namespace = module.exports = function Namespace(options) { + _.extend(this, options); +}; + +/** + * Namespace#isset(key) -> Boolean + * - key (string|number): property name + * + * Tells whenever `namespace` contains given `key` or not. + **/ +Namespace.prototype.isset = function (key) { + return _.has(this, key); +}; + +/** + * Namespace#set(key, value) -> self + * -key (string|number|object): propery name + * -value (mixed): new property value + * + * Set the property named key with value. + * If key object then set all key properties to namespace object + **/ +Namespace.prototype.set = function (key, value) { + if (typeof (key) === 'object') { + _.extend(this, key); + } else { + this[key] = value; + } + return this; +}; + +/** + * Namespace#get(key, defaultValue) -> mixed + * - key (string|number): property name + * - defaultValue (mixed): default value + * + * Return the property key or defaulValue if not set + **/ +Namespace.prototype.get = function (key, defaultValue) { + return !this[key] ? defaultValue: this[key]; +}; + +/** + * Namespace#unset(key, defaultValue) -> mixed + * - key (string|number): property name + * - defaultValue (mixed): default value + * + * Return data[key](and delete it) or defaultValue + **/ +Namespace.prototype.unset = function (key, defaultValue) { + var value = this[key]; + if (value !== null) { + delete this[key]; + return value; + } else { + return defaultValue; + } +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/LICENSE.txt b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/LICENSE.txt new file mode 100644 index 00000000000000..9cd87e5dcefe58 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js, copyright 2009-2015 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/README.md b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/README.md new file mode 100644 index 00000000000000..701a14b6b1bd87 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/README.md @@ -0,0 +1,119 @@ +# lodash v3.8.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash](https://lodash.com/) exported as [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) modules. + +Generated using [lodash-cli](https://www.npmjs.com/package/lodash-cli): +```bash +$ lodash modularize modern exports=node -o ./ +$ lodash modern -d -o ./index.js +``` + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash +``` + +In Node.js/io.js: + +```js +// load the modern build +var _ = require('lodash'); +// or a method category +var array = require('lodash/array'); +// or a method (great for smaller builds with browserify/webpack) +var chunk = require('lodash/array/chunk'); +``` + +See the [package source](https://github.com/lodash/lodash/tree/3.8.0-npm) for more details. + +**Note:**
+Don’t assign values to the [special variable](http://nodejs.org/api/repl.html#repl_repl_features) `_` when in the REPL.
+Install [n_](https://www.npmjs.com/package/n_) for a REPL that includes lodash by default. + +## Module formats + +lodash is also available in a variety of other builds & module formats. + + * npm packages for [modern](https://www.npmjs.com/package/lodash), [compatibility](https://www.npmjs.com/package/lodash-compat), & [per method](https://www.npmjs.com/browse/keyword/lodash-modularized) builds + * AMD modules for [modern](https://github.com/lodash/lodash/tree/3.8.0-amd) & [compatibility](https://github.com/lodash/lodash-compat/tree/3.8.0-amd) builds + * ES modules for the [modern](https://github.com/lodash/lodash/tree/3.8.0-es) build + +## Further Reading + + * [API Documentation](https://lodash.com/docs) + * [Build Differences](https://github.com/lodash/lodash/wiki/Build-Differences) + * [Changelog](https://github.com/lodash/lodash/wiki/Changelog) + * [Release Notes](https://github.com/lodash/lodash/releases) + * [Roadmap](https://github.com/lodash/lodash/wiki/Roadmap) + * [More Resources](https://github.com/lodash/lodash/wiki/Resources) + +## Features + + * ~100% [code coverage](https://coveralls.io/r/lodash) + * Follows [semantic versioning](http://semver.org/) for releases + * [Lazily evaluated](http://filimanjaro.com/blog/2014/introducing-lazy-evaluation/) chaining + * [_(…)](https://lodash.com/docs#_) supports intuitive chaining + * [_.add](https://lodash.com/docs#add) for mathematical composition + * [_.ary](https://lodash.com/docs#ary) & [_.rearg](https://lodash.com/docs#rearg) to change function argument limits & order + * [_.at](https://lodash.com/docs#at) for cherry-picking collection values + * [_.attempt](https://lodash.com/docs#attempt) to execute functions which may error without a try-catch + * [_.before](https://lodash.com/docs#before) to complement [_.after](https://lodash.com/docs#after) + * [_.bindKey](https://lodash.com/docs#bindKey) for binding [*“lazy”*](http://michaux.ca/articles/lazy-function-definition-pattern) defined methods + * [_.chunk](https://lodash.com/docs#chunk) for splitting an array into chunks of a given size + * [_.clone](https://lodash.com/docs#clone) supports shallow cloning of `Date` & `RegExp` objects + * [_.cloneDeep](https://lodash.com/docs#cloneDeep) for deep cloning arrays & objects + * [_.curry](https://lodash.com/docs#curry) & [_.curryRight](https://lodash.com/docs#curryRight) for creating [curried](http://hughfdjackson.com/javascript/why-curry-helps/) functions + * [_.debounce](https://lodash.com/docs#debounce) & [_.throttle](https://lodash.com/docs#throttle) are cancelable & accept options for more control + * [_.fill](https://lodash.com/docs#fill) to fill arrays with values + * [_.findKey](https://lodash.com/docs#findKey) for finding keys + * [_.flow](https://lodash.com/docs#flow) to complement [_.flowRight](https://lodash.com/docs#flowRight) (a.k.a `_.compose`) + * [_.forEach](https://lodash.com/docs#forEach) supports exiting early + * [_.forIn](https://lodash.com/docs#forIn) for iterating all enumerable properties + * [_.forOwn](https://lodash.com/docs#forOwn) for iterating own properties + * [_.get](https://lodash.com/docs#get) & [_.set](https://lodash.com/docs#set) for deep property getting & setting + * [_.inRange](https://lodash.com/docs#inRange) for checking whether a number is within a given range + * [_.isNative](https://lodash.com/docs#isNative) to check for native functions + * [_.isPlainObject](https://lodash.com/docs#isPlainObject) & [_.toPlainObject](https://lodash.com/docs#toPlainObject) to check for & convert to `Object` objects + * [_.isTypedArray](https://lodash.com/docs#isTypedArray) to check for typed arrays + * [_.mapKeys](https://lodash.com/docs#mapKeys) for mapping keys to an object + * [_.matches](https://lodash.com/docs#matches) supports deep object comparisons + * [_.matchesProperty](https://lodash.com/docs#matchesProperty) to complement [_.matches](https://lodash.com/docs#matches) & [_.property](https://lodash.com/docs#property) + * [_.method](https://lodash.com/docs#method) & [_.methodOf](https://lodash.com/docs#methodOf) to create functions that invoke methods + * [_.merge](https://lodash.com/docs#merge) for a deep [_.extend](https://lodash.com/docs#extend) + * [_.parseInt](https://lodash.com/docs#parseInt) for consistent cross-environment behavior + * [_.pull](https://lodash.com/docs#pull), [_.pullAt](https://lodash.com/docs#pullAt), & [_.remove](https://lodash.com/docs#remove) for mutating arrays + * [_.random](https://lodash.com/docs#random) supports returning floating-point numbers + * [_.restParam](https://lodash.com/docs#restParam) & [_.spread](https://lodash.com/docs#spread) for applying rest parameters & spreading arguments to functions + * [_.runInContext](https://lodash.com/docs#runInContext) for collisionless mixins & easier mocking + * [_.slice](https://lodash.com/docs#slice) for creating subsets of array-like values + * [_.sortByAll](https://lodash.com/docs#sortByAll) & [_.sortByOrder](https://lodash.com/docs#sortByOrder) for sorting by multiple properties & orders + * [_.sum](https://lodash.com/docs#sum) to get the sum of values + * [_.support](https://lodash.com/docs#support) for flagging environment features + * [_.template](https://lodash.com/docs#template) supports [*“imports”*](https://lodash.com/docs#templateSettings-imports) options & [ES template delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components) + * [_.transform](https://lodash.com/docs#transform) as a powerful alternative to [_.reduce](https://lodash.com/docs#reduce) for transforming objects + * [_.unzipWith](https://lodash.com/docs#unzipWith) & [_.zipWith](https://lodash.com/docs#zipWith) to specify how grouped values should be combined + * [_.xor](https://lodash.com/docs#xor) to complement [_.difference](https://lodash.com/docs#difference), [_.intersection](https://lodash.com/docs#intersection), & [_.union](https://lodash.com/docs#union) + * [_.valuesIn](https://lodash.com/docs#valuesIn) for getting values of all enumerable properties + * [_.bind](https://lodash.com/docs#bind), [_.curry](https://lodash.com/docs#curry), [_.partial](https://lodash.com/docs#partial), & + [more](https://lodash.com/docs "_.bindKey, _.curryRight, _.partialRight") support customizable argument placeholders + * [_.capitalize](https://lodash.com/docs#capitalize), [_.trim](https://lodash.com/docs#trim), & + [more](https://lodash.com/docs "_.camelCase, _.deburr, _.endsWith, _.escapeRegExp, _.kebabCase, _.pad, _.padLeft, _.padRight, _.repeat, _.snakeCase, _.startCase, _.startsWith, _.trimLeft, _.trimRight, _.trunc, _.words") string methods + * [_.clone](https://lodash.com/docs#clone), [_.isEqual](https://lodash.com/docs#isEqual), & + [more](https://lodash.com/docs "_.assign, _.cloneDeep, _.merge") accept customizer callbacks + * [_.dropWhile](https://lodash.com/docs#dropWhile), [_.takeWhile](https://lodash.com/docs#takeWhile), & + [more](https://lodash.com/docs "_.drop, _.dropRight, _.dropRightWhile, _.take, _.takeRight, _.takeRightWhile") to complement [_.first](https://lodash.com/docs#first), [_.initial](https://lodash.com/docs#initial), [_.last](https://lodash.com/docs#last), & [_.rest](https://lodash.com/docs#rest) + * [_.findLast](https://lodash.com/docs#findLast), [_.findLastKey](https://lodash.com/docs#findLastKey), & + [more](https://lodash.com/docs "_.curryRight, _.dropRight, _.dropRightWhile, _.flowRight, _.forEachRight, _.forInRight, _.forOwnRight, _.padRight, partialRight, _.takeRight, _.trimRight, _.takeRightWhile") right-associative methods + * [_.includes](https://lodash.com/docs#includes), [_.toArray](https://lodash.com/docs#toArray), & + [more](https://lodash.com/docs "_.at, _.countBy, _.every, _.filter, _.find, _.findLast, _.findWhere, _.forEach, _.forEachRight, _.groupBy, _.indexBy, _.invoke, _.map, _.max, _.min, _.partition, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.size, _.some, _.sortBy, _.sortByAll, _.sortByOrder, _.sum, _.where") accept strings + * [_#commit](https://lodash.com/docs#prototype-commit) & [_#plant](https://lodash.com/docs#prototype-plant) for working with chain sequences + * [_#thru](https://lodash.com/docs#thru) to pass values thru a chain sequence + +## Support + +Tested in Chrome 41-42, Firefox 36-37, IE 6-11, MS Edge, Opera 27-28, Safari 5-8, io.js 1.8.1, Node.js 0.8.28, 0.10.38, & 0.12.2, PhantomJS 1.9.8, RingoJS 0.11, & Rhino 1.7RC5. +Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. Special thanks to [Sauce Labs](https://saucelabs.com/) for providing automated browser testing. diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array.js new file mode 100644 index 00000000000000..e5121fa52ec264 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array.js @@ -0,0 +1,44 @@ +module.exports = { + 'chunk': require('./array/chunk'), + 'compact': require('./array/compact'), + 'difference': require('./array/difference'), + 'drop': require('./array/drop'), + 'dropRight': require('./array/dropRight'), + 'dropRightWhile': require('./array/dropRightWhile'), + 'dropWhile': require('./array/dropWhile'), + 'fill': require('./array/fill'), + 'findIndex': require('./array/findIndex'), + 'findLastIndex': require('./array/findLastIndex'), + 'first': require('./array/first'), + 'flatten': require('./array/flatten'), + 'flattenDeep': require('./array/flattenDeep'), + 'head': require('./array/head'), + 'indexOf': require('./array/indexOf'), + 'initial': require('./array/initial'), + 'intersection': require('./array/intersection'), + 'last': require('./array/last'), + 'lastIndexOf': require('./array/lastIndexOf'), + 'object': require('./array/object'), + 'pull': require('./array/pull'), + 'pullAt': require('./array/pullAt'), + 'remove': require('./array/remove'), + 'rest': require('./array/rest'), + 'slice': require('./array/slice'), + 'sortedIndex': require('./array/sortedIndex'), + 'sortedLastIndex': require('./array/sortedLastIndex'), + 'tail': require('./array/tail'), + 'take': require('./array/take'), + 'takeRight': require('./array/takeRight'), + 'takeRightWhile': require('./array/takeRightWhile'), + 'takeWhile': require('./array/takeWhile'), + 'union': require('./array/union'), + 'uniq': require('./array/uniq'), + 'unique': require('./array/unique'), + 'unzip': require('./array/unzip'), + 'unzipWith': require('./array/unzipWith'), + 'without': require('./array/without'), + 'xor': require('./array/xor'), + 'zip': require('./array/zip'), + 'zipObject': require('./array/zipObject'), + 'zipWith': require('./array/zipWith') +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/chunk.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/chunk.js new file mode 100644 index 00000000000000..4de9b3961843b0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/chunk.js @@ -0,0 +1,47 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** Native method references. */ +var ceil = Math.ceil; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates an array of elements split into groups the length of `size`. + * If `collection` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new array containing chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ +function chunk(array, size, guard) { + if (guard ? isIterateeCall(array, size, guard) : size == null) { + size = 1; + } else { + size = nativeMax(+size || 1, 1); + } + var index = 0, + length = array ? array.length : 0, + resIndex = -1, + result = Array(ceil(length / size)); + + while (index < length) { + result[++resIndex] = baseSlice(array, index, (index += size)); + } + return result; +} + +module.exports = chunk; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/compact.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/compact.js new file mode 100644 index 00000000000000..1dc1c55e8f1efb --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/compact.js @@ -0,0 +1,30 @@ +/** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ +function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[++resIndex] = value; + } + } + return result; +} + +module.exports = compact; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/difference.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/difference.js new file mode 100644 index 00000000000000..22a5cf899d5493 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/difference.js @@ -0,0 +1,28 @@ +var baseDifference = require('../internal/baseDifference'), + baseFlatten = require('../internal/baseFlatten'), + isArrayLike = require('../internal/isArrayLike'), + restParam = require('../function/restParam'); + +/** + * Creates an array excluding all values of the provided arrays using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.difference([1, 2, 3], [4, 2]); + * // => [1, 3] + */ +var difference = restParam(function(array, values) { + return isArrayLike(array) + ? baseDifference(array, baseFlatten(values, false, true)) + : []; +}); + +module.exports = difference; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/drop.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/drop.js new file mode 100644 index 00000000000000..039a0b5fdcdf2b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/drop.js @@ -0,0 +1,39 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, n < 0 ? 0 : n); +} + +module.exports = drop; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropRight.js new file mode 100644 index 00000000000000..14b5eb6f0a198e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropRight.js @@ -0,0 +1,40 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = dropRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropRightWhile.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropRightWhile.js new file mode 100644 index 00000000000000..be158bd5fa94c0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropRightWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that match the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [1] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); + * // => ['barney'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ +function dropRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3), true, true) + : []; +} + +module.exports = dropRightWhile; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropWhile.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropWhile.js new file mode 100644 index 00000000000000..d9eabae9fac8b2 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/dropWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [3] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropWhile(users, 'active', false), 'user'); + * // => ['pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ +function dropWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3), true) + : []; +} + +module.exports = dropWhile; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/fill.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/fill.js new file mode 100644 index 00000000000000..2c8f6da71d0620 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/fill.js @@ -0,0 +1,44 @@ +var baseFill = require('../internal/baseFill'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8], '*', 1, 2); + * // => [4, '*', 8] + */ +function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); +} + +module.exports = fill; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/findIndex.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/findIndex.js new file mode 100644 index 00000000000000..2a6b8e14bace9e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/findIndex.js @@ -0,0 +1,53 @@ +var createFindIndex = require('../internal/createFindIndex'); + +/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(chr) { + * return chr.user == 'barney'; + * }); + * // => 0 + * + * // using the `_.matches` callback shorthand + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // using the `_.matchesProperty` callback shorthand + * _.findIndex(users, 'active', false); + * // => 0 + * + * // using the `_.property` callback shorthand + * _.findIndex(users, 'active'); + * // => 2 + */ +var findIndex = createFindIndex(); + +module.exports = findIndex; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/findLastIndex.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/findLastIndex.js new file mode 100644 index 00000000000000..d6d8eca6df707b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/findLastIndex.js @@ -0,0 +1,53 @@ +var createFindIndex = require('../internal/createFindIndex'); + +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(chr) { + * return chr.user == 'pebbles'; + * }); + * // => 2 + * + * // using the `_.matches` callback shorthand + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // using the `_.matchesProperty` callback shorthand + * _.findLastIndex(users, 'active', false); + * // => 2 + * + * // using the `_.property` callback shorthand + * _.findLastIndex(users, 'active'); + * // => 0 + */ +var findLastIndex = createFindIndex(true); + +module.exports = findLastIndex; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/first.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/first.js new file mode 100644 index 00000000000000..b3b9c79c7bba5d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/first.js @@ -0,0 +1,22 @@ +/** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @alias head + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([]); + * // => undefined + */ +function first(array) { + return array ? array[0] : undefined; +} + +module.exports = first; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/flatten.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/flatten.js new file mode 100644 index 00000000000000..65bbeefb775ad8 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/flatten.js @@ -0,0 +1,32 @@ +var baseFlatten = require('../internal/baseFlatten'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Flattens a nested array. If `isDeep` is `true` the array is recursively + * flattened, otherwise it is only flattened a single level. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, 3, [4]]]); + * // => [1, 2, 3, [4]] + * + * // using `isDeep` + * _.flatten([1, [2, 3, [4]]], true); + * // => [1, 2, 3, 4] + */ +function flatten(array, isDeep, guard) { + var length = array ? array.length : 0; + if (guard && isIterateeCall(array, isDeep, guard)) { + isDeep = false; + } + return length ? baseFlatten(array, isDeep) : []; +} + +module.exports = flatten; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/flattenDeep.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/flattenDeep.js new file mode 100644 index 00000000000000..9f775febe2aeb3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/flattenDeep.js @@ -0,0 +1,21 @@ +var baseFlatten = require('../internal/baseFlatten'); + +/** + * Recursively flattens a nested array. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to recursively flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, 3, [4]]]); + * // => [1, 2, 3, 4] + */ +function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, true) : []; +} + +module.exports = flattenDeep; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/head.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/head.js new file mode 100644 index 00000000000000..1961b08c7eb538 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/head.js @@ -0,0 +1 @@ +module.exports = require('./first'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/indexOf.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/indexOf.js new file mode 100644 index 00000000000000..f8f6c9fc2cdb4f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/indexOf.js @@ -0,0 +1,54 @@ +var baseIndexOf = require('../internal/baseIndexOf'), + binaryIndex = require('../internal/binaryIndex'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it is used as the offset + * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` + * performs a faster binary search. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // using `fromIndex` + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + * + * // performing a binary search + * _.indexOf([1, 1, 2, 2], 2, true); + * // => 2 + */ +function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else if (fromIndex) { + var index = binaryIndex(array, value), + other = array[index]; + + if (value === value ? (value === other) : (other !== other)) { + return index; + } + return -1; + } + return baseIndexOf(array, value, fromIndex || 0); +} + +module.exports = indexOf; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/initial.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/initial.js new file mode 100644 index 00000000000000..59b7a7d96dfbda --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/initial.js @@ -0,0 +1,20 @@ +var dropRight = require('./dropRight'); + +/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ +function initial(array) { + return dropRight(array, 1); +} + +module.exports = initial; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/intersection.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/intersection.js new file mode 100644 index 00000000000000..13af23eb5e9060 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/intersection.js @@ -0,0 +1,65 @@ +var baseIndexOf = require('../internal/baseIndexOf'), + cacheIndexOf = require('../internal/cacheIndexOf'), + createCache = require('../internal/createCache'), + isArrayLike = require('../internal/isArrayLike'); + +/** + * Creates an array of unique values in all provided arrays using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of shared values. + * @example + * _.intersection([1, 2], [4, 2], [2, 1]); + * // => [2] + */ +function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = [], + indexOf = baseIndexOf, + isCommon = true, + result = []; + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArrayLike(value)) { + args.push(value); + caches.push((isCommon && value.length >= 120) ? createCache(argsIndex && value) : null); + } + } + argsLength = args.length; + if (argsLength < 2) { + return result; + } + var array = args[0], + index = -1, + length = array ? array.length : 0, + seen = caches[0]; + + outer: + while (++index < length) { + value = array[index]; + if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { + argsIndex = argsLength; + while (--argsIndex) { + var cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value, 0)) < 0) { + continue outer; + } + } + if (seen) { + seen.push(value); + } + result.push(value); + } + } + return result; +} + +module.exports = intersection; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/last.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/last.js new file mode 100644 index 00000000000000..299af3146ca232 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/last.js @@ -0,0 +1,19 @@ +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; +} + +module.exports = last; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/lastIndexOf.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/lastIndexOf.js new file mode 100644 index 00000000000000..02b806269bd21c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/lastIndexOf.js @@ -0,0 +1,60 @@ +var binaryIndex = require('../internal/binaryIndex'), + indexOfNaN = require('../internal/indexOfNaN'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=array.length-1] The index to search from + * or `true` to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // using `fromIndex` + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + * + * // performing a binary search + * _.lastIndexOf([1, 1, 2, 2], 2, true); + * // => 3 + */ +function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; + } else if (fromIndex) { + index = binaryIndex(array, value, true) - 1; + var other = array[index]; + if (value === value ? (value === other) : (other !== other)) { + return index; + } + return -1; + } + if (value !== value) { + return indexOfNaN(array, index, true); + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +module.exports = lastIndexOf; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/object.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/object.js new file mode 100644 index 00000000000000..f4a34531b139f9 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/object.js @@ -0,0 +1 @@ +module.exports = require('./zipObject'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/pull.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/pull.js new file mode 100644 index 00000000000000..746f196f830fe0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/pull.js @@ -0,0 +1,52 @@ +var baseIndexOf = require('../internal/baseIndexOf'); + +/** Used for native method references. */ +var arrayProto = Array.prototype; + +/** Native method references. */ +var splice = arrayProto.splice; + +/** + * Removes all provided values from `array` using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ +function pull() { + var args = arguments, + array = args[0]; + + if (!(array && array.length)) { + return array; + } + var index = 0, + indexOf = baseIndexOf, + length = args.length; + + while (++index < length) { + var fromIndex = 0, + value = args[index]; + + while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { + splice.call(array, fromIndex, 1); + } + } + return array; +} + +module.exports = pull; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/pullAt.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/pullAt.js new file mode 100644 index 00000000000000..4ca2476f0e1c78 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/pullAt.js @@ -0,0 +1,40 @@ +var baseAt = require('../internal/baseAt'), + baseCompareAscending = require('../internal/baseCompareAscending'), + baseFlatten = require('../internal/baseFlatten'), + basePullAt = require('../internal/basePullAt'), + restParam = require('../function/restParam'); + +/** + * Removes elements from `array` corresponding to the given indexes and returns + * an array of the removed elements. Indexes may be specified as an array of + * indexes or as individual arguments. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove, + * specified as individual indexes or arrays of indexes. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [5, 10, 15, 20]; + * var evens = _.pullAt(array, 1, 3); + * + * console.log(array); + * // => [5, 15] + * + * console.log(evens); + * // => [10, 20] + */ +var pullAt = restParam(function(array, indexes) { + indexes = baseFlatten(indexes); + + var result = baseAt(array, indexes); + basePullAt(array, indexes.sort(baseCompareAscending)); + return result; +}); + +module.exports = pullAt; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/remove.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/remove.js new file mode 100644 index 00000000000000..0cf979bda0b241 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/remove.js @@ -0,0 +1,64 @@ +var baseCallback = require('../internal/baseCallback'), + basePullAt = require('../internal/basePullAt'); + +/** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * **Note:** Unlike `_.filter`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ +function remove(array, predicate, thisArg) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = baseCallback(predicate, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; +} + +module.exports = remove; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/rest.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/rest.js new file mode 100644 index 00000000000000..9bfb734f1fbe64 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/rest.js @@ -0,0 +1,21 @@ +var drop = require('./drop'); + +/** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @alias tail + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + */ +function rest(array) { + return drop(array, 1); +} + +module.exports = rest; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/slice.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/slice.js new file mode 100644 index 00000000000000..48ef1a1a280f56 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/slice.js @@ -0,0 +1,30 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of `Array#slice` to support node + * lists in IE < 9 and to ensure dense arrays are returned. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + return baseSlice(array, start, end); +} + +module.exports = slice; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/sortedIndex.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/sortedIndex.js new file mode 100644 index 00000000000000..51d150e3b3ac9d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/sortedIndex.js @@ -0,0 +1,53 @@ +var createSortedIndex = require('../internal/createSortedIndex'); + +/** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. If an iteratee + * function is provided it is invoked for `value` and each element of `array` + * to compute their sort ranking. The iteratee is bound to `thisArg` and + * invoked with one argument; (value). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 4, 5, 5], 5); + * // => 2 + * + * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; + * + * // using an iteratee function + * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { + * return this.data[word]; + * }, dict); + * // => 1 + * + * // using the `_.property` callback shorthand + * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 1 + */ +var sortedIndex = createSortedIndex(); + +module.exports = sortedIndex; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/sortedLastIndex.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/sortedLastIndex.js new file mode 100644 index 00000000000000..81a4a8689e8c00 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/sortedLastIndex.js @@ -0,0 +1,25 @@ +var createSortedIndex = require('../internal/createSortedIndex'); + +/** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 4, 5, 5], 5); + * // => 4 + */ +var sortedLastIndex = createSortedIndex(true); + +module.exports = sortedLastIndex; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/tail.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/tail.js new file mode 100644 index 00000000000000..c5dfe779d6f762 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/tail.js @@ -0,0 +1 @@ +module.exports = require('./rest'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/take.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/take.js new file mode 100644 index 00000000000000..875917a746650d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/take.js @@ -0,0 +1,39 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ +function take(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = take; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeRight.js new file mode 100644 index 00000000000000..6e89c874801804 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeRight.js @@ -0,0 +1,40 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ +function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, n < 0 ? 0 : n); +} + +module.exports = takeRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeRightWhile.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeRightWhile.js new file mode 100644 index 00000000000000..5464d13b7fa2fb --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeRightWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is bound to `thisArg` + * and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [2, 3] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active'), 'user'); + * // => [] + */ +function takeRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3), false, true) + : []; +} + +module.exports = takeRightWhile; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeWhile.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeWhile.js new file mode 100644 index 00000000000000..f7e28a1d423a8e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/takeWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [1, 2] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false}, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeWhile(users, 'active', false), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeWhile(users, 'active'), 'user'); + * // => [] + */ +function takeWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3)) + : []; +} + +module.exports = takeWhile; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/union.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/union.js new file mode 100644 index 00000000000000..ee71b2782a3252 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/union.js @@ -0,0 +1,24 @@ +var baseFlatten = require('../internal/baseFlatten'), + baseUniq = require('../internal/baseUniq'), + restParam = require('../function/restParam'); + +/** + * Creates an array of unique values, in order, of the provided arrays using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([1, 2], [4, 2], [2, 1]); + * // => [1, 2, 4] + */ +var union = restParam(function(arrays) { + return baseUniq(baseFlatten(arrays, false, true)); +}); + +module.exports = union; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/uniq.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/uniq.js new file mode 100644 index 00000000000000..91ae46e244d99f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/uniq.js @@ -0,0 +1,71 @@ +var baseCallback = require('../internal/baseCallback'), + baseUniq = require('../internal/baseUniq'), + isIterateeCall = require('../internal/isIterateeCall'), + sortedUniq = require('../internal/sortedUniq'); + +/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons, in which only the first occurence of each element + * is kept. Providing `true` for `isSorted` performs a faster search algorithm + * for sorted arrays. If an iteratee function is provided it is invoked for + * each element in the array to generate the criterion by which uniqueness + * is computed. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index, array). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Array + * @param {Array} array The array to inspect. + * @param {boolean} [isSorted] Specify the array is sorted. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new duplicate-value-free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + * + * // using `isSorted` + * _.uniq([1, 1, 2], true); + * // => [1, 2] + * + * // using an iteratee function + * _.uniq([1, 2.5, 1.5, 2], function(n) { + * return this.floor(n); + * }, Math); + * // => [1, 2.5] + * + * // using the `_.property` callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ +function uniq(array, isSorted, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (isSorted != null && typeof isSorted != 'boolean') { + thisArg = iteratee; + iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted; + isSorted = false; + } + iteratee = iteratee == null ? iteratee : baseCallback(iteratee, thisArg, 3); + return (isSorted) + ? sortedUniq(array, iteratee) + : baseUniq(array, iteratee); +} + +module.exports = uniq; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unique.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unique.js new file mode 100644 index 00000000000000..396de1b80464f8 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unique.js @@ -0,0 +1 @@ +module.exports = require('./uniq'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unzip.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unzip.js new file mode 100644 index 00000000000000..0a539fa631522b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unzip.js @@ -0,0 +1,47 @@ +var arrayFilter = require('../internal/arrayFilter'), + arrayMap = require('../internal/arrayMap'), + baseProperty = require('../internal/baseProperty'), + isArrayLike = require('../internal/isArrayLike'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + * + * _.unzip(zipped); + * // => [['fred', 'barney'], [30, 40], [true, false]] + */ +function unzip(array) { + if (!(array && array.length)) { + return []; + } + var index = -1, + length = 0; + + array = arrayFilter(array, function(group) { + if (isArrayLike(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + var result = Array(length); + while (++index < length) { + result[index] = arrayMap(array, baseProperty(index)); + } + return result; +} + +module.exports = unzip; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unzipWith.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unzipWith.js new file mode 100644 index 00000000000000..324a2b1db28578 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/unzipWith.js @@ -0,0 +1,41 @@ +var arrayMap = require('../internal/arrayMap'), + arrayReduce = require('../internal/arrayReduce'), + bindCallback = require('../internal/bindCallback'), + unzip = require('./unzip'); + +/** + * This method is like `_.unzip` except that it accepts an iteratee to specify + * how regrouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee] The function to combine regrouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ +function unzipWith(array, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + iteratee = bindCallback(iteratee, thisArg, 4); + return arrayMap(result, function(group) { + return arrayReduce(group, iteratee, undefined, true); + }); +} + +module.exports = unzipWith; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/without.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/without.js new file mode 100644 index 00000000000000..19b78491af674f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/without.js @@ -0,0 +1,27 @@ +var baseDifference = require('../internal/baseDifference'), + isArrayLike = require('../internal/isArrayLike'), + restParam = require('../function/restParam'); + +/** + * Creates an array excluding all provided values using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to filter. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.without([1, 2, 1, 3], 1, 2); + * // => [3] + */ +var without = restParam(function(array, values) { + return isArrayLike(array) + ? baseDifference(array, values) + : []; +}); + +module.exports = without; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/xor.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/xor.js new file mode 100644 index 00000000000000..315b9f8e29c34d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/xor.js @@ -0,0 +1,34 @@ +var baseDifference = require('../internal/baseDifference'), + baseUniq = require('../internal/baseUniq'), + isArrayLike = require('../internal/isArrayLike'); + +/** + * Creates an array that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the provided arrays. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of values. + * @example + * + * _.xor([1, 2], [4, 2]); + * // => [1, 4] + */ +function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArrayLike(array)) { + var result = result + ? baseDifference(result, array).concat(baseDifference(array, result)) + : array; + } + } + return result ? baseUniq(result) : []; +} + +module.exports = xor; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zip.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zip.js new file mode 100644 index 00000000000000..53a6f69912158c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zip.js @@ -0,0 +1,21 @@ +var restParam = require('../function/restParam'), + unzip = require('./unzip'); + +/** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second elements + * of the given arrays, and so on. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ +var zip = restParam(unzip); + +module.exports = zip; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zipObject.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zipObject.js new file mode 100644 index 00000000000000..dec7a211b7427f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zipObject.js @@ -0,0 +1,43 @@ +var isArray = require('../lang/isArray'); + +/** + * The inverse of `_.pairs`; this method returns an object composed from arrays + * of property names and values. Provide either a single two dimensional array, + * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names + * and one of corresponding values. + * + * @static + * @memberOf _ + * @alias object + * @category Array + * @param {Array} props The property names. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject([['fred', 30], ['barney', 40]]); + * // => { 'fred': 30, 'barney': 40 } + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ +function zipObject(props, values) { + var index = -1, + length = props ? props.length : 0, + result = {}; + + if (length && !values && !isArray(props[0])) { + values = []; + } + while (++index < length) { + var key = props[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; +} + +module.exports = zipObject; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zipWith.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zipWith.js new file mode 100644 index 00000000000000..7a268df5147fda --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/array/zipWith.js @@ -0,0 +1,36 @@ +var restParam = require('../function/restParam'), + unzipWith = require('./unzipWith'); + +/** + * This method is like `_.zip` except that it accepts an iteratee to specify + * how grouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee] The function to combine grouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], _.add); + * // => [111, 222] + */ +var zipWith = restParam(function(arrays) { + var length = arrays.length, + iteratee = arrays[length - 2], + thisArg = arrays[length - 1]; + + if (length > 2 && typeof iteratee == 'function') { + length -= 2; + } else { + iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined; + thisArg = undefined; + } + arrays.length = length; + return unzipWith(arrays, iteratee, thisArg); +}); + +module.exports = zipWith; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain.js new file mode 100644 index 00000000000000..7992b733e23602 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain.js @@ -0,0 +1,15 @@ +module.exports = { + 'chain': require('./chain/chain'), + 'commit': require('./chain/commit'), + 'lodash': require('./chain/lodash'), + 'plant': require('./chain/plant'), + 'reverse': require('./chain/reverse'), + 'run': require('./chain/run'), + 'tap': require('./chain/tap'), + 'thru': require('./chain/thru'), + 'toJSON': require('./chain/toJSON'), + 'toString': require('./chain/toString'), + 'value': require('./chain/value'), + 'valueOf': require('./chain/valueOf'), + 'wrapperChain': require('./chain/wrapperChain') +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/chain.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/chain.js new file mode 100644 index 00000000000000..453ba1eb5e88cc --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/chain.js @@ -0,0 +1,35 @@ +var lodash = require('./lodash'); + +/** + * Creates a `lodash` object that wraps `value` with explicit method + * chaining enabled. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _.chain(users) + * .sortBy('age') + * .map(function(chr) { + * return chr.user + ' is ' + chr.age; + * }) + * .first() + * .value(); + * // => 'pebbles is 1' + */ +function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; +} + +module.exports = chain; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/commit.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/commit.js new file mode 100644 index 00000000000000..c732d1bf9139d0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/commit.js @@ -0,0 +1 @@ +module.exports = require('./wrapperCommit'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/lodash.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/lodash.js new file mode 100644 index 00000000000000..7ca104c44853f4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/lodash.js @@ -0,0 +1,122 @@ +var LazyWrapper = require('../internal/LazyWrapper'), + LodashWrapper = require('../internal/LodashWrapper'), + baseLodash = require('../internal/baseLodash'), + isArray = require('../lang/isArray'), + isObjectLike = require('../internal/isObjectLike'), + wrapperClone = require('../internal/wrapperClone'); + +/** Used for native method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates a `lodash` object which wraps `value` to enable implicit chaining. + * Methods that operate on and return arrays, collections, and functions can + * be chained together. Methods that return a boolean or single value will + * automatically end the chain returning the unwrapped value. Explicit chaining + * may be enabled using `_.chain`. The execution of chained methods is lazy, + * that is, execution is deferred until `_#value` is implicitly or explicitly + * called. + * + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut + * fusion is an optimization that merges iteratees to avoid creating intermediate + * arrays and reduce the number of iteratee executions. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, + * `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, + * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, + * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, + * and `where` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, + * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, + * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`, + * `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`, + * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, + * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, + * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, + * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, + * `merge`, `mixin`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, + * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`, + * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, + * `spread`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, + * `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `valuesIn`, `where`, + * `without`, `wrap`, `xor`, `zip`, and `zipObject` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`, + * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, + * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`, + * `identity`, `includes`, `indexOf`, `inRange`, `isArguments`, `isArray`, + * `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite` + * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, + * `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, + * `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`, `noConflict`, + * `noop`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, + * `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, `startsWith`, + * `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, `unescape`, + * `uniqueId`, `value`, and `words` + * + * The wrapper method `sample` will return a wrapped value when `n` is provided, + * otherwise an unwrapped value is returned. + * + * @name _ + * @constructor + * @category Chain + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(total, n) { + * return total + n; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(n) { + * return n * n; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ +function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); +} + +// Ensure wrappers are instances of `baseLodash`. +lodash.prototype = baseLodash.prototype; + +module.exports = lodash; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/plant.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/plant.js new file mode 100644 index 00000000000000..04099f238659d4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/plant.js @@ -0,0 +1 @@ +module.exports = require('./wrapperPlant'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/reverse.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/reverse.js new file mode 100644 index 00000000000000..f72a64a19b95db --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/reverse.js @@ -0,0 +1 @@ +module.exports = require('./wrapperReverse'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/run.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/run.js new file mode 100644 index 00000000000000..5e751a2c32e8af --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/run.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/tap.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/tap.js new file mode 100644 index 00000000000000..3d0257ecfde69b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/tap.js @@ -0,0 +1,29 @@ +/** + * This method invokes `interceptor` and returns `value`. The interceptor is + * bound to `thisArg` and invoked with one argument; (value). The purpose of + * this method is to "tap into" a method chain in order to perform operations + * on intermediate results within the chain. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ +function tap(value, interceptor, thisArg) { + interceptor.call(thisArg, value); + return value; +} + +module.exports = tap; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/thru.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/thru.js new file mode 100644 index 00000000000000..a7157803769d83 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/thru.js @@ -0,0 +1,26 @@ +/** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ +function thru(value, interceptor, thisArg) { + return interceptor.call(thisArg, value); +} + +module.exports = thru; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/toJSON.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/toJSON.js new file mode 100644 index 00000000000000..5e751a2c32e8af --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/toJSON.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/toString.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/toString.js new file mode 100644 index 00000000000000..c7bcbf9a543e98 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/toString.js @@ -0,0 +1 @@ +module.exports = require('./wrapperToString'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/value.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/value.js new file mode 100644 index 00000000000000..5e751a2c32e8af --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/value.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/valueOf.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/valueOf.js new file mode 100644 index 00000000000000..5e751a2c32e8af --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/valueOf.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperChain.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperChain.js new file mode 100644 index 00000000000000..38234819ba04d5 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperChain.js @@ -0,0 +1,32 @@ +var chain = require('./chain'); + +/** + * Enables explicit method chaining on the wrapper object. + * + * @name chain + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // without explicit chaining + * _(users).first(); + * // => { 'user': 'barney', 'age': 36 } + * + * // with explicit chaining + * _(users).chain() + * .first() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ +function wrapperChain() { + return chain(this); +} + +module.exports = wrapperChain; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperCommit.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperCommit.js new file mode 100644 index 00000000000000..c46a787e97d0e7 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperCommit.js @@ -0,0 +1,32 @@ +var LodashWrapper = require('../internal/LodashWrapper'); + +/** + * Executes the chained sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapper = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapper = wrapper.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapper.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ +function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); +} + +module.exports = wrapperCommit; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperPlant.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperPlant.js new file mode 100644 index 00000000000000..a3de146b13d740 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperPlant.js @@ -0,0 +1,45 @@ +var baseLodash = require('../internal/baseLodash'), + wrapperClone = require('../internal/wrapperClone'); + +/** + * Creates a clone of the chained sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapper = _(array).map(function(value) { + * return Math.pow(value, 2); + * }); + * + * var other = [3, 4]; + * var otherWrapper = wrapper.plant(other); + * + * otherWrapper.value(); + * // => [9, 16] + * + * wrapper.value(); + * // => [1, 4] + */ +function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; +} + +module.exports = wrapperPlant; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperReverse.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperReverse.js new file mode 100644 index 00000000000000..4518b3ed286c56 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperReverse.js @@ -0,0 +1,38 @@ +var LazyWrapper = require('../internal/LazyWrapper'), + LodashWrapper = require('../internal/LodashWrapper'), + thru = require('./thru'); + +/** + * Reverses the wrapped array so the first element becomes the last, the + * second element becomes the second to last, and so on. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new reversed `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ +function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + if (this.__actions__.length) { + value = new LazyWrapper(this); + } + return new LodashWrapper(value.reverse(), this.__chain__); + } + return this.thru(function(value) { + return value.reverse(); + }); +} + +module.exports = wrapperReverse; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperToString.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperToString.js new file mode 100644 index 00000000000000..db975a5a35427f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperToString.js @@ -0,0 +1,17 @@ +/** + * Produces the result of coercing the unwrapped value to a string. + * + * @name toString + * @memberOf _ + * @category Chain + * @returns {string} Returns the coerced string value. + * @example + * + * _([1, 2, 3]).toString(); + * // => '1,2,3' + */ +function wrapperToString() { + return (this.value() + ''); +} + +module.exports = wrapperToString; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperValue.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperValue.js new file mode 100644 index 00000000000000..2734e41c4a9290 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/chain/wrapperValue.js @@ -0,0 +1,20 @@ +var baseWrapperValue = require('../internal/baseWrapperValue'); + +/** + * Executes the chained sequence to extract the unwrapped value. + * + * @name value + * @memberOf _ + * @alias run, toJSON, valueOf + * @category Chain + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ +function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); +} + +module.exports = wrapperValue; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection.js new file mode 100644 index 00000000000000..03388571c3145d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection.js @@ -0,0 +1,44 @@ +module.exports = { + 'all': require('./collection/all'), + 'any': require('./collection/any'), + 'at': require('./collection/at'), + 'collect': require('./collection/collect'), + 'contains': require('./collection/contains'), + 'countBy': require('./collection/countBy'), + 'detect': require('./collection/detect'), + 'each': require('./collection/each'), + 'eachRight': require('./collection/eachRight'), + 'every': require('./collection/every'), + 'filter': require('./collection/filter'), + 'find': require('./collection/find'), + 'findLast': require('./collection/findLast'), + 'findWhere': require('./collection/findWhere'), + 'foldl': require('./collection/foldl'), + 'foldr': require('./collection/foldr'), + 'forEach': require('./collection/forEach'), + 'forEachRight': require('./collection/forEachRight'), + 'groupBy': require('./collection/groupBy'), + 'include': require('./collection/include'), + 'includes': require('./collection/includes'), + 'indexBy': require('./collection/indexBy'), + 'inject': require('./collection/inject'), + 'invoke': require('./collection/invoke'), + 'map': require('./collection/map'), + 'max': require('./math/max'), + 'min': require('./math/min'), + 'partition': require('./collection/partition'), + 'pluck': require('./collection/pluck'), + 'reduce': require('./collection/reduce'), + 'reduceRight': require('./collection/reduceRight'), + 'reject': require('./collection/reject'), + 'sample': require('./collection/sample'), + 'select': require('./collection/select'), + 'shuffle': require('./collection/shuffle'), + 'size': require('./collection/size'), + 'some': require('./collection/some'), + 'sortBy': require('./collection/sortBy'), + 'sortByAll': require('./collection/sortByAll'), + 'sortByOrder': require('./collection/sortByOrder'), + 'sum': require('./math/sum'), + 'where': require('./collection/where') +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/all.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/all.js new file mode 100644 index 00000000000000..d0839f77ed712b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/all.js @@ -0,0 +1 @@ +module.exports = require('./every'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/any.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/any.js new file mode 100644 index 00000000000000..900ac25e836b2c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/any.js @@ -0,0 +1 @@ +module.exports = require('./some'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/at.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/at.js new file mode 100644 index 00000000000000..29236e577dfb85 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/at.js @@ -0,0 +1,29 @@ +var baseAt = require('../internal/baseAt'), + baseFlatten = require('../internal/baseFlatten'), + restParam = require('../function/restParam'); + +/** + * Creates an array of elements corresponding to the given keys, or indexes, + * of `collection`. Keys may be specified as individual arguments or as arrays + * of keys. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [props] The property names + * or indexes of elements to pick, specified individually or in arrays. + * @returns {Array} Returns the new array of picked elements. + * @example + * + * _.at(['a', 'b', 'c'], [0, 2]); + * // => ['a', 'c'] + * + * _.at(['barney', 'fred', 'pebbles'], 0, 2); + * // => ['barney', 'pebbles'] + */ +var at = restParam(function(collection, props) { + return baseAt(collection, baseFlatten(props)); +}); + +module.exports = at; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/collect.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/collect.js new file mode 100644 index 00000000000000..0d1e1abfaf9700 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/collect.js @@ -0,0 +1 @@ +module.exports = require('./map'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/contains.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/contains.js new file mode 100644 index 00000000000000..594722af59a707 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/contains.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/countBy.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/countBy.js new file mode 100644 index 00000000000000..e97dbb749d1c74 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/countBy.js @@ -0,0 +1,54 @@ +var createAggregator = require('../internal/createAggregator'); + +/** Used for native method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the number of times the key was returned by `iteratee`. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ +var countBy = createAggregator(function(result, value, key) { + hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); +}); + +module.exports = countBy; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/detect.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/detect.js new file mode 100644 index 00000000000000..2fb6303efb4984 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/detect.js @@ -0,0 +1 @@ +module.exports = require('./find'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/each.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/each.js new file mode 100644 index 00000000000000..8800f42046e3ed --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/eachRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/eachRight.js new file mode 100644 index 00000000000000..3252b2aba320f3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/every.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/every.js new file mode 100644 index 00000000000000..a04d3db637783d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/every.js @@ -0,0 +1,66 @@ +var arrayEvery = require('../internal/arrayEvery'), + baseCallback = require('../internal/baseCallback'), + baseEvery = require('../internal/baseEvery'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * The predicate is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.every(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.every(users, 'active'); + * // => false + */ +function every(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = null; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = baseCallback(predicate, thisArg, 3); + } + return func(collection, predicate); +} + +module.exports = every; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/filter.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/filter.js new file mode 100644 index 00000000000000..7620aa76195125 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/filter.js @@ -0,0 +1,61 @@ +var arrayFilter = require('../internal/arrayFilter'), + baseCallback = require('../internal/baseCallback'), + baseFilter = require('../internal/baseFilter'), + isArray = require('../lang/isArray'); + +/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.filter([4, 5, 6], function(n) { + * return n % 2 == 0; + * }); + * // => [4, 6] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.filter(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.filter(users, 'active'), 'user'); + * // => ['barney'] + */ +function filter(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = baseCallback(predicate, thisArg, 3); + return func(collection, predicate); +} + +module.exports = filter; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/find.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/find.js new file mode 100644 index 00000000000000..7358cfe86cb435 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/find.js @@ -0,0 +1,56 @@ +var baseEach = require('../internal/baseEach'), + createFind = require('../internal/createFind'); + +/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias detect + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.result(_.find(users, function(chr) { + * return chr.age < 40; + * }), 'user'); + * // => 'barney' + * + * // using the `_.matches` callback shorthand + * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); + * // => 'pebbles' + * + * // using the `_.matchesProperty` callback shorthand + * _.result(_.find(users, 'active', false), 'user'); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.result(_.find(users, 'active'), 'user'); + * // => 'barney' + */ +var find = createFind(baseEach); + +module.exports = find; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/findLast.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/findLast.js new file mode 100644 index 00000000000000..75dbadca2407d0 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/findLast.js @@ -0,0 +1,25 @@ +var baseEachRight = require('../internal/baseEachRight'), + createFind = require('../internal/createFind'); + +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(baseEachRight, true); + +module.exports = findLast; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/findWhere.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/findWhere.js new file mode 100644 index 00000000000000..2d620655ed4307 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/findWhere.js @@ -0,0 +1,37 @@ +var baseMatches = require('../internal/baseMatches'), + find = require('./find'); + +/** + * Performs a deep comparison between each element in `collection` and the + * source object, returning the first element that has equivalent property + * values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); + * // => 'barney' + * + * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); + * // => 'fred' + */ +function findWhere(collection, source) { + return find(collection, baseMatches(source)); +} + +module.exports = findWhere; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/foldl.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/foldl.js new file mode 100644 index 00000000000000..26f53cf7b26816 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/foldl.js @@ -0,0 +1 @@ +module.exports = require('./reduce'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/foldr.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/foldr.js new file mode 100644 index 00000000000000..8fb199eda60041 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/foldr.js @@ -0,0 +1 @@ +module.exports = require('./reduceRight'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/forEach.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/forEach.js new file mode 100644 index 00000000000000..05a8e2140ebe1f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/forEach.js @@ -0,0 +1,37 @@ +var arrayEach = require('../internal/arrayEach'), + baseEach = require('../internal/baseEach'), + createForEach = require('../internal/createForEach'); + +/** + * Iterates over elements of `collection` invoking `iteratee` for each element. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). Iteratee functions may exit iteration early + * by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEach(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from left to right and returns the array + * + * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { + * console.log(n, key); + * }); + * // => logs each value-key pair and returns the object (iteration order is not guaranteed) + */ +var forEach = createForEach(arrayEach, baseEach); + +module.exports = forEach; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/forEachRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/forEachRight.js new file mode 100644 index 00000000000000..34997110024056 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/forEachRight.js @@ -0,0 +1,26 @@ +var arrayEachRight = require('../internal/arrayEachRight'), + baseEachRight = require('../internal/baseEachRight'), + createForEach = require('../internal/createForEach'); + +/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEachRight(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from right to left and returns the array + */ +var forEachRight = createForEach(arrayEachRight, baseEachRight); + +module.exports = forEachRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/groupBy.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/groupBy.js new file mode 100644 index 00000000000000..a925c894a0d73b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/groupBy.js @@ -0,0 +1,59 @@ +var createAggregator = require('../internal/createAggregator'); + +/** Used for native method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using the `_.property` callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ +var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + result[key] = [value]; + } +}); + +module.exports = groupBy; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/include.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/include.js new file mode 100644 index 00000000000000..594722af59a707 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/include.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/includes.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/includes.js new file mode 100644 index 00000000000000..80c90e1e3fd115 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/includes.js @@ -0,0 +1,60 @@ +var baseIndexOf = require('../internal/baseIndexOf'), + getLength = require('../internal/getLength'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'), + isLength = require('../internal/isLength'), + isString = require('../lang/isString'), + values = require('../object/values'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Checks if `value` is in `collection` using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it is used as the offset + * from the end of `collection`. + * + * @static + * @memberOf _ + * @alias contains, include + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {*} target The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {boolean} Returns `true` if a matching element is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.includes('pebbles', 'eb'); + * // => true + */ +function includes(collection, target, fromIndex, guard) { + var length = collection ? getLength(collection) : 0; + if (!isLength(length)) { + collection = values(collection); + length = collection.length; + } + if (!length) { + return false; + } + if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { + fromIndex = 0; + } else { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); + } + return (typeof collection == 'string' || !isArray(collection) && isString(collection)) + ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1) + : (baseIndexOf(collection, target, fromIndex) > -1); +} + +module.exports = includes; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/indexBy.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/indexBy.js new file mode 100644 index 00000000000000..34a941e7290c72 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/indexBy.js @@ -0,0 +1,53 @@ +var createAggregator = require('../internal/createAggregator'); + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the last element responsible for generating the key. The + * iteratee function is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keyData = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keyData, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return String.fromCharCode(object.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return this.fromCharCode(object.code); + * }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ +var indexBy = createAggregator(function(result, value, key) { + result[key] = value; +}); + +module.exports = indexBy; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/inject.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/inject.js new file mode 100644 index 00000000000000..26f53cf7b26816 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/inject.js @@ -0,0 +1 @@ +module.exports = require('./reduce'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/invoke.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/invoke.js new file mode 100644 index 00000000000000..5cb428ec2a8f9b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/invoke.js @@ -0,0 +1,42 @@ +var baseEach = require('../internal/baseEach'), + invokePath = require('../internal/invokePath'), + isArrayLike = require('../internal/isArrayLike'), + isKey = require('../internal/isKey'), + restParam = require('../function/restParam'); + +/** + * Invokes the method at `path` on each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `methodName` is a function it is + * invoked for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ +var invoke = restParam(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + isProp = isKey(path), + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? path : (isProp && value != null && value[path]); + result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); + }); + return result; +}); + +module.exports = invoke; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/map.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/map.js new file mode 100644 index 00000000000000..1413f50c9f6037 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/map.js @@ -0,0 +1,68 @@ +var arrayMap = require('../internal/arrayMap'), + baseCallback = require('../internal/baseCallback'), + baseMap = require('../internal/baseMap'), + isArray = require('../lang/isArray'); + +/** + * Creates an array of values by running each element in `collection` through + * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * Many lodash methods are guarded to work as interatees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, + * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, + * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, + * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, + * `sum`, `uniq`, and `words` + * + * @static + * @memberOf _ + * @alias collect + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new mapped array. + * @example + * + * function timesThree(n) { + * return n * 3; + * } + * + * _.map([1, 2], timesThree); + * // => [3, 6] + * + * _.map({ 'a': 1, 'b': 2 }, timesThree); + * // => [3, 6] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // using the `_.property` callback shorthand + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ +function map(collection, iteratee, thisArg) { + var func = isArray(collection) ? arrayMap : baseMap; + iteratee = baseCallback(iteratee, thisArg, 3); + return func(collection, iteratee); +} + +module.exports = map; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/max.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/max.js new file mode 100644 index 00000000000000..bb1d213c33bd47 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/max.js @@ -0,0 +1 @@ +module.exports = require('../math/max'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/min.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/min.js new file mode 100644 index 00000000000000..eef13d02b8a01e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/min.js @@ -0,0 +1 @@ +module.exports = require('../math/min'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/partition.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/partition.js new file mode 100644 index 00000000000000..ee35f27d9301b4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/partition.js @@ -0,0 +1,66 @@ +var createAggregator = require('../internal/createAggregator'); + +/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, while the second of which + * contains elements `predicate` returns falsey for. The predicate is bound + * to `thisArg` and invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * _.partition([1, 2, 3], function(n) { + * return n % 2; + * }); + * // => [[1, 3], [2]] + * + * _.partition([1.2, 2.3, 3.4], function(n) { + * return this.floor(n) % 2; + * }, Math); + * // => [[1.2, 3.4], [2.3]] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * var mapper = function(array) { + * return _.pluck(array, 'user'); + * }; + * + * // using the `_.matches` callback shorthand + * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); + * // => [['pebbles'], ['barney', 'fred']] + * + * // using the `_.matchesProperty` callback shorthand + * _.map(_.partition(users, 'active', false), mapper); + * // => [['barney', 'pebbles'], ['fred']] + * + * // using the `_.property` callback shorthand + * _.map(_.partition(users, 'active'), mapper); + * // => [['fred'], ['barney', 'pebbles']] + */ +var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); +}, function() { return [[], []]; }); + +module.exports = partition; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/pluck.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/pluck.js new file mode 100644 index 00000000000000..5ee1ec84eec53f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/pluck.js @@ -0,0 +1,31 @@ +var map = require('./map'), + property = require('../utility/property'); + +/** + * Gets the property value of `path` from all elements in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|string} path The path of the property to pluck. + * @returns {Array} Returns the property values. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.pluck(users, 'user'); + * // => ['barney', 'fred'] + * + * var userIndex = _.indexBy(users, 'user'); + * _.pluck(userIndex, 'age'); + * // => [36, 40] (iteration order is not guaranteed) + */ +function pluck(collection, path) { + return map(collection, property(path)); +} + +module.exports = pluck; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reduce.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reduce.js new file mode 100644 index 00000000000000..a483d2568b69a2 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reduce.js @@ -0,0 +1,43 @@ +var arrayReduce = require('../internal/arrayReduce'), + baseEach = require('../internal/baseEach'), + createReduce = require('../internal/createReduce'); + +/** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` through `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not provided the first element of `collection` is used as the initial + * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as interatees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `includes`, `merge`, `sortByAll`, and `sortByOrder` + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * _.reduce([1, 2], function(total, n) { + * return total + n; + * }); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { + * result[key] = n * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) + */ +var reduce = createReduce(arrayReduce, baseEach); + +module.exports = reduce; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reduceRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reduceRight.js new file mode 100644 index 00000000000000..5a5753b9c2185b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reduceRight.js @@ -0,0 +1,29 @@ +var arrayReduceRight = require('../internal/arrayReduceRight'), + baseEachRight = require('../internal/baseEachRight'), + createReduce = require('../internal/createReduce'); + +/** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ +var reduceRight = createReduce(arrayReduceRight, baseEachRight); + +module.exports = reduceRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reject.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reject.js new file mode 100644 index 00000000000000..55924539b524be --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/reject.js @@ -0,0 +1,50 @@ +var arrayFilter = require('../internal/arrayFilter'), + baseCallback = require('../internal/baseCallback'), + baseFilter = require('../internal/baseFilter'), + isArray = require('../lang/isArray'); + +/** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.reject([1, 2, 3, 4], function(n) { + * return n % 2 == 0; + * }); + * // => [1, 3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.reject(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.reject(users, 'active'), 'user'); + * // => ['barney'] + */ +function reject(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = baseCallback(predicate, thisArg, 3); + return func(collection, function(value, index, collection) { + return !predicate(value, index, collection); + }); +} + +module.exports = reject; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sample.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sample.js new file mode 100644 index 00000000000000..f090db107db89b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sample.js @@ -0,0 +1,38 @@ +var baseRandom = require('../internal/baseRandom'), + isIterateeCall = require('../internal/isIterateeCall'), + shuffle = require('./shuffle'), + toIterable = require('../internal/toIterable'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Gets a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {*} Returns the random sample(s). + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ +function sample(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n == null) { + collection = toIterable(collection); + var length = collection.length; + return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length); + return result; +} + +module.exports = sample; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/select.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/select.js new file mode 100644 index 00000000000000..ade80f6fbae9ae --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/select.js @@ -0,0 +1 @@ +module.exports = require('./filter'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/shuffle.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/shuffle.js new file mode 100644 index 00000000000000..2281d4f65b23ec --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/shuffle.js @@ -0,0 +1,35 @@ +var baseRandom = require('../internal/baseRandom'), + toIterable = require('../internal/toIterable'); + +/** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ +function shuffle(collection) { + collection = toIterable(collection); + + var index = -1, + length = collection.length, + result = Array(length); + + while (++index < length) { + var rand = baseRandom(0, index); + if (index != rand) { + result[index] = result[rand]; + } + result[rand] = collection[index]; + } + return result; +} + +module.exports = shuffle; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/size.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/size.js new file mode 100644 index 00000000000000..78dcf4ce9bea5e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/size.js @@ -0,0 +1,30 @@ +var getLength = require('../internal/getLength'), + isLength = require('../internal/isLength'), + keys = require('../object/keys'); + +/** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the size of `collection`. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ +function size(collection) { + var length = collection ? getLength(collection) : 0; + return isLength(length) ? length : keys(collection).length; +} + +module.exports = size; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/some.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/some.js new file mode 100644 index 00000000000000..2b866b464b6552 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/some.js @@ -0,0 +1,67 @@ +var arraySome = require('../internal/arraySome'), + baseCallback = require('../internal/baseCallback'), + baseSome = require('../internal/baseSome'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * The function returns as soon as it finds a passing value and does not iterate + * over the entire collection. The predicate is bound to `thisArg` and invoked + * with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.some(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.some(users, 'active'); + * // => true + */ +function some(collection, predicate, thisArg) { + var func = isArray(collection) ? arraySome : baseSome; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = null; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = baseCallback(predicate, thisArg, 3); + } + return func(collection, predicate); +} + +module.exports = some; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortBy.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortBy.js new file mode 100644 index 00000000000000..28d75f56dacce9 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortBy.js @@ -0,0 +1,71 @@ +var baseCallback = require('../internal/baseCallback'), + baseMap = require('../internal/baseMap'), + baseSortBy = require('../internal/baseSortBy'), + compareAscending = require('../internal/compareAscending'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through `iteratee`. This method performs + * a stable sort, that is, it preserves the original sort order of equal elements. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new sorted array. + * @example + * + * _.sortBy([1, 2, 3], function(n) { + * return Math.sin(n); + * }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(n) { + * return this.sin(n); + * }, Math); + * // => [3, 1, 2] + * + * var users = [ + * { 'user': 'fred' }, + * { 'user': 'pebbles' }, + * { 'user': 'barney' } + * ]; + * + * // using the `_.property` callback shorthand + * _.pluck(_.sortBy(users, 'user'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ +function sortBy(collection, iteratee, thisArg) { + if (collection == null) { + return []; + } + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = null; + } + var index = -1; + iteratee = baseCallback(iteratee, thisArg, 3); + + var result = baseMap(collection, function(value, key, collection) { + return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; + }); + return baseSortBy(result, compareAscending); +} + +module.exports = sortBy; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortByAll.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortByAll.js new file mode 100644 index 00000000000000..4766c209855c97 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortByAll.js @@ -0,0 +1,52 @@ +var baseFlatten = require('../internal/baseFlatten'), + baseSortByOrder = require('../internal/baseSortByOrder'), + isIterateeCall = require('../internal/isIterateeCall'), + restParam = require('../function/restParam'); + +/** + * This method is like `_.sortBy` except that it can sort by multiple iteratees + * or property names. + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees + * The iteratees to sort by, specified as individual values or arrays of values. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.map(_.sortByAll(users, ['user', 'age']), _.values); + * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.map(_.sortByAll(users, 'user', function(chr) { + * return Math.floor(chr.age / 10); + * }), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ +var sortByAll = restParam(function(collection, iteratees) { + if (collection == null) { + return []; + } + var guard = iteratees[2]; + if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { + iteratees.length = 1; + } + return baseSortByOrder(collection, baseFlatten(iteratees), []); +}); + +module.exports = sortByAll; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortByOrder.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortByOrder.js new file mode 100644 index 00000000000000..c704eeb61f201b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sortByOrder.js @@ -0,0 +1,55 @@ +var baseSortByOrder = require('../internal/baseSortByOrder'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * This method is like `_.sortByAll` except that it allows specifying the + * sort orders of the iteratees to sort by. A truthy value in `orders` will + * sort the corresponding property name in ascending order while a falsey + * value will sort it in descending order. + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {boolean[]} orders The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // sort by `user` in ascending order and by `age` in descending order + * _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ +function sortByOrder(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (guard && isIterateeCall(iteratees, orders, guard)) { + orders = null; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseSortByOrder(collection, iteratees, orders); +} + +module.exports = sortByOrder; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sum.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sum.js new file mode 100644 index 00000000000000..a2e93808ae8fee --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/sum.js @@ -0,0 +1 @@ +module.exports = require('../math/sum'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/where.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/where.js new file mode 100644 index 00000000000000..f603bf8ce497a6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/collection/where.js @@ -0,0 +1,37 @@ +var baseMatches = require('../internal/baseMatches'), + filter = require('./filter'); + +/** + * Performs a deep comparison between each element in `collection` and the + * source object, returning an array of all elements that have equivalent + * property values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {Array} Returns the new filtered array. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, + * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); + * // => ['barney'] + * + * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); + * // => ['fred'] + */ +function where(collection, source) { + return filter(collection, baseMatches(source)); +} + +module.exports = where; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/date.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/date.js new file mode 100644 index 00000000000000..195366e77762af --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/date.js @@ -0,0 +1,3 @@ +module.exports = { + 'now': require('./date/now') +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/date/now.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/date/now.js new file mode 100644 index 00000000000000..628225d2a0074d --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/date/now.js @@ -0,0 +1,24 @@ +var isNative = require('../lang/isNative'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeNow = isNative(nativeNow = Date.now) && nativeNow; + +/** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Date + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => logs the number of milliseconds it took for the deferred function to be invoked + */ +var now = nativeNow || function() { + return new Date().getTime(); +}; + +module.exports = now; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function.js new file mode 100644 index 00000000000000..2cacde1ee59e36 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function.js @@ -0,0 +1,27 @@ +module.exports = { + 'after': require('./function/after'), + 'ary': require('./function/ary'), + 'backflow': require('./function/backflow'), + 'before': require('./function/before'), + 'bind': require('./function/bind'), + 'bindAll': require('./function/bindAll'), + 'bindKey': require('./function/bindKey'), + 'compose': require('./function/compose'), + 'curry': require('./function/curry'), + 'curryRight': require('./function/curryRight'), + 'debounce': require('./function/debounce'), + 'defer': require('./function/defer'), + 'delay': require('./function/delay'), + 'flow': require('./function/flow'), + 'flowRight': require('./function/flowRight'), + 'memoize': require('./function/memoize'), + 'negate': require('./function/negate'), + 'once': require('./function/once'), + 'partial': require('./function/partial'), + 'partialRight': require('./function/partialRight'), + 'rearg': require('./function/rearg'), + 'restParam': require('./function/restParam'), + 'spread': require('./function/spread'), + 'throttle': require('./function/throttle'), + 'wrap': require('./function/wrap') +}; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/after.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/after.js new file mode 100644 index 00000000000000..e6a5de407a75df --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/after.js @@ -0,0 +1,48 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it is called `n` or more times. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'done saving!' after the two async saves have completed + */ +function after(n, func) { + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + n = nativeIsFinite(n = +n) ? n : 0; + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; +} + +module.exports = after; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/ary.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/ary.js new file mode 100644 index 00000000000000..1bcb6a720d3904 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/ary.js @@ -0,0 +1,34 @@ +var createWrapper = require('../internal/createWrapper'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** Used to compose bitmasks for wrapper metadata. */ +var ARY_FLAG = 128; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that accepts up to `n` arguments ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ +function ary(func, n, guard) { + if (guard && isIterateeCall(func, n, guard)) { + n = null; + } + n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); + return createWrapper(func, ARY_FLAG, null, null, null, null, n); +} + +module.exports = ary; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/backflow.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/backflow.js new file mode 100644 index 00000000000000..1954e942397b7f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/backflow.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/before.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/before.js new file mode 100644 index 00000000000000..4afd1e60af1298 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/before.js @@ -0,0 +1,42 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it is called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery('#add').on('click', _.before(5, addContactToList)); + * // => allows adding up to 4 contacts to the list + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = null; + } + return result; + }; +} + +module.exports = before; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bind.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bind.js new file mode 100644 index 00000000000000..0de126ae359412 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bind.js @@ -0,0 +1,56 @@ +var createWrapper = require('../internal/createWrapper'), + replaceHolders = require('../internal/replaceHolders'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var BIND_FLAG = 1, + PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and prepends any additional `_.bind` arguments to those provided to the + * bound function. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind` this method does not set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var greet = function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * }; + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // using placeholders + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ +var bind = restParam(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bind.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(func, bitmask, thisArg, partials, holders); +}); + +// Assign default placeholders. +bind.placeholder = {}; + +module.exports = bind; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bindAll.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bindAll.js new file mode 100644 index 00000000000000..a09e948524875c --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bindAll.js @@ -0,0 +1,50 @@ +var baseFlatten = require('../internal/baseFlatten'), + createWrapper = require('../internal/createWrapper'), + functions = require('../object/functions'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var BIND_FLAG = 1; + +/** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all enumerable function + * properties, own and inherited, of `object` are bound. + * + * **Note:** This method does not set the "length" property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} [methodNames] The object method names to bind, + * specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs' when the element is clicked + */ +var bindAll = restParam(function(object, methodNames) { + methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); + + var index = -1, + length = methodNames.length; + + while (++index < length) { + var key = methodNames[index]; + object[key] = createWrapper(object[key], BIND_FLAG, object); + } + return object; +}); + +module.exports = bindAll; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bindKey.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bindKey.js new file mode 100644 index 00000000000000..b787fe702276c6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/bindKey.js @@ -0,0 +1,66 @@ +var createWrapper = require('../internal/createWrapper'), + replaceHolders = require('../internal/replaceHolders'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes the method at `object[key]` and prepends + * any additional `_.bindKey` arguments to those provided to the bound function. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. + * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // using placeholders + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ +var bindKey = restParam(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bindKey.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(key, bitmask, object, partials, holders); +}); + +// Assign default placeholders. +bindKey.placeholder = {}; + +module.exports = bindKey; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/compose.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/compose.js new file mode 100644 index 00000000000000..1954e942397b7f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/compose.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/curry.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/curry.js new file mode 100644 index 00000000000000..b7db3fdad8ab6e --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/curry.js @@ -0,0 +1,51 @@ +var createCurry = require('../internal/createCurry'); + +/** Used to compose bitmasks for wrapper metadata. */ +var CURRY_FLAG = 8; + +/** + * Creates a function that accepts one or more arguments of `func` that when + * called either invokes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` may be specified + * if `func.length` is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ +var curry = createCurry(CURRY_FLAG); + +// Assign default placeholders. +curry.placeholder = {}; + +module.exports = curry; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/curryRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/curryRight.js new file mode 100644 index 00000000000000..11c540393b399f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/curryRight.js @@ -0,0 +1,48 @@ +var createCurry = require('../internal/createCurry'); + +/** Used to compose bitmasks for wrapper metadata. */ +var CURRY_RIGHT_FLAG = 16; + +/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ +var curryRight = createCurry(CURRY_RIGHT_FLAG); + +// Assign default placeholders. +curryRight.placeholder = {}; + +module.exports = curryRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/debounce.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/debounce.js new file mode 100644 index 00000000000000..5fdf7fce66f0f8 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/debounce.js @@ -0,0 +1,186 @@ +var isObject = require('../lang/isObject'), + now = require('../date/now'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that delays invoking `func` until after `wait` milliseconds + * have elapsed since the last time it was invoked. The created function comes + * with a `cancel` method to cancel delayed invocations. Provide an options + * object to indicate that `func` should be invoked on the leading and/or + * trailing edge of the `wait` timeout. Subsequent calls to the debounced + * function return the result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify invoking on the leading + * edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be + * delayed before it is invoked. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // invoke `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // ensure `batchLog` is invoked once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * jQuery(source).on('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * })); + * + * // cancel a debounced call + * var todoChanges = _.debounce(batchLog, 1000); + * Object.observe(models.todo, todoChanges); + * + * Object.observe(models, function(changes) { + * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { + * todoChanges.cancel(); + * } + * }, ['delete']); + * + * // ...at some point `models.todo` is changed + * models.todo.completed = true; + * + * // ...before 1 second has passed `models.todo` is deleted + * // which cancels the debounced `todoChanges` call + * delete models.todo; + */ +function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = wait < 0 ? 0 : (+wait || 0); + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); + trailing = 'trailing' in options ? options.trailing : trailing; + } + + function cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + } + + function delayed() { + var remaining = wait - (now() - stamp); + if (remaining <= 0 || remaining > wait) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + } + + function maxDelayed() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } + + function debounced() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0 || remaining > maxWait; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + } + debounced.cancel = cancel; + return debounced; +} + +module.exports = debounce; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/defer.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/defer.js new file mode 100644 index 00000000000000..369790ce64fcc6 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/defer.js @@ -0,0 +1,25 @@ +var baseDelay = require('../internal/baseDelay'), + restParam = require('./restParam'); + +/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ +var defer = restParam(function(func, args) { + return baseDelay(func, 1, args); +}); + +module.exports = defer; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/delay.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/delay.js new file mode 100644 index 00000000000000..955b059e7fa2cf --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/delay.js @@ -0,0 +1,26 @@ +var baseDelay = require('../internal/baseDelay'), + restParam = require('./restParam'); + +/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => logs 'later' after one second + */ +var delay = restParam(function(func, wait, args) { + return baseDelay(func, wait, args); +}); + +module.exports = delay; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/flow.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/flow.js new file mode 100644 index 00000000000000..a435a3d878ff48 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/flow.js @@ -0,0 +1,25 @@ +var createFlow = require('../internal/createFlow'); + +/** + * Creates a function that returns the result of invoking the provided + * functions with the `this` binding of the created function, where each + * successive invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow(_.add, square); + * addSquare(1, 2); + * // => 9 + */ +var flow = createFlow(); + +module.exports = flow; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/flowRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/flowRight.js new file mode 100644 index 00000000000000..23b9d76b58e8f5 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/flowRight.js @@ -0,0 +1,25 @@ +var createFlow = require('../internal/createFlow'); + +/** + * This method is like `_.flow` except that it creates a function that + * invokes the provided functions from right to left. + * + * @static + * @memberOf _ + * @alias backflow, compose + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight(square, _.add); + * addSquare(1, 2); + * // => 9 + */ +var flowRight = createFlow(true); + +module.exports = flowRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/memoize.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/memoize.js new file mode 100644 index 00000000000000..c9de9897cfb69a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/memoize.js @@ -0,0 +1,80 @@ +var MapCache = require('../internal/MapCache'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is coerced to a string and used as the + * cache key. The `func` is invoked with the `this` binding of the memoized + * function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object) + * method interface of `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var upperCase = _.memoize(function(string) { + * return string.toUpperCase(); + * }); + * + * upperCase('fred'); + * // => 'FRED' + * + * // modifying the result cache + * upperCase.cache.set('fred', 'BARNEY'); + * upperCase('fred'); + * // => 'BARNEY' + * + * // replacing `_.memoize.Cache` + * var object = { 'user': 'fred' }; + * var other = { 'user': 'barney' }; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'fred' } + * + * _.memoize.Cache = WeakMap; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'barney' } + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + cache = memoized.cache, + key = resolver ? resolver.apply(this, args) : args[0]; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + cache.set(key, result); + return result; + }; + memoized.cache = new memoize.Cache; + return memoized; +} + +// Assign cache to `_.memoize`. +memoize.Cache = MapCache; + +module.exports = memoize; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/negate.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/negate.js new file mode 100644 index 00000000000000..82479390ad7802 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/negate.js @@ -0,0 +1,32 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ +function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + return !predicate.apply(this, arguments); + }; +} + +module.exports = negate; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/once.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/once.js new file mode 100644 index 00000000000000..0b5bd853cb492b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/once.js @@ -0,0 +1,24 @@ +var before = require('./before'); + +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first call. The `func` is invoked + * with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` invokes `createApplication` once + */ +function once(func) { + return before(2, func); +} + +module.exports = once; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/partial.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/partial.js new file mode 100644 index 00000000000000..fb1d04fb6c5928 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/partial.js @@ -0,0 +1,43 @@ +var createPartial = require('../internal/createPartial'); + +/** Used to compose bitmasks for wrapper metadata. */ +var PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with `partial` arguments prepended + * to those provided to the new function. This method is like `_.bind` except + * it does **not** alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // using placeholders + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ +var partial = createPartial(PARTIAL_FLAG); + +// Assign default placeholders. +partial.placeholder = {}; + +module.exports = partial; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/partialRight.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/partialRight.js new file mode 100644 index 00000000000000..634e6a4c40cffa --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/partialRight.js @@ -0,0 +1,42 @@ +var createPartial = require('../internal/createPartial'); + +/** Used to compose bitmasks for wrapper metadata. */ +var PARTIAL_RIGHT_FLAG = 64; + +/** + * This method is like `_.partial` except that partially applied arguments + * are appended to those provided to the new function. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // using placeholders + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ +var partialRight = createPartial(PARTIAL_RIGHT_FLAG); + +// Assign default placeholders. +partialRight.placeholder = {}; + +module.exports = partialRight; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/rearg.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/rearg.js new file mode 100644 index 00000000000000..0a4bf8fa6d65ed --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/rearg.js @@ -0,0 +1,40 @@ +var baseFlatten = require('../internal/baseFlatten'), + createWrapper = require('../internal/createWrapper'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var REARG_FLAG = 256; + +/** + * Creates a function that invokes `func` with arguments arranged according + * to the specified indexes where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes, + * specified as individual indexes or arrays of indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, 2, 0, 1); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + * + * var map = _.rearg(_.map, [1, 0]); + * map(function(n) { + * return n * 3; + * }, [1, 2, 3]); + * // => [3, 6, 9] + */ +var rearg = restParam(function(func, indexes) { + return createWrapper(func, REARG_FLAG, null, null, null, baseFlatten(indexes)); +}); + +module.exports = rearg; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/restParam.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/restParam.js new file mode 100644 index 00000000000000..3a1c15707c748a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/restParam.js @@ -0,0 +1,58 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as an array. + * + * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.restParam(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function restParam(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + rest = Array(length); + + while (++index < length) { + rest[index] = args[start + index]; + } + switch (start) { + case 0: return func.call(this, rest); + case 1: return func.call(this, args[0], rest); + case 2: return func.call(this, args[0], args[1], rest); + } + var otherArgs = Array(start + 1); + index = -1; + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = rest; + return func.apply(this, otherArgs); + }; +} + +module.exports = restParam; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/spread.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/spread.js new file mode 100644 index 00000000000000..aad4b7147f2350 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/spread.js @@ -0,0 +1,44 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func` with the `this` binding of the created + * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). + * + * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to spread arguments over. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * // with a Promise + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ +function spread(func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function(array) { + return func.apply(this, array); + }; +} + +module.exports = spread; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/throttle.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/throttle.js new file mode 100644 index 00000000000000..7c30e646bffb48 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/throttle.js @@ -0,0 +1,72 @@ +var debounce = require('./debounce'), + isObject = require('../lang/isObject'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as an internal `_.debounce` options object by `_.throttle`. */ +var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false +}; + +/** + * Creates a function that only invokes `func` at most once per every `wait` + * milliseconds. The created function comes with a `cancel` method to cancel + * delayed invocations. Provide an options object to indicate that `func` + * should be invoked on the leading and/or trailing edge of the `wait` timeout. + * Subsequent calls to the throttled function return the result of the last + * `func` call. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify invoking on the leading + * edge of the timeout. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + * + * // cancel a trailing throttled call + * jQuery(window).on('popstate', throttled.cancel); + */ +function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = +wait; + debounceOptions.trailing = trailing; + return debounce(func, wait, debounceOptions); +} + +module.exports = throttle; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/wrap.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/wrap.js new file mode 100644 index 00000000000000..68b09af23862a4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/function/wrap.js @@ -0,0 +1,33 @@ +var createWrapper = require('../internal/createWrapper'), + identity = require('../utility/identity'); + +/** Used to compose bitmasks for wrapper metadata. */ +var PARTIAL_FLAG = 32; + +/** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Any additional arguments provided to the function are + * appended to those provided to the wrapper function. The wrapper is invoked + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ +function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []); +} + +module.exports = wrap; diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/index.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/index.js new file mode 100644 index 00000000000000..f52debbedde01f --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/index.js @@ -0,0 +1,12202 @@ +/** + * @license + * lodash 3.8.0 (Custom Build) + * Build: `lodash modern -d -o ./index.js` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '3.8.0'; + + /** Used to compose bitmasks for wrapper metadata. */ + var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + CURRY_BOUND_FLAG = 4, + CURRY_FLAG = 8, + CURRY_RIGHT_FLAG = 16, + PARTIAL_FLAG = 32, + PARTIAL_RIGHT_FLAG = 64, + ARY_FLAG = 128, + REARG_FLAG = 256; + + /** Used as default options for `_.trunc`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect when a function becomes hot. */ + var HOT_COUNT = 150, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_DROP_WHILE_FLAG = 0, + LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2; + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, + reUnescapedHtml = /[&<>"'`]/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; + + /** + * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). + * In addition to special characters the forward slash is escaped to allow for + * easier `eval` use and `Function` compilation. + */ + var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, + reHasRegExpChars = RegExp(reRegExpChars.source); + + /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ + var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** Used to match [ES template delimiters](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components). */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect hexadecimal string values. */ + var reHasHexPrefix = /^0[xX]/; + + /** Used to detect host constructors (Safari > 5). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ + var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to match words to create compound words. */ + var reWords = (function() { + var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', + lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; + + return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); + }()); + + /** Used to detect and test for whitespace. */ + var whitespace = ( + // Basic whitespace characters. + ' \t\x0b\f\xa0\ufeff' + + + // Line terminators. + '\n\r\u2028\u2029' + + + // Unicode category "Zs" space separators. + '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' + ); + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', + 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document', + 'isFinite', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + 'window' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dateTag] = typedArrayTags[errorTag] = + typedArrayTags[funcTag] = typedArrayTags[mapTag] = + typedArrayTags[numberTag] = typedArrayTags[objectTag] = + typedArrayTags[regexpTag] = typedArrayTags[setTag] = + typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = + cloneableTags[dateTag] = cloneableTags[float32Tag] = + cloneableTags[float64Tag] = cloneableTags[int8Tag] = + cloneableTags[int16Tag] = cloneableTags[int32Tag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[stringTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[mapTag] = cloneableTags[setTag] = + cloneableTags[weakMapTag] = false; + + /** Used as an internal `_.debounce` options object by `_.throttle`. */ + var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false + }; + + /** Used to map latin-1 supplementary letters to basic latin letters. */ + var deburredLetters = { + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'", + '`': '`' + }; + + /** Used to determine if values are of the language type `Object`. */ + var objectTypes = { + 'function': true, + 'object': true + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Detect free variable `exports`. */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; + + /** Detect free variable `self`. */ + var freeSelf = objectTypes[typeof self] && self && self.Object && self; + + /** Detect free variable `window`. */ + var freeWindow = objectTypes[typeof window] && window && window.Object && window; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** + * Used as a reference to the global object. + * + * The `this` value is used if it is the global object to avoid Greasemonkey's + * restricted `window` object, otherwise the `window` object is used. + */ + var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; + + /** + * The base implementation of `compareAscending` which compares values and + * sorts them in ascending order without guaranteeing a stable sort. + * + * @private + * @param {*} value The value to compare to `other`. + * @param {*} other The value to compare to `value`. + * @returns {number} Returns the sort order indicator for `value`. + */ + function baseCompareAscending(value, other) { + if (value !== other) { + var valIsReflexive = value === value, + othIsReflexive = other === other; + + if (value > other || !valIsReflexive || (value === undefined && othIsReflexive)) { + return 1; + } + if (value < other || !othIsReflexive || (other === undefined && valIsReflexive)) { + return -1; + } + } + return 0; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to search. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without support for binary searches. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return indexOfNaN(array, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isFunction` without support for environments + * with incorrect `typeof` results. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + */ + function baseIsFunction(value) { + // Avoid a Chakra JIT bug in compatibility modes of IE 11. + // See https://github.com/jashkenas/underscore/issues/1621 for more details. + return typeof value == 'function' || false; + } + + /** + * Converts `value` to a string if it is not one. An empty string is returned + * for `null` or `undefined` values. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); + } + + /** + * Used by `_.max` and `_.min` as the default callback for string values. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the code unit of the first character of the string. + */ + function charAtCallback(string) { + return string.charCodeAt(0); + } + + /** + * Used by `_.trim` and `_.trimLeft` to get the index of the first character + * of `string` that is not found in `chars`. + * + * @private + * @param {string} string The string to inspect. + * @param {string} chars The characters to find. + * @returns {number} Returns the index of the first character not found in `chars`. + */ + function charsLeftIndex(string, chars) { + var index = -1, + length = string.length; + + while (++index < length && chars.indexOf(string.charAt(index)) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimRight` to get the index of the last character + * of `string` that is not found in `chars`. + * + * @private + * @param {string} string The string to inspect. + * @param {string} chars The characters to find. + * @returns {number} Returns the index of the last character not found in `chars`. + */ + function charsRightIndex(string, chars) { + var index = string.length; + + while (index-- && chars.indexOf(string.charAt(index)) > -1) {} + return index; + } + + /** + * Used by `_.sortBy` to compare transformed elements of a collection and stable + * sort them in ascending order. + * + * @private + * @param {Object} object The object to compare to `other`. + * @param {Object} other The object to compare to `object`. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareAscending(object, other) { + return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); + } + + /** + * Used by `_.sortByOrder` to compare multiple properties of each element + * in a collection and stable sort them in the following order: + * + * If `orders` is unspecified, sort in ascending order for all properties. + * Otherwise, for each property, sort in ascending order if its corresponding value in + * orders is true, and descending order if false. + * + * @private + * @param {Object} object The object to compare to `other`. + * @param {Object} other The object to compare to `object`. + * @param {boolean[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = baseCompareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + return result * (orders[index] ? 1 : -1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://code.google.com/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + function deburrLetter(letter) { + return deburredLetters[letter]; + } + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(chr) { + return htmlEscapes[chr]; + } + + /** + * Used by `_.template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the index at which the first occurrence of `NaN` is found in `array`. + * + * @private + * @param {Array} array The array to search. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched `NaN`, else `-1`. + */ + function indexOfNaN(array, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 0 : -1); + + while ((fromRight ? index-- : ++index < length)) { + var other = array[index]; + if (other !== other) { + return index; + } + } + return -1; + } + + /** + * Checks if `value` is object-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + */ + function isObjectLike(value) { + return !!value && typeof value == 'object'; + } + + /** + * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a + * character code is whitespace. + * + * @private + * @param {number} charCode The character code to inspect. + * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. + */ + function isSpace(charCode) { + return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || + (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + if (array[index] === placeholder) { + array[index] = PLACEHOLDER; + result[++resIndex] = index; + } + } + return result; + } + + /** + * An implementation of `_.uniq` optimized for sorted arrays without support + * for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The function invoked per iteration. + * @returns {Array} Returns the new duplicate-value-free array. + */ + function sortedUniq(array, iteratee) { + var seen, + index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value, index, array) : value; + + if (!index || seen !== computed) { + seen = computed; + result[++resIndex] = value; + } + } + return result; + } + + /** + * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the first non-whitespace character. + */ + function trimmedLeftIndex(string) { + var index = -1, + length = string.length; + + while (++index < length && isSpace(string.charCodeAt(index))) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedRightIndex(string) { + var index = string.length; + + while (index-- && isSpace(string.charCodeAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(chr) { + return htmlUnescapes[chr]; + } + + /** + * Create a new pristine `lodash` function using the given `context` object. + * + * @static + * @memberOf _ + * @category Utility + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // using `context` to mock `Date#getTime` use in `_.now` + * var mock = _.runInContext({ + * 'Date': function() { + * return { 'getTime': getTimeMock }; + * } + * }); + * + * // or creating a suped-up `defer` in Node.js + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See https://es5.github.io/#x11.1.5 for more details. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for native method references. */ + var arrayProto = Array.prototype, + objectProto = Object.prototype, + stringProto = String.prototype; + + /** Used to detect DOM support. */ + var document = (document = context.window) && document.document; + + /** Used to resolve the decompiled source of functions. */ + var fnToString = Function.prototype.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** + * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) + * of values. + */ + var objToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = context._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + escapeRegExp(objToString) + .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Native method references. */ + var ArrayBuffer = isNative(ArrayBuffer = context.ArrayBuffer) && ArrayBuffer, + bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice, + ceil = Math.ceil, + clearTimeout = context.clearTimeout, + floor = Math.floor, + getOwnPropertySymbols = isNative(getOwnPropertySymbols = Object.getOwnPropertySymbols) && getOwnPropertySymbols, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + push = arrayProto.push, + preventExtensions = isNative(preventExtensions = Object.preventExtensions) && preventExtensions, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + Set = isNative(Set = context.Set) && Set, + setTimeout = context.setTimeout, + splice = arrayProto.splice, + Uint8Array = isNative(Uint8Array = context.Uint8Array) && Uint8Array, + WeakMap = isNative(WeakMap = context.WeakMap) && WeakMap; + + /** Used to clone array buffers. */ + var Float64Array = (function() { + // Safari 5 errors when using an array buffer to initialize a typed array + // where the array buffer's `byteLength` is not a multiple of the typed + // array's `BYTES_PER_ELEMENT`. + try { + var func = isNative(func = context.Float64Array) && func, + result = new func(new ArrayBuffer(10), 0, 1) && func; + } catch(e) {} + return result; + }()); + + /** Used as `baseAssign`. */ + var nativeAssign = (function() { + // Avoid `Object.assign` in Firefox 34-37 which have an early implementation + // with a now defunct try/catch behavior. See https://bugzilla.mozilla.org/show_bug.cgi?id=1103344 + // for more details. + // + // Use `Object.preventExtensions` on a plain object instead of simply using + // `Object('x')` because Chrome and IE fail to throw an error when attempting + // to assign values to readonly indexes of strings. + var func = preventExtensions && isNative(func = Object.assign) && func; + try { + if (func) { + var object = preventExtensions({ '1': 0 }); + object[0] = 1; + } + } catch(e) { + // Only attempt in strict mode. + try { func(object, 'xo'); } catch(e) {} + return !object[1] && func; + } + return false; + }()); + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsFinite = context.isFinite, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = isNative(nativeNow = Date.now) && nativeNow, + nativeNumIsFinite = isNative(nativeNumIsFinite = Number.isFinite) && nativeNumIsFinite, + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used as references for `-Infinity` and `Infinity`. */ + var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, + POSITIVE_INFINITY = Number.POSITIVE_INFINITY; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used as the size, in bytes, of each `Float64Array` element. */ + var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0; + + /** + * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) + * of an array-like value. + */ + var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** + * Creates a `lodash` object which wraps `value` to enable implicit chaining. + * Methods that operate on and return arrays, collections, and functions can + * be chained together. Methods that return a boolean or single value will + * automatically end the chain returning the unwrapped value. Explicit chaining + * may be enabled using `_.chain`. The execution of chained methods is lazy, + * that is, execution is deferred until `_#value` is implicitly or explicitly + * called. + * + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut + * fusion is an optimization that merges iteratees to avoid creating intermediate + * arrays and reduce the number of iteratee executions. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, + * `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, + * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, + * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, + * and `where` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, + * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, + * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`, + * `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`, + * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`, + * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, + * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, + * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, + * `merge`, `mixin`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, + * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`, + * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `sortByOrder`, `splice`, + * `spread`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, + * `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `valuesIn`, `where`, + * `without`, `wrap`, `xor`, `zip`, and `zipObject` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`, + * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, + * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`, + * `identity`, `includes`, `indexOf`, `inRange`, `isArguments`, `isArray`, + * `isBoolean`, `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite` + * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, + * `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, + * `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`, `noConflict`, + * `noop`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, + * `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, `startsWith`, + * `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, `unescape`, + * `uniqueId`, `value`, and `words` + * + * The wrapper method `sample` will return a wrapped value when `n` is provided, + * otherwise an unwrapped value is returned. + * + * @name _ + * @constructor + * @category Chain + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(total, n) { + * return total + n; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(n) { + * return n * n; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The function whose prototype all chaining wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable chaining for all wrapper methods. + * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. + */ + function LodashWrapper(value, chainAll, actions) { + this.__wrapped__ = value; + this.__actions__ = actions || []; + this.__chain__ = !!chainAll; + } + + /** + * An object environment feature flags. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + (function(x) { + var Ctor = function() { this.x = x; }, + args = arguments, + object = { '0': x, 'length': x }, + props = []; + + Ctor.prototype = { 'valueOf': x, 'y': x }; + for (var key in new Ctor) { props.push(key); } + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but Firefox OS certified apps, older Opera mobile browsers, and + * the PlayStation 3; forced `false` for Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = /\bthis\b/.test(function() { return this; }); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * Detect if the DOM is supported. + * + * @memberOf _.support + * @type boolean + */ + try { + support.dom = document.createDocumentFragment().nodeType === 11; + } catch(e) { + support.dom = false; + } + + /** + * Detect if `arguments` object indexes are non-enumerable. + * + * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object + * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat + * `arguments` object indexes as non-enumerable and fail `hasOwnProperty` + * checks for indexes that exceed the number of function parameters and + * whose associated argument values are `0`. + * + * @memberOf _.support + * @type boolean + */ + try { + support.nonEnumArgs = !propertyIsEnumerable.call(args, 1); + } catch(e) { + support.nonEnumArgs = true; + } + }(1, 0)); + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB). Change the following template settings to use + * alternative delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = null; + this.__dir__ = 1; + this.__dropCount__ = 0; + this.__filtered__ = false; + this.__iteratees__ = null; + this.__takeCount__ = POSITIVE_INFINITY; + this.__views__ = null; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var actions = this.__actions__, + iteratees = this.__iteratees__, + views = this.__views__, + result = new LazyWrapper(this.__wrapped__); + + result.__actions__ = actions ? arrayCopy(actions) : null; + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null; + result.__takeCount__ = this.__takeCount__; + result.__views__ = views ? arrayCopy(views) : null; + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(); + if (!isArray(array)) { + return baseWrapperValue(array, this.__actions__); + } + var dir = this.__dir__, + isRight = dir < 0, + view = getView(0, array.length, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + takeCount = nativeMin(length, this.__takeCount__), + iteratees = this.__iteratees__, + iterLength = iteratees ? iteratees.length : 0, + resIndex = 0, + result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type; + + if (type == LAZY_DROP_WHILE_FLAG) { + if (data.done && (isRight ? (index > data.index) : (index < data.index))) { + data.count = 0; + data.done = false; + } + data.index = index; + if (!data.done) { + var limit = data.limit; + if (!(data.done = limit > -1 ? (data.count++ >= limit) : !iteratee(value))) { + continue outer; + } + } + } else { + var computed = iteratee(value); + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + } + result[resIndex++] = value; + } + return result; + } + + /** + * Creates a cache object to store key/value pairs. + * + * @private + * @static + * @name Cache + * @memberOf _.memoize + */ + function MapCache() { + this.__data__ = {}; + } + + /** + * Removes `key` and its value from the cache. + * + * @private + * @name delete + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. + */ + function mapDelete(key) { + return this.has(key) && delete this.__data__[key]; + } + + /** + * Gets the cached value for `key`. + * + * @private + * @name get + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to get. + * @returns {*} Returns the cached value. + */ + function mapGet(key) { + return key == '__proto__' ? undefined : this.__data__[key]; + } + + /** + * Checks if a cached value for `key` exists. + * + * @private + * @name has + * @memberOf _.memoize.Cache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapHas(key) { + return key != '__proto__' && hasOwnProperty.call(this.__data__, key); + } + + /** + * Sets `value` to `key` of the cache. + * + * @private + * @name set + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to cache. + * @param {*} value The value to cache. + * @returns {Object} Returns the cache object. + */ + function mapSet(key, value) { + if (key != '__proto__') { + this.__data__[key] = value; + } + return this; + } + + /** + * + * Creates a cache object to store unique values. + * + * @private + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var length = values ? values.length : 0; + + this.data = { 'hash': nativeCreate(null), 'set': new Set }; + while (length--) { + this.push(values[length]); + } + } + + /** + * Checks if `value` is in `cache` mimicking the return signature of + * `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache to search. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var data = cache.data, + result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; + + return result ? 0 : -1; + } + + /** + * Adds `value` to the cache. + * + * @private + * @name push + * @memberOf SetCache + * @param {*} value The value to cache. + */ + function cachePush(value) { + var data = this.data; + if (typeof value == 'string' || isObject(value)) { + data.set.add(value); + } else { + data.hash[value] = true; + } + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function arrayCopy(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * A specialized version of `_.forEach` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * A specialized version of `_.map` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * A specialized version of `_.max` for arrays without support for iteratees. + * + * @private + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + */ + function arrayMax(array) { + var index = -1, + length = array.length, + result = NEGATIVE_INFINITY; + + while (++index < length) { + var value = array[index]; + if (value > result) { + result = value; + } + } + return result; + } + + /** + * A specialized version of `_.min` for arrays without support for iteratees. + * + * @private + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + */ + function arrayMin(array) { + var index = -1, + length = array.length, + result = POSITIVE_INFINITY; + + while (++index < length) { + var value = array[index]; + if (value < result) { + result = value; + } + } + return result; + } + + /** + * A specialized version of `_.reduce` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initFromArray] Specify using the first element of `array` + * as the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initFromArray) { + var index = -1, + length = array.length; + + if (initFromArray && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initFromArray] Specify using the last element of `array` + * as the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initFromArray) { + var length = array.length; + if (initFromArray && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.sum` for arrays without support for iteratees. + * + * @private + * @param {Array} array The array to iterate over. + * @returns {number} Returns the sum. + */ + function arraySum(array) { + var length = array.length, + result = 0; + + while (length--) { + result += +array[length] || 0; + } + return result; + } + + /** + * Used by `_.defaults` to customize its `_.assign` use. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @returns {*} Returns the value to assign to the destination object. + */ + function assignDefaults(objectValue, sourceValue) { + return objectValue === undefined ? sourceValue : objectValue; + } + + /** + * Used by `_.template` to customize its `_.assign` use. + * + * **Note:** This function is like `assignDefaults` except that it ignores + * inherited property values when checking if a property is `undefined`. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @param {string} key The key associated with the object and source values. + * @param {Object} object The destination object. + * @returns {*} Returns the value to assign to the destination object. + */ + function assignOwnDefaults(objectValue, sourceValue, key, object) { + return (objectValue === undefined || !hasOwnProperty.call(object, key)) + ? sourceValue + : objectValue; + } + + /** + * A specialized version of `_.assign` for customizing assigned values without + * support for argument juggling, multiple sources, and `this` binding `customizer` + * functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + */ + function assignWith(object, source, customizer) { + var props = keys(source); + push.apply(props, getSymbols(source)); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index], + value = object[key], + result = customizer(value, source[key], key, object, source); + + if ((result === result ? (result !== value) : (value === value)) || + (value === undefined && !(key in object))) { + object[key] = result; + } + } + return object; + } + + /** + * The base implementation of `_.assign` without support for argument juggling, + * multiple sources, and `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + var baseAssign = nativeAssign || function(object, source) { + return source == null + ? object + : baseCopy(source, getSymbols(source), baseCopy(source, keys(source), object)); + }; + + /** + * The base implementation of `_.at` without support for string collections + * and individual key arguments. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {number[]|string[]} props The property names or indexes of elements to pick. + * @returns {Array} Returns the new array of picked elements. + */ + function baseAt(collection, props) { + var index = -1, + isNil = collection == null, + isArr = !isNil && isArrayLike(collection), + length = isArr && collection.length, + propsLength = props.length, + result = Array(propsLength); + + while(++index < propsLength) { + var key = props[index]; + if (isArr) { + result[index] = isIndex(key, length) ? collection[key] : undefined; + } else { + result[index] = isNil ? undefined : collection[key]; + } + } + return result; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property names to copy. + * @param {Object} [object={}] The object to copy properties to. + * @returns {Object} Returns `object`. + */ + function baseCopy(source, props, object) { + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + object[key] = source[key]; + } + return object; + } + + /** + * The base implementation of `_.callback` which supports specifying the + * number of arguments to provide to `func`. + * + * @private + * @param {*} [func=_.identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function baseCallback(func, thisArg, argCount) { + var type = typeof func; + if (type == 'function') { + return thisArg === undefined + ? func + : bindCallback(func, thisArg, argCount); + } + if (func == null) { + return identity; + } + if (type == 'object') { + return baseMatches(func); + } + return thisArg === undefined + ? property(func) + : baseMatchesProperty(func, thisArg); + } + + /** + * The base implementation of `_.clone` without support for argument juggling + * and `this` binding `customizer` functions. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The object `value` belongs to. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { + var result; + if (customizer) { + result = object ? customizer(value, key, object) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return arrayCopy(value, result); + } + } else { + var tag = objToString.call(value), + isFunc = tag == funcTag; + + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return baseAssign(result, value); + } + } else { + return cloneableTags[tag] + ? initCloneByTag(value, tag, isDeep) + : (object ? value : {}); + } + } + // Check for circular references and return corresponding clone. + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + // Add the source value to the stack of traversed objects and associate it with its clone. + stackA.push(value); + stackB.push(result); + + // Recursively populate clone (susceptible to call stack limits). + (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { + result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); + }); + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function Object() {} + return function(prototype) { + if (isObject(prototype)) { + Object.prototype = prototype; + var result = new Object; + Object.prototype = null; + } + return result || context.Object(); + }; + }()); + + /** + * The base implementation of `_.delay` and `_.defer` which accepts an index + * of where to slice the arguments to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Object} args The arguments provide to `func`. + * @returns {number} Returns the timer id. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of `_.difference` which accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values) { + var length = array ? array.length : 0, + result = []; + + if (!length) { + return result; + } + var index = -1, + indexOf = getIndexOf(), + isCommon = indexOf == baseIndexOf, + cache = (isCommon && values.length >= 200) ? createCache(values) : null, + valuesLength = values.length; + + if (cache) { + indexOf = cacheIndexOf; + isCommon = false; + values = cache; + } + outer: + while (++index < length) { + var value = array[index]; + + if (isCommon && value === value) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === value) { + continue outer; + } + } + result.push(value); + } + else if (indexOf(values, value, 0) < 0) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object|string} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object|string} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = start == null ? 0 : (+start || 0); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : (+end || 0); + if (end < 0) { + end += length; + } + length = start > end ? 0 : (end >>> 0); + start >>>= 0; + + while (start < length) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, + * without support for callback shorthands and `this` binding, which iterates + * over `collection` using the provided `eachFunc`. + * + * @private + * @param {Array|Object|string} collection The collection to search. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @param {boolean} [retKey] Specify returning the key of the found element + * instead of the element itself. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFind(collection, predicate, eachFunc, retKey) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = retKey ? key : value; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with added support for restricting + * flattening and specifying the start index. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, isDeep, isStrict) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (isObjectLike(value) && isArrayLike(value) && + (isStrict || isArray(value) || isArguments(value))) { + if (isDeep) { + // Recursively flatten arrays (susceptible to call stack limits). + value = baseFlatten(value, isDeep, isStrict); + } + var valIndex = -1, + valLength = value.length; + + while (++valIndex < valLength) { + result[++resIndex] = value[valIndex]; + } + } else if (!isStrict) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForIn` and `baseForOwn` which iterates + * over `object` properties returned by `keysFunc` invoking `iteratee` for + * each property. Iteratee functions may exit iteration early by explicitly + * returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forIn` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForIn(object, iteratee) { + return baseFor(object, iteratee, keysIn); + } + + /** + * The base implementation of `_.forOwn` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from those provided. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the new array of filtered property names. + */ + function baseFunctions(object, props) { + var index = -1, + length = props.length, + resIndex = -1, + result = []; + + while (++index < length) { + var key = props[index]; + if (isFunction(object[key])) { + result[++resIndex] = key; + } + } + return result; + } + + /** + * The base implementation of `get` without support for string paths + * and default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path of the property to get. + * @param {string} [pathKey] The key representation of path. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path, pathKey) { + if (object == null) { + return; + } + if (pathKey !== undefined && pathKey in toObject(object)) { + path = [pathKey]; + } + var index = -1, + length = path.length; + + while (object != null && ++index < length) { + object = object[path[index]]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `_.isEqual` without support for `this` binding + * `customizer` functions. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparing values. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { + // Exit early for identical values. + if (value === other) { + return true; + } + var valType = typeof value, + othType = typeof other; + + // Exit early for unlike primitive values. + if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') || + value == null || other == null) { + // Return `false` unless both values are `NaN`. + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing objects. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `value` objects. + * @param {Array} [stackB=[]] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = objToString.call(object); + if (objTag == argsTag) { + objTag = objectTag; + } else if (objTag != objectTag) { + objIsArr = isTypedArray(object); + } + } + if (!othIsArr) { + othTag = objToString.call(other); + if (othTag == argsTag) { + othTag = objectTag; + } else if (othTag != objectTag) { + othIsArr = isTypedArray(other); + } + } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && !(objIsArr || objIsObj)) { + return equalByTag(object, other, objTag); + } + if (!isLoose) { + var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (valWrapped || othWrapped) { + return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); + } + } + if (!isSameTag) { + return false; + } + // Assume cyclic values are equal. + // For more information on detecting circular references see https://es5.github.io/#JO. + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == object) { + return stackB[length] == other; + } + } + // Add `object` and `other` to the stack of traversed objects. + stackA.push(object); + stackB.push(other); + + var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); + + stackA.pop(); + stackB.pop(); + + return result; + } + + /** + * The base implementation of `_.isMatch` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The source property names to match. + * @param {Array} values The source values to match. + * @param {Array} strictCompareFlags Strict comparison flags for source values. + * @param {Function} [customizer] The function to customize comparing objects. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, props, values, strictCompareFlags, customizer) { + var index = -1, + length = props.length, + noCustomizer = !customizer; + + while (++index < length) { + if ((noCustomizer && strictCompareFlags[index]) + ? values[index] !== object[props[index]] + : !(props[index] in object) + ) { + return false; + } + } + index = -1; + while (++index < length) { + var key = props[index], + objValue = object[key], + srcValue = values[index]; + + if (noCustomizer && strictCompareFlags[index]) { + var result = objValue !== undefined || (key in object); + } else { + result = customizer ? customizer(objValue, srcValue, key) : undefined; + if (result === undefined) { + result = baseIsEqual(srcValue, objValue, customizer, true); + } + } + if (!result) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.map` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which does not clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new function. + */ + function baseMatches(source) { + var props = keys(source), + length = props.length; + + if (!length) { + return constant(true); + } + if (length == 1) { + var key = props[0], + value = source[key]; + + if (isStrictComparable(value)) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === value && (value !== undefined || (key in toObject(object))); + }; + } + } + var values = Array(length), + strictCompareFlags = Array(length); + + while (length--) { + value = source[props[length]]; + values[length] = value; + strictCompareFlags[length] = isStrictComparable(value); + } + return function(object) { + return object != null && baseIsMatch(toObject(object), props, values, strictCompareFlags); + }; + } + + /** + * The base implementation of `_.matchesProperty` which does not which does + * not clone `value`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} value The value to compare. + * @returns {Function} Returns the new function. + */ + function baseMatchesProperty(path, value) { + var isArr = isArray(path), + isCommon = isKey(path) && isStrictComparable(value), + pathKey = (path + ''); + + path = toPath(path); + return function(object) { + if (object == null) { + return false; + } + var key = pathKey; + object = toObject(object); + if ((isArr || !isCommon) && !(key in object)) { + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + if (object == null) { + return false; + } + key = last(path); + object = toObject(object); + } + return object[key] === value + ? (value !== undefined || (key in object)) + : baseIsEqual(value, object[key], null, true); + }; + } + + /** + * The base implementation of `_.merge` without support for argument juggling, + * multiple sources, and `this` binding `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [customizer] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + * @returns {Object} Returns `object`. + */ + function baseMerge(object, source, customizer, stackA, stackB) { + if (!isObject(object)) { + return object; + } + var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)); + if (!isSrcArr) { + var props = keys(source); + push.apply(props, getSymbols(source)); + } + arrayEach(props || source, function(srcValue, key) { + if (props) { + key = srcValue; + srcValue = source[key]; + } + if (isObjectLike(srcValue)) { + stackA || (stackA = []); + stackB || (stackB = []); + baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); + } + else { + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = result === undefined; + + if (isCommon) { + result = srcValue; + } + if ((isSrcArr || result !== undefined) && + (isCommon || (result === result ? (result !== value) : (value === value)))) { + object[key] = result; + } + } + }); + return object; + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { + var length = stackA.length, + srcValue = source[key]; + + while (length--) { + if (stackA[length] == srcValue) { + object[key] = stackB[length]; + return; + } + } + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = result === undefined; + + if (isCommon) { + result = srcValue; + if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { + result = isArray(value) + ? value + : (isArrayLike(value) ? arrayCopy(value) : []); + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + result = isArguments(value) + ? toPlainObject(value) + : (isPlainObject(value) ? value : {}); + } + else { + isCommon = false; + } + } + // Add the source value to the stack of traversed objects and associate + // it with its merged value. + stackA.push(srcValue); + stackB.push(result); + + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); + } else if (result === result ? (result !== value) : (value === value)) { + object[key] = result; + } + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new function. + */ + function basePropertyDeep(path) { + var pathKey = (path + ''); + path = toPath(path); + return function(object) { + return baseGet(object, path, pathKey); + }; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * index arguments and capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0; + while (length--) { + var index = parseFloat(indexes[length]); + if (index != previous && isIndex(index)) { + var previous = index; + splice.call(array, index, 1); + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for argument juggling + * and returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns the random number. + */ + function baseRandom(min, max) { + return min + floor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight` without support + * for callback shorthands and `this` binding, which iterates over `collection` + * using the provided `eachFunc`. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initFromCollection Specify using the first or last element + * of `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initFromCollection + ? (initFromCollection = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `setData` without support for hot loop detection. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + start = start == null ? 0 : (+start || 0); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : (+end || 0); + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define + * the sort order of `array` and replaces criteria objects with their + * corresponding values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sortByOrder` without param guards. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {boolean[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseSortByOrder(collection, iteratees, orders) { + var callback = getCallback(), + index = -1; + + iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); }); + + var result = baseMap(collection, function(value) { + var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.sum` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(collection, iteratee) { + var result = 0; + baseEach(collection, function(value, index, collection) { + result += +iteratee(value, index, collection) || 0; + }); + return result; + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The function invoked per iteration. + * @returns {Array} Returns the new duplicate-value-free array. + */ + function baseUniq(array, iteratee) { + var index = -1, + indexOf = getIndexOf(), + length = array.length, + isCommon = indexOf == baseIndexOf, + isLarge = isCommon && length >= 200, + seen = isLarge ? createCache() : null, + result = []; + + if (seen) { + indexOf = cacheIndexOf; + isCommon = false; + } else { + isLarge = false; + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value, index, array) : value; + + if (isCommon && value === value) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (indexOf(seen, computed, 0) < 0) { + if (iteratee || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + var index = -1, + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /** + * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`, + * and `_.takeWhile` without support for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to peform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + var index = -1, + length = actions.length; + + while (++index < length) { + var args = [result], + action = actions[index]; + + push.apply(args, action.args); + result = action.func.apply(action.thisArg, args); + } + return result; + } + + /** + * Performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function binaryIndex(array, value, retHighest) { + var low = 0, + high = array ? array.length : low; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (retHighest ? (computed <= value) : (computed < value)) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return binaryIndexBy(array, value, identity, retHighest); + } + + /** + * This function is like `binaryIndex` except that it invokes `iteratee` for + * `value` and each element of `array` to compute their sort ranking. The + * iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The function invoked per iteration. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function binaryIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array ? array.length : 0, + valIsNaN = value !== value, + valIsUndef = value === undefined; + + while (low < high) { + var mid = floor((low + high) / 2), + computed = iteratee(array[mid]), + isReflexive = computed === computed; + + if (valIsNaN) { + var setLow = isReflexive || retHighest; + } else if (valIsUndef) { + setLow = isReflexive && (retHighest || computed !== undefined); + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * A specialized version of `baseCallback` which only supports `this` binding + * and specifying the number of arguments to provide to `func`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function bindCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + if (thisArg === undefined) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + case 5: return function(value, other, key, object, source) { + return func.call(thisArg, value, other, key, object, source); + }; + } + return function() { + return func.apply(thisArg, arguments); + }; + } + + /** + * Creates a clone of the given array buffer. + * + * @private + * @param {ArrayBuffer} buffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function bufferClone(buffer) { + return bufferSlice.call(buffer, 0); + } + if (!bufferSlice) { + // PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`. + bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) { + var byteLength = buffer.byteLength, + floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0, + offset = floatLength * FLOAT64_BYTES_PER_ELEMENT, + result = new ArrayBuffer(byteLength); + + if (floatLength) { + var view = new Float64Array(result, 0, floatLength); + view.set(new Float64Array(buffer, 0, floatLength)); + } + if (byteLength != offset) { + view = new Uint8Array(result, offset); + view.set(new Uint8Array(buffer, offset)); + } + return result; + }; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array|Object} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders) { + var holdersLength = holders.length, + argsIndex = -1, + argsLength = nativeMax(args.length - holdersLength, 0), + leftIndex = -1, + leftLength = partials.length, + result = Array(argsLength + leftLength); + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + while (argsLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array|Object} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders) { + var holdersIndex = -1, + holdersLength = holders.length, + argsIndex = -1, + argsLength = nativeMax(args.length - holdersLength, 0), + rightIndex = -1, + rightLength = partials.length, + result = Array(argsLength + rightLength); + + while (++argsIndex < argsLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + return result; + } + + /** + * Creates a function that aggregates a collection, creating an accumulator + * object composed from the results of running each element in the collection + * through an iteratee. + * + * **Note:** This function is used to create `_.countBy`, `_.groupBy`, `_.indexBy`, + * and `_.partition`. + * + * @private + * @param {Function} setter The function to set keys and values of the accumulator object. + * @param {Function} [initializer] The function to initialize the accumulator object. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee, thisArg) { + var result = initializer ? initializer() : {}; + iteratee = getCallback(iteratee, thisArg, 3); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + setter(result, value, iteratee(value, index, collection), collection); + } + } else { + baseEach(collection, function(value, key, collection) { + setter(result, value, iteratee(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a function that assigns properties of source object(s) to a given + * destination object. + * + * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return restParam(function(object, sources) { + var index = -1, + length = object == null ? 0 : sources.length, + customizer = length > 2 && sources[length - 2], + guard = length > 2 && sources[2], + thisArg = length > 1 && sources[length - 1]; + + if (typeof customizer == 'function') { + customizer = bindCallback(customizer, thisArg, 5); + length -= 2; + } else { + customizer = typeof thisArg == 'function' ? thisArg : null; + length -= (customizer ? 1 : 0); + } + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? null : customizer; + length = 1; + } + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + var length = collection ? getLength(collection) : 0; + if (!isLength(length)) { + return eachFunc(collection, iteratee); + } + var index = fromRight ? length : -1, + iterable = toObject(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for `_.forIn` or `_.forInRight`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var iterable = toObject(object), + props = keysFunc(object), + length = props.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length)) { + var key = props[index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` and invokes it with the `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new bound function. + */ + function createBindWrapper(func, thisArg) { + var Ctor = createCtorWrapper(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(thisArg, arguments); + } + return wrapper; + } + + /** + * Creates a `Set` cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [values] The values to cache. + * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. + */ + var createCache = !(nativeCreate && Set) ? constant(null) : function(values) { + return new SetCache(values); + }; + + /** + * Creates a function that produces compound words out of the words in a + * given string. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + var index = -1, + array = words(deburr(string)), + length = array.length, + result = ''; + + while (++index < length) { + result = callback(result, array[index], index); + } + return result; + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtorWrapper(Ctor) { + return function() { + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, arguments); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a `_.curry` or `_.curryRight` function. + * + * @private + * @param {boolean} flag The curry bit flag. + * @returns {Function} Returns the new curry function. + */ + function createCurry(flag) { + function curryFunc(func, arity, guard) { + if (guard && isIterateeCall(func, arity, guard)) { + arity = null; + } + var result = createWrapper(func, flag, null, null, null, null, null, arity); + result.placeholder = curryFunc.placeholder; + return result; + } + return curryFunc; + } + + /** + * Creates a `_.max` or `_.min` function. + * + * @private + * @param {Function} arrayFunc The function to get the extremum value from an array. + * @param {boolean} [isMin] Specify returning the minimum, instead of the maximum, + * extremum value. + * @returns {Function} Returns the new extremum function. + */ + function createExtremum(arrayFunc, isMin) { + return function(collection, iteratee, thisArg) { + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = null; + } + var func = getCallback(), + noIteratee = iteratee == null; + + if (!(func === baseCallback && noIteratee)) { + noIteratee = false; + iteratee = func(iteratee, thisArg, 3); + } + if (noIteratee) { + var isArr = isArray(collection); + if (!isArr && isString(collection)) { + iteratee = charAtCallback; + } else { + return arrayFunc(isArr ? collection : toIterable(collection)); + } + } + return extremumBy(collection, iteratee, isMin); + }; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new find function. + */ + function createFind(eachFunc, fromRight) { + return function(collection, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + if (isArray(collection)) { + var index = baseFindIndex(collection, predicate, fromRight); + return index > -1 ? collection[index] : undefined; + } + return baseFind(collection, predicate, eachFunc); + }; + } + + /** + * Creates a `_.findIndex` or `_.findLastIndex` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new find function. + */ + function createFindIndex(fromRight) { + return function(array, predicate, thisArg) { + if (!(array && array.length)) { + return -1; + } + predicate = getCallback(predicate, thisArg, 3); + return baseFindIndex(array, predicate, fromRight); + }; + } + + /** + * Creates a `_.findKey` or `_.findLastKey` function. + * + * @private + * @param {Function} objectFunc The function to iterate over an object. + * @returns {Function} Returns the new find function. + */ + function createFindKey(objectFunc) { + return function(object, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + return baseFind(object, predicate, objectFunc, true); + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return function() { + var length = arguments.length; + if (!length) { + return function() { return arguments[0]; }; + } + var wrapper, + index = fromRight ? length : -1, + leftIndex = 0, + funcs = Array(length); + + while ((fromRight ? index-- : ++index < length)) { + var func = funcs[leftIndex++] = arguments[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var funcName = wrapper ? '' : getFuncName(func); + wrapper = funcName == 'wrapper' ? new LodashWrapper([]) : wrapper; + } + index = wrapper ? -1 : length; + while (++index < length) { + func = funcs[index]; + funcName = getFuncName(func); + + var data = funcName == 'wrapper' ? getData(func) : null; + if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); + } + } + return function() { + var args = arguments; + if (wrapper && args.length == 1 && isArray(args[0])) { + return wrapper.plant(args[0]).value(); + } + var index = 0, + result = funcs[index].apply(this, args); + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }; + } + + /** + * Creates a function for `_.forEach` or `_.forEachRight`. + * + * @private + * @param {Function} arrayFunc The function to iterate over an array. + * @param {Function} eachFunc The function to iterate over a collection. + * @returns {Function} Returns the new each function. + */ + function createForEach(arrayFunc, eachFunc) { + return function(collection, iteratee, thisArg) { + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) + ? arrayFunc(collection, iteratee) + : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); + }; + } + + /** + * Creates a function for `_.forIn` or `_.forInRight`. + * + * @private + * @param {Function} objectFunc The function to iterate over an object. + * @returns {Function} Returns the new each function. + */ + function createForIn(objectFunc) { + return function(object, iteratee, thisArg) { + if (typeof iteratee != 'function' || thisArg !== undefined) { + iteratee = bindCallback(iteratee, thisArg, 3); + } + return objectFunc(object, iteratee, keysIn); + }; + } + + /** + * Creates a function for `_.forOwn` or `_.forOwnRight`. + * + * @private + * @param {Function} objectFunc The function to iterate over an object. + * @returns {Function} Returns the new each function. + */ + function createForOwn(objectFunc) { + return function(object, iteratee, thisArg) { + if (typeof iteratee != 'function' || thisArg !== undefined) { + iteratee = bindCallback(iteratee, thisArg, 3); + } + return objectFunc(object, iteratee); + }; + } + + /** + * Creates a function for `_.mapKeys` or `_.mapValues`. + * + * @private + * @param {boolean} [isMapKeys] Specify mapping keys instead of values. + * @returns {Function} Returns the new map function. + */ + function createObjectMapper(isMapKeys) { + return function(object, iteratee, thisArg) { + var result = {}; + iteratee = getCallback(iteratee, thisArg, 3); + + baseForOwn(object, function(value, key, object) { + var mapped = iteratee(value, key, object); + key = isMapKeys ? mapped : key; + value = isMapKeys ? value : mapped; + result[key] = value; + }); + return result; + }; + } + + /** + * Creates a function for `_.padLeft` or `_.padRight`. + * + * @private + * @param {boolean} [fromRight] Specify padding from the right. + * @returns {Function} Returns the new pad function. + */ + function createPadDir(fromRight) { + return function(string, length, chars) { + string = baseToString(string); + return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string); + }; + } + + /** + * Creates a `_.partial` or `_.partialRight` function. + * + * @private + * @param {boolean} flag The partial bit flag. + * @returns {Function} Returns the new partial function. + */ + function createPartial(flag) { + var partialFunc = restParam(function(func, partials) { + var holders = replaceHolders(partials, partialFunc.placeholder); + return createWrapper(func, flag, null, partials, holders); + }); + return partialFunc; + } + + /** + * Creates a function for `_.reduce` or `_.reduceRight`. + * + * @private + * @param {Function} arrayFunc The function to iterate over an array. + * @param {Function} eachFunc The function to iterate over a collection. + * @returns {Function} Returns the new each function. + */ + function createReduce(arrayFunc, eachFunc) { + return function(collection, iteratee, accumulator, thisArg) { + var initFromArray = arguments.length < 3; + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) + ? arrayFunc(collection, iteratee, accumulator, initFromArray) + : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); + }; + } + + /** + * Creates a function that wraps `func` and invokes it with optional `this` + * binding of, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & ARY_FLAG, + isBind = bitmask & BIND_FLAG, + isBindKey = bitmask & BIND_KEY_FLAG, + isCurry = bitmask & CURRY_FLAG, + isCurryBound = bitmask & CURRY_BOUND_FLAG, + isCurryRight = bitmask & CURRY_RIGHT_FLAG; + + var Ctor = !isBindKey && createCtorWrapper(func), + key = func; + + function wrapper() { + // Avoid `arguments` object use disqualifying optimizations by + // converting it to an array before providing it to other functions. + var length = arguments.length, + index = length, + args = Array(length); + + while (index--) { + args[index] = arguments[index]; + } + if (partials) { + args = composeArgs(args, partials, holders); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight); + } + if (isCurry || isCurryRight) { + var placeholder = wrapper.placeholder, + argsHolders = replaceHolders(args, placeholder); + + length -= argsHolders.length; + if (length < arity) { + var newArgPos = argPos ? arrayCopy(argPos) : null, + newArity = nativeMax(arity - length, 0), + newsHolders = isCurry ? argsHolders : null, + newHoldersRight = isCurry ? null : argsHolders, + newPartials = isCurry ? args : null, + newPartialsRight = isCurry ? null : args; + + bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); + + if (!isCurryBound) { + bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); + } + var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity], + result = createHybridWrapper.apply(undefined, newData); + + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return result; + } + } + var thisBinding = isBind ? thisArg : this; + if (isBindKey) { + func = thisBinding[key]; + } + if (argPos) { + args = reorder(args, argPos); + } + if (isAry && ary < args.length) { + args.length = ary; + } + var fn = (this && this !== root && this instanceof wrapper) ? (Ctor || createCtorWrapper(func)) : func; + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates the padding required for `string` based on the given `length`. + * The `chars` string is truncated if the number of characters exceeds `length`. + * + * @private + * @param {string} string The string to create padding for. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the pad for `string`. + */ + function createPadding(string, length, chars) { + var strLength = string.length; + length = +length; + + if (strLength >= length || !nativeIsFinite(length)) { + return ''; + } + var padLength = length - strLength; + chars = chars == null ? ' ' : (chars + ''); + return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength); + } + + /** + * Creates a function that wraps `func` and invokes it with the optional `this` + * binding of `thisArg` and the `partials` prepended to those provided to + * the wrapper. + * + * @private + * @param {Function} func The function to partially apply arguments to. + * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to the new function. + * @returns {Function} Returns the new bound function. + */ + function createPartialWrapper(func, bitmask, thisArg, partials) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtorWrapper(func); + + function wrapper() { + // Avoid `arguments` object use disqualifying optimizations by + // converting it to an array before providing it `func`. + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(argsLength + leftLength); + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.sortedIndex` or `_.sortedLastIndex` function. + * + * @private + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {Function} Returns the new index function. + */ + function createSortedIndex(retHighest) { + return function(array, value, iteratee, thisArg) { + var func = getCallback(iteratee); + return (func === baseCallback && iteratee == null) + ? binaryIndex(array, value, retHighest) + : binaryIndexBy(array, value, func(iteratee, thisArg, 1), retHighest); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of flags. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); + partials = holders = null; + } + length -= (holders ? holders.length : 0); + if (bitmask & PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = null; + } + var data = isBindKey ? null : getData(func), + newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; + + if (data) { + mergeData(newData, data); + bitmask = newData[1]; + arity = newData[9]; + } + newData[9] = arity == null + ? (isBindKey ? 0 : func.length) + : (nativeMax(arity - length, 0) || 0); + + if (bitmask == BIND_FLAG) { + var result = createBindWrapper(newData[0], newData[2]); + } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { + result = createPartialWrapper.apply(undefined, newData); + } else { + result = createHybridWrapper.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setter(result, newData); + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing arrays. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { + var index = -1, + arrLength = array.length, + othLength = other.length, + result = true; + + if (arrLength != othLength && !(isLoose && othLength > arrLength)) { + return false; + } + // Deep compare the contents, ignoring non-numeric properties. + while (result && ++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + result = undefined; + if (customizer) { + result = isLoose + ? customizer(othValue, arrValue, index) + : customizer(arrValue, othValue, index); + } + if (result === undefined) { + // Recursively compare arrays (susceptible to call stack limits). + if (isLoose) { + var othIndex = othLength; + while (othIndex--) { + othValue = other[othIndex]; + result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); + if (result) { + break; + } + } + } else { + result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); + } + } + } + return !!result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} value The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag) { + switch (tag) { + case boolTag: + case dateTag: + // Coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. + return +object == +other; + + case errorTag: + return object.name == other.name && object.message == other.message; + + case numberTag: + // Treat `NaN` vs. `NaN` as equal. + return (object != +object) + ? other != +other + : object == +other; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings primitives and string + // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. + return object == (other + ''); + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing values. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { + var objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isLoose) { + return false; + } + var skipCtor = isLoose, + index = -1; + + while (++index < objLength) { + var key = objProps[index], + result = isLoose ? key in other : hasOwnProperty.call(other, key); + + if (result) { + var objValue = object[key], + othValue = other[key]; + + result = undefined; + if (customizer) { + result = isLoose + ? customizer(othValue, objValue, key) + : customizer(objValue, othValue, key); + } + if (result === undefined) { + // Recursively compare objects (susceptible to call stack limits). + result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB); + } + } + if (!result) { + return false; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (!skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + return false; + } + } + return true; + } + + /** + * Gets the extremum value of `collection` invoking `iteratee` for each value + * in `collection` to generate the criterion by which the value is ranked. + * The `iteratee` is invoked with three arguments: (value, index, collection). + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {boolean} [isMin] Specify returning the minimum, instead of the + * maximum, extremum value. + * @returns {*} Returns the extremum value. + */ + function extremumBy(collection, iteratee, isMin) { + var exValue = isMin ? POSITIVE_INFINITY : NEGATIVE_INFINITY, + computed = exValue, + result = computed; + + baseEach(collection, function(value, index, collection) { + var current = iteratee(value, index, collection); + if ((isMin ? (current < computed) : (current > computed)) || + (current === exValue && current === result)) { + computed = current; + result = value; + } + }); + return result; + } + + /** + * Gets the appropriate "callback" function. If the `_.callback` method is + * customized this function returns the custom method, otherwise it returns + * the `baseCallback` function. If arguments are provided the chosen function + * is invoked with them and its result is returned. + * + * @private + * @returns {Function} Returns the chosen function or its result. + */ + function getCallback(func, thisArg, argCount) { + var result = lodash.callback || callback; + result = result === callback ? baseCallback : result; + return argCount ? result(func, thisArg, argCount) : result; + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + var getFuncName = (function() { + if (!support.funcNames) { + return constant(''); + } + if (constant.name == 'constant') { + return baseProperty('name'); + } + return function(func) { + var result = func.name, + array = realNames[result], + length = array ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + }; + }()); + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized this function returns the custom method, otherwise it returns + * the `baseIndexOf` function. If arguments are provided the chosen function + * is invoked with them and its result is returned. + * + * @private + * @returns {Function|number} Returns the chosen function or its result. + */ + function getIndexOf(collection, target, fromIndex) { + var result = lodash.indexOf || indexOf; + result = result === indexOf ? baseIndexOf : result; + return collection ? result(collection, target, fromIndex) : result; + } + + /** + * Gets the "length" property value of `object`. + * + * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) + * that affects Safari on at least iOS 8.1-8.3 ARM64. + * + * @private + * @param {Object} object The object to query. + * @returns {*} Returns the "length" value. + */ + var getLength = baseProperty('length'); + + /** + * Creates an array of the own symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !getOwnPropertySymbols ? constant([]) : function(object) { + return getOwnPropertySymbols(toObject(object)); + }; + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} [transforms] The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms ? transforms.length : 0; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add array properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + var Ctor = object.constructor; + if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { + Ctor = Object; + } + return new Ctor; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return bufferClone(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + var buffer = object.buffer; + return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + var result = new Ctor(object.source, reFlags.exec(object)); + result.lastIndex = object.lastIndex; + } + return result; + } + + /** + * Invokes the method at `path` on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function invokePath(object, path, args) { + if (object != null && !isKey(path, object)) { + path = toPath(path); + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + path = last(path); + } + var func = object == null ? object : object[path]; + return func == null ? undefined : func.apply(object, args); + } + + /** + * Checks if `value` is array-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + */ + function isArrayLike(value) { + return value != null && isLength(getLength(value)); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + value = +value; + length = length == null ? MAX_SAFE_INTEGER : length; + return value > -1 && value % 1 == 0 && value < length; + } + + /** + * Checks if the provided arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object)) { + var other = object[index]; + return value === value ? (value === other) : (other !== other); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + var type = typeof value; + if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { + return true; + } + if (isArray(value)) { + return false; + } + var result = !reIsDeepProp.test(value); + return result || (object != null && value in toObject(object)); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func); + return !!funcName && func === lodash[funcName] && funcName in LazyWrapper.prototype; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + */ + function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers required to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` + * augment function arguments, making the order in which they are executed important, + * preventing the merging of metadata. However, we make an exception for a safe + * common case where curried functions have `_.ary` and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < ARY_FLAG; + + var isCombo = + (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) || + (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) || + (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = arrayCopy(value); + } + // Use source `ary` if it's smaller. + if (srcBitmask & ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * A specialized version of `_.pick` which picks `object` properties specified + * by `props`. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property names to pick. + * @returns {Object} Returns the new object. + */ + function pickByArray(object, props) { + object = toObject(object); + + var index = -1, + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + return result; + } + + /** + * A specialized version of `_.pick` which picks `object` properties `predicate` + * returns truthy for. + * + * @private + * @param {Object} object The source object. + * @param {Function} predicate The function invoked per iteration. + * @returns {Object} Returns the new object. + */ + function pickByCallback(object, predicate) { + var result = {}; + baseForIn(object, function(value, key, object) { + if (predicate(value, key, object)) { + result[key] = value; + } + }); + return result; + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = arrayCopy(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity function + * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = (function() { + var count = 0, + lastCalled = 0; + + return function(key, value) { + var stamp = now(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return key; + } + } else { + count = 0; + } + return baseSetData(key, value); + }; + }()); + + /** + * A fallback implementation of `_.isPlainObject` which checks if `value` + * is an object created by the `Object` constructor or has a `[[Prototype]]` + * of `null`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var Ctor, + support = lodash.support; + + // Exit early for non `Object` objects. + if (!(isObjectLike(value) && objToString.call(value) == objectTag) || + (!hasOwnProperty.call(value, 'constructor') && + (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { + return false; + } + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + var result; + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + baseForIn(value, function(subValue, key) { + result = key; + }); + return result === undefined || hasOwnProperty.call(value, result); + } + + /** + * A fallback implementation of `Object.keys` which creates an array of the + * own enumerable property names of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function shimKeys(object) { + var props = keysIn(object), + propsLength = props.length, + length = propsLength && object.length, + support = lodash.support; + + var allowIndexes = length && isLength(length) && + (isArray(object) || (support.nonEnumArgs && isArguments(object))); + + var index = -1, + result = []; + + while (++index < propsLength) { + var key = props[index]; + if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to an array-like object if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array|Object} Returns the array-like object. + */ + function toIterable(value) { + if (value == null) { + return []; + } + if (!isArrayLike(value)) { + return values(value); + } + return isObject(value) ? value : Object(value); + } + + /** + * Converts `value` to an object if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Object} Returns the object. + */ + function toObject(value) { + return isObject(value) ? value : Object(value); + } + + /** + * Converts `value` to property path array if it is not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array} Returns the property path array. + */ + function toPath(value) { + if (isArray(value)) { + return value; + } + var result = []; + baseToString(value).replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + return wrapper instanceof LazyWrapper + ? wrapper.clone() + : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); + } + + /** + * Creates an array of elements split into groups the length of `size`. + * If `collection` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new array containing chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if (guard ? isIterateeCall(array, size, guard) : size == null) { + size = 1; + } else { + size = nativeMax(+size || 1, 1); + } + var index = 0, + length = array ? array.length : 0, + resIndex = -1, + result = Array(ceil(length / size)); + + while (index < length) { + result[++resIndex] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * Creates an array excluding all values of the provided arrays using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.difference([1, 2, 3], [4, 2]); + * // => [1, 3] + */ + var difference = restParam(function(array, values) { + return isArrayLike(array) + ? baseDifference(array, baseFlatten(values, false, true)) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that match the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [1] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); + * // => ['barney'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [3] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropWhile(users, 'active', false), 'user'); + * // => ['pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8], '*', 1, 2); + * // => [4, '*', 8] + */ + function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(chr) { + * return chr.user == 'barney'; + * }); + * // => 0 + * + * // using the `_.matches` callback shorthand + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // using the `_.matchesProperty` callback shorthand + * _.findIndex(users, 'active', false); + * // => 0 + * + * // using the `_.property` callback shorthand + * _.findIndex(users, 'active'); + * // => 2 + */ + var findIndex = createFindIndex(); + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(chr) { + * return chr.user == 'pebbles'; + * }); + * // => 2 + * + * // using the `_.matches` callback shorthand + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // using the `_.matchesProperty` callback shorthand + * _.findLastIndex(users, 'active', false); + * // => 2 + * + * // using the `_.property` callback shorthand + * _.findLastIndex(users, 'active'); + * // => 0 + */ + var findLastIndex = createFindIndex(true); + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @alias head + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([]); + * // => undefined + */ + function first(array) { + return array ? array[0] : undefined; + } + + /** + * Flattens a nested array. If `isDeep` is `true` the array is recursively + * flattened, otherwise it is only flattened a single level. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, 3, [4]]]); + * // => [1, 2, 3, [4]] + * + * // using `isDeep` + * _.flatten([1, [2, 3, [4]]], true); + * // => [1, 2, 3, 4] + */ + function flatten(array, isDeep, guard) { + var length = array ? array.length : 0; + if (guard && isIterateeCall(array, isDeep, guard)) { + isDeep = false; + } + return length ? baseFlatten(array, isDeep) : []; + } + + /** + * Recursively flattens a nested array. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to recursively flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, 3, [4]]]); + * // => [1, 2, 3, 4] + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, true) : []; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it is used as the offset + * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` + * performs a faster binary search. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // using `fromIndex` + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + * + * // performing a binary search + * _.indexOf([1, 1, 2, 2], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else if (fromIndex) { + var index = binaryIndex(array, value), + other = array[index]; + + if (value === value ? (value === other) : (other !== other)) { + return index; + } + return -1; + } + return baseIndexOf(array, value, fromIndex || 0); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + return dropRight(array, 1); + } + + /** + * Creates an array of unique values in all provided arrays using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of shared values. + * @example + * _.intersection([1, 2], [4, 2], [2, 1]); + * // => [2] + */ + function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = [], + indexOf = getIndexOf(), + isCommon = indexOf == baseIndexOf, + result = []; + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArrayLike(value)) { + args.push(value); + caches.push((isCommon && value.length >= 120) ? createCache(argsIndex && value) : null); + } + } + argsLength = args.length; + if (argsLength < 2) { + return result; + } + var array = args[0], + index = -1, + length = array ? array.length : 0, + seen = caches[0]; + + outer: + while (++index < length) { + value = array[index]; + if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { + argsIndex = argsLength; + while (--argsIndex) { + var cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value, 0)) < 0) { + continue outer; + } + } + if (seen) { + seen.push(value); + } + result.push(value); + } + } + return result; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=array.length-1] The index to search from + * or `true` to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // using `fromIndex` + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + * + * // performing a binary search + * _.lastIndexOf([1, 1, 2, 2], 2, true); + * // => 3 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; + } else if (fromIndex) { + index = binaryIndex(array, value, true) - 1; + var other = array[index]; + if (value === value ? (value === other) : (other !== other)) { + return index; + } + return -1; + } + if (value !== value) { + return indexOfNaN(array, index, true); + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from `array` using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull() { + var args = arguments, + array = args[0]; + + if (!(array && array.length)) { + return array; + } + var index = 0, + indexOf = getIndexOf(), + length = args.length; + + while (++index < length) { + var fromIndex = 0, + value = args[index]; + + while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * Removes elements from `array` corresponding to the given indexes and returns + * an array of the removed elements. Indexes may be specified as an array of + * indexes or as individual arguments. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove, + * specified as individual indexes or arrays of indexes. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [5, 10, 15, 20]; + * var evens = _.pullAt(array, 1, 3); + * + * console.log(array); + * // => [5, 15] + * + * console.log(evens); + * // => [10, 20] + */ + var pullAt = restParam(function(array, indexes) { + indexes = baseFlatten(indexes); + + var result = baseAt(array, indexes); + basePullAt(array, indexes.sort(baseCompareAscending)); + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * **Note:** Unlike `_.filter`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate, thisArg) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getCallback(predicate, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @alias tail + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + */ + function rest(array) { + return drop(array, 1); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of `Array#slice` to support node + * lists in IE < 9 and to ensure dense arrays are returned. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. If an iteratee + * function is provided it is invoked for `value` and each element of `array` + * to compute their sort ranking. The iteratee is bound to `thisArg` and + * invoked with one argument; (value). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 4, 5, 5], 5); + * // => 2 + * + * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; + * + * // using an iteratee function + * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { + * return this.data[word]; + * }, dict); + * // => 1 + * + * // using the `_.property` callback shorthand + * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 1 + */ + var sortedIndex = createSortedIndex(); + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 4, 5, 5], 5); + * // => 4 + */ + var sortedLastIndex = createSortedIndex(true); + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is bound to `thisArg` + * and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [2, 3] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active'), 'user'); + * // => [] + */ + function takeRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [1, 2] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false}, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeWhile(users, 'active', false), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeWhile(users, 'active'), 'user'); + * // => [] + */ + function takeWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, of the provided arrays using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([1, 2], [4, 2], [2, 1]); + * // => [1, 2, 4] + */ + var union = restParam(function(arrays) { + return baseUniq(baseFlatten(arrays, false, true)); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons, in which only the first occurence of each element + * is kept. Providing `true` for `isSorted` performs a faster search algorithm + * for sorted arrays. If an iteratee function is provided it is invoked for + * each element in the array to generate the criterion by which uniqueness + * is computed. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index, array). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Array + * @param {Array} array The array to inspect. + * @param {boolean} [isSorted] Specify the array is sorted. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new duplicate-value-free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + * + * // using `isSorted` + * _.uniq([1, 1, 2], true); + * // => [1, 2] + * + * // using an iteratee function + * _.uniq([1, 2.5, 1.5, 2], function(n) { + * return this.floor(n); + * }, Math); + * // => [1, 2.5] + * + * // using the `_.property` callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (isSorted != null && typeof isSorted != 'boolean') { + thisArg = iteratee; + iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted; + isSorted = false; + } + var func = getCallback(); + if (!(func === baseCallback && iteratee == null)) { + iteratee = func(iteratee, thisArg, 3); + } + return (isSorted && getIndexOf() == baseIndexOf) + ? sortedUniq(array, iteratee) + : baseUniq(array, iteratee); + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + * + * _.unzip(zipped); + * // => [['fred', 'barney'], [30, 40], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var index = -1, + length = 0; + + array = arrayFilter(array, function(group) { + if (isArrayLike(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + var result = Array(length); + while (++index < length) { + result[index] = arrayMap(array, baseProperty(index)); + } + return result; + } + + /** + * This method is like `_.unzip` except that it accepts an iteratee to specify + * how regrouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee] The function to combine regrouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + iteratee = bindCallback(iteratee, thisArg, 4); + return arrayMap(result, function(group) { + return arrayReduce(group, iteratee, undefined, true); + }); + } + + /** + * Creates an array excluding all provided values using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to filter. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.without([1, 2, 1, 3], 1, 2); + * // => [3] + */ + var without = restParam(function(array, values) { + return isArrayLike(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the provided arrays. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of values. + * @example + * + * _.xor([1, 2], [4, 2]); + * // => [1, 4] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArrayLike(array)) { + var result = result + ? baseDifference(result, array).concat(baseDifference(array, result)) + : array; + } + } + return result ? baseUniq(result) : []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second elements + * of the given arrays, and so on. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + var zip = restParam(unzip); + + /** + * The inverse of `_.pairs`; this method returns an object composed from arrays + * of property names and values. Provide either a single two dimensional array, + * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names + * and one of corresponding values. + * + * @static + * @memberOf _ + * @alias object + * @category Array + * @param {Array} props The property names. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject([['fred', 30], ['barney', 40]]); + * // => { 'fred': 30, 'barney': 40 } + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(props, values) { + var index = -1, + length = props ? props.length : 0, + result = {}; + + if (length && !values && !isArray(props[0])) { + values = []; + } + while (++index < length) { + var key = props[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /** + * This method is like `_.zip` except that it accepts an iteratee to specify + * how grouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee] The function to combine grouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], _.add); + * // => [111, 222] + */ + var zipWith = restParam(function(arrays) { + var length = arrays.length, + iteratee = arrays[length - 2], + thisArg = arrays[length - 1]; + + if (length > 2 && typeof iteratee == 'function') { + length -= 2; + } else { + iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined; + thisArg = undefined; + } + arrays.length = length; + return unzipWith(arrays, iteratee, thisArg); + }); + + /** + * Creates a `lodash` object that wraps `value` with explicit method + * chaining enabled. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _.chain(users) + * .sortBy('age') + * .map(function(chr) { + * return chr.user + ' is ' + chr.age; + * }) + * .first() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor is + * bound to `thisArg` and invoked with one argument; (value). The purpose of + * this method is to "tap into" a method chain in order to perform operations + * on intermediate results within the chain. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor, thisArg) { + interceptor.call(thisArg, value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor, thisArg) { + return interceptor.call(thisArg, value); + } + + /** + * Enables explicit method chaining on the wrapper object. + * + * @name chain + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // without explicit chaining + * _(users).first(); + * // => { 'user': 'barney', 'age': 36 } + * + * // with explicit chaining + * _(users).chain() + * .first() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chained sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapper = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapper = wrapper.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapper.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Creates a clone of the chained sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapper = _(array).map(function(value) { + * return Math.pow(value, 2); + * }); + * + * var other = [3, 4]; + * var otherWrapper = wrapper.plant(other); + * + * otherWrapper.value(); + * // => [9, 16] + * + * wrapper.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * Reverses the wrapped array so the first element becomes the last, the + * second element becomes the second to last, and so on. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new reversed `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + if (this.__actions__.length) { + value = new LazyWrapper(this); + } + return new LodashWrapper(value.reverse(), this.__chain__); + } + return this.thru(function(value) { + return value.reverse(); + }); + } + + /** + * Produces the result of coercing the unwrapped value to a string. + * + * @name toString + * @memberOf _ + * @category Chain + * @returns {string} Returns the coerced string value. + * @example + * + * _([1, 2, 3]).toString(); + * // => '1,2,3' + */ + function wrapperToString() { + return (this.value() + ''); + } + + /** + * Executes the chained sequence to extract the unwrapped value. + * + * @name value + * @memberOf _ + * @alias run, toJSON, valueOf + * @category Chain + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /** + * Creates an array of elements corresponding to the given keys, or indexes, + * of `collection`. Keys may be specified as individual arguments or as arrays + * of keys. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [props] The property names + * or indexes of elements to pick, specified individually or in arrays. + * @returns {Array} Returns the new array of picked elements. + * @example + * + * _.at(['a', 'b', 'c'], [0, 2]); + * // => ['a', 'c'] + * + * _.at(['barney', 'fred', 'pebbles'], 0, 2); + * // => ['barney', 'pebbles'] + */ + var at = restParam(function(collection, props) { + return baseAt(collection, baseFlatten(props)); + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the number of times the key was returned by `iteratee`. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * The predicate is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.every(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = null; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = getCallback(predicate, thisArg, 3); + } + return func(collection, predicate); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.filter([4, 5, 6], function(n) { + * return n % 2 == 0; + * }); + * // => [4, 6] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.filter(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.filter(users, 'active'), 'user'); + * // => ['barney'] + */ + function filter(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = getCallback(predicate, thisArg, 3); + return func(collection, predicate); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias detect + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.result(_.find(users, function(chr) { + * return chr.age < 40; + * }), 'user'); + * // => 'barney' + * + * // using the `_.matches` callback shorthand + * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); + * // => 'pebbles' + * + * // using the `_.matchesProperty` callback shorthand + * _.result(_.find(users, 'active', false), 'user'); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.result(_.find(users, 'active'), 'user'); + * // => 'barney' + */ + var find = createFind(baseEach); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(baseEachRight, true); + + /** + * Performs a deep comparison between each element in `collection` and the + * source object, returning the first element that has equivalent property + * values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); + * // => 'barney' + * + * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); + * // => 'fred' + */ + function findWhere(collection, source) { + return find(collection, baseMatches(source)); + } + + /** + * Iterates over elements of `collection` invoking `iteratee` for each element. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). Iteratee functions may exit iteration early + * by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEach(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from left to right and returns the array + * + * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { + * console.log(n, key); + * }); + * // => logs each value-key pair and returns the object (iteration order is not guaranteed) + */ + var forEach = createForEach(arrayEach, baseEach); + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEachRight(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from right to left and returns the array + */ + var forEachRight = createForEach(arrayEachRight, baseEachRight); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using the `_.property` callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + result[key] = [value]; + } + }); + + /** + * Checks if `value` is in `collection` using + * [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it is used as the offset + * from the end of `collection`. + * + * @static + * @memberOf _ + * @alias contains, include + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {*} target The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {boolean} Returns `true` if a matching element is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.includes('pebbles', 'eb'); + * // => true + */ + function includes(collection, target, fromIndex, guard) { + var length = collection ? getLength(collection) : 0; + if (!isLength(length)) { + collection = values(collection); + length = collection.length; + } + if (!length) { + return false; + } + if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { + fromIndex = 0; + } else { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); + } + return (typeof collection == 'string' || !isArray(collection) && isString(collection)) + ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1) + : (getIndexOf(collection, target, fromIndex) > -1); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the last element responsible for generating the key. The + * iteratee function is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keyData = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keyData, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return String.fromCharCode(object.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return this.fromCharCode(object.code); + * }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method at `path` on each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `methodName` is a function it is + * invoked for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invoke = restParam(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + isProp = isKey(path), + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? path : (isProp && value != null && value[path]); + result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); + }); + return result; + }); + + /** + * Creates an array of values by running each element in `collection` through + * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * Many lodash methods are guarded to work as interatees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, + * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, + * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, + * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, + * `sum`, `uniq`, and `words` + * + * @static + * @memberOf _ + * @alias collect + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new mapped array. + * @example + * + * function timesThree(n) { + * return n * 3; + * } + * + * _.map([1, 2], timesThree); + * // => [3, 6] + * + * _.map({ 'a': 1, 'b': 2 }, timesThree); + * // => [3, 6] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // using the `_.property` callback shorthand + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee, thisArg) { + var func = isArray(collection) ? arrayMap : baseMap; + iteratee = getCallback(iteratee, thisArg, 3); + return func(collection, iteratee); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, while the second of which + * contains elements `predicate` returns falsey for. The predicate is bound + * to `thisArg` and invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * _.partition([1, 2, 3], function(n) { + * return n % 2; + * }); + * // => [[1, 3], [2]] + * + * _.partition([1.2, 2.3, 3.4], function(n) { + * return this.floor(n) % 2; + * }, Math); + * // => [[1.2, 3.4], [2.3]] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * var mapper = function(array) { + * return _.pluck(array, 'user'); + * }; + * + * // using the `_.matches` callback shorthand + * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); + * // => [['pebbles'], ['barney', 'fred']] + * + * // using the `_.matchesProperty` callback shorthand + * _.map(_.partition(users, 'active', false), mapper); + * // => [['barney', 'pebbles'], ['fred']] + * + * // using the `_.property` callback shorthand + * _.map(_.partition(users, 'active'), mapper); + * // => [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Gets the property value of `path` from all elements in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|string} path The path of the property to pluck. + * @returns {Array} Returns the property values. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.pluck(users, 'user'); + * // => ['barney', 'fred'] + * + * var userIndex = _.indexBy(users, 'user'); + * _.pluck(userIndex, 'age'); + * // => [36, 40] (iteration order is not guaranteed) + */ + function pluck(collection, path) { + return map(collection, property(path)); + } + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` through `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not provided the first element of `collection` is used as the initial + * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as interatees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `includes`, `merge`, `sortByAll`, and `sortByOrder` + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * _.reduce([1, 2], function(total, n) { + * return total + n; + * }); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { + * result[key] = n * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) + */ + var reduce = createReduce(arrayReduce, baseEach); + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + var reduceRight = createReduce(arrayReduceRight, baseEachRight); + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.reject([1, 2, 3, 4], function(n) { + * return n % 2 == 0; + * }); + * // => [1, 3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.reject(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.reject(users, 'active'), 'user'); + * // => ['barney'] + */ + function reject(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = getCallback(predicate, thisArg, 3); + return func(collection, function(value, index, collection) { + return !predicate(value, index, collection); + }); + } + + /** + * Gets a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {*} Returns the random sample(s). + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n == null) { + collection = toIterable(collection); + var length = collection.length; + return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length); + return result; + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + collection = toIterable(collection); + + var index = -1, + length = collection.length, + result = Array(length); + + while (++index < length) { + var rand = baseRandom(0, index); + if (index != rand) { + result[index] = result[rand]; + } + result[rand] = collection[index]; + } + return result; + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the size of `collection`. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? getLength(collection) : 0; + return isLength(length) ? length : keys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * The function returns as soon as it finds a passing value and does not iterate + * over the entire collection. The predicate is bound to `thisArg` and invoked + * with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.some(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, thisArg) { + var func = isArray(collection) ? arraySome : baseSome; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = null; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = getCallback(predicate, thisArg, 3); + } + return func(collection, predicate); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through `iteratee`. This method performs + * a stable sort, that is, it preserves the original sort order of equal elements. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new sorted array. + * @example + * + * _.sortBy([1, 2, 3], function(n) { + * return Math.sin(n); + * }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(n) { + * return this.sin(n); + * }, Math); + * // => [3, 1, 2] + * + * var users = [ + * { 'user': 'fred' }, + * { 'user': 'pebbles' }, + * { 'user': 'barney' } + * ]; + * + * // using the `_.property` callback shorthand + * _.pluck(_.sortBy(users, 'user'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function sortBy(collection, iteratee, thisArg) { + if (collection == null) { + return []; + } + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = null; + } + var index = -1; + iteratee = getCallback(iteratee, thisArg, 3); + + var result = baseMap(collection, function(value, key, collection) { + return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; + }); + return baseSortBy(result, compareAscending); + } + + /** + * This method is like `_.sortBy` except that it can sort by multiple iteratees + * or property names. + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees + * The iteratees to sort by, specified as individual values or arrays of values. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.map(_.sortByAll(users, ['user', 'age']), _.values); + * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.map(_.sortByAll(users, 'user', function(chr) { + * return Math.floor(chr.age / 10); + * }), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ + var sortByAll = restParam(function(collection, iteratees) { + if (collection == null) { + return []; + } + var guard = iteratees[2]; + if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { + iteratees.length = 1; + } + return baseSortByOrder(collection, baseFlatten(iteratees), []); + }); + + /** + * This method is like `_.sortByAll` except that it allows specifying the + * sort orders of the iteratees to sort by. A truthy value in `orders` will + * sort the corresponding property name in ascending order while a falsey + * value will sort it in descending order. + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {boolean[]} orders The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // sort by `user` in ascending order and by `age` in descending order + * _.map(_.sortByOrder(users, ['user', 'age'], [true, false]), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ + function sortByOrder(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (guard && isIterateeCall(iteratees, orders, guard)) { + orders = null; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseSortByOrder(collection, iteratees, orders); + } + + /** + * Performs a deep comparison between each element in `collection` and the + * source object, returning an array of all elements that have equivalent + * property values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {Array} Returns the new filtered array. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, + * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); + * // => ['barney'] + * + * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); + * // => ['fred'] + */ + function where(collection, source) { + return filter(collection, baseMatches(source)); + } + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Date + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => logs the number of milliseconds it took for the deferred function to be invoked + */ + var now = nativeNow || function() { + return new Date().getTime(); + }; + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it is called `n` or more times. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'done saving!' after the two async saves have completed + */ + function after(n, func) { + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + n = nativeIsFinite(n = +n) ? n : 0; + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that accepts up to `n` arguments ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + if (guard && isIterateeCall(func, n, guard)) { + n = null; + } + n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); + return createWrapper(func, ARY_FLAG, null, null, null, null, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it is called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery('#add').on('click', _.before(5, addContactToList)); + * // => allows adding up to 4 contacts to the list + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = null; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and prepends any additional `_.bind` arguments to those provided to the + * bound function. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind` this method does not set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var greet = function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * }; + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // using placeholders + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = restParam(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bind.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(func, bitmask, thisArg, partials, holders); + }); + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all enumerable function + * properties, own and inherited, of `object` are bound. + * + * **Note:** This method does not set the "length" property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} [methodNames] The object method names to bind, + * specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs' when the element is clicked + */ + var bindAll = restParam(function(object, methodNames) { + methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); + + var index = -1, + length = methodNames.length; + + while (++index < length) { + var key = methodNames[index]; + object[key] = createWrapper(object[key], BIND_FLAG, object); + } + return object; + }); + + /** + * Creates a function that invokes the method at `object[key]` and prepends + * any additional `_.bindKey` arguments to those provided to the bound function. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. + * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // using placeholders + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = restParam(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bindKey.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts one or more arguments of `func` that when + * called either invokes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` may be specified + * if `func.length` is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + var curry = createCurry(CURRY_FLAG); + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + var curryRight = createCurry(CURRY_RIGHT_FLAG); + + /** + * Creates a function that delays invoking `func` until after `wait` milliseconds + * have elapsed since the last time it was invoked. The created function comes + * with a `cancel` method to cancel delayed invocations. Provide an options + * object to indicate that `func` should be invoked on the leading and/or + * trailing edge of the `wait` timeout. Subsequent calls to the debounced + * function return the result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify invoking on the leading + * edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be + * delayed before it is invoked. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // invoke `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // ensure `batchLog` is invoked once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * jQuery(source).on('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * })); + * + * // cancel a debounced call + * var todoChanges = _.debounce(batchLog, 1000); + * Object.observe(models.todo, todoChanges); + * + * Object.observe(models, function(changes) { + * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { + * todoChanges.cancel(); + * } + * }, ['delete']); + * + * // ...at some point `models.todo` is changed + * models.todo.completed = true; + * + * // ...before 1 second has passed `models.todo` is deleted + * // which cancels the debounced `todoChanges` call + * delete models.todo; + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = wait < 0 ? 0 : (+wait || 0); + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); + trailing = 'trailing' in options ? options.trailing : trailing; + } + + function cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + } + + function delayed() { + var remaining = wait - (now() - stamp); + if (remaining <= 0 || remaining > wait) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + } + + function maxDelayed() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } + + function debounced() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0 || remaining > maxWait; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + } + debounced.cancel = cancel; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + var defer = restParam(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => logs 'later' after one second + */ + var delay = restParam(function(func, wait, args) { + return baseDelay(func, wait, args); + }); + + /** + * Creates a function that returns the result of invoking the provided + * functions with the `this` binding of the created function, where each + * successive invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow(_.add, square); + * addSquare(1, 2); + * // => 9 + */ + var flow = createFlow(); + + /** + * This method is like `_.flow` except that it creates a function that + * invokes the provided functions from right to left. + * + * @static + * @memberOf _ + * @alias backflow, compose + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight(square, _.add); + * addSquare(1, 2); + * // => 9 + */ + var flowRight = createFlow(true); + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is coerced to a string and used as the + * cache key. The `func` is invoked with the `this` binding of the memoized + * function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the [`Map`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object) + * method interface of `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var upperCase = _.memoize(function(string) { + * return string.toUpperCase(); + * }); + * + * upperCase('fred'); + * // => 'FRED' + * + * // modifying the result cache + * upperCase.cache.set('fred', 'BARNEY'); + * upperCase('fred'); + * // => 'BARNEY' + * + * // replacing `_.memoize.Cache` + * var object = { 'user': 'fred' }; + * var other = { 'user': 'barney' }; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'fred' } + * + * _.memoize.Cache = WeakMap; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'barney' } + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + cache = memoized.cache, + key = resolver ? resolver.apply(this, args) : args[0]; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + cache.set(key, result); + return result; + }; + memoized.cache = new memoize.Cache; + return memoized; + } + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + return !predicate.apply(this, arguments); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first call. The `func` is invoked + * with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` invokes `createApplication` once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with `partial` arguments prepended + * to those provided to the new function. This method is like `_.bind` except + * it does **not** alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // using placeholders + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = createPartial(PARTIAL_FLAG); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to those provided to the new function. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // using placeholders + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = createPartial(PARTIAL_RIGHT_FLAG); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified indexes where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes, + * specified as individual indexes or arrays of indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, 2, 0, 1); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + * + * var map = _.rearg(_.map, [1, 0]); + * map(function(n) { + * return n * 3; + * }, [1, 2, 3]); + * // => [3, 6, 9] + */ + var rearg = restParam(function(func, indexes) { + return createWrapper(func, REARG_FLAG, null, null, null, baseFlatten(indexes)); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as an array. + * + * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.restParam(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function restParam(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + rest = Array(length); + + while (++index < length) { + rest[index] = args[start + index]; + } + switch (start) { + case 0: return func.call(this, rest); + case 1: return func.call(this, args[0], rest); + case 2: return func.call(this, args[0], args[1], rest); + } + var otherArgs = Array(start + 1); + index = -1; + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = rest; + return func.apply(this, otherArgs); + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of the created + * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). + * + * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to spread arguments over. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * // with a Promise + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function(array) { + return func.apply(this, array); + }; + } + + /** + * Creates a function that only invokes `func` at most once per every `wait` + * milliseconds. The created function comes with a `cancel` method to cancel + * delayed invocations. Provide an options object to indicate that `func` + * should be invoked on the leading and/or trailing edge of the `wait` timeout. + * Subsequent calls to the throttled function return the result of the last + * `func` call. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify invoking on the leading + * edge of the timeout. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + * + * // cancel a trailing throttled call + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = +wait; + debounceOptions.trailing = trailing; + return debounce(func, wait, debounceOptions); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Any additional arguments provided to the function are + * appended to those provided to the wrapper function. The wrapper is invoked + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []); + } + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, + * otherwise they are assigned by reference. If `customizer` is provided it is + * invoked to produce the cloned values. If `customizer` returns `undefined` + * cloning is handled by the method instead. The `customizer` is bound to + * `thisArg` and invoked with two argument; (value [, index|key, object]). + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). + * The enumerable properties of `arguments` objects and objects created by + * constructors other than `Object` are cloned to plain `Object` objects. An + * empty object is returned for uncloneable values such as functions, DOM nodes, + * Maps, Sets, and WeakMaps. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {*} Returns the cloned value. + * @example + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * var shallow = _.clone(users); + * shallow[0] === users[0]; + * // => true + * + * var deep = _.clone(users, true); + * deep[0] === users[0]; + * // => false + * + * // using a customizer callback + * var el = _.clone(document.body, function(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * }); + * + * el === document.body + * // => false + * el.nodeName + * // => BODY + * el.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, customizer, thisArg) { + if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { + isDeep = false; + } + else if (typeof isDeep == 'function') { + thisArg = customizer; + customizer = isDeep; + isDeep = false; + } + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); + return baseClone(value, isDeep, customizer); + } + + /** + * Creates a deep clone of `value`. If `customizer` is provided it is invoked + * to produce the cloned values. If `customizer` returns `undefined` cloning + * is handled by the method instead. The `customizer` is bound to `thisArg` + * and invoked with two argument; (value [, index|key, object]). + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). + * The enumerable properties of `arguments` objects and objects created by + * constructors other than `Object` are cloned to plain `Object` objects. An + * empty object is returned for uncloneable values such as functions, DOM nodes, + * Maps, Sets, and WeakMaps. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * var deep = _.cloneDeep(users); + * deep[0] === users[0]; + * // => false + * + * // using a customizer callback + * var el = _.cloneDeep(document.body, function(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * }); + * + * el === document.body + * // => false + * el.nodeName + * // => BODY + * el.childNodes.length; + * // => 20 + */ + function cloneDeep(value, customizer, thisArg) { + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); + return baseClone(value, true, customizer); + } + + /** + * Checks if `value` is classified as an `arguments` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return isObjectLike(value) && isArrayLike(value) && objToString.call(value) == argsTag; + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(function() { return arguments; }()); + * // => false + */ + var isArray = nativeIsArray || function(value) { + return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; + }; + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag); + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + function isDate(value) { + return isObjectLike(value) && objToString.call(value) == dateTag; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return !!value && value.nodeType === 1 && isObjectLike(value) && + (objToString.call(value).indexOf('Element') > -1); + } + // Fallback for environments without DOM support. + if (!support.dom) { + isElement = function(value) { + return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); + }; + } + + /** + * Checks if `value` is empty. A value is considered empty unless it is an + * `arguments` object, array, string, or jQuery-like collection with a length + * greater than `0` or an object with own enumerable properties. + * + * @static + * @memberOf _ + * @category Lang + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) || + (isObjectLike(value) && isFunction(value.splice)))) { + return !value.length; + } + return !keys(value).length; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. If `customizer` is provided it is invoked to compare values. + * If `customizer` returns `undefined` comparisons are handled by the method + * instead. The `customizer` is bound to `thisArg` and invoked with three + * arguments: (value, other [, index|key]). + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. Functions and DOM nodes + * are **not** supported. Provide a customizer function to extend support + * for comparing other values. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize value comparisons. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'user': 'fred' }; + * var other = { 'user': 'fred' }; + * + * object == other; + * // => false + * + * _.isEqual(object, other); + * // => true + * + * // using a customizer callback + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqual(array, other, function(value, other) { + * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { + * return true; + * } + * }); + * // => true + */ + function isEqual(value, other, customizer, thisArg) { + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); + if (!customizer && isStrictComparable(value) && isStrictComparable(other)) { + return value === other; + } + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag; + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on [`Number.isFinite`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite). + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(10); + * // => true + * + * _.isFinite('10'); + * // => false + * + * _.isFinite(true); + * // => false + * + * _.isFinite(Object(10)); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + var isFinite = nativeNumIsFinite || function(value) { + return typeof value == 'number' && nativeIsFinite(value); + }; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in older versions of Chrome and Safari which return 'function' for regexes + // and Safari 8 equivalents which return 'object' for typed array constructors. + return objToString.call(value) == funcTag; + }; + + /** + * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // Avoid a V8 JIT bug in Chrome 19-20. + // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. + var type = typeof value; + return type == 'function' || (!!value && type == 'object'); + } + + /** + * Performs a deep comparison between `object` and `source` to determine if + * `object` contains equivalent property values. If `customizer` is provided + * it is invoked to compare values. If `customizer` returns `undefined` + * comparisons are handled by the method instead. The `customizer` is bound + * to `thisArg` and invoked with three arguments: (value, other, index|key). + * + * **Note:** This method supports comparing properties of arrays, booleans, + * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions + * and DOM nodes are **not** supported. Provide a customizer function to extend + * support for comparing other values. + * + * @static + * @memberOf _ + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize value comparisons. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.isMatch(object, { 'age': 40 }); + * // => true + * + * _.isMatch(object, { 'age': 36 }); + * // => false + * + * // using a customizer callback + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatch(object, source, function(value, other) { + * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; + * }); + * // => true + */ + function isMatch(object, source, customizer, thisArg) { + var props = keys(source), + length = props.length; + + if (!length) { + return true; + } + if (object == null) { + return false; + } + customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3); + object = toObject(object); + if (!customizer && length == 1) { + var key = props[0], + value = source[key]; + + if (isStrictComparable(value)) { + return value === object[key] && (value !== undefined || (key in object)); + } + } + var values = Array(length), + strictCompareFlags = Array(length); + + while (length--) { + value = values[length] = source[props[length]]; + strictCompareFlags[length] = isStrictComparable(value); + } + return baseIsMatch(object, props, values, strictCompareFlags, customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4) + * which returns `true` for `undefined` and other non-numeric values. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some host objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a native function. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (value == null) { + return false; + } + if (objToString.call(value) == funcTag) { + return reIsNative.test(fnToString.call(value)); + } + return isObjectLike(value) && reIsHostCtor.test(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(8.4); + * // => true + * + * _.isNumber(NaN); + * // => true + * + * _.isNumber('8.4'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * **Note:** This method assumes objects created by the `Object` constructor + * have no inherited enumerable properties. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && objToString.call(value) == objectTag)) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + function isRegExp(value) { + return isObjectLike(value) && objToString.call(value) == regexpTag; + } + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + function isTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Converts `value` to an array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * (function() { + * return _.toArray(arguments).slice(1); + * }(1, 2, 3)); + * // => [2, 3] + */ + function toArray(value) { + var length = value ? getLength(value) : 0; + if (!isLength(length)) { + return values(value); + } + if (!length) { + return []; + } + return arrayCopy(value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable + * properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return baseCopy(value, keysIn(value)); + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources overwrite property assignments of previous sources. + * If `customizer` is provided it is invoked to produce the assigned values. + * The `customizer` is bound to `thisArg` and invoked with five arguments: + * (objectValue, sourceValue, key, object, source). + * + * **Note:** This method mutates `object` and is based on + * [`Object.assign`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign). + * + * @static + * @memberOf _ + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); + * // => { 'user': 'fred', 'age': 40 } + * + * // using a customizer callback + * var defaults = _.partialRight(_.assign, function(value, other) { + * return _.isUndefined(value) ? other : value; + * }); + * + * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + var assign = createAssigner(function(object, source, customizer) { + return customizer + ? assignWith(object, source, customizer) + : baseAssign(object, source); + }); + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties, guard) { + var result = baseCreate(prototype); + if (guard && isIterateeCall(prototype, properties, guard)) { + properties = null; + } + return properties ? baseAssign(result, properties) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + var defaults = restParam(function(args) { + var object = args[0]; + if (object == null) { + return object; + } + args.push(assignDefaults); + return assign.apply(undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {string|undefined} Returns the key of the matched element, else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(chr) { + * return chr.age < 40; + * }); + * // => 'barney' (iteration order is not guaranteed) + * + * // using the `_.matches` callback shorthand + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // using the `_.matchesProperty` callback shorthand + * _.findKey(users, 'active', false); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.findKey(users, 'active'); + * // => 'barney' + */ + var findKey = createFindKey(baseForOwn); + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {string|undefined} Returns the key of the matched element, else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(chr) { + * return chr.age < 40; + * }); + * // => returns `pebbles` assuming `_.findKey` returns `barney` + * + * // using the `_.matches` callback shorthand + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // using the `_.matchesProperty` callback shorthand + * _.findLastKey(users, 'active', false); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + var findLastKey = createFindKey(baseForOwnRight); + + /** + * Iterates over own and inherited enumerable properties of an object invoking + * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) + */ + var forIn = createForIn(baseFor); + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c' + */ + var forInRight = createForIn(baseForRight); + + /** + * Iterates over own enumerable properties of an object invoking `iteratee` + * for each property. The `iteratee` is bound to `thisArg` and invoked with + * three arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'a' and 'b' (iteration order is not guaranteed) + */ + var forOwn = createForOwn(baseForOwn); + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b' + */ + var forOwnRight = createForOwn(baseForOwnRight); + + /** + * Creates an array of function property names from all enumerable properties, + * own and inherited, of `object`. + * + * @static + * @memberOf _ + * @alias methods + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the new array of property names. + * @example + * + * _.functions(_); + * // => ['after', 'ary', 'assign', ...] + */ + function functions(object) { + return baseFunctions(object, keysIn(object)); + } + + /** + * Gets the property value of `path` on `object`. If the resolved value is + * `undefined` the `defaultValue` is used in its place. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` is a direct property, else `false`. + * @example + * + * var object = { 'a': { 'b': { 'c': 3 } } }; + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b.c'); + * // => true + * + * _.has(object, ['a', 'b', 'c']); + * // => true + */ + function has(object, path) { + if (object == null) { + return false; + } + var result = hasOwnProperty.call(object, path); + if (!result && !isKey(path)) { + path = toPath(path); + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + path = last(path); + result = object != null && hasOwnProperty.call(object, path); + } + return result; + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite property + * assignments of previous values unless `multiValue` is `true`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to invert. + * @param {boolean} [multiValue] Allow multiple values per key. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + * + * // with `multiValue` + * _.invert(object, true); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function invert(object, multiValue, guard) { + if (guard && isIterateeCall(object, multiValue, guard)) { + multiValue = null; + } + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index], + value = object[key]; + + if (multiValue) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + else { + result[value] = key; + } + } + return result; + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) + * for more details. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = !nativeKeys ? shimKeys : function(object) { + var Ctor = object != null && object.constructor; + if ((typeof Ctor == 'function' && Ctor.prototype === object) || + (typeof object != 'function' && isArrayLike(object))) { + return shimKeys(object); + } + return isObject(object) ? nativeKeys(object) : []; + }; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + if (object == null) { + return []; + } + if (!isObject(object)) { + object = Object(object); + } + var length = object.length; + length = (length && isLength(length) && + (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0; + + var Ctor = object.constructor, + index = -1, + isProto = typeof Ctor == 'function' && Ctor.prototype === object, + result = Array(length), + skipIndexes = length > 0; + + while (++index < length) { + result[index] = (index + ''); + } + for (var key in object) { + if (!(skipIndexes && isIndex(key, length)) && + !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * property of `object` through `iteratee`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the new mapped object. + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + var mapKeys = createObjectMapper(true); + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through `iteratee`. The + * iteratee function is bound to `thisArg` and invoked with three arguments: + * (value, key, object). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the new mapped object. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2 }, function(n) { + * return n * 3; + * }); + * // => { 'a': 3, 'b': 6 } + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * // using the `_.property` callback shorthand + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + var mapValues = createObjectMapper(); + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * overwrite property assignments of previous sources. If `customizer` is + * provided it is invoked to produce the merged values of the destination and + * source properties. If `customizer` returns `undefined` merging is handled + * by the method instead. The `customizer` is bound to `thisArg` and invoked + * with five arguments: (objectValue, sourceValue, key, object, source). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * var users = { + * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] + * }; + * + * var ages = { + * 'data': [{ 'age': 36 }, { 'age': 40 }] + * }; + * + * _.merge(users, ages); + * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } + * + * // using a customizer callback + * var object = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var other = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(object, other, function(a, b) { + * if (_.isArray(a)) { + * return a.concat(b); + * } + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } + */ + var merge = createAssigner(baseMerge); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable properties of `object` that are not omitted. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {Function|...(string|string[])} [predicate] The function invoked per + * iteration or property names to omit, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.omit(object, 'age'); + * // => { 'user': 'fred' } + * + * _.omit(object, _.isNumber); + * // => { 'user': 'fred' } + */ + var omit = restParam(function(object, props) { + if (object == null) { + return {}; + } + if (typeof props[0] != 'function') { + var props = arrayMap(baseFlatten(props), String); + return pickByArray(object, baseDifference(keysIn(object), props)); + } + var predicate = bindCallback(props[0], props[1], 3); + return pickByCallback(object, function(value, key, object) { + return !predicate(value, key, object); + }); + }); + + /** + * Creates a two dimensional array of the key-value pairs for `object`, + * e.g. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates an object composed of the picked `object` properties. Property + * names may be specified as individual arguments or as arrays of property + * names. If `predicate` is provided it is invoked for each property of `object` + * picking the properties `predicate` returns truthy for. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {Function|...(string|string[])} [predicate] The function invoked per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.pick(object, 'user'); + * // => { 'user': 'fred' } + * + * _.pick(object, _.isString); + * // => { 'user': 'fred' } + */ + var pick = restParam(function(object, props) { + if (object == null) { + return {}; + } + return typeof props[0] == 'function' + ? pickByCallback(object, bindCallback(props[0], props[1], 3)) + : pickByArray(object, baseFlatten(props)); + }); + + /** + * This method is like `_.get` except that if the resolved value is a function + * it is invoked with the `this` binding of its parent object and its result + * is returned. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a.b.c', 'default'); + * // => 'default' + * + * _.result(object, 'a.b.c', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + var result = object == null ? undefined : object[path]; + if (result === undefined) { + if (object != null && !isKey(path, object)) { + path = toPath(path); + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + result = object == null ? undefined : object[last(path)]; + } + result = result === undefined ? defaultValue : result; + } + return isFunction(result) ? result.call(object) : result; + } + + /** + * Sets the property value of `path` on `object`. If a portion of `path` + * does not exist it is created. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to augment. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, 'x[0].y.z', 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + if (object == null) { + return object; + } + var pathKey = (path + ''); + path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); + + var index = -1, + length = path.length, + endIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = path[index]; + if (isObject(nested)) { + if (index == endIndex) { + nested[key] = value; + } else if (nested[key] == null) { + nested[key] = isIndex(path[index + 1]) ? [] : {}; + } + } + nested = nested[key]; + } + return object; + } + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own enumerable + * properties through `iteratee`, with each invocation potentially mutating + * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked + * with four arguments: (accumulator, value, key, object). Iteratee functions + * may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Array|Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { + * result[key] = n * 3; + * }); + * // => { 'a': 3, 'b': 6 } + */ + function transform(object, iteratee, accumulator, thisArg) { + var isArr = isArray(object) || isTypedArray(object); + iteratee = getCallback(iteratee, thisArg, 4); + + if (accumulator == null) { + if (isArr || isObject(object)) { + var Ctor = object.constructor; + if (isArr) { + accumulator = isArray(object) ? new Ctor : []; + } else { + accumulator = baseCreate(isFunction(Ctor) && Ctor.prototype); + } + } else { + accumulator = {}; + } + } + (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Creates an array of the own enumerable property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable property values + * of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return baseValues(object, keysIn(object)); + } + + /** + * Checks if `n` is between `start` and up to but not including, `end`. If + * `end` is not specified it is set to `start` with `start` then set to `0`. + * + * @static + * @memberOf _ + * @category Number + * @param {number} n The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `n` is in the range, else `false`. + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + */ + function inRange(value, start, end) { + start = +start || 0; + if (typeof end === 'undefined') { + end = start; + start = 0; + } else { + end = +end || 0; + } + return value >= nativeMin(start, end) && value < nativeMax(start, end); + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number is returned. + * If `floating` is `true`, or either `min` or `max` are floats, a floating-point + * number is returned instead of an integer. + * + * @static + * @memberOf _ + * @category Number + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + if (floating && isIterateeCall(min, max, floating)) { + max = floating = null; + } + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (noMax && typeof min == 'boolean') { + floating = min; + min = 1; + } + else if (typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + noMax = false; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); + } + return baseRandom(min, max); + } + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar'); + * // => 'fooBar' + * + * _.camelCase('__foo_bar__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word); + }); + + /** + * Capitalizes the first character of `string`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('fred'); + * // => 'Fred' + */ + function capitalize(string) { + string = baseToString(string); + return string && (string.charAt(0).toUpperCase() + string.slice(1)); + } + + /** + * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = baseToString(string); + return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to search. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search from. + * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = baseToString(string); + target = (target + ''); + + var length = string.length; + position = position === undefined + ? length + : nativeMin(position < 0 ? 0 : (+position || 0), length); + + position -= target.length; + return position >= 0 && string.indexOf(target, position) == position; + } + + /** + * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to + * their corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional characters + * use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't require escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. + * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * Backticks are escaped because in Internet Explorer < 9, they can break out + * of attribute values or HTML comments. See [#59](https://html5sec.org/#59), + * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and + * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/) + * for more details. + * + * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) + * to reduce XSS vectors. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + // Reset `lastIndex` because in IE < 9 `String#replace` does not. + string = baseToString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", + * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' + */ + function escapeRegExp(string) { + string = baseToString(string); + return (string && reHasRegExpChars.test(string)) + ? string.replace(reRegExpChars, '\\$&') + : string; + } + + /** + * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__foo_bar__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Pads `string` on the left and right sides if it is shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = baseToString(string); + length = +length; + + var strLength = string.length; + if (strLength >= length || !nativeIsFinite(length)) { + return string; + } + var mid = (length - strLength) / 2, + leftLength = floor(mid), + rightLength = ceil(mid); + + chars = createPadding('', rightLength, chars); + return chars.slice(0, leftLength) + string + chars; + } + + /** + * Pads `string` on the left side if it is shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padLeft('abc', 6); + * // => ' abc' + * + * _.padLeft('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padLeft('abc', 3); + * // => 'abc' + */ + var padLeft = createPadDir(); + + /** + * Pads `string` on the right side if it is shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padRight('abc', 6); + * // => 'abc ' + * + * _.padRight('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padRight('abc', 3); + * // => 'abc' + */ + var padRight = createPadDir(true); + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal, + * in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E) + * of `parseInt`. + * + * @static + * @memberOf _ + * @category String + * @param {string} string The string to convert. + * @param {number} [radix] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard && isIterateeCall(string, radix, guard)) { + radix = 0; + } + return nativeParseInt(string, radix); + } + // Fallback for environments with pre-ES5 implementations. + if (nativeParseInt(whitespace + '08') != 8) { + parseInt = function(string, radix, guard) { + // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`. + // Chrome fails to trim leading whitespace characters. + // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. + if (guard ? isIterateeCall(string, radix, guard) : radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + string = trim(string); + return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); + }; + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=0] The number of times to repeat the string. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n) { + var result = ''; + string = baseToString(string); + n = +n; + if (n < 1 || !string || !nativeIsFinite(n)) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = floor(n / 2); + string += string; + } while (n); + + return result; + } + + /** + * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--foo-bar'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__foo_bar__'); + * // => 'Foo Bar' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1)); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to search. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = baseToString(string); + position = position == null + ? 0 + : nativeMin(position < 0 ? 0 : (+position || 0), string.length); + + return string.lastIndexOf(target, position) == position; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is provided it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as free variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [options.sourceURL] The sourceURL of the template's compiled source. + * @param {string} [options.variable] The data object variable name. + * @param- {Object} [otherOptions] Enables the legacy `options` param signature. + * @returns {Function} Returns the compiled template function. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // using the HTML "escape" delimiter to escape data property values + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + + + + +
{{ "%+010d"|sprintf:-123 }}
+
{{ "%+010d"|vsprintf:[-123] }}
+
{{ "%+010d"|fmt:-123 }}
+
{{ "%+010d"|vfmt:[-123] }}
+
{{ "I've got %2$d apples and %1$d oranges."|fmt:4:2 }}
+
{{ "I've got %(apples)d apples and %(oranges)d oranges."|fmt:{apples: 2, oranges: 4} }}
+ + + + diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/angular-sprintf.min.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/angular-sprintf.min.js new file mode 100644 index 00000000000000..dbaf744d83c214 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/angular-sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +angular.module("sprintf",[]).filter("sprintf",function(){return function(){return sprintf.apply(null,arguments)}}).filter("fmt",["$filter",function(a){return a("sprintf")}]).filter("vsprintf",function(){return function(a,b){return vsprintf(a,b)}}).filter("vfmt",["$filter",function(a){return a("vsprintf")}]); +//# sourceMappingURL=angular-sprintf.min.map \ No newline at end of file diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/angular-sprintf.min.map b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/angular-sprintf.min.map new file mode 100644 index 00000000000000..055964c624c1ac --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/angular-sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"angular-sprintf.min.js","sources":["../src/angular-sprintf.js"],"names":["angular","module","filter","sprintf","apply","arguments","$filter","format","argv","vsprintf"],"mappings":";;AAAAA,QACIC,OAAO,cACPC,OAAO,UAAW,WACd,MAAO,YACH,MAAOC,SAAQC,MAAM,KAAMC,cAGnCH,OAAO,OAAQ,UAAW,SAASI,GAC/B,MAAOA,GAAQ,cAEnBJ,OAAO,WAAY,WACf,MAAO,UAASK,EAAQC,GACpB,MAAOC,UAASF,EAAQC,MAGhCN,OAAO,QAAS,UAAW,SAASI,GAChC,MAAOA,GAAQ"} \ No newline at end of file diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/sprintf.min.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/sprintf.min.js new file mode 100644 index 00000000000000..d5bcd097f0e5a8 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/sprintf.min.js @@ -0,0 +1,4 @@ +/*! sprintf-js | Alexandru Marasteanu (http://alexei.ro/) | BSD-3-Clause */ + +!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[dief]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window); +//# sourceMappingURL=sprintf.min.map \ No newline at end of file diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/sprintf.min.map b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/sprintf.min.map new file mode 100644 index 00000000000000..33fe1636d58e47 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/dist/sprintf.min.map @@ -0,0 +1 @@ +{"version":3,"file":"sprintf.min.js","sources":["../src/sprintf.js"],"names":["window","sprintf","key","arguments","cache","hasOwnProperty","parse","format","call","get_type","variable","Object","prototype","toString","slice","toLowerCase","str_repeat","input","multiplier","Array","join","re","not_string","number","text","modulo","placeholder","key_access","index_access","sign","parse_tree","argv","arg","i","k","match","pad","pad_character","pad_length","cursor","tree_length","length","node_type","output","is_positive","Error","test","isNaN","TypeError","String","fromCharCode","parseInt","toExponential","parseFloat","toFixed","substring","toUpperCase","replace","charAt","fmt","_fmt","arg_names","exec","SyntaxError","field_list","replacement_field","field_match","vsprintf","_argv","splice","apply","exports","define","amd","this"],"mappings":";;CAAA,SAAUA,GAaN,QAASC,KACL,GAAIC,GAAMC,UAAU,GAAIC,EAAQH,EAAQG,KAIxC,OAHMA,GAAMF,IAAQE,EAAMC,eAAeH,KACrCE,EAAMF,GAAOD,EAAQK,MAAMJ,IAExBD,EAAQM,OAAOC,KAAK,KAAMJ,EAAMF,GAAMC,WAoJjD,QAASM,GAASC,GACd,MAAOC,QAAOC,UAAUC,SAASL,KAAKE,GAAUI,MAAM,EAAG,IAAIC,cAGjE,QAASC,GAAWC,EAAOC,GACvB,MAAOC,OAAMD,EAAa,GAAGE,KAAKH,GA1KtC,GAAII,IACAC,WAAY,OACZC,OAAQ,SACRC,KAAM,YACNC,OAAQ,WACRC,YAAa,wFACbxB,IAAK,sBACLyB,WAAY,wBACZC,aAAc,aACdC,KAAM,UAWV5B,GAAQM,OAAS,SAASuB,EAAYC,GAClC,GAAiEC,GAAkBC,EAAGC,EAAGC,EAAOC,EAAKC,EAAeC,EAAhHC,EAAS,EAAGC,EAAcV,EAAWW,OAAQC,EAAY,GAASC,KAA0DC,GAAc,EAAMf,EAAO,EAC3J,KAAKI,EAAI,EAAOO,EAAJP,EAAiBA,IAEzB,GADAS,EAAYjC,EAASqB,EAAWG,IACd,WAAdS,EACAC,EAAOA,EAAOF,QAAUX,EAAWG,OAElC,IAAkB,UAAdS,EAAuB,CAE5B,GADAP,EAAQL,EAAWG,GACfE,EAAM,GAEN,IADAH,EAAMD,EAAKQ,GACNL,EAAI,EAAGA,EAAIC,EAAM,GAAGM,OAAQP,IAAK,CAClC,IAAKF,EAAI3B,eAAe8B,EAAM,GAAGD,IAC7B,KAAM,IAAIW,OAAM5C,EAAQ,yCAA0CkC,EAAM,GAAGD,IAE/EF,GAAMA,EAAIG,EAAM,GAAGD,QAIvBF,GADKG,EAAM,GACLJ,EAAKI,EAAM,IAGXJ,EAAKQ,IAOf,IAJqB,YAAjB9B,EAASuB,KACTA,EAAMA,KAGNX,EAAGC,WAAWwB,KAAKX,EAAM,KAAyB,UAAjB1B,EAASuB,IAAoBe,MAAMf,GACpE,KAAM,IAAIgB,WAAU/C,EAAQ,0CAA2CQ,EAASuB,IAOpF,QAJIX,EAAGE,OAAOuB,KAAKX,EAAM,MACrBS,EAAcZ,GAAO,GAGjBG,EAAM,IACV,IAAK,IACDH,EAAMA,EAAInB,SAAS,EACvB,MACA,KAAK,IACDmB,EAAMiB,OAAOC,aAAalB,EAC9B,MACA,KAAK,IACL,IAAK,IACDA,EAAMmB,SAASnB,EAAK,GACxB,MACA,KAAK,IACDA,EAAMG,EAAM,GAAKH,EAAIoB,cAAcjB,EAAM,IAAMH,EAAIoB,eACvD,MACA,KAAK,IACDpB,EAAMG,EAAM,GAAKkB,WAAWrB,GAAKsB,QAAQnB,EAAM,IAAMkB,WAAWrB,EACpE,MACA,KAAK,IACDA,EAAMA,EAAInB,SAAS,EACvB,MACA,KAAK,IACDmB,GAAQA,EAAMiB,OAAOjB,KAASG,EAAM,GAAKH,EAAIuB,UAAU,EAAGpB,EAAM,IAAMH,CAC1E,MACA,KAAK,IACDA,KAAc,CAClB,MACA,KAAK,IACDA,EAAMA,EAAInB,SAAS,GACvB,MACA,KAAK,IACDmB,EAAMA,EAAInB,SAAS,IAAI2C,eAG3BnC,EAAGE,OAAOuB,KAAKX,EAAM,KAASS,IAAeT,EAAM,GAKnDN,EAAO,IAJPA,EAAOe,EAAc,IAAM,IAC3BZ,EAAMA,EAAInB,WAAW4C,QAAQpC,EAAGQ,KAAM,KAK1CQ,EAAgBF,EAAM,GAAkB,MAAbA,EAAM,GAAa,IAAMA,EAAM,GAAGuB,OAAO,GAAK,IACzEpB,EAAaH,EAAM,IAAMN,EAAOG,GAAKS,OACrCL,EAAMD,EAAM,IAAMG,EAAa,EAAItB,EAAWqB,EAAeC,GAAoB,GACjFK,EAAOA,EAAOF,QAAUN,EAAM,GAAKN,EAAOG,EAAMI,EAAyB,MAAlBC,EAAwBR,EAAOO,EAAMJ,EAAMI,EAAMP,EAAOG,EAGvH,MAAOW,GAAOvB,KAAK,KAGvBnB,EAAQG,SAERH,EAAQK,MAAQ,SAASqD,GAErB,IADA,GAAIC,GAAOD,EAAKxB,KAAYL,KAAiB+B,EAAY,EAClDD,GAAM,CACT,GAAqC,QAAhCzB,EAAQd,EAAGG,KAAKsC,KAAKF,IACtB9B,EAAWA,EAAWW,QAAUN,EAAM,OAErC,IAAuC,QAAlCA,EAAQd,EAAGI,OAAOqC,KAAKF,IAC7B9B,EAAWA,EAAWW,QAAU,QAE/B,CAAA,GAA4C,QAAvCN,EAAQd,EAAGK,YAAYoC,KAAKF,IAgClC,KAAM,IAAIG,aAAY,mCA/BtB,IAAI5B,EAAM,GAAI,CACV0B,GAAa,CACb,IAAIG,MAAiBC,EAAoB9B,EAAM,GAAI+B,IACnD,IAAuD,QAAlDA,EAAc7C,EAAGnB,IAAI4D,KAAKG,IAe3B,KAAM,IAAIF,aAAY,+CAbtB,KADAC,EAAWA,EAAWvB,QAAUyB,EAAY,GACwC,MAA5ED,EAAoBA,EAAkBV,UAAUW,EAAY,GAAGzB,UACnE,GAA8D,QAAzDyB,EAAc7C,EAAGM,WAAWmC,KAAKG,IAClCD,EAAWA,EAAWvB,QAAUyB,EAAY,OAE3C,CAAA,GAAgE,QAA3DA,EAAc7C,EAAGO,aAAakC,KAAKG,IAIzC,KAAM,IAAIF,aAAY,+CAHtBC,GAAWA,EAAWvB,QAAUyB,EAAY,GAUxD/B,EAAM,GAAK6B,MAGXH,IAAa,CAEjB,IAAkB,IAAdA,EACA,KAAM,IAAIhB,OAAM,4EAEpBf,GAAWA,EAAWW,QAAUN,EAKpCyB,EAAOA,EAAKL,UAAUpB,EAAM,GAAGM,QAEnC,MAAOX,GAGX,IAAIqC,GAAW,SAASR,EAAK5B,EAAMqC,GAG/B,MAFAA,IAASrC,OAAYjB,MAAM,GAC3BsD,EAAMC,OAAO,EAAG,EAAGV,GACZ1D,EAAQqE,MAAM,KAAMF,GAiBR,oBAAZG,UACPA,QAAQtE,QAAUA,EAClBsE,QAAQJ,SAAWA,IAGnBnE,EAAOC,QAAUA,EACjBD,EAAOmE,SAAWA,EAEI,kBAAXK,SAAyBA,OAAOC,KACvCD,OAAO,WACH,OACIvE,QAASA,EACTkE,SAAUA,OAKT,mBAAXnE,QAAyB0E,KAAO1E"} \ No newline at end of file diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/gruntfile.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/gruntfile.js new file mode 100644 index 00000000000000..246e1c3b9801fc --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/gruntfile.js @@ -0,0 +1,36 @@ +module.exports = function(grunt) { + grunt.initConfig({ + pkg: grunt.file.readJSON("package.json"), + + uglify: { + options: { + banner: "/*! <%= pkg.name %> | <%= pkg.author %> | <%= pkg.license %> */\n", + sourceMap: true + }, + build: { + files: [ + { + src: "src/sprintf.js", + dest: "dist/sprintf.min.js" + }, + { + src: "src/angular-sprintf.js", + dest: "dist/angular-sprintf.min.js" + } + ] + } + }, + + watch: { + js: { + files: "src/*.js", + tasks: ["uglify"] + } + } + }) + + grunt.loadNpmTasks("grunt-contrib-uglify") + grunt.loadNpmTasks("grunt-contrib-watch") + + grunt.registerTask("default", ["uglify", "watch"]) +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/package.json b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/package.json new file mode 100644 index 00000000000000..64e267c719a6bf --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/package.json @@ -0,0 +1,51 @@ +{ + "name": "sprintf-js", + "version": "1.0.2", + "description": "JavaScript sprintf implementation", + "author": { + "name": "Alexandru Marasteanu", + "email": "hello@alexei.ro", + "url": "http://alexei.ro/" + }, + "main": "src/sprintf.js", + "scripts": { + "test": "mocha test/test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/alexei/sprintf.js.git" + }, + "license": "BSD-3-Clause", + "devDependencies": { + "mocha": "*", + "grunt": "*", + "grunt-contrib-watch": "*", + "grunt-contrib-uglify": "*" + }, + "gitHead": "e8c73065cd1a79a32c697806a4e85f1fe7917592", + "bugs": { + "url": "https://github.com/alexei/sprintf.js/issues" + }, + "homepage": "https://github.com/alexei/sprintf.js", + "_id": "sprintf-js@1.0.2", + "_shasum": "11e4d84ff32144e35b0bf3a66f8587f38d8f9978", + "_from": "sprintf-js@>=1.0.2 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "alexei", + "email": "hello@alexei.ro" + }, + "maintainers": [ + { + "name": "alexei", + "email": "hello@alexei.ro" + } + ], + "dist": { + "shasum": "11e4d84ff32144e35b0bf3a66f8587f38d8f9978", + "tarball": "http://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/src/angular-sprintf.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/src/angular-sprintf.js new file mode 100644 index 00000000000000..9c69123bea291a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/src/angular-sprintf.js @@ -0,0 +1,18 @@ +angular. + module("sprintf", []). + filter("sprintf", function() { + return function() { + return sprintf.apply(null, arguments) + } + }). + filter("fmt", ["$filter", function($filter) { + return $filter("sprintf") + }]). + filter("vsprintf", function() { + return function(format, argv) { + return vsprintf(format, argv) + } + }). + filter("vfmt", ["$filter", function($filter) { + return $filter("vsprintf") + }]) diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/src/sprintf.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/src/sprintf.js new file mode 100644 index 00000000000000..0ccb64c981e878 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/src/sprintf.js @@ -0,0 +1,195 @@ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[dief]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ + } + + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) + } + return sprintf.format.call(null, cache[key], arguments) + } + + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } + return output.join("") + } + + sprintf.cache = {} + + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) + } + return parse_tree + } + + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) + } + + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() + } + + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf + + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) + } + } +})(typeof window === "undefined" ? this : window); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/test/test.js b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/test/test.js new file mode 100644 index 00000000000000..1717d8fd09684b --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/node_modules/sprintf-js/test/test.js @@ -0,0 +1,72 @@ +var assert = require("assert"), + sprintfjs = require("../src/sprintf.js"), + sprintf = sprintfjs.sprintf, + vsprintf = sprintfjs.vsprintf + +describe("sprintfjs", function() { + it("should return formated strings for simple placeholders", function() { + assert.equal("%", sprintf("%%")) + assert.equal("10", sprintf("%b", 2)) + assert.equal("A", sprintf("%c", 65)) + assert.equal("2", sprintf("%d", 2)) + assert.equal("2", sprintf("%i", 2)) + assert.equal("2", sprintf("%d", "2")) + assert.equal("2", sprintf("%i", "2")) + assert.equal("2e+0", sprintf("%e", 2)) + assert.equal("2", sprintf("%u", 2)) + assert.equal("4294967294", sprintf("%u", -2)) + assert.equal("2.2", sprintf("%f", 2.2)) + assert.equal("10", sprintf("%o", 8)) + assert.equal("%s", sprintf("%s", "%s")) + assert.equal("ff", sprintf("%x", 255)) + assert.equal("FF", sprintf("%X", 255)) + assert.equal("Polly wants a cracker", sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants")) + assert.equal("Hello world!", sprintf("Hello %(who)s!", {"who": "world"})) + }) + + it("should return formated strings for complex placeholders", function() { + // sign + assert.equal("2", sprintf("%d", 2)) + assert.equal("-2", sprintf("%d", -2)) + assert.equal("+2", sprintf("%+d", 2)) + assert.equal("-2", sprintf("%+d", -2)) + assert.equal("2", sprintf("%i", 2)) + assert.equal("-2", sprintf("%i", -2)) + assert.equal("+2", sprintf("%+i", 2)) + assert.equal("-2", sprintf("%+i", -2)) + assert.equal("2.2", sprintf("%f", 2.2)) + assert.equal("-2.2", sprintf("%f", -2.2)) + assert.equal("+2.2", sprintf("%+f", 2.2)) + assert.equal("-2.2", sprintf("%+f", -2.2)) + assert.equal("-2.3", sprintf("%+.1f", -2.34)) + assert.equal("-0.0", sprintf("%+.1f", -0.01)) + assert.equal("-000000123", sprintf("%+010d", -123)) + assert.equal("______-123", sprintf("%+'_10d", -123)) + assert.equal("-234.34 123.2", sprintf("%f %f", -234.34, 123.2)) + + // padding + assert.equal("-0002", sprintf("%05d", -2)) + assert.equal("-0002", sprintf("%05i", -2)) + assert.equal(" <", sprintf("%5s", "<")) + assert.equal("0000<", sprintf("%05s", "<")) + assert.equal("____<", sprintf("%'_5s", "<")) + assert.equal("> ", sprintf("%-5s", ">")) + assert.equal(">0000", sprintf("%0-5s", ">")) + assert.equal(">____", sprintf("%'_-5s", ">")) + assert.equal("xxxxxx", sprintf("%5s", "xxxxxx")) + assert.equal("1234", sprintf("%02u", 1234)) + assert.equal(" -10.235", sprintf("%8.3f", -10.23456)) + assert.equal("-12.34 xxx", sprintf("%f %s", -12.34, "xxx")) + + // precision + assert.equal("2.3", sprintf("%.1f", 2.345)) + assert.equal("xxxxx", sprintf("%5.5s", "xxxxxx")) + assert.equal(" x", sprintf("%5.1s", "xxxxxx")) + + }) + + it("should return formated strings for callbacks", function() { + assert.equal("foobar", sprintf("%s", function() { return "foobar" })) + assert.equal(Date.now(), sprintf("%s", Date.now)) // should pass... + }) +}) diff --git a/tools/eslint/node_modules/js-yaml/node_modules/argparse/package.json b/tools/eslint/node_modules/js-yaml/node_modules/argparse/package.json new file mode 100644 index 00000000000000..3c1b7fd712bbcc --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/argparse/package.json @@ -0,0 +1,62 @@ +{ + "name": "argparse", + "description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library", + "version": "1.0.2", + "keywords": [ + "cli", + "parser", + "argparse", + "option", + "args" + ], + "homepage": "https://github.com/nodeca/argparse", + "contributors": [ + { + "name": "Eugene Shkuropat" + }, + { + "name": "Paul Jacobson" + } + ], + "bugs": { + "url": "https://github.com/nodeca/argparse/issues" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/nodeca/argparse.git" + }, + "main": "./index.js", + "scripts": { + "test": "make test" + }, + "dependencies": { + "lodash": ">= 3.2.0 < 4.0.0", + "sprintf-js": "~1.0.2" + }, + "devDependencies": { + "mocha": "*" + }, + "gitHead": "990f1b5332e70dd3c1c437d2f4077a2b63ac9674", + "_id": "argparse@1.0.2", + "_shasum": "bcfae39059656d1973d0b9e6a1a74154b5a9a136", + "_from": "argparse@>=1.0.2 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "vitaly", + "email": "vitaly@rcdesign.ru" + }, + "maintainers": [ + { + "name": "vitaly", + "email": "vitaly@rcdesign.ru" + } + ], + "dist": { + "shasum": "bcfae39059656d1973d0b9e6a1a74154b5a9a136", + "tarball": "http://registry.npmjs.org/argparse/-/argparse-1.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/ChangeLog b/tools/eslint/node_modules/js-yaml/node_modules/esprima/ChangeLog new file mode 100644 index 00000000000000..72d64b5d813cf5 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/ChangeLog @@ -0,0 +1,111 @@ +2015-04-17: Version 2.2.0 + + * Support ES6 import and export declarations (issue 1000) + * Fix line terminator before arrow not recognized as error (issue 1009) + * Support ES6 destructuring (issue 1045) + * Support ES6 template literal (issue 1074) + * Fix the handling of invalid/incomplete string escape sequences (issue 1106) + * Fix ES3 static member access restriction (issue 1120) + * Support for `super` in ES6 class (issue 1147) + +2015-03-09: Version 2.1.0 + + * Support ES6 class (issue 1001) + * Support ES6 rest parameter (issue 1011) + * Expand the location of property getter, setter, and methods (issue 1029) + * Enable TryStatement transition to a single handler (issue 1031) + * Support ES6 computed property name (issue 1037) + * Tolerate unclosed block comment (issue 1041) + * Support ES6 lexical declaration (issue 1065) + +2015-02-06: Version 2.0.0 + + * Support ES6 arrow function (issue 517) + * Support ES6 Unicode code point escape (issue 521) + * Improve the speed and accuracy of comment attachment (issue 522) + * Support ES6 default parameter (issue 519) + * Support ES6 regular expression flags (issue 557) + * Fix scanning of implicit octal literals (issue 565) + * Fix the handling of automatic semicolon insertion (issue 574) + * Support ES6 method definition (issue 620) + * Support ES6 octal integer literal (issue 621) + * Support ES6 binary integer literal (issue 622) + * Support ES6 object literal property value shorthand (issue 624) + +2015-03-03: Version 1.2.5 + + * Fix scanning of implicit octal literals (issue 565) + +2015-02-05: Version 1.2.4 + + * Fix parsing of LeftHandSideExpression in ForInStatement (issue 560) + * Fix the handling of automatic semicolon insertion (issue 574) + +2015-01-18: Version 1.2.3 + + * Fix division by this (issue 616) + +2014-05-18: Version 1.2.2 + + * Fix duplicated tokens when collecting comments (issue 537) + +2014-05-04: Version 1.2.1 + + * Ensure that Program node may still have leading comments (issue 536) + +2014-04-29: Version 1.2.0 + + * Fix semicolon handling for expression statement (issue 462, 533) + * Disallow escaped characters in regular expression flags (issue 503) + * Performance improvement for location tracking (issue 520) + * Improve the speed of comment attachment (issue 522) + +2014-03-26: Version 1.1.1 + + * Fix token handling of forward slash after an array literal (issue 512) + +2014-03-23: Version 1.1.0 + + * Optionally attach comments to the owning syntax nodes (issue 197) + * Simplify binary parsing with stack-based shift reduce (issue 352) + * Always include the raw source of literals (issue 376) + * Add optional input source information (issue 386) + * Tokenizer API for pure lexical scanning (issue 398) + * Improve the web site and its online demos (issue 337, 400, 404) + * Performance improvement for location tracking (issue 417, 424) + * Support HTML comment syntax (issue 451) + * Drop support for legacy browsers (issue 474) + +2013-08-27: Version 1.0.4 + + * Minimize the payload for packages (issue 362) + * Fix missing cases on an empty switch statement (issue 436) + * Support escaped ] in regexp literal character classes (issue 442) + * Tolerate invalid left-hand side expression (issue 130) + +2013-05-17: Version 1.0.3 + + * Variable declaration needs at least one declarator (issue 391) + * Fix benchmark's variance unit conversion (issue 397) + * IE < 9: \v should be treated as vertical tab (issue 405) + * Unary expressions should always have prefix: true (issue 418) + * Catch clause should only accept an identifier (issue 423) + * Tolerate setters without parameter (issue 426) + +2012-11-02: Version 1.0.2 + + Improvement: + + * Fix esvalidate JUnit output upon a syntax error (issue 374) + +2012-10-28: Version 1.0.1 + + Improvements: + + * esvalidate understands shebang in a Unix shell script (issue 361) + * esvalidate treats fatal parsing failure as an error (issue 361) + * Reduce Node.js package via .npmignore (issue 362) + +2012-10-22: Version 1.0.0 + + Initial release. diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/LICENSE.BSD b/tools/eslint/node_modules/js-yaml/node_modules/esprima/LICENSE.BSD new file mode 100644 index 00000000000000..3e580c355a96e5 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/LICENSE.BSD @@ -0,0 +1,19 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/README.md b/tools/eslint/node_modules/js-yaml/node_modules/esprima/README.md new file mode 100644 index 00000000000000..9ba7c0f53088a3 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/README.md @@ -0,0 +1,23 @@ +**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, +standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) +parser written in ECMAScript (also popularly known as +[JavaScript](https://en.wikipedia.org/wiki/JavaScript). +Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), +with the help of [many contributors](https://github.com/jquery/esprima/contributors). + +### Features + +- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) +- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/spec.md) as standardized by [EStree project](https://github.com/estree/estree) +- Optional tracking of syntax node location (index-based and line-column) +- Heavily tested (~1000 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://travis-ci.org/jquery/esprima)) +- [Partial support](https://github.com/jquery/esprima/issues/1099) for ECMAScript 6 + +Esprima serves as a **building block** for some JavaScript +language tools, from [code instrumentation](http://esprima.org/demo/functiontrace.html) +to [editor autocompletion](http://esprima.org/demo/autocomplete.html). + +Esprima runs on many popular web browsers, as well as other ECMAScript platforms such as +[Rhino](http://www.mozilla.org/rhino), [Nashorn](http://openjdk.java.net/projects/nashorn/), and [Node.js](https://npmjs.org/package/esprima). + +For more information, check the web site [esprima.org](http://esprima.org). diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/bin/esparse.js b/tools/eslint/node_modules/js-yaml/node_modules/esprima/bin/esparse.js new file mode 100755 index 00000000000000..560366695a1e37 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/bin/esparse.js @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true node:true rhino:true */ + +var fs, esprima, fname, content, options, syntax; + +if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); +} else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esparse.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esparse [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --comment Gather all line and block comments in an array'); + console.log(' --loc Include line-column location info for each syntax node'); + console.log(' --range Include index-based range for each syntax node'); + console.log(' --raw Display the raw value of literals'); + console.log(' --tokens List all tokens in an array'); + console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); + console.log(' -v, --version Shows program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = {}; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry === '--comment') { + options.comment = true; + } else if (entry === '--loc') { + options.loc = true; + } else if (entry === '--range') { + options.range = true; + } else if (entry === '--raw') { + options.raw = true; + } else if (entry === '--tokens') { + options.tokens = true; + } else if (entry === '--tolerant') { + options.tolerant = true; + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else if (typeof fname === 'string') { + console.log('Error: more than one input file.'); + process.exit(1); + } else { + fname = entry; + } +}); + +if (typeof fname !== 'string') { + console.log('Error: no input file.'); + process.exit(1); +} + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +try { + content = fs.readFileSync(fname, 'utf-8'); + syntax = esprima.parse(content, options); + console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); +} catch (e) { + console.log('Error: ' + e.message); + process.exit(1); +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/bin/esvalidate.js b/tools/eslint/node_modules/js-yaml/node_modules/esprima/bin/esvalidate.js new file mode 100755 index 00000000000000..dddd8a2ada461a --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/bin/esvalidate.js @@ -0,0 +1,199 @@ +#!/usr/bin/env node +/* + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint sloppy:true plusplus:true node:true rhino:true */ +/*global phantom:true */ + +var fs, system, esprima, options, fnames, count; + +if (typeof esprima === 'undefined') { + // PhantomJS can only require() relative files + if (typeof phantom === 'object') { + fs = require('fs'); + system = require('system'); + esprima = require('./esprima'); + } else if (typeof require === 'function') { + fs = require('fs'); + esprima = require('esprima'); + } else if (typeof load === 'function') { + try { + load('esprima.js'); + } catch (e) { + load('../esprima.js'); + } + } +} + +// Shims to Node.js objects when running under PhantomJS 1.7+. +if (typeof phantom === 'object') { + fs.readFileSync = fs.read; + process = { + argv: [].slice.call(system.args), + exit: phantom.exit + }; + process.argv.unshift('phantomjs'); +} + +// Shims to Node.js objects when running under Rhino. +if (typeof console === 'undefined' && typeof process === 'undefined') { + console = { log: print }; + fs = { readFileSync: readFile }; + process = { argv: arguments, exit: quit }; + process.argv.unshift('esvalidate.js'); + process.argv.unshift('rhino'); +} + +function showUsage() { + console.log('Usage:'); + console.log(' esvalidate [options] file.js'); + console.log(); + console.log('Available options:'); + console.log(); + console.log(' --format=type Set the report format, plain (default) or junit'); + console.log(' -v, --version Print program version'); + console.log(); + process.exit(1); +} + +if (process.argv.length <= 2) { + showUsage(); +} + +options = { + format: 'plain' +}; + +fnames = []; + +process.argv.splice(2).forEach(function (entry) { + + if (entry === '-h' || entry === '--help') { + showUsage(); + } else if (entry === '-v' || entry === '--version') { + console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); + console.log(); + process.exit(0); + } else if (entry.slice(0, 9) === '--format=') { + options.format = entry.slice(9); + if (options.format !== 'plain' && options.format !== 'junit') { + console.log('Error: unknown report format ' + options.format + '.'); + process.exit(1); + } + } else if (entry.slice(0, 2) === '--') { + console.log('Error: unknown option ' + entry + '.'); + process.exit(1); + } else { + fnames.push(entry); + } +}); + +if (fnames.length === 0) { + console.log('Error: no input file.'); + process.exit(1); +} + +if (options.format === 'junit') { + console.log(''); + console.log(''); +} + +count = 0; +fnames.forEach(function (fname) { + var content, timestamp, syntax, name; + try { + content = fs.readFileSync(fname, 'utf-8'); + + if (content[0] === '#' && content[1] === '!') { + content = '//' + content.substr(2, content.length); + } + + timestamp = Date.now(); + syntax = esprima.parse(content, { tolerant: true }); + + if (options.format === 'junit') { + + name = fname; + if (name.lastIndexOf('/') >= 0) { + name = name.slice(name.lastIndexOf('/') + 1); + } + + console.log(''); + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + console.log(' '); + console.log(' ' + + error.message + '(' + name + ':' + error.lineNumber + ')' + + ''); + console.log(' '); + }); + + console.log(''); + + } else if (options.format === 'plain') { + + syntax.errors.forEach(function (error) { + var msg = error.message; + msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); + msg = fname + ':' + error.lineNumber + ': ' + msg; + console.log(msg); + ++count; + }); + + } + } catch (e) { + ++count; + if (options.format === 'junit') { + console.log(''); + console.log(' '); + console.log(' ' + + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + + ')'); + console.log(' '); + console.log(''); + } else { + console.log('Error: ' + e.message); + } + } +}); + +if (options.format === 'junit') { + console.log(''); +} + +if (count > 0) { + process.exit(1); +} + +if (count === 0 && typeof phantom === 'object') { + process.exit(0); +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/esprima.js b/tools/eslint/node_modules/js-yaml/node_modules/esprima/esprima.js new file mode 100644 index 00000000000000..2d7fc11cc3cfd2 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/esprima.js @@ -0,0 +1,5321 @@ +/* + Copyright (C) 2013 Ariya Hidayat + Copyright (C) 2013 Thaddee Tyl + Copyright (C) 2013 Mathias Bynens + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Mathias Bynens + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Kris Kowal + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +(function (root, factory) { + 'use strict'; + + // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, + // Rhino, and plain browser loading. + + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define(['exports'], factory); + } else if (typeof exports !== 'undefined') { + factory(exports); + } else { + factory((root.esprima = {})); + } +}(this, function (exports) { + 'use strict'; + + var Token, + TokenName, + FnExprTokens, + Syntax, + PlaceHolders, + Messages, + Regex, + source, + strict, + sourceType, + index, + lineNumber, + lineStart, + hasLineTerminator, + lastIndex, + lastLineNumber, + lastLineStart, + startIndex, + startLineNumber, + startLineStart, + scanning, + length, + lookahead, + state, + extra, + isBindingElement, + isAssignmentTarget, + firstCoverInitializedNameError; + + Token = { + BooleanLiteral: 1, + EOF: 2, + Identifier: 3, + Keyword: 4, + NullLiteral: 5, + NumericLiteral: 6, + Punctuator: 7, + StringLiteral: 8, + RegularExpression: 9, + Template: 10 + }; + + TokenName = {}; + TokenName[Token.BooleanLiteral] = 'Boolean'; + TokenName[Token.EOF] = ''; + TokenName[Token.Identifier] = 'Identifier'; + TokenName[Token.Keyword] = 'Keyword'; + TokenName[Token.NullLiteral] = 'Null'; + TokenName[Token.NumericLiteral] = 'Numeric'; + TokenName[Token.Punctuator] = 'Punctuator'; + TokenName[Token.StringLiteral] = 'String'; + TokenName[Token.RegularExpression] = 'RegularExpression'; + TokenName[Token.Template] = 'Template'; + + // A function following one of those tokens is an expression. + FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', + 'return', 'case', 'delete', 'throw', 'void', + // assignment operators + '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', + '&=', '|=', '^=', ',', + // binary/unary operators + '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', + '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', + '<=', '<', '>', '!=', '!==']; + + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement' + }; + + PlaceHolders = { + ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder' + }; + + // Error messages should be identical to V8. + Messages = { + UnexpectedToken: 'Unexpected token %0', + UnexpectedNumber: 'Unexpected number', + UnexpectedString: 'Unexpected string', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedTemplate: 'Unexpected quasi %0', + UnexpectedEOS: 'Unexpected end of input', + NewlineAfterThrow: 'Illegal newline after throw', + InvalidRegExp: 'Invalid regular expression', + UnterminatedRegExp: 'Invalid regular expression: missing /', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NoCatchOrFinally: 'Missing catch or finally after try', + UnknownLabel: 'Undefined label \'%0\'', + Redeclaration: '%0 \'%1\' has already been declared', + IllegalContinue: 'Illegal continue statement', + IllegalBreak: 'Illegal break statement', + IllegalReturn: 'Illegal return statement', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode', + TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', + ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', + DefaultRestParameter: 'Unexpected token =', + ObjectPatternAsRestParameter: 'Unexpected token {', + DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', + ConstructorSpecialMethod: 'Class constructor may not be an accessor', + DuplicateConstructor: 'A class may only have one constructor', + StaticPrototype: 'Classes may not have static property named prototype', + MissingFromClause: 'Unexpected token', + NoAsAfterImportNamespace: 'Unexpected token', + InvalidModuleSpecifier: 'Unexpected token', + IllegalImportDeclaration: 'Unexpected token', + IllegalExportDeclaration: 'Unexpected token' + }; + + // See also tools/generate-unicode-regex.py. + Regex = { + NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), + NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') + }; + + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + + function isDecimalDigit(ch) { + return (ch >= 0x30 && ch <= 0x39); // 0..9 + } + + function isHexDigit(ch) { + return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; + } + + function isOctalDigit(ch) { + return '01234567'.indexOf(ch) >= 0; + } + + function octalToDecimal(ch) { + // \0 is not octal escape sequence + var octal = (ch !== '0'), code = '01234567'.indexOf(ch); + + if (index < length && isOctalDigit(source[index])) { + octal = true; + code = code * 8 + '01234567'.indexOf(source[index++]); + + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && + index < length && + isOctalDigit(source[index])) { + code = code * 8 + '01234567'.indexOf(source[index++]); + } + } + + return { + code: code, + octal: octal + }; + } + + // 7.2 White Space + + function isWhiteSpace(ch) { + return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || + (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); + } + + // 7.3 Line Terminators + + function isLineTerminator(ch) { + return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); + } + + // 7.6 Identifier Names and Identifiers + + function isIdentifierStart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); + } + + function isIdentifierPart(ch) { + return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) + (ch >= 0x41 && ch <= 0x5A) || // A..Z + (ch >= 0x61 && ch <= 0x7A) || // a..z + (ch >= 0x30 && ch <= 0x39) || // 0..9 + (ch === 0x5C) || // \ (backslash) + ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } + + // 7.6.1.2 Future Reserved Words + + function isFutureReservedWord(id) { + switch (id) { + case 'enum': + case 'export': + case 'import': + case 'super': + return true; + default: + return false; + } + } + + // 11.6.2.2 Future Reserved Words + + function isStrictModeReservedWord(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + default: + return false; + } + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + // 7.6.1.1 Keywords + + function isKeyword(id) { + + // 'const' is specialized as Keyword in V8. + // 'yield' and 'let' are for compatibility with SpiderMonkey and ES.next. + // Some others are from future reserved words. + + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + } + + // 7.4 Comments + + function addComment(type, value, start, end, loc) { + var comment; + + assert(typeof start === 'number', 'Comment must have valid position'); + + state.lastCommentStart = start; + + comment = { + type: type, + value: value + }; + if (extra.range) { + comment.range = [start, end]; + } + if (extra.loc) { + comment.loc = loc; + } + extra.comments.push(comment); + if (extra.attachComment) { + extra.leadingComments.push(comment); + extra.trailingComments.push(comment); + } + } + + function skipSingleLineComment(offset) { + var start, loc, ch, comment; + + start = index - offset; + loc = { + start: { + line: lineNumber, + column: index - lineStart - offset + } + }; + + while (index < length) { + ch = source.charCodeAt(index); + ++index; + if (isLineTerminator(ch)) { + hasLineTerminator = true; + if (extra.comments) { + comment = source.slice(start + offset, index - 1); + loc.end = { + line: lineNumber, + column: index - lineStart - 1 + }; + addComment('Line', comment, start, index - 1, loc); + } + if (ch === 13 && source.charCodeAt(index) === 10) { + ++index; + } + ++lineNumber; + lineStart = index; + return; + } + } + + if (extra.comments) { + comment = source.slice(start + offset, index); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Line', comment, start, index, loc); + } + } + + function skipMultiLineComment() { + var start, loc, ch, comment; + + if (extra.comments) { + start = index - 2; + loc = { + start: { + line: lineNumber, + column: index - lineStart - 2 + } + }; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (isLineTerminator(ch)) { + if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { + ++index; + } + hasLineTerminator = true; + ++lineNumber; + ++index; + lineStart = index; + } else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (source.charCodeAt(index + 1) === 0x2F) { + ++index; + ++index; + if (extra.comments) { + comment = source.slice(start + 2, index - 2); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + addComment('Block', comment, start, index, loc); + } + return; + } + ++index; + } else { + ++index; + } + } + + // Ran off the end of the file - the whole thing is a comment + if (extra.comments) { + loc.end = { + line: lineNumber, + column: index - lineStart + }; + comment = source.slice(start + 2, index); + addComment('Block', comment, start, index, loc); + } + tolerateUnexpectedToken(); + } + + function skipComment() { + var ch, start; + hasLineTerminator = false; + + start = (index === 0); + while (index < length) { + ch = source.charCodeAt(index); + + if (isWhiteSpace(ch)) { + ++index; + } else if (isLineTerminator(ch)) { + hasLineTerminator = true; + ++index; + if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { + ++index; + } + ++lineNumber; + lineStart = index; + start = true; + } else if (ch === 0x2F) { // U+002F is '/' + ch = source.charCodeAt(index + 1); + if (ch === 0x2F) { + ++index; + ++index; + skipSingleLineComment(2); + start = true; + } else if (ch === 0x2A) { // U+002A is '*' + ++index; + ++index; + skipMultiLineComment(); + } else { + break; + } + } else if (start && ch === 0x2D) { // U+002D is '-' + // U+003E is '>' + if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { + // '-->' is a single-line comment + index += 3; + skipSingleLineComment(3); + } else { + break; + } + } else if (ch === 0x3C) { // U+003C is '<' + if (source.slice(index + 1, index + 4) === '!--') { + ++index; // `<` + ++index; // `!` + ++index; // `-` + ++index; // `-` + skipSingleLineComment(4); + } else { + break; + } + } else { + break; + } + } + } + + function scanHexEscape(prefix) { + var i, len, ch, code = 0; + + len = (prefix === 'u') ? 4 : 2; + for (i = 0; i < len; ++i) { + if (index < length && isHexDigit(source[index])) { + ch = source[index++]; + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } else { + return ''; + } + } + return String.fromCharCode(code); + } + + function scanUnicodeCodePointEscape() { + var ch, code, cu1, cu2; + + ch = source[index]; + code = 0; + + // At least, one hex digit is required. + if (ch === '}') { + throwUnexpectedToken(); + } + + while (index < length) { + ch = source[index++]; + if (!isHexDigit(ch)) { + break; + } + code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + + if (code > 0x10FFFF || ch !== '}') { + throwUnexpectedToken(); + } + + // UTF-16 Encoding + if (code <= 0xFFFF) { + return String.fromCharCode(code); + } + cu1 = ((code - 0x10000) >> 10) + 0xD800; + cu2 = ((code - 0x10000) & 1023) + 0xDC00; + return String.fromCharCode(cu1, cu2); + } + + function getEscapedIdentifier() { + var ch, id; + + ch = source.charCodeAt(index++); + id = String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + if (source.charCodeAt(index) !== 0x75) { + throwUnexpectedToken(); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { + throwUnexpectedToken(); + } + id = ch; + } + + while (index < length) { + ch = source.charCodeAt(index); + if (!isIdentifierPart(ch)) { + break; + } + ++index; + id += String.fromCharCode(ch); + + // '\u' (U+005C, U+0075) denotes an escaped character. + if (ch === 0x5C) { + id = id.substr(0, id.length - 1); + if (source.charCodeAt(index) !== 0x75) { + throwUnexpectedToken(); + } + ++index; + ch = scanHexEscape('u'); + if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { + throwUnexpectedToken(); + } + id += ch; + } + } + + return id; + } + + function getIdentifier() { + var start, ch; + + start = index++; + while (index < length) { + ch = source.charCodeAt(index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + index = start; + return getEscapedIdentifier(); + } + if (isIdentifierPart(ch)) { + ++index; + } else { + break; + } + } + + return source.slice(start, index); + } + + function scanIdentifier() { + var start, id, type; + + start = index; + + // Backslash (U+005C) starts an escaped character. + id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); + + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = Token.Identifier; + } else if (isKeyword(id)) { + type = Token.Keyword; + } else if (id === 'null') { + type = Token.NullLiteral; + } else if (id === 'true' || id === 'false') { + type = Token.BooleanLiteral; + } else { + type = Token.Identifier; + } + + return { + type: type, + value: id, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + + // 7.7 Punctuators + + function scanPunctuator() { + var token, str; + + token = { + type: Token.Punctuator, + value: '', + lineNumber: lineNumber, + lineStart: lineStart, + start: index, + end: index + }; + + // Check for most common single-character punctuators. + str = source[index]; + switch (str) { + + case '(': + if (extra.tokenize) { + extra.openParenToken = extra.tokens.length; + } + ++index; + break; + + case '{': + if (extra.tokenize) { + extra.openCurlyToken = extra.tokens.length; + } + state.curlyStack.push('{'); + ++index; + break; + + case '.': + ++index; + if (source[index] === '.' && source[index + 1] === '.') { + // Spread operator: ... + index += 2; + str = '...'; + } + break; + + case '}': + ++index; + state.curlyStack.pop(); + break; + case ')': + case ';': + case ',': + case '[': + case ']': + case ':': + case '?': + case '~': + ++index; + break; + + default: + // 4-character punctuator. + str = source.substr(index, 4); + if (str === '>>>=') { + index += 4; + } else { + + // 3-character punctuators. + str = str.substr(0, 3); + if (str === '===' || str === '!==' || str === '>>>' || + str === '<<=' || str === '>>=') { + index += 3; + } else { + + // 2-character punctuators. + str = str.substr(0, 2); + if (str === '&&' || str === '||' || str === '==' || str === '!=' || + str === '+=' || str === '-=' || str === '*=' || str === '/=' || + str === '++' || str === '--' || str === '<<' || str === '>>' || + str === '&=' || str === '|=' || str === '^=' || str === '%=' || + str === '<=' || str === '>=' || str === '=>') { + index += 2; + } else { + + // 1-character punctuators. + str = source[index]; + if ('<>=!+-*%&|^/'.indexOf(str) >= 0) { + ++index; + } + } + } + } + } + + if (index === token.start) { + throwUnexpectedToken(); + } + + token.end = index; + token.value = str; + return token; + } + + // 7.8.3 Numeric Literals + + function scanHexLiteral(start) { + var number = ''; + + while (index < length) { + if (!isHexDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + throwUnexpectedToken(); + } + + if (isIdentifierStart(source.charCodeAt(index))) { + throwUnexpectedToken(); + } + + return { + type: Token.NumericLiteral, + value: parseInt('0x' + number, 16), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function scanBinaryLiteral(start) { + var ch, number; + + number = ''; + + while (index < length) { + ch = source[index]; + if (ch !== '0' && ch !== '1') { + break; + } + number += source[index++]; + } + + if (number.length === 0) { + // only 0b or 0B + throwUnexpectedToken(); + } + + if (index < length) { + ch = source.charCodeAt(index); + /* istanbul ignore else */ + if (isIdentifierStart(ch) || isDecimalDigit(ch)) { + throwUnexpectedToken(); + } + } + + return { + type: Token.NumericLiteral, + value: parseInt(number, 2), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function scanOctalLiteral(prefix, start) { + var number, octal; + + if (isOctalDigit(prefix)) { + octal = true; + number = '0' + source[index++]; + } else { + octal = false; + ++index; + number = ''; + } + + while (index < length) { + if (!isOctalDigit(source[index])) { + break; + } + number += source[index++]; + } + + if (!octal && number.length === 0) { + // only 0o or 0O + throwUnexpectedToken(); + } + + if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { + throwUnexpectedToken(); + } + + return { + type: Token.NumericLiteral, + value: parseInt(number, 8), + octal: octal, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function isImplicitOctalLiteral() { + var i, ch; + + // Implicit octal, unless there is a non-octal digit. + // (Annex B.1.1 on Numeric Literals) + for (i = index + 1; i < length; ++i) { + ch = source[i]; + if (ch === '8' || ch === '9') { + return false; + } + if (!isOctalDigit(ch)) { + return true; + } + } + + return true; + } + + function scanNumericLiteral() { + var number, start, ch; + + ch = source[index]; + assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), + 'Numeric literal must start with a decimal digit or a decimal point'); + + start = index; + number = ''; + if (ch !== '.') { + number = source[index++]; + ch = source[index]; + + // Hex number starts with '0x'. + // Octal number starts with '0'. + // Octal number in ES6 starts with '0o'. + // Binary number in ES6 starts with '0b'. + if (number === '0') { + if (ch === 'x' || ch === 'X') { + ++index; + return scanHexLiteral(start); + } + if (ch === 'b' || ch === 'B') { + ++index; + return scanBinaryLiteral(start); + } + if (ch === 'o' || ch === 'O') { + return scanOctalLiteral(ch, start); + } + + if (isOctalDigit(ch)) { + if (isImplicitOctalLiteral()) { + return scanOctalLiteral(ch, start); + } + } + } + + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === '.') { + number += source[index++]; + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + ch = source[index]; + } + + if (ch === 'e' || ch === 'E') { + number += source[index++]; + + ch = source[index]; + if (ch === '+' || ch === '-') { + number += source[index++]; + } + if (isDecimalDigit(source.charCodeAt(index))) { + while (isDecimalDigit(source.charCodeAt(index))) { + number += source[index++]; + } + } else { + throwUnexpectedToken(); + } + } + + if (isIdentifierStart(source.charCodeAt(index))) { + throwUnexpectedToken(); + } + + return { + type: Token.NumericLiteral, + value: parseFloat(number), + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + // 7.8.4 String Literals + + function scanStringLiteral() { + var str = '', quote, start, ch, unescaped, octToDec, octal = false; + + quote = source[index]; + assert((quote === '\'' || quote === '"'), + 'String literal must starts with a quote'); + + start = index; + ++index; + + while (index < length) { + ch = source[index++]; + + if (ch === quote) { + quote = ''; + break; + } else if (ch === '\\') { + ch = source[index++]; + if (!ch || !isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'u': + case 'x': + if (source[index] === '{') { + ++index; + str += scanUnicodeCodePointEscape(); + } else { + unescaped = scanHexEscape(ch); + if (!unescaped) { + throw throwUnexpectedToken(); + } + str += unescaped; + } + break; + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\x0B'; + break; + case '8': + case '9': + throw throwUnexpectedToken(); + + default: + if (isOctalDigit(ch)) { + octToDec = octalToDecimal(ch); + + octal = octToDec.octal || octal; + str += String.fromCharCode(octToDec.code); + } else { + str += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + } + } else if (isLineTerminator(ch.charCodeAt(0))) { + break; + } else { + str += ch; + } + } + + if (quote !== '') { + throwUnexpectedToken(); + } + + return { + type: Token.StringLiteral, + value: str, + octal: octal, + lineNumber: startLineNumber, + lineStart: startLineStart, + start: start, + end: index + }; + } + + function scanTemplate() { + var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped; + + terminated = false; + tail = false; + start = index; + head = (source[index] === '`'); + rawOffset = 2; + + ++index; + + while (index < length) { + ch = source[index++]; + if (ch === '`') { + rawOffset = 1; + tail = true; + terminated = true; + break; + } else if (ch === '$') { + if (source[index] === '{') { + state.curlyStack.push('${'); + ++index; + terminated = true; + break; + } + cooked += ch; + } else if (ch === '\\') { + ch = source[index++]; + if (!isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'n': + cooked += '\n'; + break; + case 'r': + cooked += '\r'; + break; + case 't': + cooked += '\t'; + break; + case 'u': + case 'x': + if (source[index] === '{') { + ++index; + cooked += scanUnicodeCodePointEscape(); + } else { + restore = index; + unescaped = scanHexEscape(ch); + if (unescaped) { + cooked += unescaped; + } else { + index = restore; + cooked += ch; + } + } + break; + case 'b': + cooked += '\b'; + break; + case 'f': + cooked += '\f'; + break; + case 'v': + cooked += '\v'; + break; + + default: + if (ch === '0') { + if (isDecimalDigit(source.charCodeAt(index))) { + // Illegal: \01 \02 and so on + throwError(Messages.TemplateOctalLiteral); + } + cooked += '\0'; + } else if (isOctalDigit(ch)) { + // Illegal: \1 \2 + throwError(Messages.TemplateOctalLiteral); + } else { + cooked += ch; + } + break; + } + } else { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + } + } else if (isLineTerminator(ch.charCodeAt(0))) { + ++lineNumber; + if (ch === '\r' && source[index] === '\n') { + ++index; + } + lineStart = index; + cooked += '\n'; + } else { + cooked += ch; + } + } + + if (!terminated) { + throwUnexpectedToken(); + } + + if (!head) { + state.curlyStack.pop(); + } + + return { + type: Token.Template, + value: { + cooked: cooked, + raw: source.slice(start + 1, index - rawOffset) + }, + head: head, + tail: tail, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + function testRegExp(pattern, flags) { + var tmp = pattern; + + if (flags.indexOf('u') >= 0) { + // Replace each astral symbol and every Unicode escape sequence + // that possibly represents an astral symbol or a paired surrogate + // with a single ASCII symbol to avoid throwing on regular + // expressions that are only valid in combination with the `/u` + // flag. + // Note: replacing with the ASCII symbol `x` might cause false + // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a + // perfectly valid pattern that is equivalent to `[a-b]`, but it + // would be replaced by `[x-b]` which throws an error. + tmp = tmp + .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { + if (parseInt($1, 16) <= 0x10FFFF) { + return 'x'; + } + throwUnexpectedToken(null, Messages.InvalidRegExp); + }) + .replace( + /\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, + 'x' + ); + } + + // First, detect invalid regular expressions. + try { + RegExp(tmp); + } catch (e) { + throwUnexpectedToken(null, Messages.InvalidRegExp); + } + + // Return a regular expression object for this pattern-flag pair, or + // `null` in case the current environment doesn't support the flags it + // uses. + try { + return new RegExp(pattern, flags); + } catch (exception) { + return null; + } + } + + function scanRegExpBody() { + var ch, str, classMarker, terminated, body; + + ch = source[index]; + assert(ch === '/', 'Regular expression literal must start with a slash'); + str = source[index++]; + + classMarker = false; + terminated = false; + while (index < length) { + ch = source[index++]; + str += ch; + if (ch === '\\') { + ch = source[index++]; + // ECMA-262 7.8.5 + if (isLineTerminator(ch.charCodeAt(0))) { + throwUnexpectedToken(null, Messages.UnterminatedRegExp); + } + str += ch; + } else if (isLineTerminator(ch.charCodeAt(0))) { + throwUnexpectedToken(null, Messages.UnterminatedRegExp); + } else if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } else { + if (ch === '/') { + terminated = true; + break; + } else if (ch === '[') { + classMarker = true; + } + } + } + + if (!terminated) { + throwUnexpectedToken(null, Messages.UnterminatedRegExp); + } + + // Exclude leading and trailing slash. + body = str.substr(1, str.length - 2); + return { + value: body, + literal: str + }; + } + + function scanRegExpFlags() { + var ch, str, flags, restore; + + str = ''; + flags = ''; + while (index < length) { + ch = source[index]; + if (!isIdentifierPart(ch.charCodeAt(0))) { + break; + } + + ++index; + if (ch === '\\' && index < length) { + ch = source[index]; + if (ch === 'u') { + ++index; + restore = index; + ch = scanHexEscape('u'); + if (ch) { + flags += ch; + for (str += '\\u'; restore < index; ++restore) { + str += source[restore]; + } + } else { + index = restore; + flags += 'u'; + str += '\\u'; + } + tolerateUnexpectedToken(); + } else { + str += '\\'; + tolerateUnexpectedToken(); + } + } else { + flags += ch; + str += ch; + } + } + + return { + value: flags, + literal: str + }; + } + + function scanRegExp() { + scanning = true; + var start, body, flags, value; + + lookahead = null; + skipComment(); + start = index; + + body = scanRegExpBody(); + flags = scanRegExpFlags(); + value = testRegExp(body.value, flags.value); + scanning = false; + if (extra.tokenize) { + return { + type: Token.RegularExpression, + value: value, + regex: { + pattern: body.value, + flags: flags.value + }, + lineNumber: lineNumber, + lineStart: lineStart, + start: start, + end: index + }; + } + + return { + literal: body.literal + flags.literal, + value: value, + regex: { + pattern: body.value, + flags: flags.value + }, + start: start, + end: index + }; + } + + function collectRegex() { + var pos, loc, regex, token; + + skipComment(); + + pos = index; + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + regex = scanRegExp(); + + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + /* istanbul ignore next */ + if (!extra.tokenize) { + // Pop the previous token, which is likely '/' or '/=' + if (extra.tokens.length > 0) { + token = extra.tokens[extra.tokens.length - 1]; + if (token.range[0] === pos && token.type === 'Punctuator') { + if (token.value === '/' || token.value === '/=') { + extra.tokens.pop(); + } + } + } + + extra.tokens.push({ + type: 'RegularExpression', + value: regex.literal, + regex: regex.regex, + range: [pos, index], + loc: loc + }); + } + + return regex; + } + + function isIdentifierName(token) { + return token.type === Token.Identifier || + token.type === Token.Keyword || + token.type === Token.BooleanLiteral || + token.type === Token.NullLiteral; + } + + function advanceSlash() { + var prevToken, + checkToken; + // Using the following algorithm: + // https://github.com/mozilla/sweet.js/wiki/design + prevToken = extra.tokens[extra.tokens.length - 1]; + if (!prevToken) { + // Nothing before that: it cannot be a division. + return collectRegex(); + } + if (prevToken.type === 'Punctuator') { + if (prevToken.value === ']') { + return scanPunctuator(); + } + if (prevToken.value === ')') { + checkToken = extra.tokens[extra.openParenToken - 1]; + if (checkToken && + checkToken.type === 'Keyword' && + (checkToken.value === 'if' || + checkToken.value === 'while' || + checkToken.value === 'for' || + checkToken.value === 'with')) { + return collectRegex(); + } + return scanPunctuator(); + } + if (prevToken.value === '}') { + // Dividing a function by anything makes little sense, + // but we have to check for that. + if (extra.tokens[extra.openCurlyToken - 3] && + extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { + // Anonymous function. + checkToken = extra.tokens[extra.openCurlyToken - 4]; + if (!checkToken) { + return scanPunctuator(); + } + } else if (extra.tokens[extra.openCurlyToken - 4] && + extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { + // Named function. + checkToken = extra.tokens[extra.openCurlyToken - 5]; + if (!checkToken) { + return collectRegex(); + } + } else { + return scanPunctuator(); + } + // checkToken determines whether the function is + // a declaration or an expression. + if (FnExprTokens.indexOf(checkToken.value) >= 0) { + // It is an expression. + return scanPunctuator(); + } + // It is a declaration. + return collectRegex(); + } + return collectRegex(); + } + if (prevToken.type === 'Keyword' && prevToken.value !== 'this') { + return collectRegex(); + } + return scanPunctuator(); + } + + function advance() { + var ch, token; + + if (index >= length) { + return { + type: Token.EOF, + lineNumber: lineNumber, + lineStart: lineStart, + start: index, + end: index + }; + } + + ch = source.charCodeAt(index); + + if (isIdentifierStart(ch)) { + token = scanIdentifier(); + if (strict && isStrictModeReservedWord(token.value)) { + token.type = Token.Keyword; + } + return token; + } + + // Very common: ( and ) and ; + if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { + return scanPunctuator(); + } + + // String literal starts with single quote (U+0027) or double quote (U+0022). + if (ch === 0x27 || ch === 0x22) { + return scanStringLiteral(); + } + + // Dot (.) U+002E can also start a floating-point number, hence the need + // to check the next character. + if (ch === 0x2E) { + if (isDecimalDigit(source.charCodeAt(index + 1))) { + return scanNumericLiteral(); + } + return scanPunctuator(); + } + + if (isDecimalDigit(ch)) { + return scanNumericLiteral(); + } + + // Slash (/) U+002F can also start a regex. + if (extra.tokenize && ch === 0x2F) { + return advanceSlash(); + } + + // Template literals start with ` (U+0060) for template head + // or } (U+007D) for template middle or template tail. + if (ch === 0x60 || (ch === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) { + return scanTemplate(); + } + + return scanPunctuator(); + } + + function collectToken() { + var loc, token, value, entry; + + loc = { + start: { + line: lineNumber, + column: index - lineStart + } + }; + + token = advance(); + loc.end = { + line: lineNumber, + column: index - lineStart + }; + + if (token.type !== Token.EOF) { + value = source.slice(token.start, token.end); + entry = { + type: TokenName[token.type], + value: value, + range: [token.start, token.end], + loc: loc + }; + if (token.regex) { + entry.regex = { + pattern: token.regex.pattern, + flags: token.regex.flags + }; + } + extra.tokens.push(entry); + } + + return token; + } + + function lex() { + var token; + scanning = true; + + lastIndex = index; + lastLineNumber = lineNumber; + lastLineStart = lineStart; + + skipComment(); + + token = lookahead; + + startIndex = index; + startLineNumber = lineNumber; + startLineStart = lineStart; + + lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + scanning = false; + return token; + } + + function peek() { + scanning = true; + + skipComment(); + + lastIndex = index; + lastLineNumber = lineNumber; + lastLineStart = lineStart; + + startIndex = index; + startLineNumber = lineNumber; + startLineStart = lineStart; + + lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); + scanning = false; + } + + function Position() { + this.line = startLineNumber; + this.column = startIndex - startLineStart; + } + + function SourceLocation() { + this.start = new Position(); + this.end = null; + } + + function WrappingSourceLocation(startToken) { + this.start = { + line: startToken.lineNumber, + column: startToken.start - startToken.lineStart + }; + this.end = null; + } + + function Node() { + if (extra.range) { + this.range = [startIndex, 0]; + } + if (extra.loc) { + this.loc = new SourceLocation(); + } + } + + function WrappingNode(startToken) { + if (extra.range) { + this.range = [startToken.start, 0]; + } + if (extra.loc) { + this.loc = new WrappingSourceLocation(startToken); + } + } + + WrappingNode.prototype = Node.prototype = { + + processComment: function () { + var lastChild, + leadingComments, + trailingComments, + bottomRight = extra.bottomRightStack, + i, + comment, + last = bottomRight[bottomRight.length - 1]; + + if (this.type === Syntax.Program) { + if (this.body.length > 0) { + return; + } + } + + if (extra.trailingComments.length > 0) { + trailingComments = []; + for (i = extra.trailingComments.length - 1; i >= 0; --i) { + comment = extra.trailingComments[i]; + if (comment.range[0] >= this.range[1]) { + trailingComments.unshift(comment); + extra.trailingComments.splice(i, 1); + } + } + extra.trailingComments = []; + } else { + if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) { + trailingComments = last.trailingComments; + delete last.trailingComments; + } + } + + // Eating the stack. + if (last) { + while (last && last.range[0] >= this.range[0]) { + lastChild = last; + last = bottomRight.pop(); + } + } + + if (lastChild) { + if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= this.range[0]) { + this.leadingComments = lastChild.leadingComments; + lastChild.leadingComments = undefined; + } + } else if (extra.leadingComments.length > 0) { + leadingComments = []; + for (i = extra.leadingComments.length - 1; i >= 0; --i) { + comment = extra.leadingComments[i]; + if (comment.range[1] <= this.range[0]) { + leadingComments.unshift(comment); + extra.leadingComments.splice(i, 1); + } + } + } + + + if (leadingComments && leadingComments.length > 0) { + this.leadingComments = leadingComments; + } + if (trailingComments && trailingComments.length > 0) { + this.trailingComments = trailingComments; + } + + bottomRight.push(this); + }, + + finish: function () { + if (extra.range) { + this.range[1] = lastIndex; + } + if (extra.loc) { + this.loc.end = { + line: lastLineNumber, + column: lastIndex - lastLineStart + }; + if (extra.source) { + this.loc.source = extra.source; + } + } + + if (extra.attachComment) { + this.processComment(); + } + }, + + finishArrayExpression: function (elements) { + this.type = Syntax.ArrayExpression; + this.elements = elements; + this.finish(); + return this; + }, + + finishArrayPattern: function (elements) { + this.type = Syntax.ArrayPattern; + this.elements = elements; + this.finish(); + return this; + }, + + finishArrowFunctionExpression: function (params, defaults, body, expression) { + this.type = Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.defaults = defaults; + this.body = body; + this.generator = false; + this.expression = expression; + this.finish(); + return this; + }, + + finishAssignmentExpression: function (operator, left, right) { + this.type = Syntax.AssignmentExpression; + this.operator = operator; + this.left = left; + this.right = right; + this.finish(); + return this; + }, + + finishAssignmentPattern: function (left, right) { + this.type = Syntax.AssignmentPattern; + this.left = left; + this.right = right; + this.finish(); + return this; + }, + + finishBinaryExpression: function (operator, left, right) { + this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; + this.operator = operator; + this.left = left; + this.right = right; + this.finish(); + return this; + }, + + finishBlockStatement: function (body) { + this.type = Syntax.BlockStatement; + this.body = body; + this.finish(); + return this; + }, + + finishBreakStatement: function (label) { + this.type = Syntax.BreakStatement; + this.label = label; + this.finish(); + return this; + }, + + finishCallExpression: function (callee, args) { + this.type = Syntax.CallExpression; + this.callee = callee; + this.arguments = args; + this.finish(); + return this; + }, + + finishCatchClause: function (param, body) { + this.type = Syntax.CatchClause; + this.param = param; + this.body = body; + this.finish(); + return this; + }, + + finishClassBody: function (body) { + this.type = Syntax.ClassBody; + this.body = body; + this.finish(); + return this; + }, + + finishClassDeclaration: function (id, superClass, body) { + this.type = Syntax.ClassDeclaration; + this.id = id; + this.superClass = superClass; + this.body = body; + this.finish(); + return this; + }, + + finishClassExpression: function (id, superClass, body) { + this.type = Syntax.ClassExpression; + this.id = id; + this.superClass = superClass; + this.body = body; + this.finish(); + return this; + }, + + finishConditionalExpression: function (test, consequent, alternate) { + this.type = Syntax.ConditionalExpression; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + this.finish(); + return this; + }, + + finishContinueStatement: function (label) { + this.type = Syntax.ContinueStatement; + this.label = label; + this.finish(); + return this; + }, + + finishDebuggerStatement: function () { + this.type = Syntax.DebuggerStatement; + this.finish(); + return this; + }, + + finishDoWhileStatement: function (body, test) { + this.type = Syntax.DoWhileStatement; + this.body = body; + this.test = test; + this.finish(); + return this; + }, + + finishEmptyStatement: function () { + this.type = Syntax.EmptyStatement; + this.finish(); + return this; + }, + + finishExpressionStatement: function (expression) { + this.type = Syntax.ExpressionStatement; + this.expression = expression; + this.finish(); + return this; + }, + + finishForStatement: function (init, test, update, body) { + this.type = Syntax.ForStatement; + this.init = init; + this.test = test; + this.update = update; + this.body = body; + this.finish(); + return this; + }, + + finishForInStatement: function (left, right, body) { + this.type = Syntax.ForInStatement; + this.left = left; + this.right = right; + this.body = body; + this.each = false; + this.finish(); + return this; + }, + + finishFunctionDeclaration: function (id, params, defaults, body) { + this.type = Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.defaults = defaults; + this.body = body; + this.generator = false; + this.expression = false; + this.finish(); + return this; + }, + + finishFunctionExpression: function (id, params, defaults, body) { + this.type = Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.defaults = defaults; + this.body = body; + this.generator = false; + this.expression = false; + this.finish(); + return this; + }, + + finishIdentifier: function (name) { + this.type = Syntax.Identifier; + this.name = name; + this.finish(); + return this; + }, + + finishIfStatement: function (test, consequent, alternate) { + this.type = Syntax.IfStatement; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + this.finish(); + return this; + }, + + finishLabeledStatement: function (label, body) { + this.type = Syntax.LabeledStatement; + this.label = label; + this.body = body; + this.finish(); + return this; + }, + + finishLiteral: function (token) { + this.type = Syntax.Literal; + this.value = token.value; + this.raw = source.slice(token.start, token.end); + if (token.regex) { + this.regex = token.regex; + } + this.finish(); + return this; + }, + + finishMemberExpression: function (accessor, object, property) { + this.type = Syntax.MemberExpression; + this.computed = accessor === '['; + this.object = object; + this.property = property; + this.finish(); + return this; + }, + + finishNewExpression: function (callee, args) { + this.type = Syntax.NewExpression; + this.callee = callee; + this.arguments = args; + this.finish(); + return this; + }, + + finishObjectExpression: function (properties) { + this.type = Syntax.ObjectExpression; + this.properties = properties; + this.finish(); + return this; + }, + + finishObjectPattern: function (properties) { + this.type = Syntax.ObjectPattern; + this.properties = properties; + this.finish(); + return this; + }, + + finishPostfixExpression: function (operator, argument) { + this.type = Syntax.UpdateExpression; + this.operator = operator; + this.argument = argument; + this.prefix = false; + this.finish(); + return this; + }, + + finishProgram: function (body) { + this.type = Syntax.Program; + this.body = body; + if (sourceType === 'module') { + // very restrictive for now + this.sourceType = sourceType; + } + this.finish(); + return this; + }, + + finishProperty: function (kind, key, computed, value, method, shorthand) { + this.type = Syntax.Property; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.method = method; + this.shorthand = shorthand; + this.finish(); + return this; + }, + + finishRestElement: function (argument) { + this.type = Syntax.RestElement; + this.argument = argument; + this.finish(); + return this; + }, + + finishReturnStatement: function (argument) { + this.type = Syntax.ReturnStatement; + this.argument = argument; + this.finish(); + return this; + }, + + finishSequenceExpression: function (expressions) { + this.type = Syntax.SequenceExpression; + this.expressions = expressions; + this.finish(); + return this; + }, + + finishSpreadElement: function (argument) { + this.type = Syntax.SpreadElement; + this.argument = argument; + this.finish(); + return this; + }, + + finishSwitchCase: function (test, consequent) { + this.type = Syntax.SwitchCase; + this.test = test; + this.consequent = consequent; + this.finish(); + return this; + }, + + finishSuper: function () { + this.type = Syntax.Super; + this.finish(); + return this; + }, + + finishSwitchStatement: function (discriminant, cases) { + this.type = Syntax.SwitchStatement; + this.discriminant = discriminant; + this.cases = cases; + this.finish(); + return this; + }, + + finishTaggedTemplateExpression: function (tag, quasi) { + this.type = Syntax.TaggedTemplateExpression; + this.tag = tag; + this.quasi = quasi; + this.finish(); + return this; + }, + + finishTemplateElement: function (value, tail) { + this.type = Syntax.TemplateElement; + this.value = value; + this.tail = tail; + this.finish(); + return this; + }, + + finishTemplateLiteral: function (quasis, expressions) { + this.type = Syntax.TemplateLiteral; + this.quasis = quasis; + this.expressions = expressions; + this.finish(); + return this; + }, + + finishThisExpression: function () { + this.type = Syntax.ThisExpression; + this.finish(); + return this; + }, + + finishThrowStatement: function (argument) { + this.type = Syntax.ThrowStatement; + this.argument = argument; + this.finish(); + return this; + }, + + finishTryStatement: function (block, handler, finalizer) { + this.type = Syntax.TryStatement; + this.block = block; + this.guardedHandlers = []; + this.handlers = handler ? [ handler ] : []; + this.handler = handler; + this.finalizer = finalizer; + this.finish(); + return this; + }, + + finishUnaryExpression: function (operator, argument) { + this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression; + this.operator = operator; + this.argument = argument; + this.prefix = true; + this.finish(); + return this; + }, + + finishVariableDeclaration: function (declarations) { + this.type = Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = 'var'; + this.finish(); + return this; + }, + + finishLexicalDeclaration: function (declarations, kind) { + this.type = Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = kind; + this.finish(); + return this; + }, + + finishVariableDeclarator: function (id, init) { + this.type = Syntax.VariableDeclarator; + this.id = id; + this.init = init; + this.finish(); + return this; + }, + + finishWhileStatement: function (test, body) { + this.type = Syntax.WhileStatement; + this.test = test; + this.body = body; + this.finish(); + return this; + }, + + finishWithStatement: function (object, body) { + this.type = Syntax.WithStatement; + this.object = object; + this.body = body; + this.finish(); + return this; + }, + + finishExportSpecifier: function (local, exported) { + this.type = Syntax.ExportSpecifier; + this.exported = exported || local; + this.local = local; + this.finish(); + return this; + }, + + finishImportDefaultSpecifier: function (local) { + this.type = Syntax.ImportDefaultSpecifier; + this.local = local; + this.finish(); + return this; + }, + + finishImportNamespaceSpecifier: function (local) { + this.type = Syntax.ImportNamespaceSpecifier; + this.local = local; + this.finish(); + return this; + }, + + finishExportNamedDeclaration: function (declaration, specifiers, src) { + this.type = Syntax.ExportNamedDeclaration; + this.declaration = declaration; + this.specifiers = specifiers; + this.source = src; + this.finish(); + return this; + }, + + finishExportDefaultDeclaration: function (declaration) { + this.type = Syntax.ExportDefaultDeclaration; + this.declaration = declaration; + this.finish(); + return this; + }, + + finishExportAllDeclaration: function (src) { + this.type = Syntax.ExportAllDeclaration; + this.source = src; + this.finish(); + return this; + }, + + finishImportSpecifier: function (local, imported) { + this.type = Syntax.ImportSpecifier; + this.local = local || imported; + this.imported = imported; + this.finish(); + return this; + }, + + finishImportDeclaration: function (specifiers, src) { + this.type = Syntax.ImportDeclaration; + this.specifiers = specifiers; + this.source = src; + this.finish(); + return this; + } + }; + + + function recordError(error) { + var e, existing; + + for (e = 0; e < extra.errors.length; e++) { + existing = extra.errors[e]; + // Prevent duplicated error. + /* istanbul ignore next */ + if (existing.index === error.index && existing.message === error.message) { + return; + } + } + + extra.errors.push(error); + } + + function createError(line, pos, description) { + var error = new Error('Line ' + line + ': ' + description); + error.index = pos; + error.lineNumber = line; + error.column = pos - (scanning ? lineStart : lastLineStart) + 1; + error.description = description; + return error; + } + + // Throw an exception + + function throwError(messageFormat) { + var args, msg; + + args = Array.prototype.slice.call(arguments, 1); + msg = messageFormat.replace(/%(\d)/g, + function (whole, idx) { + assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + } + ); + + throw createError(lastLineNumber, lastIndex, msg); + } + + function tolerateError(messageFormat) { + var args, msg, error; + + args = Array.prototype.slice.call(arguments, 1); + /* istanbul ignore next */ + msg = messageFormat.replace(/%(\d)/g, + function (whole, idx) { + assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + } + ); + + error = createError(lineNumber, lastIndex, msg); + if (extra.errors) { + recordError(error); + } else { + throw error; + } + } + + // Throw an exception because of the token. + + function unexpectedTokenError(token, message) { + var value, msg = message || Messages.UnexpectedToken; + + if (token) { + if (!message) { + msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS : + (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier : + (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber : + (token.type === Token.StringLiteral) ? Messages.UnexpectedString : + (token.type === Token.Template) ? Messages.UnexpectedTemplate : + Messages.UnexpectedToken; + + if (token.type === Token.Keyword) { + if (isFutureReservedWord(token.value)) { + msg = Messages.UnexpectedReserved; + } else if (strict && isStrictModeReservedWord(token.value)) { + msg = Messages.StrictReservedWord; + } + } + } + + value = (token.type === Token.Template) ? token.value.raw : token.value; + } else { + value = 'ILLEGAL'; + } + + msg = msg.replace('%0', value); + + return (token && typeof token.lineNumber === 'number') ? + createError(token.lineNumber, token.start, msg) : + createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg); + } + + function throwUnexpectedToken(token, message) { + throw unexpectedTokenError(token, message); + } + + function tolerateUnexpectedToken(token, message) { + var error = unexpectedTokenError(token, message); + if (extra.errors) { + recordError(error); + } else { + throw error; + } + } + + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + + function expect(value) { + var token = lex(); + if (token.type !== Token.Punctuator || token.value !== value) { + throwUnexpectedToken(token); + } + } + + /** + * @name expectCommaSeparator + * @description Quietly expect a comma when in tolerant mode, otherwise delegates + * to expect(value) + * @since 2.0 + */ + function expectCommaSeparator() { + var token; + + if (extra.errors) { + token = lookahead; + if (token.type === Token.Punctuator && token.value === ',') { + lex(); + } else if (token.type === Token.Punctuator && token.value === ';') { + lex(); + tolerateUnexpectedToken(token); + } else { + tolerateUnexpectedToken(token, Messages.UnexpectedToken); + } + } else { + expect(','); + } + } + + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + + function expectKeyword(keyword) { + var token = lex(); + if (token.type !== Token.Keyword || token.value !== keyword) { + throwUnexpectedToken(token); + } + } + + // Return true if the next token matches the specified punctuator. + + function match(value) { + return lookahead.type === Token.Punctuator && lookahead.value === value; + } + + // Return true if the next token matches the specified keyword + + function matchKeyword(keyword) { + return lookahead.type === Token.Keyword && lookahead.value === keyword; + } + + // Return true if the next token matches the specified contextual keyword + // (where an identifier is sometimes a keyword depending on the context) + + function matchContextualKeyword(keyword) { + return lookahead.type === Token.Identifier && lookahead.value === keyword; + } + + // Return true if the next token is an assignment operator + + function matchAssign() { + var op; + + if (lookahead.type !== Token.Punctuator) { + return false; + } + op = lookahead.value; + return op === '=' || + op === '*=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + } + + function consumeSemicolon() { + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(startIndex) === 0x3B || match(';')) { + lex(); + return; + } + + if (hasLineTerminator) { + return; + } + + // FIXME(ikarienator): this is seemingly an issue in the previous location info convention. + lastIndex = startIndex; + lastLineNumber = startLineNumber; + lastLineStart = startLineStart; + + if (lookahead.type !== Token.EOF && !match('}')) { + throwUnexpectedToken(lookahead); + } + } + + // Cover grammar support. + // + // When an assignment expression position starts with an left parenthesis, the determination of the type + // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) + // or the first comma. This situation also defers the determination of all the expressions nested in the pair. + // + // There are three productions that can be parsed in a parentheses pair that needs to be determined + // after the outermost pair is closed. They are: + // + // 1. AssignmentExpression + // 2. BindingElements + // 3. AssignmentTargets + // + // In order to avoid exponential backtracking, we use two flags to denote if the production can be + // binding element or assignment target. + // + // The three productions have the relationship: + // + // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression + // + // with a single exception that CoverInitializedName when used directly in an Expression, generates + // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the + // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. + // + // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not + // effect the current flags. This means the production the parser parses is only used as an expression. Therefore + // the CoverInitializedName check is conducted. + // + // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates + // the flags outside of the parser. This means the production the parser parses is used as a part of a potential + // pattern. The CoverInitializedName check is deferred. + function isolateCoverGrammar(parser) { + var oldIsBindingElement = isBindingElement, + oldIsAssignmentTarget = isAssignmentTarget, + oldFirstCoverInitializedNameError = firstCoverInitializedNameError, + result; + isBindingElement = true; + isAssignmentTarget = true; + firstCoverInitializedNameError = null; + result = parser(); + if (firstCoverInitializedNameError !== null) { + throwUnexpectedToken(firstCoverInitializedNameError); + } + isBindingElement = oldIsBindingElement; + isAssignmentTarget = oldIsAssignmentTarget; + firstCoverInitializedNameError = oldFirstCoverInitializedNameError; + return result; + } + + function inheritCoverGrammar(parser) { + var oldIsBindingElement = isBindingElement, + oldIsAssignmentTarget = isAssignmentTarget, + oldFirstCoverInitializedNameError = firstCoverInitializedNameError, + result; + isBindingElement = true; + isAssignmentTarget = true; + firstCoverInitializedNameError = null; + result = parser(); + isBindingElement = isBindingElement && oldIsBindingElement; + isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget; + firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError; + return result; + } + + function parseArrayPattern() { + var node = new Node(), elements = [], rest, restNode; + expect('['); + + while (!match(']')) { + if (match(',')) { + lex(); + elements.push(null); + } else { + if (match('...')) { + restNode = new Node(); + lex(); + rest = parseVariableIdentifier(); + elements.push(restNode.finishRestElement(rest)); + break; + } else { + elements.push(parsePatternWithDefault()); + } + if (!match(']')) { + expect(','); + } + } + + } + + expect(']'); + + return node.finishArrayPattern(elements); + } + + function parsePropertyPattern() { + var node = new Node(), key, computed = match('['), init; + if (lookahead.type === Token.Identifier) { + key = parseVariableIdentifier(); + if (match('=')) { + lex(); + init = parseAssignmentExpression(); + return node.finishProperty( + 'init', key, false, + new WrappingNode(key).finishAssignmentPattern(key, init), false, false); + } else if (!match(':')) { + return node.finishProperty('init', key, false, key, false, true); + } + } else { + key = parseObjectPropertyKey(); + } + expect(':'); + init = parsePatternWithDefault(); + return node.finishProperty('init', key, computed, init, false, false); + } + + function parseObjectPattern() { + var node = new Node(), properties = []; + + expect('{'); + + while (!match('}')) { + properties.push(parsePropertyPattern()); + if (!match('}')) { + expect(','); + } + } + + lex(); + + return node.finishObjectPattern(properties); + } + + function parsePattern() { + if (lookahead.type === Token.Identifier) { + return parseVariableIdentifier(); + } else if (match('[')) { + return parseArrayPattern(); + } else if (match('{')) { + return parseObjectPattern(); + } + throwUnexpectedToken(lookahead); + } + + function parsePatternWithDefault() { + var startToken = lookahead, pattern, right; + pattern = parsePattern(); + if (match('=')) { + lex(); + right = isolateCoverGrammar(parseAssignmentExpression); + pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right); + } + return pattern; + } + + // 11.1.4 Array Initialiser + + function parseArrayInitialiser() { + var elements = [], node = new Node(), restSpread; + + expect('['); + + while (!match(']')) { + if (match(',')) { + lex(); + elements.push(null); + } else if (match('...')) { + restSpread = new Node(); + lex(); + restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression)); + + if (!match(']')) { + isAssignmentTarget = isBindingElement = false; + expect(','); + } + elements.push(restSpread); + } else { + elements.push(inheritCoverGrammar(parseAssignmentExpression)); + + if (!match(']')) { + expect(','); + } + } + } + + lex(); + + return node.finishArrayExpression(elements); + } + + // 11.1.5 Object Initialiser + + function parsePropertyFunction(node, paramInfo) { + var previousStrict, body; + + isAssignmentTarget = isBindingElement = false; + + previousStrict = strict; + body = isolateCoverGrammar(parseFunctionSourceElements); + + if (strict && paramInfo.firstRestricted) { + tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message); + } + if (strict && paramInfo.stricted) { + tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message); + } + + strict = previousStrict; + return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body); + } + + function parsePropertyMethodFunction() { + var params, method, node = new Node(); + + params = parseParams(); + method = parsePropertyFunction(node, params); + + return method; + } + + function parseObjectPropertyKey() { + var token, node = new Node(), expr; + + token = lex(); + + // Note: This function is called only from parseObjectProperty(), where + // EOF and Punctuator tokens are already filtered out. + + switch (token.type) { + case Token.StringLiteral: + case Token.NumericLiteral: + if (strict && token.octal) { + tolerateUnexpectedToken(token, Messages.StrictOctalLiteral); + } + return node.finishLiteral(token); + case Token.Identifier: + case Token.BooleanLiteral: + case Token.NullLiteral: + case Token.Keyword: + return node.finishIdentifier(token.value); + case Token.Punctuator: + if (token.value === '[') { + expr = isolateCoverGrammar(parseAssignmentExpression); + expect(']'); + return expr; + } + break; + } + throwUnexpectedToken(token); + } + + function lookaheadPropertyName() { + switch (lookahead.type) { + case Token.Identifier: + case Token.StringLiteral: + case Token.BooleanLiteral: + case Token.NullLiteral: + case Token.NumericLiteral: + case Token.Keyword: + return true; + case Token.Punctuator: + return lookahead.value === '['; + } + return false; + } + + // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals, + // it might be called at a position where there is in fact a short hand identifier pattern or a data property. + // This can only be determined after we consumed up to the left parentheses. + // + // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller + // is responsible to visit other options. + function tryParseMethodDefinition(token, key, computed, node) { + var value, options, methodNode; + + if (token.type === Token.Identifier) { + // check for `get` and `set`; + + if (token.value === 'get' && lookaheadPropertyName()) { + computed = match('['); + key = parseObjectPropertyKey(); + methodNode = new Node(); + expect('('); + expect(')'); + value = parsePropertyFunction(methodNode, { + params: [], + defaults: [], + stricted: null, + firstRestricted: null, + message: null + }); + return node.finishProperty('get', key, computed, value, false, false); + } else if (token.value === 'set' && lookaheadPropertyName()) { + computed = match('['); + key = parseObjectPropertyKey(); + methodNode = new Node(); + expect('('); + + options = { + params: [], + defaultCount: 0, + defaults: [], + firstRestricted: null, + paramSet: {} + }; + if (match(')')) { + tolerateUnexpectedToken(lookahead); + } else { + parseParam(options); + if (options.defaultCount === 0) { + options.defaults = []; + } + } + expect(')'); + + value = parsePropertyFunction(methodNode, options); + return node.finishProperty('set', key, computed, value, false, false); + } + } + + if (match('(')) { + value = parsePropertyMethodFunction(); + return node.finishProperty('init', key, computed, value, true, false); + } + + // Not a MethodDefinition. + return null; + } + + function checkProto(key, computed, hasProto) { + if (computed === false && (key.type === Syntax.Identifier && key.name === '__proto__' || + key.type === Syntax.Literal && key.value === '__proto__')) { + if (hasProto.value) { + tolerateError(Messages.DuplicateProtoProperty); + } else { + hasProto.value = true; + } + } + } + + function parseObjectProperty(hasProto) { + var token = lookahead, node = new Node(), computed, key, maybeMethod, value; + + computed = match('['); + key = parseObjectPropertyKey(); + maybeMethod = tryParseMethodDefinition(token, key, computed, node); + + if (maybeMethod) { + checkProto(maybeMethod.key, maybeMethod.computed, hasProto); + // finished + return maybeMethod; + } + + // init property or short hand property. + checkProto(key, computed, hasProto); + + if (match(':')) { + lex(); + value = inheritCoverGrammar(parseAssignmentExpression); + return node.finishProperty('init', key, computed, value, false, false); + } + + if (token.type === Token.Identifier) { + if (match('=')) { + firstCoverInitializedNameError = lookahead; + lex(); + value = isolateCoverGrammar(parseAssignmentExpression); + return node.finishProperty('init', key, computed, + new WrappingNode(token).finishAssignmentPattern(key, value), false, true); + } + return node.finishProperty('init', key, computed, key, false, true); + } + + throwUnexpectedToken(lookahead); + } + + function parseObjectInitialiser() { + var properties = [], hasProto = {value: false}, node = new Node(); + + expect('{'); + + while (!match('}')) { + properties.push(parseObjectProperty(hasProto)); + + if (!match('}')) { + expectCommaSeparator(); + } + } + + expect('}'); + + return node.finishObjectExpression(properties); + } + + function reinterpretExpressionAsPattern(expr) { + var i; + switch (expr.type) { + case Syntax.Identifier: + case Syntax.MemberExpression: + case Syntax.RestElement: + case Syntax.AssignmentPattern: + break; + case Syntax.SpreadElement: + expr.type = Syntax.RestElement; + reinterpretExpressionAsPattern(expr.argument); + break; + case Syntax.ArrayExpression: + expr.type = Syntax.ArrayPattern; + for (i = 0; i < expr.elements.length; i++) { + if (expr.elements[i] !== null) { + reinterpretExpressionAsPattern(expr.elements[i]); + } + } + break; + case Syntax.ObjectExpression: + expr.type = Syntax.ObjectPattern; + for (i = 0; i < expr.properties.length; i++) { + reinterpretExpressionAsPattern(expr.properties[i].value); + } + break; + case Syntax.AssignmentExpression: + expr.type = Syntax.AssignmentPattern; + reinterpretExpressionAsPattern(expr.left); + break; + default: + // Allow other node type for tolerant parsing. + break; + } + } + + function parseTemplateElement(option) { + var node, token; + + if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) { + throwUnexpectedToken(); + } + + node = new Node(); + token = lex(); + + return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail); + } + + function parseTemplateLiteral() { + var quasi, quasis, expressions, node = new Node(); + + quasi = parseTemplateElement({ head: true }); + quasis = [ quasi ]; + expressions = []; + + while (!quasi.tail) { + expressions.push(parseExpression()); + quasi = parseTemplateElement({ head: false }); + quasis.push(quasi); + } + + return node.finishTemplateLiteral(quasis, expressions); + } + + // 11.1.6 The Grouping Operator + + function parseGroupExpression() { + var expr, expressions, startToken, i; + + expect('('); + + if (match(')')) { + lex(); + if (!match('=>')) { + expect('=>'); + } + return { + type: PlaceHolders.ArrowParameterPlaceHolder, + params: [] + }; + } + + startToken = lookahead; + if (match('...')) { + expr = parseRestElement(); + expect(')'); + if (!match('=>')) { + expect('=>'); + } + return { + type: PlaceHolders.ArrowParameterPlaceHolder, + params: [expr] + }; + } + + isBindingElement = true; + expr = inheritCoverGrammar(parseAssignmentExpression); + + if (match(',')) { + isAssignmentTarget = false; + expressions = [expr]; + + while (startIndex < length) { + if (!match(',')) { + break; + } + lex(); + + if (match('...')) { + if (!isBindingElement) { + throwUnexpectedToken(lookahead); + } + expressions.push(parseRestElement()); + expect(')'); + if (!match('=>')) { + expect('=>'); + } + isBindingElement = false; + for (i = 0; i < expressions.length; i++) { + reinterpretExpressionAsPattern(expressions[i]); + } + return { + type: PlaceHolders.ArrowParameterPlaceHolder, + params: expressions + }; + } + + expressions.push(inheritCoverGrammar(parseAssignmentExpression)); + } + + expr = new WrappingNode(startToken).finishSequenceExpression(expressions); + } + + + expect(')'); + + if (match('=>')) { + if (!isBindingElement) { + throwUnexpectedToken(lookahead); + } + + if (expr.type === Syntax.SequenceExpression) { + for (i = 0; i < expr.expressions.length; i++) { + reinterpretExpressionAsPattern(expr.expressions[i]); + } + } else { + reinterpretExpressionAsPattern(expr); + } + + expr = { + type: PlaceHolders.ArrowParameterPlaceHolder, + params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr] + }; + } + isBindingElement = false; + return expr; + } + + + // 11.1 Primary Expressions + + function parsePrimaryExpression() { + var type, token, expr, node; + + if (match('(')) { + isBindingElement = false; + return inheritCoverGrammar(parseGroupExpression); + } + + if (match('[')) { + return inheritCoverGrammar(parseArrayInitialiser); + } + + if (match('{')) { + return inheritCoverGrammar(parseObjectInitialiser); + } + + type = lookahead.type; + node = new Node(); + + if (type === Token.Identifier) { + expr = node.finishIdentifier(lex().value); + } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { + isAssignmentTarget = isBindingElement = false; + if (strict && lookahead.octal) { + tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral); + } + expr = node.finishLiteral(lex()); + } else if (type === Token.Keyword) { + isAssignmentTarget = isBindingElement = false; + if (matchKeyword('function')) { + return parseFunctionExpression(); + } + if (matchKeyword('this')) { + lex(); + return node.finishThisExpression(); + } + if (matchKeyword('class')) { + return parseClassExpression(); + } + throwUnexpectedToken(lex()); + } else if (type === Token.BooleanLiteral) { + isAssignmentTarget = isBindingElement = false; + token = lex(); + token.value = (token.value === 'true'); + expr = node.finishLiteral(token); + } else if (type === Token.NullLiteral) { + isAssignmentTarget = isBindingElement = false; + token = lex(); + token.value = null; + expr = node.finishLiteral(token); + } else if (match('/') || match('/=')) { + isAssignmentTarget = isBindingElement = false; + index = startIndex; + + if (typeof extra.tokens !== 'undefined') { + token = collectRegex(); + } else { + token = scanRegExp(); + } + lex(); + expr = node.finishLiteral(token); + } else if (type === Token.Template) { + expr = parseTemplateLiteral(); + } else { + throwUnexpectedToken(lex()); + } + + return expr; + } + + // 11.2 Left-Hand-Side Expressions + + function parseArguments() { + var args = []; + + expect('('); + + if (!match(')')) { + while (startIndex < length) { + args.push(isolateCoverGrammar(parseAssignmentExpression)); + if (match(')')) { + break; + } + expectCommaSeparator(); + } + } + + expect(')'); + + return args; + } + + function parseNonComputedProperty() { + var token, node = new Node(); + + token = lex(); + + if (!isIdentifierName(token)) { + throwUnexpectedToken(token); + } + + return node.finishIdentifier(token.value); + } + + function parseNonComputedMember() { + expect('.'); + + return parseNonComputedProperty(); + } + + function parseComputedMember() { + var expr; + + expect('['); + + expr = isolateCoverGrammar(parseExpression); + + expect(']'); + + return expr; + } + + function parseNewExpression() { + var callee, args, node = new Node(); + + expectKeyword('new'); + callee = isolateCoverGrammar(parseLeftHandSideExpression); + args = match('(') ? parseArguments() : []; + + isAssignmentTarget = isBindingElement = false; + + return node.finishNewExpression(callee, args); + } + + function parseLeftHandSideExpressionAllowCall() { + var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn; + + startToken = lookahead; + state.allowIn = true; + + if (matchKeyword('super') && state.inFunctionBody) { + expr = new Node(); + lex(); + expr = expr.finishSuper(); + if (!match('(') && !match('.') && !match('[')) { + throwUnexpectedToken(lookahead); + } + } else { + expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression); + } + + for (;;) { + if (match('.')) { + isBindingElement = false; + isAssignmentTarget = true; + property = parseNonComputedMember(); + expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); + } else if (match('(')) { + isBindingElement = false; + isAssignmentTarget = false; + args = parseArguments(); + expr = new WrappingNode(startToken).finishCallExpression(expr, args); + } else if (match('[')) { + isBindingElement = false; + isAssignmentTarget = true; + property = parseComputedMember(); + expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); + } else if (lookahead.type === Token.Template && lookahead.head) { + quasi = parseTemplateLiteral(); + expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi); + } else { + break; + } + } + state.allowIn = previousAllowIn; + + return expr; + } + + function parseLeftHandSideExpression() { + var quasi, expr, property, startToken; + assert(state.allowIn, 'callee of new expression always allow in keyword.'); + + startToken = lookahead; + + if (matchKeyword('super') && state.inFunctionBody) { + expr = new Node(); + lex(); + expr = expr.finishSuper(); + if (!match('[') && !match('.')) { + throwUnexpectedToken(lookahead); + } + } else { + expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression); + } + + for (;;) { + if (match('[')) { + isBindingElement = false; + isAssignmentTarget = true; + property = parseComputedMember(); + expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); + } else if (match('.')) { + isBindingElement = false; + isAssignmentTarget = true; + property = parseNonComputedMember(); + expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); + } else if (lookahead.type === Token.Template && lookahead.head) { + quasi = parseTemplateLiteral(); + expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi); + } else { + break; + } + } + return expr; + } + + // 11.3 Postfix Expressions + + function parsePostfixExpression() { + var expr, token, startToken = lookahead; + + expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall); + + if (!hasLineTerminator && lookahead.type === Token.Punctuator) { + if (match('++') || match('--')) { + // 11.3.1, 11.3.2 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + tolerateError(Messages.StrictLHSPostfix); + } + + if (!isAssignmentTarget) { + tolerateError(Messages.InvalidLHSInAssignment); + } + + isAssignmentTarget = isBindingElement = false; + + token = lex(); + expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr); + } + } + + return expr; + } + + // 11.4 Unary Operators + + function parseUnaryExpression() { + var token, expr, startToken; + + if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { + expr = parsePostfixExpression(); + } else if (match('++') || match('--')) { + startToken = lookahead; + token = lex(); + expr = inheritCoverGrammar(parseUnaryExpression); + // 11.4.4, 11.4.5 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + tolerateError(Messages.StrictLHSPrefix); + } + + if (!isAssignmentTarget) { + tolerateError(Messages.InvalidLHSInAssignment); + } + expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); + isAssignmentTarget = isBindingElement = false; + } else if (match('+') || match('-') || match('~') || match('!')) { + startToken = lookahead; + token = lex(); + expr = inheritCoverGrammar(parseUnaryExpression); + expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); + isAssignmentTarget = isBindingElement = false; + } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { + startToken = lookahead; + token = lex(); + expr = inheritCoverGrammar(parseUnaryExpression); + expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); + if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { + tolerateError(Messages.StrictDelete); + } + isAssignmentTarget = isBindingElement = false; + } else { + expr = parsePostfixExpression(); + } + + return expr; + } + + function binaryPrecedence(token, allowIn) { + var prec = 0; + + if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { + return 0; + } + + switch (token.value) { + case '||': + prec = 1; + break; + + case '&&': + prec = 2; + break; + + case '|': + prec = 3; + break; + + case '^': + prec = 4; + break; + + case '&': + prec = 5; + break; + + case '==': + case '!=': + case '===': + case '!==': + prec = 6; + break; + + case '<': + case '>': + case '<=': + case '>=': + case 'instanceof': + prec = 7; + break; + + case 'in': + prec = allowIn ? 7 : 0; + break; + + case '<<': + case '>>': + case '>>>': + prec = 8; + break; + + case '+': + case '-': + prec = 9; + break; + + case '*': + case '/': + case '%': + prec = 11; + break; + + default: + break; + } + + return prec; + } + + // 11.5 Multiplicative Operators + // 11.6 Additive Operators + // 11.7 Bitwise Shift Operators + // 11.8 Relational Operators + // 11.9 Equality Operators + // 11.10 Binary Bitwise Operators + // 11.11 Binary Logical Operators + + function parseBinaryExpression() { + var marker, markers, expr, token, prec, stack, right, operator, left, i; + + marker = lookahead; + left = inheritCoverGrammar(parseUnaryExpression); + + token = lookahead; + prec = binaryPrecedence(token, state.allowIn); + if (prec === 0) { + return left; + } + isAssignmentTarget = isBindingElement = false; + token.prec = prec; + lex(); + + markers = [marker, lookahead]; + right = isolateCoverGrammar(parseUnaryExpression); + + stack = [left, token, right]; + + while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { + + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { + right = stack.pop(); + operator = stack.pop().value; + left = stack.pop(); + markers.pop(); + expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right); + stack.push(expr); + } + + // Shift. + token = lex(); + token.prec = prec; + stack.push(token); + markers.push(lookahead); + expr = isolateCoverGrammar(parseUnaryExpression); + stack.push(expr); + } + + // Final reduce to clean-up the stack. + i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr); + i -= 2; + } + + return expr; + } + + + // 11.12 Conditional Operator + + function parseConditionalExpression() { + var expr, previousAllowIn, consequent, alternate, startToken; + + startToken = lookahead; + + expr = inheritCoverGrammar(parseBinaryExpression); + if (match('?')) { + lex(); + previousAllowIn = state.allowIn; + state.allowIn = true; + consequent = isolateCoverGrammar(parseAssignmentExpression); + state.allowIn = previousAllowIn; + expect(':'); + alternate = isolateCoverGrammar(parseAssignmentExpression); + + expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate); + isAssignmentTarget = isBindingElement = false; + } + + return expr; + } + + // [ES6] 14.2 Arrow Function + + function parseConciseBody() { + if (match('{')) { + return parseFunctionSourceElements(); + } + return isolateCoverGrammar(parseAssignmentExpression); + } + + function checkPatternParam(options, param) { + var i; + switch (param.type) { + case Syntax.Identifier: + validateParam(options, param, param.name); + break; + case Syntax.RestElement: + checkPatternParam(options, param.argument); + break; + case Syntax.AssignmentPattern: + checkPatternParam(options, param.left); + break; + case Syntax.ArrayPattern: + for (i = 0; i < param.elements.length; i++) { + if (param.elements[i] !== null) { + checkPatternParam(options, param.elements[i]); + } + } + break; + default: + assert(param.type === Syntax.ObjectPattern, 'Invalid type'); + for (i = 0; i < param.properties.length; i++) { + checkPatternParam(options, param.properties[i].value); + } + break; + } + } + function reinterpretAsCoverFormalsList(expr) { + var i, len, param, params, defaults, defaultCount, options, token; + + defaults = []; + defaultCount = 0; + params = [expr]; + + switch (expr.type) { + case Syntax.Identifier: + break; + case PlaceHolders.ArrowParameterPlaceHolder: + params = expr.params; + break; + default: + return null; + } + + options = { + paramSet: {} + }; + + for (i = 0, len = params.length; i < len; i += 1) { + param = params[i]; + switch (param.type) { + case Syntax.AssignmentPattern: + params[i] = param.left; + defaults.push(param.right); + ++defaultCount; + checkPatternParam(options, param.left); + break; + default: + checkPatternParam(options, param); + params[i] = param; + defaults.push(null); + break; + } + } + + if (options.message === Messages.StrictParamDupe) { + token = strict ? options.stricted : options.firstRestricted; + throwUnexpectedToken(token, options.message); + } + + if (defaultCount === 0) { + defaults = []; + } + + return { + params: params, + defaults: defaults, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + } + + function parseArrowFunctionExpression(options, node) { + var previousStrict, body; + + if (hasLineTerminator) { + tolerateUnexpectedToken(lookahead); + } + expect('=>'); + previousStrict = strict; + + body = parseConciseBody(); + + if (strict && options.firstRestricted) { + throwUnexpectedToken(options.firstRestricted, options.message); + } + if (strict && options.stricted) { + tolerateUnexpectedToken(options.stricted, options.message); + } + + strict = previousStrict; + + return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement); + } + + // 11.13 Assignment Operators + + function parseAssignmentExpression() { + var token, expr, right, list, startToken; + + startToken = lookahead; + token = lookahead; + + expr = parseConditionalExpression(); + + if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) { + isAssignmentTarget = isBindingElement = false; + list = reinterpretAsCoverFormalsList(expr); + + if (list) { + firstCoverInitializedNameError = null; + return parseArrowFunctionExpression(list, new WrappingNode(startToken)); + } + + return expr; + } + + if (matchAssign()) { + if (!isAssignmentTarget) { + tolerateError(Messages.InvalidLHSInAssignment); + } + + // 11.13.1 + if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { + tolerateUnexpectedToken(token, Messages.StrictLHSAssignment); + } + + if (!match('=')) { + isAssignmentTarget = isBindingElement = false; + } else { + reinterpretExpressionAsPattern(expr); + } + + token = lex(); + right = isolateCoverGrammar(parseAssignmentExpression); + expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right); + firstCoverInitializedNameError = null; + } + + return expr; + } + + // 11.14 Comma Operator + + function parseExpression() { + var expr, startToken = lookahead, expressions; + + expr = isolateCoverGrammar(parseAssignmentExpression); + + if (match(',')) { + expressions = [expr]; + + while (startIndex < length) { + if (!match(',')) { + break; + } + lex(); + expressions.push(isolateCoverGrammar(parseAssignmentExpression)); + } + + expr = new WrappingNode(startToken).finishSequenceExpression(expressions); + } + + return expr; + } + + // 12.1 Block + + function parseStatementListItem() { + if (lookahead.type === Token.Keyword) { + switch (lookahead.value) { + case 'export': + if (sourceType !== 'module') { + tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration); + } + return parseExportDeclaration(); + case 'import': + if (sourceType !== 'module') { + tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration); + } + return parseImportDeclaration(); + case 'const': + case 'let': + return parseLexicalDeclaration({inFor: false}); + case 'function': + return parseFunctionDeclaration(new Node()); + case 'class': + return parseClassDeclaration(); + } + } + + return parseStatement(); + } + + function parseStatementList() { + var list = []; + while (startIndex < length) { + if (match('}')) { + break; + } + list.push(parseStatementListItem()); + } + + return list; + } + + function parseBlock() { + var block, node = new Node(); + + expect('{'); + + block = parseStatementList(); + + expect('}'); + + return node.finishBlockStatement(block); + } + + // 12.2 Variable Statement + + function parseVariableIdentifier() { + var token, node = new Node(); + + token = lex(); + + if (token.type !== Token.Identifier) { + if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) { + tolerateUnexpectedToken(token, Messages.StrictReservedWord); + } else { + throwUnexpectedToken(token); + } + } + + return node.finishIdentifier(token.value); + } + + function parseVariableDeclaration() { + var init = null, id, node = new Node(); + + id = parsePattern(); + + // 12.2.1 + if (strict && isRestrictedWord(id.name)) { + tolerateError(Messages.StrictVarName); + } + + if (match('=')) { + lex(); + init = isolateCoverGrammar(parseAssignmentExpression); + } else if (id.type !== Syntax.Identifier) { + expect('='); + } + + return node.finishVariableDeclarator(id, init); + } + + function parseVariableDeclarationList() { + var list = []; + + do { + list.push(parseVariableDeclaration()); + if (!match(',')) { + break; + } + lex(); + } while (startIndex < length); + + return list; + } + + function parseVariableStatement(node) { + var declarations; + + expectKeyword('var'); + + declarations = parseVariableDeclarationList(); + + consumeSemicolon(); + + return node.finishVariableDeclaration(declarations); + } + + function parseLexicalBinding(kind, options) { + var init = null, id, node = new Node(); + + id = parsePattern(); + + // 12.2.1 + if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) { + tolerateError(Messages.StrictVarName); + } + + if (kind === 'const') { + if (!matchKeyword('in')) { + expect('='); + init = isolateCoverGrammar(parseAssignmentExpression); + } + } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) { + expect('='); + init = isolateCoverGrammar(parseAssignmentExpression); + } + + return node.finishVariableDeclarator(id, init); + } + + function parseBindingList(kind, options) { + var list = []; + + do { + list.push(parseLexicalBinding(kind, options)); + if (!match(',')) { + break; + } + lex(); + } while (startIndex < length); + + return list; + } + + function parseLexicalDeclaration(options) { + var kind, declarations, node = new Node(); + + kind = lex().value; + assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); + + declarations = parseBindingList(kind, options); + + consumeSemicolon(); + + return node.finishLexicalDeclaration(declarations, kind); + } + + function parseRestElement() { + var param, node = new Node(); + + lex(); + + if (match('{')) { + throwError(Messages.ObjectPatternAsRestParameter); + } + + param = parseVariableIdentifier(); + + if (match('=')) { + throwError(Messages.DefaultRestParameter); + } + + if (!match(')')) { + throwError(Messages.ParameterAfterRestParameter); + } + + return node.finishRestElement(param); + } + + // 12.3 Empty Statement + + function parseEmptyStatement(node) { + expect(';'); + return node.finishEmptyStatement(); + } + + // 12.4 Expression Statement + + function parseExpressionStatement(node) { + var expr = parseExpression(); + consumeSemicolon(); + return node.finishExpressionStatement(expr); + } + + // 12.5 If statement + + function parseIfStatement(node) { + var test, consequent, alternate; + + expectKeyword('if'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + consequent = parseStatement(); + + if (matchKeyword('else')) { + lex(); + alternate = parseStatement(); + } else { + alternate = null; + } + + return node.finishIfStatement(test, consequent, alternate); + } + + // 12.6 Iteration Statements + + function parseDoWhileStatement(node) { + var body, test, oldInIteration; + + expectKeyword('do'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + if (match(';')) { + lex(); + } + + return node.finishDoWhileStatement(body, test); + } + + function parseWhileStatement(node) { + var test, body, oldInIteration; + + expectKeyword('while'); + + expect('('); + + test = parseExpression(); + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = parseStatement(); + + state.inIteration = oldInIteration; + + return node.finishWhileStatement(test, body); + } + + function parseForStatement(node) { + var init, initSeq, initStartToken, test, update, left, right, kind, declarations, + body, oldInIteration, previousAllowIn = state.allowIn; + + init = test = update = null; + + expectKeyword('for'); + + expect('('); + + if (match(';')) { + lex(); + } else { + if (matchKeyword('var')) { + init = new Node(); + lex(); + + state.allowIn = false; + init = init.finishVariableDeclaration(parseVariableDeclarationList()); + state.allowIn = previousAllowIn; + + if (init.declarations.length === 1 && matchKeyword('in')) { + lex(); + left = init; + right = parseExpression(); + init = null; + } else { + expect(';'); + } + } else if (matchKeyword('const') || matchKeyword('let')) { + init = new Node(); + kind = lex().value; + + state.allowIn = false; + declarations = parseBindingList(kind, {inFor: true}); + state.allowIn = previousAllowIn; + + if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) { + init = init.finishLexicalDeclaration(declarations, kind); + lex(); + left = init; + right = parseExpression(); + init = null; + } else { + consumeSemicolon(); + init = init.finishLexicalDeclaration(declarations, kind); + } + } else { + initStartToken = lookahead; + state.allowIn = false; + init = inheritCoverGrammar(parseAssignmentExpression); + state.allowIn = previousAllowIn; + + if (matchKeyword('in')) { + if (!isAssignmentTarget) { + tolerateError(Messages.InvalidLHSInForIn); + } + + lex(); + reinterpretExpressionAsPattern(init); + left = init; + right = parseExpression(); + init = null; + } else { + if (match(',')) { + initSeq = [init]; + while (match(',')) { + lex(); + initSeq.push(isolateCoverGrammar(parseAssignmentExpression)); + } + init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq); + } + expect(';'); + } + } + } + + if (typeof left === 'undefined') { + + if (!match(';')) { + test = parseExpression(); + } + expect(';'); + + if (!match(')')) { + update = parseExpression(); + } + } + + expect(')'); + + oldInIteration = state.inIteration; + state.inIteration = true; + + body = isolateCoverGrammar(parseStatement); + + state.inIteration = oldInIteration; + + return (typeof left === 'undefined') ? + node.finishForStatement(init, test, update, body) : + node.finishForInStatement(left, right, body); + } + + // 12.7 The continue statement + + function parseContinueStatement(node) { + var label = null, key; + + expectKeyword('continue'); + + // Optimize the most common form: 'continue;'. + if (source.charCodeAt(startIndex) === 0x3B) { + lex(); + + if (!state.inIteration) { + throwError(Messages.IllegalContinue); + } + + return node.finishContinueStatement(null); + } + + if (hasLineTerminator) { + if (!state.inIteration) { + throwError(Messages.IllegalContinue); + } + + return node.finishContinueStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + key = '$' + label.name; + if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError(Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !state.inIteration) { + throwError(Messages.IllegalContinue); + } + + return node.finishContinueStatement(label); + } + + // 12.8 The break statement + + function parseBreakStatement(node) { + var label = null, key; + + expectKeyword('break'); + + // Catch the very common case first: immediately a semicolon (U+003B). + if (source.charCodeAt(lastIndex) === 0x3B) { + lex(); + + if (!(state.inIteration || state.inSwitch)) { + throwError(Messages.IllegalBreak); + } + + return node.finishBreakStatement(null); + } + + if (hasLineTerminator) { + if (!(state.inIteration || state.inSwitch)) { + throwError(Messages.IllegalBreak); + } + + return node.finishBreakStatement(null); + } + + if (lookahead.type === Token.Identifier) { + label = parseVariableIdentifier(); + + key = '$' + label.name; + if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError(Messages.UnknownLabel, label.name); + } + } + + consumeSemicolon(); + + if (label === null && !(state.inIteration || state.inSwitch)) { + throwError(Messages.IllegalBreak); + } + + return node.finishBreakStatement(label); + } + + // 12.9 The return statement + + function parseReturnStatement(node) { + var argument = null; + + expectKeyword('return'); + + if (!state.inFunctionBody) { + tolerateError(Messages.IllegalReturn); + } + + // 'return' followed by a space and an identifier is very common. + if (source.charCodeAt(lastIndex) === 0x20) { + if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) { + argument = parseExpression(); + consumeSemicolon(); + return node.finishReturnStatement(argument); + } + } + + if (hasLineTerminator) { + // HACK + return node.finishReturnStatement(null); + } + + if (!match(';')) { + if (!match('}') && lookahead.type !== Token.EOF) { + argument = parseExpression(); + } + } + + consumeSemicolon(); + + return node.finishReturnStatement(argument); + } + + // 12.10 The with statement + + function parseWithStatement(node) { + var object, body; + + if (strict) { + tolerateError(Messages.StrictModeWith); + } + + expectKeyword('with'); + + expect('('); + + object = parseExpression(); + + expect(')'); + + body = parseStatement(); + + return node.finishWithStatement(object, body); + } + + // 12.10 The swith statement + + function parseSwitchCase() { + var test, consequent = [], statement, node = new Node(); + + if (matchKeyword('default')) { + lex(); + test = null; + } else { + expectKeyword('case'); + test = parseExpression(); + } + expect(':'); + + while (startIndex < length) { + if (match('}') || matchKeyword('default') || matchKeyword('case')) { + break; + } + statement = parseStatementListItem(); + consequent.push(statement); + } + + return node.finishSwitchCase(test, consequent); + } + + function parseSwitchStatement(node) { + var discriminant, cases, clause, oldInSwitch, defaultFound; + + expectKeyword('switch'); + + expect('('); + + discriminant = parseExpression(); + + expect(')'); + + expect('{'); + + cases = []; + + if (match('}')) { + lex(); + return node.finishSwitchStatement(discriminant, cases); + } + + oldInSwitch = state.inSwitch; + state.inSwitch = true; + defaultFound = false; + + while (startIndex < length) { + if (match('}')) { + break; + } + clause = parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + throwError(Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + + state.inSwitch = oldInSwitch; + + expect('}'); + + return node.finishSwitchStatement(discriminant, cases); + } + + // 12.13 The throw statement + + function parseThrowStatement(node) { + var argument; + + expectKeyword('throw'); + + if (hasLineTerminator) { + throwError(Messages.NewlineAfterThrow); + } + + argument = parseExpression(); + + consumeSemicolon(); + + return node.finishThrowStatement(argument); + } + + // 12.14 The try statement + + function parseCatchClause() { + var param, body, node = new Node(); + + expectKeyword('catch'); + + expect('('); + if (match(')')) { + throwUnexpectedToken(lookahead); + } + + param = parsePattern(); + + // 12.14.1 + if (strict && isRestrictedWord(param.name)) { + tolerateError(Messages.StrictCatchVariable); + } + + expect(')'); + body = parseBlock(); + return node.finishCatchClause(param, body); + } + + function parseTryStatement(node) { + var block, handler = null, finalizer = null; + + expectKeyword('try'); + + block = parseBlock(); + + if (matchKeyword('catch')) { + handler = parseCatchClause(); + } + + if (matchKeyword('finally')) { + lex(); + finalizer = parseBlock(); + } + + if (!handler && !finalizer) { + throwError(Messages.NoCatchOrFinally); + } + + return node.finishTryStatement(block, handler, finalizer); + } + + // 12.15 The debugger statement + + function parseDebuggerStatement(node) { + expectKeyword('debugger'); + + consumeSemicolon(); + + return node.finishDebuggerStatement(); + } + + // 12 Statements + + function parseStatement() { + var type = lookahead.type, + expr, + labeledBody, + key, + node; + + if (type === Token.EOF) { + throwUnexpectedToken(lookahead); + } + + if (type === Token.Punctuator && lookahead.value === '{') { + return parseBlock(); + } + isAssignmentTarget = isBindingElement = true; + node = new Node(); + + if (type === Token.Punctuator) { + switch (lookahead.value) { + case ';': + return parseEmptyStatement(node); + case '(': + return parseExpressionStatement(node); + default: + break; + } + } else if (type === Token.Keyword) { + switch (lookahead.value) { + case 'break': + return parseBreakStatement(node); + case 'continue': + return parseContinueStatement(node); + case 'debugger': + return parseDebuggerStatement(node); + case 'do': + return parseDoWhileStatement(node); + case 'for': + return parseForStatement(node); + case 'function': + return parseFunctionDeclaration(node); + case 'if': + return parseIfStatement(node); + case 'return': + return parseReturnStatement(node); + case 'switch': + return parseSwitchStatement(node); + case 'throw': + return parseThrowStatement(node); + case 'try': + return parseTryStatement(node); + case 'var': + return parseVariableStatement(node); + case 'while': + return parseWhileStatement(node); + case 'with': + return parseWithStatement(node); + default: + break; + } + } + + expr = parseExpression(); + + // 12.12 Labelled Statements + if ((expr.type === Syntax.Identifier) && match(':')) { + lex(); + + key = '$' + expr.name; + if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + throwError(Messages.Redeclaration, 'Label', expr.name); + } + + state.labelSet[key] = true; + labeledBody = parseStatement(); + delete state.labelSet[key]; + return node.finishLabeledStatement(expr, labeledBody); + } + + consumeSemicolon(); + + return node.finishExpressionStatement(expr); + } + + // 13 Function Definition + + function parseFunctionSourceElements() { + var statement, body = [], token, directive, firstRestricted, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount, + node = new Node(); + + expect('{'); + + while (startIndex < length) { + if (lookahead.type !== Token.StringLiteral) { + break; + } + token = lookahead; + + statement = parseStatementListItem(); + body.push(statement); + if (statement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = source.slice(token.start + 1, token.end - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + oldLabelSet = state.labelSet; + oldInIteration = state.inIteration; + oldInSwitch = state.inSwitch; + oldInFunctionBody = state.inFunctionBody; + oldParenthesisCount = state.parenthesizedCount; + + state.labelSet = {}; + state.inIteration = false; + state.inSwitch = false; + state.inFunctionBody = true; + state.parenthesizedCount = 0; + + while (startIndex < length) { + if (match('}')) { + break; + } + body.push(parseStatementListItem()); + } + + expect('}'); + + state.labelSet = oldLabelSet; + state.inIteration = oldInIteration; + state.inSwitch = oldInSwitch; + state.inFunctionBody = oldInFunctionBody; + state.parenthesizedCount = oldParenthesisCount; + + return node.finishBlockStatement(body); + } + + function validateParam(options, param, name) { + var key = '$' + name; + if (strict) { + if (isRestrictedWord(name)) { + options.stricted = param; + options.message = Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = Messages.StrictParamDupe; + } + } else if (!options.firstRestricted) { + if (isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamName; + } else if (isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictReservedWord; + } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.firstRestricted = param; + options.message = Messages.StrictParamDupe; + } + } + options.paramSet[key] = true; + } + + function parseParam(options) { + var token, param, def; + + token = lookahead; + if (token.value === '...') { + param = parseRestElement(); + validateParam(options, param.argument, param.argument.name); + options.params.push(param); + options.defaults.push(null); + return false; + } + + param = parsePatternWithDefault(); + validateParam(options, token, token.value); + + if (param.type === Syntax.AssignmentPattern) { + def = param.right; + param = param.left; + ++options.defaultCount; + } + + options.params.push(param); + options.defaults.push(def); + + return !match(')'); + } + + function parseParams(firstRestricted) { + var options; + + options = { + params: [], + defaultCount: 0, + defaults: [], + firstRestricted: firstRestricted + }; + + expect('('); + + if (!match(')')) { + options.paramSet = {}; + while (startIndex < length) { + if (!parseParam(options)) { + break; + } + expect(','); + } + } + + expect(')'); + + if (options.defaultCount === 0) { + options.defaults = []; + } + + return { + params: options.params, + defaults: options.defaults, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + } + + function parseFunctionDeclaration(node, identifierIsOptional) { + var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict; + + expectKeyword('function'); + if (!identifierIsOptional || !match('(')) { + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + tolerateUnexpectedToken(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + tmp = parseParams(firstRestricted); + params = tmp.params; + defaults = tmp.defaults; + stricted = tmp.stricted; + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwUnexpectedToken(firstRestricted, message); + } + if (strict && stricted) { + tolerateUnexpectedToken(stricted, message); + } + strict = previousStrict; + + return node.finishFunctionDeclaration(id, params, defaults, body); + } + + function parseFunctionExpression() { + var token, id = null, stricted, firstRestricted, message, tmp, + params = [], defaults = [], body, previousStrict, node = new Node(); + + expectKeyword('function'); + + if (!match('(')) { + token = lookahead; + id = parseVariableIdentifier(); + if (strict) { + if (isRestrictedWord(token.value)) { + tolerateUnexpectedToken(token, Messages.StrictFunctionName); + } + } else { + if (isRestrictedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictFunctionName; + } else if (isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = Messages.StrictReservedWord; + } + } + } + + tmp = parseParams(firstRestricted); + params = tmp.params; + defaults = tmp.defaults; + stricted = tmp.stricted; + firstRestricted = tmp.firstRestricted; + if (tmp.message) { + message = tmp.message; + } + + previousStrict = strict; + body = parseFunctionSourceElements(); + if (strict && firstRestricted) { + throwUnexpectedToken(firstRestricted, message); + } + if (strict && stricted) { + tolerateUnexpectedToken(stricted, message); + } + strict = previousStrict; + + return node.finishFunctionExpression(id, params, defaults, body); + } + + + function parseClassBody() { + var classBody, token, isStatic, hasConstructor = false, body, method, computed, key; + + classBody = new Node(); + + expect('{'); + body = []; + while (!match('}')) { + if (match(';')) { + lex(); + } else { + method = new Node(); + token = lookahead; + isStatic = false; + computed = match('['); + key = parseObjectPropertyKey(); + if (key.name === 'static' && lookaheadPropertyName()) { + token = lookahead; + isStatic = true; + computed = match('['); + key = parseObjectPropertyKey(); + } + method = tryParseMethodDefinition(token, key, computed, method); + if (method) { + method['static'] = isStatic; + if (method.kind === 'init') { + method.kind = 'method'; + } + if (!isStatic) { + if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') { + if (method.kind !== 'method' || !method.method || method.value.generator) { + throwUnexpectedToken(token, Messages.ConstructorSpecialMethod); + } + if (hasConstructor) { + throwUnexpectedToken(token, Messages.DuplicateConstructor); + } else { + hasConstructor = true; + } + method.kind = 'constructor'; + } + } else { + if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') { + throwUnexpectedToken(token, Messages.StaticPrototype); + } + } + method.type = Syntax.MethodDefinition; + delete method.method; + delete method.shorthand; + body.push(method); + } else { + throwUnexpectedToken(lookahead); + } + } + } + lex(); + return classBody.finishClassBody(body); + } + + function parseClassDeclaration(identifierIsOptional) { + var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict; + strict = true; + + expectKeyword('class'); + + if (!identifierIsOptional || lookahead.type === Token.Identifier) { + id = parseVariableIdentifier(); + } + + if (matchKeyword('extends')) { + lex(); + superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall); + } + classBody = parseClassBody(); + strict = previousStrict; + + return classNode.finishClassDeclaration(id, superClass, classBody); + } + + function parseClassExpression() { + var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict; + strict = true; + + expectKeyword('class'); + + if (lookahead.type === Token.Identifier) { + id = parseVariableIdentifier(); + } + + if (matchKeyword('extends')) { + lex(); + superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall); + } + classBody = parseClassBody(); + strict = previousStrict; + + return classNode.finishClassExpression(id, superClass, classBody); + } + + // Modules grammar from: + // people.mozilla.org/~jorendorff/es6-draft.html + + function parseModuleSpecifier() { + var node = new Node(); + + if (lookahead.type !== Token.StringLiteral) { + throwError(Messages.InvalidModuleSpecifier); + } + return node.finishLiteral(lex()); + } + + function parseExportSpecifier() { + var exported, local, node = new Node(), def; + if (matchKeyword('default')) { + // export {default} from 'something'; + def = new Node(); + lex(); + local = def.finishIdentifier('default'); + } else { + local = parseVariableIdentifier(); + } + if (matchContextualKeyword('as')) { + lex(); + exported = parseNonComputedProperty(); + } + return node.finishExportSpecifier(local, exported); + } + + function parseExportNamedDeclaration(node) { + var declaration = null, + isExportFromIdentifier, + src = null, specifiers = []; + + // non-default export + if (lookahead.type === Token.Keyword) { + // covers: + // export var f = 1; + switch (lookahead.value) { + case 'let': + case 'const': + case 'var': + case 'class': + case 'function': + declaration = parseStatementListItem(); + return node.finishExportNamedDeclaration(declaration, specifiers, null); + } + } + + expect('{'); + if (!match('}')) { + do { + isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); + specifiers.push(parseExportSpecifier()); + } while (match(',') && lex()); + } + expect('}'); + + if (matchContextualKeyword('from')) { + // covering: + // export {default} from 'foo'; + // export {foo} from 'foo'; + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + } else if (isExportFromIdentifier) { + // covering: + // export {default}; // missing fromClause + throwError(lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } else { + // cover + // export {foo}; + consumeSemicolon(); + } + return node.finishExportNamedDeclaration(declaration, specifiers, src); + } + + function parseExportDefaultDeclaration(node) { + var declaration = null, + expression = null; + + // covers: + // export default ... + expectKeyword('default'); + + if (matchKeyword('function')) { + // covers: + // export default function foo () {} + // export default function () {} + declaration = parseFunctionDeclaration(new Node(), true); + return node.finishExportDefaultDeclaration(declaration); + } + if (matchKeyword('class')) { + declaration = parseClassDeclaration(true); + return node.finishExportDefaultDeclaration(declaration); + } + + if (matchContextualKeyword('from')) { + throwError(Messages.UnexpectedToken, lookahead.value); + } + + // covers: + // export default {}; + // export default []; + // export default (1 + 2); + if (match('{')) { + expression = parseObjectInitialiser(); + } else if (match('[')) { + expression = parseArrayInitialiser(); + } else { + expression = parseAssignmentExpression(); + } + consumeSemicolon(); + return node.finishExportDefaultDeclaration(expression); + } + + function parseExportAllDeclaration(node) { + var src; + + // covers: + // export * from 'foo'; + expect('*'); + if (!matchContextualKeyword('from')) { + throwError(lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + + return node.finishExportAllDeclaration(src); + } + + function parseExportDeclaration() { + var node = new Node(); + if (state.inFunctionBody) { + throwError(Messages.IllegalExportDeclaration); + } + + expectKeyword('export'); + + if (matchKeyword('default')) { + return parseExportDefaultDeclaration(node); + } + if (match('*')) { + return parseExportAllDeclaration(node); + } + return parseExportNamedDeclaration(node); + } + + function parseImportSpecifier() { + // import {} ...; + var local, imported, node = new Node(); + + imported = parseNonComputedProperty(); + if (matchContextualKeyword('as')) { + lex(); + local = parseVariableIdentifier(); + } + + return node.finishImportSpecifier(local, imported); + } + + function parseNamedImports() { + var specifiers = []; + // {foo, bar as bas} + expect('{'); + if (!match('}')) { + do { + specifiers.push(parseImportSpecifier()); + } while (match(',') && lex()); + } + expect('}'); + return specifiers; + } + + function parseImportDefaultSpecifier() { + // import ...; + var local, node = new Node(); + + local = parseNonComputedProperty(); + + return node.finishImportDefaultSpecifier(local); + } + + function parseImportNamespaceSpecifier() { + // import <* as foo> ...; + var local, node = new Node(); + + expect('*'); + if (!matchContextualKeyword('as')) { + throwError(Messages.NoAsAfterImportNamespace); + } + lex(); + local = parseNonComputedProperty(); + + return node.finishImportNamespaceSpecifier(local); + } + + function parseImportDeclaration() { + var specifiers, src, node = new Node(); + + if (state.inFunctionBody) { + throwError(Messages.IllegalImportDeclaration); + } + + expectKeyword('import'); + specifiers = []; + + if (lookahead.type === Token.StringLiteral) { + // covers: + // import 'foo'; + src = parseModuleSpecifier(); + consumeSemicolon(); + return node.finishImportDeclaration(specifiers, src); + } + + if (!matchKeyword('default') && isIdentifierName(lookahead)) { + // covers: + // import foo + // import foo, ... + specifiers.push(parseImportDefaultSpecifier()); + if (match(',')) { + lex(); + } + } + if (match('*')) { + // covers: + // import foo, * as foo + // import * as foo + specifiers.push(parseImportNamespaceSpecifier()); + } else if (match('{')) { + // covers: + // import foo, {bar} + // import {bar} + specifiers = specifiers.concat(parseNamedImports()); + } + + if (!matchContextualKeyword('from')) { + throwError(lookahead.value ? + Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); + } + lex(); + src = parseModuleSpecifier(); + consumeSemicolon(); + + return node.finishImportDeclaration(specifiers, src); + } + + // 14 Program + + function parseScriptBody() { + var statement, body = [], token, directive, firstRestricted; + + while (startIndex < length) { + token = lookahead; + if (token.type !== Token.StringLiteral) { + break; + } + + statement = parseStatementListItem(); + body.push(statement); + if (statement.expression.type !== Syntax.Literal) { + // this is not directive + break; + } + directive = source.slice(token.start + 1, token.end - 1); + if (directive === 'use strict') { + strict = true; + if (firstRestricted) { + tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral); + } + } else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + + while (startIndex < length) { + statement = parseStatementListItem(); + /* istanbul ignore if */ + if (typeof statement === 'undefined') { + break; + } + body.push(statement); + } + return body; + } + + function parseProgram() { + var body, node; + + peek(); + node = new Node(); + + body = parseScriptBody(); + return node.finishProgram(body); + } + + function filterTokenLocation() { + var i, entry, token, tokens = []; + + for (i = 0; i < extra.tokens.length; ++i) { + entry = extra.tokens[i]; + token = { + type: entry.type, + value: entry.value + }; + if (entry.regex) { + token.regex = { + pattern: entry.regex.pattern, + flags: entry.regex.flags + }; + } + if (extra.range) { + token.range = entry.range; + } + if (extra.loc) { + token.loc = entry.loc; + } + tokens.push(token); + } + + extra.tokens = tokens; + } + + function tokenize(code, options) { + var toString, + tokens; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + startIndex = index; + startLineNumber = lineNumber; + startLineStart = lineStart; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1, + curlyStack: [] + }; + + extra = {}; + + // Options matching. + options = options || {}; + + // Of course we collect tokens here. + options.tokens = true; + extra.tokens = []; + extra.tokenize = true; + // The following two fields are necessary to compute the Regex tokens. + extra.openParenToken = -1; + extra.openCurlyToken = -1; + + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + + try { + peek(); + if (lookahead.type === Token.EOF) { + return extra.tokens; + } + + lex(); + while (lookahead.type !== Token.EOF) { + try { + lex(); + } catch (lexError) { + if (extra.errors) { + recordError(lexError); + // We have to break on the first error + // to avoid infinite loops. + break; + } else { + throw lexError; + } + } + } + + filterTokenLocation(); + tokens = extra.tokens; + if (typeof extra.comments !== 'undefined') { + tokens.comments = extra.comments; + } + if (typeof extra.errors !== 'undefined') { + tokens.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + return tokens; + } + + function parse(code, options) { + var program, toString; + + toString = String; + if (typeof code !== 'string' && !(code instanceof String)) { + code = toString(code); + } + + source = code; + index = 0; + lineNumber = (source.length > 0) ? 1 : 0; + lineStart = 0; + startIndex = index; + startLineNumber = lineNumber; + startLineStart = lineStart; + length = source.length; + lookahead = null; + state = { + allowIn: true, + labelSet: {}, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + lastCommentStart: -1, + curlyStack: [] + }; + sourceType = 'script'; + strict = false; + + extra = {}; + if (typeof options !== 'undefined') { + extra.range = (typeof options.range === 'boolean') && options.range; + extra.loc = (typeof options.loc === 'boolean') && options.loc; + extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; + + if (extra.loc && options.source !== null && options.source !== undefined) { + extra.source = toString(options.source); + } + + if (typeof options.tokens === 'boolean' && options.tokens) { + extra.tokens = []; + } + if (typeof options.comment === 'boolean' && options.comment) { + extra.comments = []; + } + if (typeof options.tolerant === 'boolean' && options.tolerant) { + extra.errors = []; + } + if (extra.attachComment) { + extra.range = true; + extra.comments = []; + extra.bottomRightStack = []; + extra.trailingComments = []; + extra.leadingComments = []; + } + if (options.sourceType === 'module') { + // very restrictive condition for now + sourceType = options.sourceType; + strict = true; + } + } + + try { + program = parseProgram(); + if (typeof extra.comments !== 'undefined') { + program.comments = extra.comments; + } + if (typeof extra.tokens !== 'undefined') { + filterTokenLocation(); + program.tokens = extra.tokens; + } + if (typeof extra.errors !== 'undefined') { + program.errors = extra.errors; + } + } catch (e) { + throw e; + } finally { + extra = {}; + } + + return program; + } + + // Sync with *.json manifests. + exports.version = '2.2.0'; + + exports.tokenize = tokenize; + + exports.parse = parse; + + // Deep copy. + /* istanbul ignore next */ + exports.Syntax = (function () { + var name, types = {}; + + if (typeof Object.create === 'function') { + types = Object.create(null); + } + + for (name in Syntax) { + if (Syntax.hasOwnProperty(name)) { + types[name] = Syntax[name]; + } + } + + if (typeof Object.freeze === 'function') { + Object.freeze(types); + } + + return types; + }()); + +})); +/* vim: set sw=4 ts=4 et tw=80 : */ diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/package.json b/tools/eslint/node_modules/js-yaml/node_modules/esprima/package.json new file mode 100644 index 00000000000000..965f6cb6afe6a4 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/package.json @@ -0,0 +1,93 @@ +{ + "name": "esprima", + "description": "ECMAScript parsing infrastructure for multipurpose analysis", + "homepage": "http://esprima.org", + "main": "esprima.js", + "bin": { + "esparse": "./bin/esparse.js", + "esvalidate": "./bin/esvalidate.js" + }, + "version": "2.2.0", + "files": [ + "bin", + "test/run.js", + "test/runner.js", + "test/test.js", + "esprima.js" + ], + "engines": { + "node": ">=0.4.0" + }, + "author": { + "name": "Ariya Hidayat", + "email": "ariya.hidayat@gmail.com" + }, + "maintainers": [ + { + "name": "ariya", + "email": "ariya.hidayat@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jquery/esprima.git" + }, + "bugs": { + "url": "http://issues.esprima.org" + }, + "licenses": [ + { + "type": "BSD", + "url": "https://github.com/jquery/esprima/raw/master/LICENSE.BSD" + } + ], + "devDependencies": { + "eslint": "~0.19.0", + "jscs": "~1.12.0", + "istanbul": "~0.3.7", + "escomplex-js": "1.2.0", + "complexity-report": "~1.4.0", + "regenerate": "~0.6.2", + "unicode-7.0.0": "~0.1.5", + "json-diff": "~0.3.1", + "optimist": "~0.6.0" + }, + "keywords": [ + "ast", + "ecmascript", + "javascript", + "parser", + "syntax" + ], + "scripts": { + "generate-regex": "node tools/generate-identifier-regex.js", + "test": "node test/run.js && npm run lint && npm run coverage", + "lint": "npm run check-version && npm run eslint && npm run jscs && npm run complexity", + "check-version": "node tools/check-version.js", + "jscs": "jscs esprima.js", + "eslint": "node node_modules/eslint/bin/eslint.js esprima.js", + "complexity": "node tools/list-complexity.js && cr -s -l -w --maxcyc 17 esprima.js", + "coverage": "npm run analyze-coverage && npm run check-coverage", + "analyze-coverage": "istanbul cover test/runner.js", + "check-coverage": "istanbul check-coverage --statement 100 --branch 100 --function 100", + "benchmark": "node test/benchmarks.js", + "benchmark-quick": "node test/benchmarks.js quick" + }, + "gitHead": "deef03ca006b03912d9f74b041f9239a9045181f", + "_id": "esprima@2.2.0", + "_shasum": "4292c1d68e4173d815fa2290dc7afc96d81fcd83", + "_from": "esprima@>=2.2.0 <2.3.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "ariya", + "email": "ariya.hidayat@gmail.com" + }, + "dist": { + "shasum": "4292c1d68e4173d815fa2290dc7afc96d81fcd83", + "tarball": "http://registry.npmjs.org/esprima/-/esprima-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/esprima/-/esprima-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/test/run.js b/tools/eslint/node_modules/js-yaml/node_modules/esprima/test/run.js new file mode 100644 index 00000000000000..a5b919bfdf0003 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/test/run.js @@ -0,0 +1,66 @@ +/* + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint node:true */ + +(function () { + 'use strict'; + + var child = require('child_process'), + nodejs = '"' + process.execPath + '"', + ret = 0, + suites, + index; + + suites = [ + 'runner', + 'parselibs' + ]; + + function nextTest() { + var suite = suites[index]; + + if (index < suites.length) { + child.exec(nodejs + ' ./test/' + suite + '.js', function (err, stdout, stderr) { + if (stdout) { + process.stdout.write(suite + ': ' + stdout); + } + if (stderr) { + process.stderr.write(suite + ': ' + stderr); + } + if (err) { + ret = err.code; + } + index += 1; + nextTest(); + }); + } else { + process.exit(ret); + } + } + + index = 0; + nextTest(); +}()); diff --git a/tools/eslint/node_modules/js-yaml/node_modules/esprima/test/runner.js b/tools/eslint/node_modules/js-yaml/node_modules/esprima/test/runner.js new file mode 100644 index 00000000000000..7f4a1738bb9e85 --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/node_modules/esprima/test/runner.js @@ -0,0 +1,475 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Yusuke Suzuki + Copyright (C) 2011 Arpad Borsos + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/*jslint browser:true node:true */ +/*global esprima:true, testFixture:true */ + +var runTests; + +function NotMatchingError(expected, actual) { + 'use strict'; + Error.call(this, 'Expected '); + this.expected = expected; + this.actual = actual; +} +NotMatchingError.prototype = new Error(); + +function errorToObject(e) { + 'use strict'; + var msg = e.toString(); + + // Opera 9.64 produces an non-standard string in toString(). + if (msg.substr(0, 6) !== 'Error:') { + if (typeof e.message === 'string') { + msg = 'Error: ' + e.message; + } + } + + return { + index: e.index, + lineNumber: e.lineNumber, + column: e.column, + message: msg + }; +} + +function sortedObject(o) { + if (o === null) { + return o; + } + if (Array.isArray(o)) { + return o.map(sortedObject); + } + if (typeof o !== 'object') { + return o; + } + if (o instanceof RegExp) { + return o; + } + var keys = Object.keys(o); + var result = { + range: undefined, + loc: undefined + }; + keys.forEach(function (key) { + if (o.hasOwnProperty(key)){ + result[key] = sortedObject(o[key]); + } + }); + return result; +} + +function hasAttachedComment(syntax) { + var key; + for (key in syntax) { + if (key === 'leadingComments' || key === 'trailingComments') { + return true; + } + if (typeof syntax[key] === 'object' && syntax[key] !== null) { + if (hasAttachedComment(syntax[key])) { + return true; + } + } + } + return false; +} + +function testParse(esprima, code, syntax) { + 'use strict'; + var expected, tree, actual, options, StringObject, i, len; + + // alias, so that JSLint does not complain. + StringObject = String; + + options = { + comment: (typeof syntax.comments !== 'undefined'), + range: true, + loc: true, + tokens: (typeof syntax.tokens !== 'undefined'), + raw: true, + tolerant: (typeof syntax.errors !== 'undefined'), + source: null, + sourceType: syntax.sourceType + }; + + if (options.comment) { + options.attachComment = hasAttachedComment(syntax); + } + + if (typeof syntax.tokens !== 'undefined') { + if (syntax.tokens.length > 0) { + options.range = (typeof syntax.tokens[0].range !== 'undefined'); + options.loc = (typeof syntax.tokens[0].loc !== 'undefined'); + } + } + + if (typeof syntax.comments !== 'undefined') { + if (syntax.comments.length > 0) { + options.range = (typeof syntax.comments[0].range !== 'undefined'); + options.loc = (typeof syntax.comments[0].loc !== 'undefined'); + } + } + + if (options.loc) { + options.source = syntax.loc.source; + } + + syntax = sortedObject(syntax); + expected = JSON.stringify(syntax, null, 4); + try { + // Some variations of the options. + tree = esprima.parse(code, { tolerant: options.tolerant, sourceType: options.sourceType }); + tree = esprima.parse(code, { tolerant: options.tolerant, sourceType: options.sourceType, range: true }); + tree = esprima.parse(code, { tolerant: options.tolerant, sourceType: options.sourceType, loc: true }); + + tree = esprima.parse(code, options); + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + tree = sortedObject(tree); + actual = JSON.stringify(tree, null, 4); + + // Only to ensure that there is no error when using string object. + esprima.parse(new StringObject(code), options); + + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } + + function filter(key, value) { + return (key === 'loc' || key === 'range') ? undefined : value; + } + + if (options.tolerant) { + return; + } + + + // Check again without any location info. + options.range = false; + options.loc = false; + syntax = sortedObject(syntax); + expected = JSON.stringify(syntax, filter, 4); + try { + tree = esprima.parse(code, options); + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + tree = sortedObject(tree); + actual = JSON.stringify(tree, filter, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function testTokenize(esprima, code, tokens) { + 'use strict'; + var options, expected, actual, tree; + + options = { + comment: true, + tolerant: true, + loc: true, + range: true + }; + + expected = JSON.stringify(tokens, null, 4); + + try { + tree = esprima.tokenize(code, options); + actual = JSON.stringify(tree, null, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + + +function testModule(esprima, code, exception) { + 'use strict'; + var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize; + + // Different parsing options should give the same error. + options = [ + { sourceType: 'module' }, + { sourceType: 'module', comment: true }, + { sourceType: 'module', raw: true }, + { sourceType: 'module', raw: true, comment: true } + ]; + + if (!exception.message) { + exception.message = 'Error: Line 1: ' + exception.description; + } + exception.description = exception.message.replace(/Error: Line [0-9]+: /, ''); + + expected = JSON.stringify(exception); + + for (i = 0; i < options.length; i += 1) { + + try { + esprima.parse(code, options[i]); + } catch (e) { + err = errorToObject(e); + err.description = e.description; + actual = JSON.stringify(err); + } + + if (expected !== actual) { + + // Compensate for old V8 which does not handle invalid flag. + if (exception.message.indexOf('Invalid regular expression') > 0) { + if (typeof actual === 'undefined' && !handleInvalidRegexFlag) { + return; + } + } + + throw new NotMatchingError(expected, actual); + } + + } +} + +function testError(esprima, code, exception) { + 'use strict'; + var i, options, expected, actual, err, handleInvalidRegexFlag, tokenize; + + // Different parsing options should give the same error. + options = [ + {}, + { comment: true }, + { raw: true }, + { raw: true, comment: true } + ]; + + // If handleInvalidRegexFlag is true, an invalid flag in a regular expression + // will throw an exception. In some old version of V8, this is not the case + // and hence handleInvalidRegexFlag is false. + handleInvalidRegexFlag = false; + try { + 'test'.match(new RegExp('[a-z]', 'x')); + } catch (e) { + handleInvalidRegexFlag = true; + } + + exception.description = exception.message.replace(/Error: Line [0-9]+: /, ''); + + if (exception.tokenize) { + tokenize = true; + exception.tokenize = undefined; + } + expected = JSON.stringify(exception); + + for (i = 0; i < options.length; i += 1) { + + try { + if (tokenize) { + esprima.tokenize(code, options[i]); + } else { + esprima.parse(code, options[i]); + } + } catch (e) { + err = errorToObject(e); + err.description = e.description; + actual = JSON.stringify(err); + } + + if (expected !== actual) { + + // Compensate for old V8 which does not handle invalid flag. + if (exception.message.indexOf('Invalid regular expression') > 0) { + if (typeof actual === 'undefined' && !handleInvalidRegexFlag) { + return; + } + } + + throw new NotMatchingError(expected, actual); + } + + } +} + +function testAPI(esprima, code, expected) { + var result; + // API test. + expected = JSON.stringify(expected, null, 4); + try { + result = eval(code); + result = JSON.stringify(result, null, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== result) { + throw new NotMatchingError(expected, result); + } +} + +function generateTestCase(esprima, testCase) { + var tree, fileName = testCase.key + ".tree.json"; + try { + tree = esprima.parse(testCase.case, {loc: true, range: true}); + tree = JSON.stringify(tree, null, 4); + } catch (e) { + if (typeof e.index === 'undefined') { + console.error("Failed to generate test result."); + throw e; + } + tree = errorToObject(e); + tree.description = e.description; + tree = JSON.stringify(tree); + fileName = testCase.key + ".failure.json"; + } + require('fs').writeFileSync(fileName, tree); + console.error("Done."); +} + +if (typeof window === 'undefined') { + (function () { + 'use strict'; + + var esprima = require('../esprima'), + vm = require('vm'), + fs = require('fs'), + diff = require('json-diff').diffString, + total = 0, + result, + failures = [], + cases = {}, + context = {source: '', result: null}, + tick = new Date(), + expected, + testCase, + header; + + function enumerateFixtures(root) { + var dirs = fs.readdirSync(root), key, kind, + kinds = ['case', 'source', 'module', 'run', 'tree', 'tokens', 'failure', 'result'], + suffices = ['js', 'js', 'json', 'js', 'json', 'json', 'json', 'json']; + + dirs.forEach(function (item) { + var i; + if (fs.statSync(root + '/' + item).isDirectory()) { + enumerateFixtures(root + '/' + item); + } else { + kind = 'case'; + key = item.slice(0, -3); + for (i = 1; i < kinds.length; i++) { + var suffix = '.' + kinds[i] + '.' + suffices[i]; + if (item.slice(-suffix.length) === suffix) { + key = item.slice(0, -suffix.length); + kind = kinds[i]; + } + } + key = root + '/' + key; + if (!cases[key]) { + total++; + cases[key] = { key: key }; + } + cases[key][kind] = fs.readFileSync(root + '/' + item, 'utf-8'); + } + }); + } + + enumerateFixtures(__dirname + '/fixtures'); + + for (var key in cases) { + if (cases.hasOwnProperty(key)) { + testCase = cases[key]; + + if (testCase.hasOwnProperty('source')) { + testCase.case = eval(testCase.source + ';source'); + } + + try { + if (testCase.hasOwnProperty('module')) { + testModule(esprima, testCase.case, JSON.parse(testCase.module)); + } else if (testCase.hasOwnProperty('tree')) { + testParse(esprima, testCase.case, JSON.parse(testCase.tree)); + } else if (testCase.hasOwnProperty('tokens')) { + testTokenize(esprima, testCase.case, JSON.parse(testCase.tokens)); + } else if (testCase.hasOwnProperty('failure')) { + testError(esprima, testCase.case, JSON.parse(testCase.failure)); + } else if (testCase.hasOwnProperty('result')) { + testAPI(esprima, testCase.run, JSON.parse(testCase.result)); + } else { + console.error('Incomplete test case:' + testCase.key + '. Generating test result...'); + generateTestCase(esprima, testCase); + } + } catch (e) { + if (!e.expected) { + throw e; + } + e.source = testCase.case || testCase.key; + failures.push(e); + } + } + } + + tick = (new Date()) - tick; + + header = total + ' tests. ' + failures.length + ' failures. ' + + tick + ' ms'; + if (failures.length) { + console.error(header); + failures.forEach(function (failure) { + try { + var expectedObject = JSON.parse(failure.expected); + var actualObject = JSON.parse(failure.actual); + + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual + '\nDiff:\n' + + diff(expectedObject, actualObject)); + } catch (ex) { + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual); + } + }); + } else { + console.log(header); + } + process.exit(failures.length === 0 ? 0 : 1); + + }()); +} diff --git a/tools/eslint/node_modules/js-yaml/package.json b/tools/eslint/node_modules/js-yaml/package.json new file mode 100644 index 00000000000000..f52da7b733b3ba --- /dev/null +++ b/tools/eslint/node_modules/js-yaml/package.json @@ -0,0 +1,84 @@ +{ + "name": "js-yaml", + "version": "3.3.0", + "description": "YAML 1.2 parser and serializer", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "homepage": "https://github.com/nodeca/js-yaml", + "author": { + "name": "Dervus Grim", + "email": "dervus.grim@gmail.com" + }, + "contributors": [ + { + "name": "Aleksey V Zapparov", + "email": "ixti@member.fsf.org", + "url": "http://www.ixti.net/" + }, + { + "name": "Vitaly Puzrin", + "email": "vitaly@rcdesign.ru", + "url": "https://github.com/puzrin" + }, + { + "name": "Martin Grenfell", + "email": "martin.grenfell@gmail.com", + "url": "http://got-ravings.blogspot.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git://github.com/nodeca/js-yaml.git" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "dependencies": { + "argparse": "~1.0.2", + "esprima": "~2.2.0" + }, + "devDependencies": { + "ansi": "*", + "benchmark": "*", + "eslint": "0.18.0", + "eslint-plugin-nodeca": "^1.0.3", + "istanbul": "*", + "mocha": "*" + }, + "browser": { + "buffer": false + }, + "scripts": { + "test": "make test" + }, + "gitHead": "9cc570a50a767b08c3b0fcd0e61efec880aa7c11", + "bugs": { + "url": "https://github.com/nodeca/js-yaml/issues" + }, + "_id": "js-yaml@3.3.0", + "_shasum": "cb6422d39168dbde419fecb7fd06fbe27ad56210", + "_from": "js-yaml@>=3.2.5 <4.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "vitaly", + "email": "vitaly@rcdesign.ru" + }, + "maintainers": [ + { + "name": "vitaly", + "email": "vitaly@rcdesign.ru" + } + ], + "dist": { + "shasum": "cb6422d39168dbde419fecb7fd06fbe27ad56210", + "tarball": "http://registry.npmjs.org/js-yaml/-/js-yaml-3.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/minimatch/LICENSE b/tools/eslint/node_modules/minimatch/LICENSE new file mode 100644 index 00000000000000..05a4010949cac3 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/minimatch/README.md b/tools/eslint/node_modules/minimatch/README.md new file mode 100644 index 00000000000000..d458bc2e0a6b03 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/README.md @@ -0,0 +1,216 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instanting the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +## Functions + +The top-level exported function has a `cache` property, which is an LRU +cache set to store 100 items. So, calling these methods repeatedly +with the same pattern and options will use the same Minimatch object, +saving the cost of parsing it multiple times. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/tools/eslint/node_modules/minimatch/browser.js b/tools/eslint/node_modules/minimatch/browser.js new file mode 100644 index 00000000000000..967b45c0d67eba --- /dev/null +++ b/tools/eslint/node_modules/minimatch/browser.js @@ -0,0 +1,1113 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new Error('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var plType + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + plType = stateChar + patternListStack.push({ type: plType, start: i - 1, reStart: re.length }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + re += ')' + plType = patternListStack.pop().type + // negation is (?:(?!js)[^/]*) + // The others are (?:) + switch (plType) { + case '!': + re += '[^/]*?)' + break + case '?': + case '+': + case '*': + re += plType + break + case '@': break // the default anyway + } + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (var pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) re = '(?=.)' + re + + if (addPatternStart) re = patternStart + re + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + var regExp = new RegExp('^' + re + '$', flags) + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + +},{"brace-expansion":2,"path":undefined}],2:[function(require,module,exports){ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + var expansions = expand(escapeBraces(str)); + return expansions.filter(identity).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = /^(.*,)+(.+)?$/.test(m.body); + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0]).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + expansions.push([pre, N[j], post[k]].join('')) + } + } + + return expansions; +} + + +},{"balanced-match":3,"concat-map":4}],3:[function(require,module,exports){ +module.exports = balanced; +function balanced(a, b, str) { + var bal = 0; + var m = {}; + var ended = false; + + for (var i = 0; i < str.length; i++) { + if (a == str.substr(i, a.length)) { + if (!('start' in m)) m.start = i; + bal++; + } + else if (b == str.substr(i, b.length) && 'start' in m) { + ended = true; + bal--; + if (!bal) { + m.end = i; + m.pre = str.substr(0, m.start); + m.body = (m.end - m.start > 1) + ? str.substring(m.start + a.length, m.end) + : ''; + m.post = str.slice(m.end + b.length); + return m; + } + } + } + + // if we opened more than we closed, find the one we closed + if (bal && ended) { + var start = m.start + a.length; + m = balanced(a, b, str.substr(start)); + if (m) { + m.start += start; + m.end += start; + m.pre = str.slice(0, start) + m.pre; + } + return m; + } +} + +},{}],4:[function(require,module,exports){ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (Array.isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +},{}]},{},[1]); diff --git a/tools/eslint/node_modules/minimatch/minimatch.js b/tools/eslint/node_modules/minimatch/minimatch.js new file mode 100644 index 00000000000000..5e13d6d5b2e62b --- /dev/null +++ b/tools/eslint/node_modules/minimatch/minimatch.js @@ -0,0 +1,867 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new Error('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var plType + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + plType = stateChar + patternListStack.push({ type: plType, start: i - 1, reStart: re.length }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + re += ')' + plType = patternListStack.pop().type + // negation is (?:(?!js)[^/]*) + // The others are (?:) + switch (plType) { + case '!': + re += '[^/]*?)' + break + case '?': + case '+': + case '*': + re += plType + break + case '@': break // the default anyway + } + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (var pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) re = '(?=.)' + re + + if (addPatternStart) re = patternStart + re + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + var regExp = new RegExp('^' + re + '$', flags) + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/.npmignore b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/.npmignore new file mode 100644 index 00000000000000..249bc20eb5573c --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/.npmignore @@ -0,0 +1,2 @@ +node_modules +*.sw* diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/.travis.yml b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/.travis.yml new file mode 100644 index 00000000000000..6e5919de39a312 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/README.md b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/README.md new file mode 100644 index 00000000000000..62bc7bae3fed28 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/README.md @@ -0,0 +1,121 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma seperated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/example.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/example.js new file mode 100644 index 00000000000000..60ecfc74d41618 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/example.js @@ -0,0 +1,8 @@ +var expand = require('./'); + +console.log(expand('http://any.org/archive{1996..1999}/vol{1..4}/part{a,b,c}.html')); +console.log(expand('http://www.numericals.com/file{1..100..10}.txt')); +console.log(expand('http://www.letters.com/file{a..z..2}.txt')); +console.log(expand('mkdir /usr/local/src/bash/{old,new,dist,bugs}')); +console.log(expand('chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}')); + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/index.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/index.js new file mode 100644 index 00000000000000..a23104e9550173 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/index.js @@ -0,0 +1,191 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = /^(.*,)+(.+)?$/.test(m.body); + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore new file mode 100644 index 00000000000000..fd4f2b066b339e --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore @@ -0,0 +1,2 @@ +node_modules +.DS_Store diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml new file mode 100644 index 00000000000000..cc4dba29d959a2 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile new file mode 100644 index 00000000000000..fa5da71a6d0d34 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test/*.js + +.PHONY: test + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md new file mode 100644 index 00000000000000..2aff0ebff4403e --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md @@ -0,0 +1,80 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js new file mode 100644 index 00000000000000..c02ad348e69aec --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js @@ -0,0 +1,5 @@ +var balanced = require('./'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js new file mode 100644 index 00000000000000..d165ae8174ca82 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js @@ -0,0 +1,38 @@ +module.exports = balanced; +function balanced(a, b, str) { + var bal = 0; + var m = {}; + var ended = false; + + for (var i = 0; i < str.length; i++) { + if (a == str.substr(i, a.length)) { + if (!('start' in m)) m.start = i; + bal++; + } + else if (b == str.substr(i, b.length) && 'start' in m) { + ended = true; + bal--; + if (!bal) { + m.end = i; + m.pre = str.substr(0, m.start); + m.body = (m.end - m.start > 1) + ? str.substring(m.start + a.length, m.end) + : ''; + m.post = str.slice(m.end + b.length); + return m; + } + } + } + + // if we opened more than we closed, find the one we closed + if (bal && ended) { + var start = m.start + a.length; + m = balanced(a, b, str.substr(start)); + if (m) { + m.start += start; + m.end += start; + m.pre = str.slice(0, start) + m.pre; + } + return m; + } +} diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json new file mode 100644 index 00000000000000..a63236feb7d8a4 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json @@ -0,0 +1,56 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "0.2.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.1" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "readme": "# balanced-match\n\nMatch balanced string pairs, like `{` and `}` or `` and ``.\n\n[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)\n[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)\n\n[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)\n\n## Example\n\nGet the first matching pair of braces:\n\n```js\nvar balanced = require('balanced-match');\n\nconsole.log(balanced('{', '}', 'pre{in{nested}}post'));\nconsole.log(balanced('{', '}', 'pre{first}between{second}post'));\n```\n\nThe matches are:\n\n```bash\n$ node example.js\n{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }\n{ start: 3,\n end: 9,\n pre: 'pre',\n body: 'first',\n post: 'between{second}post' }\n```\n\n## API\n\n### var m = balanced(a, b, str)\n\nFor the first non-nested matching pair of `a` and `b` in `str`, return an\nobject with those keys:\n\n* **start** the index of the first match of `a`\n* **end** the index of the matching `b`\n* **pre** the preamble, `a` and `b` not included\n* **body** the match, `a` and `b` not included\n* **post** the postscript, `a` and `b` not included\n\nIf there's no match, `undefined` will be returned.\n\nIf the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']`.\n\n## Installation\n\nWith [npm](https://npmjs.org) do:\n\n```bash\nnpm install balanced-match\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "_id": "balanced-match@0.2.0", + "_shasum": "38f6730c03aab6d5edbb52bd934885e756d71674", + "_from": "balanced-match@>=0.2.0 <0.3.0", + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.2.0.tgz" +} diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js new file mode 100644 index 00000000000000..36bfd39954850d --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js @@ -0,0 +1,56 @@ +var test = require('tape'); +var balanced = require('..'); + +test('balanced', function(t) { + t.deepEqual(balanced('{', '}', 'pre{in{nest}}post'), { + start: 3, + end: 12, + pre: 'pre', + body: 'in{nest}', + post: 'post' + }); + t.deepEqual(balanced('{', '}', '{{{{{{{{{in}post'), { + start: 8, + end: 11, + pre: '{{{{{{{{', + body: 'in', + post: 'post' + }); + t.deepEqual(balanced('{', '}', 'pre{body{in}post'), { + start: 8, + end: 11, + pre: 'pre{body', + body: 'in', + post: 'post' + }); + t.deepEqual(balanced('{', '}', 'pre}{in{nest}}post'), { + start: 4, + end: 13, + pre: 'pre}', + body: 'in{nest}', + post: 'post' + }); + t.deepEqual(balanced('{', '}', 'pre{body}between{body2}post'), { + start: 3, + end: 8, + pre: 'pre', + body: 'body', + post: 'between{body2}post' + }); + t.notOk(balanced('{', '}', 'nope'), 'should be notOk'); + t.deepEqual(balanced('', '', 'preinnestpost'), { + start: 3, + end: 19, + pre: 'pre', + body: 'innest', + post: 'post' + }); + t.deepEqual(balanced('', '', 'preinnestpost'), { + start: 7, + end: 23, + pre: 'pre', + body: 'innest', + post: 'post' + }); + t.end(); +}); diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml new file mode 100644 index 00000000000000..f1d0f13c8a54d0 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE new file mode 100644 index 00000000000000..ee27ba4b4412b0 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown new file mode 100644 index 00000000000000..408f70a1be473c --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js new file mode 100644 index 00000000000000..33656217b61d8f --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js new file mode 100644 index 00000000000000..b29a7812e5055a --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json new file mode 100644 index 00000000000000..b516138098fba9 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json @@ -0,0 +1,83 @@ +{ + "name": "concat-map", + "description": "concatenative mapdashery", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/substack/node-concat-map.git" + }, + "main": "index.js", + "keywords": [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "directories": { + "example": "example", + "test": "test" + }, + "scripts": { + "test": "tape test/*.js" + }, + "devDependencies": { + "tape": "~2.4.0" + }, + "license": "MIT", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "bugs": { + "url": "https://github.com/substack/node-concat-map/issues" + }, + "homepage": "https://github.com/substack/node-concat-map", + "_id": "concat-map@0.0.1", + "dist": { + "shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", + "tarball": "http://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" + }, + "_from": "concat-map@0.0.1", + "_npmVersion": "1.3.21", + "_npmUser": { + "name": "substack", + "email": "mail@substack.net" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + } + ], + "_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", + "_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js new file mode 100644 index 00000000000000..fdbd7022f6da17 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/package.json b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/package.json new file mode 100644 index 00000000000000..5f1866c8b5a29e --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/package.json @@ -0,0 +1,75 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh" + }, + "dependencies": { + "balanced-match": "^0.2.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "tape": "^3.0.3" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "gitHead": "b5fa3b1c74e5e2dba2d0efa19b28335641bc1164", + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "_id": "brace-expansion@1.1.0", + "_shasum": "c9b7d03c03f37bc704be100e522b40db8f6cfcd9", + "_from": "brace-expansion@>=1.0.0 <2.0.0", + "_npmVersion": "2.1.10", + "_nodeVersion": "0.10.32", + "_npmUser": { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + "maintainers": [ + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + } + ], + "dist": { + "shasum": "c9b7d03c03f37bc704be100e522b40db8f6cfcd9", + "tarball": "http://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js new file mode 100644 index 00000000000000..5fe2b8ad48cc1c --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js @@ -0,0 +1,32 @@ +var test = require('tape'); +var expand = require('..'); +var fs = require('fs'); +var resfile = __dirname + '/bash-results.txt'; +var cases = fs.readFileSync(resfile, 'utf8').split('><><><><'); + +// throw away the EOF marker +cases.pop() + +test('matches bash expansions', function(t) { + cases.forEach(function(testcase) { + var set = testcase.split('\n'); + var pattern = set.shift(); + var actual = expand(pattern); + + // If it expands to the empty string, then it's actually + // just nothing, but Bash is a singly typed language, so + // "nothing" is the same as "". + if (set.length === 1 && set[0] === '') { + set = [] + } else { + // otherwise, strip off the [] that were added so that + // "" expansions would be preserved properly. + set = set.map(function (s) { + return s.replace(/^\[|\]$/g, '') + }) + } + + t.same(actual, set, pattern); + }); + t.end(); +}) diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt new file mode 100644 index 00000000000000..958148d26aacb9 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt @@ -0,0 +1,1075 @@ +A{b,{d,e},{f,g}}Z +[AbZ] +[AdZ] +[AeZ] +[AfZ] +[AgZ]><><><><><><><\{a,b}{{a,b},a,b} +[{a,b}a] +[{a,b}b] +[{a,b}a] +[{a,b}b]><><><><{{a,b} +[{a] +[{b]><><><><{a,b}} +[a}] +[b}]><><><><{,} +><><><><><><><{,}b +[b] +[b]><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><{-01..5} +[-01] +[000] +[001] +[002] +[003] +[004] +[005]><><><><{-05..100..5} +[-05] +[000] +[005] +[010] +[015] +[020] +[025] +[030] +[035] +[040] +[045] +[050] +[055] +[060] +[065] +[070] +[075] +[080] +[085] +[090] +[095] +[100]><><><><{-05..100} +[-05] +[-04] +[-03] +[-02] +[-01] +[000] +[001] +[002] +[003] +[004] +[005] +[006] +[007] +[008] +[009] +[010] +[011] +[012] +[013] +[014] +[015] +[016] +[017] +[018] +[019] +[020] +[021] +[022] +[023] +[024] +[025] +[026] +[027] +[028] +[029] +[030] +[031] +[032] +[033] +[034] +[035] +[036] +[037] +[038] +[039] +[040] +[041] +[042] +[043] +[044] +[045] +[046] +[047] +[048] +[049] +[050] +[051] +[052] +[053] +[054] +[055] +[056] +[057] +[058] +[059] +[060] +[061] +[062] +[063] +[064] +[065] +[066] +[067] +[068] +[069] +[070] +[071] +[072] +[073] +[074] +[075] +[076] +[077] +[078] +[079] +[080] +[081] +[082] +[083] +[084] +[085] +[086] +[087] +[088] +[089] +[090] +[091] +[092] +[093] +[094] +[095] +[096] +[097] +[098] +[099] +[100]><><><><{0..5..2} +[0] +[2] +[4]><><><><{0001..05..2} +[0001] +[0003] +[0005]><><><><{0001..-5..2} +[0001] +[-001] +[-003] +[-005]><><><><{0001..-5..-2} +[0001] +[-001] +[-003] +[-005]><><><><{0001..5..-2} +[0001] +[0003] +[0005]><><><><{01..5} +[01] +[02] +[03] +[04] +[05]><><><><{1..05} +[01] +[02] +[03] +[04] +[05]><><><><{1..05..3} +[01] +[04]><><><><{05..100} +[005] +[006] +[007] +[008] +[009] +[010] +[011] +[012] +[013] +[014] +[015] +[016] +[017] +[018] +[019] +[020] +[021] +[022] +[023] +[024] +[025] +[026] +[027] +[028] +[029] +[030] +[031] +[032] +[033] +[034] +[035] +[036] +[037] +[038] +[039] +[040] +[041] +[042] +[043] +[044] +[045] +[046] +[047] +[048] +[049] +[050] +[051] +[052] +[053] +[054] +[055] +[056] +[057] +[058] +[059] +[060] +[061] +[062] +[063] +[064] +[065] +[066] +[067] +[068] +[069] +[070] +[071] +[072] +[073] +[074] +[075] +[076] +[077] +[078] +[079] +[080] +[081] +[082] +[083] +[084] +[085] +[086] +[087] +[088] +[089] +[090] +[091] +[092] +[093] +[094] +[095] +[096] +[097] +[098] +[099] +[100]><><><><{0a..0z} +[{0a..0z}]><><><><{a,b\}c,d} +[a] +[b}c] +[d]><><><><{a,b{c,d} +[{a,bc] +[{a,bd]><><><><{a,b}c,d} +[ac,d}] +[bc,d}]><><><><{a..F} +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z] +[Y] +[X] +[W] +[V] +[U] +[T] +[S] +[R] +[Q] +[P] +[O] +[N] +[M] +[L] +[K] +[J] +[I] +[H] +[G] +[F]><><><><{A..f} +[A] +[B] +[C] +[D] +[E] +[F] +[G] +[H] +[I] +[J] +[K] +[L] +[M] +[N] +[O] +[P] +[Q] +[R] +[S] +[T] +[U] +[V] +[W] +[X] +[Y] +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a] +[b] +[c] +[d] +[e] +[f]><><><><{a..Z} +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z]><><><><{A..z} +[A] +[B] +[C] +[D] +[E] +[F] +[G] +[H] +[I] +[J] +[K] +[L] +[M] +[N] +[O] +[P] +[Q] +[R] +[S] +[T] +[U] +[V] +[W] +[X] +[Y] +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a] +[b] +[c] +[d] +[e] +[f] +[g] +[h] +[i] +[j] +[k] +[l] +[m] +[n] +[o] +[p] +[q] +[r] +[s] +[t] +[u] +[v] +[w] +[x] +[y] +[z]><><><><{z..A} +[z] +[y] +[x] +[w] +[v] +[u] +[t] +[s] +[r] +[q] +[p] +[o] +[n] +[m] +[l] +[k] +[j] +[i] +[h] +[g] +[f] +[e] +[d] +[c] +[b] +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z] +[Y] +[X] +[W] +[V] +[U] +[T] +[S] +[R] +[Q] +[P] +[O] +[N] +[M] +[L] +[K] +[J] +[I] +[H] +[G] +[F] +[E] +[D] +[C] +[B] +[A]><><><><{Z..a} +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a]><><><><{a..F..2} +[a] +[_] +[]] +[[] +[Y] +[W] +[U] +[S] +[Q] +[O] +[M] +[K] +[I] +[G]><><><><{A..f..02} +[A] +[C] +[E] +[G] +[I] +[K] +[M] +[O] +[Q] +[S] +[U] +[W] +[Y] +[[] +[]] +[_] +[a] +[c] +[e]><><><><{a..Z..5} +[a] +[]><><><><><><><{A..z..10} +[A] +[K] +[U] +[_] +[i] +[s]><><><><{z..A..-2} +[z] +[x] +[v] +[t] +[r] +[p] +[n] +[l] +[j] +[h] +[f] +[d] +[b] +[`] +[^] +[] +[Z] +[X] +[V] +[T] +[R] +[P] +[N] +[L] +[J] +[H] +[F] +[D] +[B]><><><><{Z..a..20} +[Z]><><><><{a{,b} +[{a] +[{ab]><><><><{a},b} +[a}] +[b]><><><><{x,y{,}g} +[x] +[yg] +[yg]><><><><{x,y{}g} +[x] +[y{}g]><><><><{{a,b} +[{a] +[{b]><><><><{{a,b},c} +[a] +[b] +[c]><><><><{{a,b}c} +[{ac}] +[{bc}]><><><><{{a,b},} +[a] +[b]><><><><><><><{{a,b},}c +[ac] +[bc] +[c]><><><><{{a,b}.} +[{a.}] +[{b.}]><><><><{{a,b}} +[{a}] +[{b}]><><><><><><>< +><><><><{-10..00} +[-10] +[-09] +[-08] +[-07] +[-06] +[-05] +[-04] +[-03] +[-02] +[-01] +[000]><><><><{a,\\{a,b}c} +[a] +[\ac] +[\bc]><><><><{a,\{a,b}c} +[ac}] +[{ac}] +[bc}]><><><><><><><{-10.\.00} +[{-10..00}]><><><><><><><><><><{l,n,m}xyz +[lxyz] +[nxyz] +[mxyz]><><><><{abc\,def} +[{abc,def}]><><><><{abc} +[{abc}]><><><><{x\,y,\{abc\},trie} +[x,y] +[{abc}] +[trie]><><><><{} +[{}]><><><><} +[}]><><><><{ +[{]><><><><><><><{1..10} +[1] +[2] +[3] +[4] +[5] +[6] +[7] +[8] +[9] +[10]><><><><{0..10,braces} +[0..10] +[braces]><><><><{{0..10},braces} +[0] +[1] +[2] +[3] +[4] +[5] +[6] +[7] +[8] +[9] +[10] +[braces]><><><><><><><{3..3} +[3]><><><><><><><{10..1} +[10] +[9] +[8] +[7] +[6] +[5] +[4] +[3] +[2] +[1]><><><><{10..1}y +[10y] +[9y] +[8y] +[7y] +[6y] +[5y] +[4y] +[3y] +[2y] +[1y]><><><><><><><{a..f} +[a] +[b] +[c] +[d] +[e] +[f]><><><><{f..a} +[f] +[e] +[d] +[c] +[b] +[a]><><><><{a..A} +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z] +[Y] +[X] +[W] +[V] +[U] +[T] +[S] +[R] +[Q] +[P] +[O] +[N] +[M] +[L] +[K] +[J] +[I] +[H] +[G] +[F] +[E] +[D] +[C] +[B] +[A]><><><><{A..a} +[A] +[B] +[C] +[D] +[E] +[F] +[G] +[H] +[I] +[J] +[K] +[L] +[M] +[N] +[O] +[P] +[Q] +[R] +[S] +[T] +[U] +[V] +[W] +[X] +[Y] +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a]><><><><{f..f} +[f]><><><><{1..f} +[{1..f}]><><><><{f..1} +[{f..1}]><><><><{-1..-10} +[-1] +[-2] +[-3] +[-4] +[-5] +[-6] +[-7] +[-8] +[-9] +[-10]><><><><{-20..0} +[-20] +[-19] +[-18] +[-17] +[-16] +[-15] +[-14] +[-13] +[-12] +[-11] +[-10] +[-9] +[-8] +[-7] +[-6] +[-5] +[-4] +[-3] +[-2] +[-1] +[0]><><><><><><><><><><{klklkl}{1,2,3} +[{klklkl}1] +[{klklkl}2] +[{klklkl}3]><><><><{1..10..2} +[1] +[3] +[5] +[7] +[9]><><><><{-1..-10..2} +[-1] +[-3] +[-5] +[-7] +[-9]><><><><{-1..-10..-2} +[-1] +[-3] +[-5] +[-7] +[-9]><><><><{10..1..-2} +[10] +[8] +[6] +[4] +[2]><><><><{10..1..2} +[10] +[8] +[6] +[4] +[2]><><><><{1..20..2} +[1] +[3] +[5] +[7] +[9] +[11] +[13] +[15] +[17] +[19]><><><><{1..20..20} +[1]><><><><{100..0..5} +[100] +[95] +[90] +[85] +[80] +[75] +[70] +[65] +[60] +[55] +[50] +[45] +[40] +[35] +[30] +[25] +[20] +[15] +[10] +[5] +[0]><><><><{100..0..-5} +[100] +[95] +[90] +[85] +[80] +[75] +[70] +[65] +[60] +[55] +[50] +[45] +[40] +[35] +[30] +[25] +[20] +[15] +[10] +[5] +[0]><><><><{a..z} +[a] +[b] +[c] +[d] +[e] +[f] +[g] +[h] +[i] +[j] +[k] +[l] +[m] +[n] +[o] +[p] +[q] +[r] +[s] +[t] +[u] +[v] +[w] +[x] +[y] +[z]><><><><{a..z..2} +[a] +[c] +[e] +[g] +[i] +[k] +[m] +[o] +[q] +[s] +[u] +[w] +[y]><><><><{z..a..-2} +[z] +[x] +[v] +[t] +[r] +[p] +[n] +[l] +[j] +[h] +[f] +[d] +[b]><><><><{2147483645..2147483649} +[2147483645] +[2147483646] +[2147483647] +[2147483648] +[2147483649]><><><><{10..0..2} +[10] +[8] +[6] +[4] +[2] +[0]><><><><{10..0..-2} +[10] +[8] +[6] +[4] +[2] +[0]><><><><{-50..-0..5} +[-50] +[-45] +[-40] +[-35] +[-30] +[-25] +[-20] +[-15] +[-10] +[-5] +[0]><><><><{1..10.f} +[{1..10.f}]><><><><{1..ff} +[{1..ff}]><><><><{1..10..ff} +[{1..10..ff}]><><><><{1.20..2} +[{1.20..2}]><><><><{1..20..f2} +[{1..20..f2}]><><><><{1..20..2f} +[{1..20..2f}]><><><><{1..2f..2} +[{1..2f..2}]><><><><{1..ff..2} +[{1..ff..2}]><><><><{1..ff} +[{1..ff}]><><><><{1..f} +[{1..f}]><><><><{1..0f} +[{1..0f}]><><><><{1..10f} +[{1..10f}]><><><><{1..10.f} +[{1..10.f}]><><><><{1..10.f} +[{1..10.f}]><><><>< \ No newline at end of file diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt new file mode 100644 index 00000000000000..e5161c3da869f3 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt @@ -0,0 +1,182 @@ +# skip quotes for now +# "{x,x}" +# {"x,x"} +# {x","x} +# '{a,b}{{a,b},a,b}' +A{b,{d,e},{f,g}}Z +PRE-{a,b}{{a,b},a,b}-POST +\\{a,b}{{a,b},a,b} +{{a,b} +{a,b}} +{,} +a{,} +{,}b +a{,}b +a{b}c +a{1..5}b +a{01..5}b +a{-01..5}b +a{-01..5..3}b +a{001..9}b +a{b,c{d,e},{f,g}h}x{y,z +a{b,c{d,e},{f,g}h}x{y,z\\} +a{b,c{d,e},{f,g}h}x{y,z} +a{b{c{d,e}f{x,y{{g}h +a{b{c{d,e}f{x,y{}g}h +a{b{c{d,e}f{x,y}}g}h +a{b{c{d,e}f}g}h +a{{x,y},z}b +f{x,y{g,z}}h +f{x,y{{g,z}}h +f{x,y{{g,z}}h} +f{x,y{{g}h +f{x,y{{g}}h +f{x,y{}g}h +z{a,b{,c}d +z{a,b},c}d +{-01..5} +{-05..100..5} +{-05..100} +{0..5..2} +{0001..05..2} +{0001..-5..2} +{0001..-5..-2} +{0001..5..-2} +{01..5} +{1..05} +{1..05..3} +{05..100} +{0a..0z} +{a,b\\}c,d} +{a,b{c,d} +{a,b}c,d} +{a..F} +{A..f} +{a..Z} +{A..z} +{z..A} +{Z..a} +{a..F..2} +{A..f..02} +{a..Z..5} +d{a..Z..5}b +{A..z..10} +{z..A..-2} +{Z..a..20} +{a{,b} +{a},b} +{x,y{,}g} +{x,y{}g} +{{a,b} +{{a,b},c} +{{a,b}c} +{{a,b},} +X{{a,b},}X +{{a,b},}c +{{a,b}.} +{{a,b}} +X{a..#}X +# this next one is an empty string + +{-10..00} +# Need to escape slashes in here for reasons i guess. +{a,\\\\{a,b}c} +{a,\\{a,b}c} +a,\\{b,c} +{-10.\\.00} +#### bash tests/braces.tests +# Note that some tests are edited out because some features of +# bash are intentionally not supported in this brace expander. +ff{c,b,a} +f{d,e,f}g +{l,n,m}xyz +{abc\\,def} +{abc} +{x\\,y,\\{abc\\},trie} +# not impementing back-ticks obviously +# XXXX\\{`echo a b c | tr ' ' ','`\\} +{} +# We only ever have to worry about parsing a single argument, +# not a command line, so spaces have a different meaning than bash. +# { } +} +{ +abcd{efgh +# spaces +# foo {1,2} bar +# not impementing back-ticks obviously +# `zecho foo {1,2} bar` +# $(zecho foo {1,2} bar) +# ${var} is not a variable here, like it is in bash. omit. +# foo{bar,${var}.} +# foo{bar,${var}} +# isaacs: skip quotes for now +# "${var}"{x,y} +# $var{x,y} +# ${var}{x,y} +# new sequence brace operators +{1..10} +# this doesn't work yet +{0..10,braces} +# but this does +{{0..10},braces} +x{{0..10},braces}y +{3..3} +x{3..3}y +{10..1} +{10..1}y +x{10..1}y +{a..f} +{f..a} +{a..A} +{A..a} +{f..f} +# mixes are incorrectly-formed brace expansions +{1..f} +{f..1} +# spaces +# 0{1..9} {10..20} +# do negative numbers work? +{-1..-10} +{-20..0} +# weirdly-formed brace expansions -- fixed in post-bash-3.1 +a-{b{d,e}}-c +a-{bdef-{g,i}-c +# isaacs: skip quotes for now +# {"klklkl"}{1,2,3} +# isaacs: this is a valid test, though +{klklkl}{1,2,3} +# {"x,x"} +{1..10..2} +{-1..-10..2} +{-1..-10..-2} +{10..1..-2} +{10..1..2} +{1..20..2} +{1..20..20} +{100..0..5} +{100..0..-5} +{a..z} +{a..z..2} +{z..a..-2} +# make sure brace expansion handles ints > 2**31 - 1 using intmax_t +{2147483645..2147483649} +# unwanted zero-padding -- fixed post-bash-4.0 +{10..0..2} +{10..0..-2} +{-50..-0..5} +# bad +{1..10.f} +{1..ff} +{1..10..ff} +{1.20..2} +{1..20..f2} +{1..20..2f} +{1..2f..2} +{1..ff..2} +{1..ff} +{1..f} +{1..0f} +{1..10f} +{1..10.f} +{1..10.f} diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js new file mode 100644 index 00000000000000..3fcc185a7d6dcc --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var expand = require('..'); + +test('ignores ${', function(t) { + t.deepEqual(expand('${1..3}'), ['${1..3}']); + t.deepEqual(expand('${a,b}${c,d}'), ['${a,b}${c,d}']); + t.deepEqual(expand('x${a,b}x${c,d}x'), ['x${a,b}x${c,d}x']); + t.end(); +}); diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js new file mode 100644 index 00000000000000..e429121eab8059 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js @@ -0,0 +1,10 @@ +var test = require('tape'); +var expand = require('..'); + +test('empty option', function(t) { + t.deepEqual(expand('-v{,,,,}'), [ + '-v', '-v', '-v', '-v', '-v' + ]); + t.end(); +}); + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh new file mode 100644 index 00000000000000..e040e664d9f881 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -e + +# Bash 4.3 because of arbitrary need to pick a single standard. + +if [ "${BASH_VERSINFO[0]}" != "4" ] || [ "${BASH_VERSINFO[1]}" != "3" ]; then + echo "this script requires bash 4.3" >&2 + exit 1 +fi + +CDPATH= cd "$(dirname "$0")" + +js='require("./")(process.argv[1]).join(" ")' + +cat cases.txt | \ + while read case; do + if [ "${case:0:1}" = "#" ]; then + continue; + fi; + b="$($BASH -c 'for c in '"$case"'; do echo ["$c"]; done')" + echo "$case" + echo -n "$b><><><><"; + done > bash-results.txt diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js new file mode 100644 index 00000000000000..8d434c23d4514d --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var expand = require('..'); + +test('negative increment', function(t) { + t.deepEqual(expand('{3..1}'), ['3', '2', '1']); + t.deepEqual(expand('{10..8}'), ['10', '9', '8']); + t.deepEqual(expand('{10..08}'), ['10', '09', '08']); + t.deepEqual(expand('{c..a}'), ['c', 'b', 'a']); + + t.deepEqual(expand('{4..0..2}'), ['4', '2', '0']); + t.deepEqual(expand('{4..0..-2}'), ['4', '2', '0']); + t.deepEqual(expand('{e..a..2}'), ['e', 'c', 'a']); + + t.end(); +}); diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/nested.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/nested.js new file mode 100644 index 00000000000000..0862dc51f90aee --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/nested.js @@ -0,0 +1,16 @@ +var test = require('tape'); +var expand = require('..'); + +test('nested', function(t) { + t.deepEqual(expand('{a,b{1..3},c}'), [ + 'a', 'b1', 'b2', 'b3', 'c' + ]); + t.deepEqual(expand('{{A..Z},{a..z}}'), + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') + ); + t.deepEqual(expand('ppp{,config,oe{,conf}}'), [ + 'ppp', 'pppconfig', 'pppoe', 'pppoeconf' + ]); + t.end(); +}); + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/order.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/order.js new file mode 100644 index 00000000000000..c00ad155fe6760 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/order.js @@ -0,0 +1,10 @@ +var test = require('tape'); +var expand = require('..'); + +test('order', function(t) { + t.deepEqual(expand('a{d,c,b}e'), [ + 'ade', 'ace', 'abe' + ]); + t.end(); +}); + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/pad.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/pad.js new file mode 100644 index 00000000000000..e4158775f1bd06 --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/pad.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var expand = require('..'); + +test('pad', function(t) { + t.deepEqual(expand('{9..11}'), [ + '9', '10', '11' + ]); + t.deepEqual(expand('{09..11}'), [ + '09', '10', '11' + ]); + t.end(); +}); + diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js new file mode 100644 index 00000000000000..3038fba7416b3a --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js @@ -0,0 +1,7 @@ +var test = require('tape'); +var expand = require('..'); + +test('x and y of same type', function(t) { + t.deepEqual(expand('{a..9}'), ['{a..9}']); + t.end(); +}); diff --git a/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js new file mode 100644 index 00000000000000..f73a9579ab398b --- /dev/null +++ b/tools/eslint/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js @@ -0,0 +1,50 @@ +var test = require('tape'); +var expand = require('..'); + +test('numeric sequences', function(t) { + t.deepEqual(expand('a{1..2}b{2..3}c'), [ + 'a1b2c', 'a1b3c', 'a2b2c', 'a2b3c' + ]); + t.deepEqual(expand('{1..2}{2..3}'), [ + '12', '13', '22', '23' + ]); + t.end(); +}); + +test('numeric sequences with step count', function(t) { + t.deepEqual(expand('{0..8..2}'), [ + '0', '2', '4', '6', '8' + ]); + t.deepEqual(expand('{1..8..2}'), [ + '1', '3', '5', '7' + ]); + t.end(); +}); + +test('numeric sequence with negative x / y', function(t) { + t.deepEqual(expand('{3..-2}'), [ + '3', '2', '1', '0', '-1', '-2' + ]); + t.end(); +}); + +test('alphabetic sequences', function(t) { + t.deepEqual(expand('1{a..b}2{b..c}3'), [ + '1a2b3', '1a2c3', '1b2b3', '1b2c3' + ]); + t.deepEqual(expand('{a..b}{b..c}'), [ + 'ab', 'ac', 'bb', 'bc' + ]); + t.end(); +}); + +test('alphabetic sequences with step count', function(t) { + t.deepEqual(expand('{a..k..2}'), [ + 'a', 'c', 'e', 'g', 'i', 'k' + ]); + t.deepEqual(expand('{b..k..2}'), [ + 'b', 'd', 'f', 'h', 'j' + ]); + t.end(); +}); + diff --git a/tools/eslint/node_modules/minimatch/package.json b/tools/eslint/node_modules/minimatch/package.json new file mode 100644 index 00000000000000..b438bdb9458aea --- /dev/null +++ b/tools/eslint/node_modules/minimatch/package.json @@ -0,0 +1,66 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "2.0.7", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "pretest": "standard minimatch.js test/*.js", + "test": "tap test/*.js", + "prepublish": "browserify -o browser.js -e minimatch.js --bare" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "brace-expansion": "^1.0.0" + }, + "devDependencies": { + "browserify": "^9.0.3", + "standard": "^3.7.2", + "tap": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" + }, + "files": [ + "minimatch.js", + "browser.js" + ], + "gitHead": "4bd6dc22c248c7ea07cc49d63181fe6f6aafae9c", + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "homepage": "https://github.com/isaacs/minimatch", + "_id": "minimatch@2.0.7", + "_shasum": "d23652ab10e663e7d914602e920e21f9f66492be", + "_from": "minimatch@>=2.0.1 <3.0.0", + "_npmVersion": "2.7.6", + "_nodeVersion": "1.7.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "d23652ab10e663e7d914602e920e21f9f66492be", + "tarball": "http://registry.npmjs.org/minimatch/-/minimatch-2.0.7.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/mkdirp/.npmignore b/tools/eslint/node_modules/mkdirp/.npmignore new file mode 100644 index 00000000000000..9303c347ee69a1 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log \ No newline at end of file diff --git a/tools/eslint/node_modules/mkdirp/.travis.yml b/tools/eslint/node_modules/mkdirp/.travis.yml new file mode 100644 index 00000000000000..c693a939df9809 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - "0.10" diff --git a/tools/eslint/node_modules/mkdirp/LICENSE b/tools/eslint/node_modules/mkdirp/LICENSE new file mode 100644 index 00000000000000..432d1aeb01df66 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/mkdirp/bin/cmd.js b/tools/eslint/node_modules/mkdirp/bin/cmd.js new file mode 100755 index 00000000000000..d95de15ae9743f --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/tools/eslint/node_modules/mkdirp/bin/usage.txt b/tools/eslint/node_modules/mkdirp/bin/usage.txt new file mode 100644 index 00000000000000..f952aa2c7a979e --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/bin/usage.txt @@ -0,0 +1,12 @@ +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + diff --git a/tools/eslint/node_modules/mkdirp/examples/pow.js b/tools/eslint/node_modules/mkdirp/examples/pow.js new file mode 100644 index 00000000000000..e6924212e6a244 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/examples/pow.js @@ -0,0 +1,6 @@ +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); diff --git a/tools/eslint/node_modules/mkdirp/index.js b/tools/eslint/node_modules/mkdirp/index.js new file mode 100644 index 00000000000000..a1742b20694fe3 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/index.js @@ -0,0 +1,97 @@ +var path = require('path'); +var fs = require('fs'); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/.travis.yml b/tools/eslint/node_modules/mkdirp/node_modules/minimist/.travis.yml new file mode 100644 index 00000000000000..cc4dba29d959a2 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/LICENSE b/tools/eslint/node_modules/mkdirp/node_modules/minimist/LICENSE new file mode 100644 index 00000000000000..ee27ba4b4412b0 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/example/parse.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/example/parse.js new file mode 100644 index 00000000000000..abff3e8ee8f5ef --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.dir(argv); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/index.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/index.js new file mode 100644 index 00000000000000..584f551a6da734 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/index.js @@ -0,0 +1,187 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {} }; + + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + }); + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function setArg (key, val) { + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + setArg(m[1], m[2]); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2)); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, args[i+1]); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + } + else { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + notFlags.forEach(function(key) { + argv._.push(key); + }); + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function longest (xs) { + return Math.max.apply(null, xs.map(function (x) { return x.length })); +} diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/package.json b/tools/eslint/node_modules/mkdirp/node_modules/minimist/package.json new file mode 100644 index 00000000000000..d181aafcd40179 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/package.json @@ -0,0 +1,68 @@ +{ + "name": "minimist", + "version": "0.0.8", + "description": "parse argument options", + "main": "index.js", + "devDependencies": { + "tape": "~1.0.4", + "tap": "~0.4.0" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "_id": "minimist@0.0.8", + "dist": { + "shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", + "tarball": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz" + }, + "_from": "minimist@0.0.8", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "substack", + "email": "mail@substack.net" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + } + ], + "directories": {}, + "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "readme": "# minimist\n\nparse argument options\n\nThis module is the guts of optimist's argument parser without all the\nfanciful decoration.\n\n[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist)\n\n[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist)\n\n# example\n\n``` js\nvar argv = require('minimist')(process.argv.slice(2));\nconsole.dir(argv);\n```\n\n```\n$ node example/parse.js -a beep -b boop\n{ _: [], a: 'beep', b: 'boop' }\n```\n\n```\n$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz\n{ _: [ 'foo', 'bar', 'baz' ],\n x: 3,\n y: 4,\n n: 5,\n a: true,\n b: true,\n c: true,\n beep: 'boop' }\n```\n\n# methods\n\n``` js\nvar parseArgs = require('minimist')\n```\n\n## var argv = parseArgs(args, opts={})\n\nReturn an argument object `argv` populated with the array arguments from `args`.\n\n`argv._` contains all the arguments that didn't have an option associated with\nthem.\n\nNumeric-looking arguments will be returned as numbers unless `opts.string` or\n`opts.boolean` is set for that argument name.\n\nAny arguments after `'--'` will not be parsed and will end up in `argv._`.\n\noptions can be:\n\n* `opts.string` - a string or array of strings argument names to always treat as\nstrings\n* `opts.boolean` - a string or array of strings to always treat as booleans\n* `opts.alias` - an object mapping string names to strings or arrays of string\nargument names to use as aliases\n* `opts.default` - an object mapping string argument names to default values\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install minimist\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown" +} diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/readme.markdown b/tools/eslint/node_modules/mkdirp/node_modules/minimist/readme.markdown new file mode 100644 index 00000000000000..c25635323e1661 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/readme.markdown @@ -0,0 +1,73 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) + +[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.dir(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/dash.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/dash.js new file mode 100644 index 00000000000000..8b034b99a9eace --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/dash.js @@ -0,0 +1,24 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/default_bool.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/default_bool.js new file mode 100644 index 00000000000000..f0041ee40cd05f --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/default_bool.js @@ -0,0 +1,20 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/dotted.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/dotted.js new file mode 100644 index 00000000000000..ef0ae349bf3bf5 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/dotted.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/long.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/long.js new file mode 100644 index 00000000000000..5d3a1e09d3b64c --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/parse.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/parse.js new file mode 100644 index 00000000000000..8a90646696628e --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/parse.js @@ -0,0 +1,318 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); + +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js new file mode 100644 index 00000000000000..21851b036ee6d9 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: ['123'] }); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/short.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/short.js new file mode 100644 index 00000000000000..d513a1c2529095 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/whitespace.js b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/whitespace.js new file mode 100644 index 00000000000000..8a52a58cecfd7a --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/tools/eslint/node_modules/mkdirp/package.json b/tools/eslint/node_modules/mkdirp/package.json new file mode 100644 index 00000000000000..b1493bac2c175c --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/package.json @@ -0,0 +1,59 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "0.5.0", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "main": "./index", + "keywords": [ + "mkdir", + "directory" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "minimist": "0.0.8" + }, + "devDependencies": { + "tap": "~0.4.0", + "mock-fs": "~2.2.0" + }, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "homepage": "https://github.com/substack/node-mkdirp", + "_id": "mkdirp@0.5.0", + "dist": { + "shasum": "1d73076a6df986cd9344e15e71fcc05a4c9abf12", + "tarball": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz" + }, + "_from": "mkdirp@>=0.5.0 <0.6.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "substack", + "email": "mail@substack.net" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + } + ], + "directories": {}, + "_shasum": "1d73076a6df986cd9344e15e71fcc05a4c9abf12", + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", + "readme": "# mkdirp\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\n# example\n\n## pow.js\n\n```js\nvar mkdirp = require('mkdirp');\n \nmkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n});\n```\n\nOutput\n\n```\npow!\n```\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\n# methods\n\n```js\nvar mkdirp = require('mkdirp');\n```\n\n## mkdirp(dir, opts, cb)\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `opts.mode`. If `opts` is a non-object, it will be treated as\nthe `opts.mode`.\n\nIf `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\nYou can optionally pass in an alternate `fs` implementation by passing in\n`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and\n`opts.fs.stat(path, cb)`.\n\n## mkdirp.sync(dir, opts)\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `opts.mode`. If `opts` is a non-object, it will be\ntreated as the `opts.mode`.\n\nIf `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\nYou can optionally pass in an alternate `fs` implementation by passing in\n`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and\n`opts.fs.statSync(path)`.\n\n# usage\n\nThis package also ships with a `mkdirp` command.\n\n```\nusage: mkdirp [DIR1,DIR2..] {OPTIONS}\n\n Create each supplied directory including any necessary parent directories that\n don't yet exist.\n \n If the directory already exists, do nothing.\n\nOPTIONS are:\n\n -m, --mode If a directory needs to be created, set the mode as an octal\n permission string.\n\n```\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\nto get the library, or\n\n```\nnpm install -g mkdirp\n```\n\nto get the command.\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown" +} diff --git a/tools/eslint/node_modules/mkdirp/readme.markdown b/tools/eslint/node_modules/mkdirp/readme.markdown new file mode 100644 index 00000000000000..3cc13153851162 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/readme.markdown @@ -0,0 +1,100 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, opts, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a non-object, it will be treated as +the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and +`opts.fs.stat(path, cb)`. + +## mkdirp.sync(dir, opts) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `opts.mode`. If `opts` is a non-object, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +Returns the first directory that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and +`opts.fs.statSync(path)`. + +# usage + +This package also ships with a `mkdirp` command. + +``` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library, or + +``` +npm install -g mkdirp +``` + +to get the command. + +# license + +MIT diff --git a/tools/eslint/node_modules/mkdirp/test/chmod.js b/tools/eslint/node_modules/mkdirp/test/chmod.js new file mode 100644 index 00000000000000..520dcb8e9b5a75 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/chmod.js @@ -0,0 +1,38 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +test('chmod-pre', function (t) { + var mode = 0744 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); + t.end(); + }); + }); +}); + +test('chmod', function (t) { + var mode = 0755 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.end(); + }); + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/clobber.js b/tools/eslint/node_modules/mkdirp/test/clobber.js new file mode 100644 index 00000000000000..0eb709987002f0 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/clobber.js @@ -0,0 +1,37 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +// a file in the way +var itw = ps.slice(0, 3).join('/'); + + +test('clobber-pre', function (t) { + console.error("about to write to "+itw) + fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); + + fs.stat(itw, function (er, stat) { + t.ifError(er) + t.ok(stat && stat.isFile(), 'should be file') + t.end() + }) +}) + +test('clobber', function (t) { + t.plan(2); + mkdirp(file, 0755, function (err) { + t.ok(err); + t.equal(err.code, 'ENOTDIR'); + t.end(); + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/mkdirp.js b/tools/eslint/node_modules/mkdirp/test/mkdirp.js new file mode 100644 index 00000000000000..3b624ddbeb0db8 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/mkdirp.js @@ -0,0 +1,26 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('woo', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, 0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/opts_fs.js b/tools/eslint/node_modules/mkdirp/test/opts_fs.js new file mode 100644 index 00000000000000..f1fbeca146d128 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/opts_fs.js @@ -0,0 +1,27 @@ +var mkdirp = require('../'); +var path = require('path'); +var test = require('tap').test; +var mockfs = require('mock-fs'); + +test('opts.fs', function (t) { + t.plan(5); + + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/beep/boop/' + [x,y,z].join('/'); + var xfs = mockfs.fs(); + + mkdirp(file, { fs: xfs, mode: 0755 }, function (err) { + t.ifError(err); + xfs.exists(file, function (ex) { + t.ok(ex, 'created file'); + xfs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/opts_fs_sync.js b/tools/eslint/node_modules/mkdirp/test/opts_fs_sync.js new file mode 100644 index 00000000000000..224b50642feafd --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/opts_fs_sync.js @@ -0,0 +1,25 @@ +var mkdirp = require('../'); +var path = require('path'); +var test = require('tap').test; +var mockfs = require('mock-fs'); + +test('opts.fs sync', function (t) { + t.plan(4); + + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/beep/boop/' + [x,y,z].join('/'); + var xfs = mockfs.fs(); + + mkdirp.sync(file, { fs: xfs, mode: 0755 }); + xfs.exists(file, function (ex) { + t.ok(ex, 'created file'); + xfs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/perm.js b/tools/eslint/node_modules/mkdirp/test/perm.js new file mode 100644 index 00000000000000..2c975905204646 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/perm.js @@ -0,0 +1,30 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('async perm', function (t) { + t.plan(5); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); + + mkdirp(file, 0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); + +test('async root perm', function (t) { + mkdirp('/tmp', 0755, function (err) { + if (err) t.fail(err); + t.end(); + }); + t.end(); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/perm_sync.js b/tools/eslint/node_modules/mkdirp/test/perm_sync.js new file mode 100644 index 00000000000000..327e54b2e951f2 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/perm_sync.js @@ -0,0 +1,34 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('sync perm', function (t) { + t.plan(4); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; + + mkdirp.sync(file, 0755); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); + +test('sync root perm', function (t) { + t.plan(3); + + var file = '/tmp'; + mkdirp.sync(file, 0755); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/race.js b/tools/eslint/node_modules/mkdirp/test/race.js new file mode 100644 index 00000000000000..7c295f410de2cc --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/race.js @@ -0,0 +1,40 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('race', function (t) { + t.plan(6); + var ps = [ '', 'tmp' ]; + + for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); + } + var file = ps.join('/'); + + var res = 2; + mk(file, function () { + if (--res === 0) t.end(); + }); + + mk(file, function () { + if (--res === 0) t.end(); + }); + + function mk (file, cb) { + mkdirp(file, 0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + if (cb) cb(); + }); + }) + }); + } +}); diff --git a/tools/eslint/node_modules/mkdirp/test/rel.js b/tools/eslint/node_modules/mkdirp/test/rel.js new file mode 100644 index 00000000000000..d1f175c2406543 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/rel.js @@ -0,0 +1,30 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('rel', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var cwd = process.cwd(); + process.chdir('/tmp'); + + var file = [x,y,z].join('/'); + + mkdirp(file, 0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + process.chdir(cwd); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/return.js b/tools/eslint/node_modules/mkdirp/test/return.js new file mode 100644 index 00000000000000..bce68e5613e3f9 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/return.js @@ -0,0 +1,25 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, '/tmp/' + x); + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, null); + }); + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/return_sync.js b/tools/eslint/node_modules/mkdirp/test/return_sync.js new file mode 100644 index 00000000000000..7c222d3558d6f0 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/return_sync.js @@ -0,0 +1,24 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + // Note that this will throw on failure, which will fail the test. + var made = mkdirp.sync(file); + t.equal(made, '/tmp/' + x); + + // making the same file again should have no effect. + made = mkdirp.sync(file); + t.equal(made, null); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/root.js b/tools/eslint/node_modules/mkdirp/test/root.js new file mode 100644 index 00000000000000..97ad7a2f358e93 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/root.js @@ -0,0 +1,18 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('root', function (t) { + // '/' on unix, 'c:/' on windows. + var file = path.resolve('/'); + + mkdirp(file, 0755, function (err) { + if (err) throw err + fs.stat(file, function (er, stat) { + if (er) throw er + t.ok(stat.isDirectory(), 'target is a directory'); + t.end(); + }) + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/sync.js b/tools/eslint/node_modules/mkdirp/test/sync.js new file mode 100644 index 00000000000000..88fa4324ee1901 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/sync.js @@ -0,0 +1,30 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('sync', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file, 0755); + } catch (err) { + t.fail(err); + return t.end(); + } + + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/umask.js b/tools/eslint/node_modules/mkdirp/test/umask.js new file mode 100644 index 00000000000000..82c393a006a8f5 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/umask.js @@ -0,0 +1,26 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('implicit mode from umask', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, 0777 & (~process.umask())); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }) + }); +}); diff --git a/tools/eslint/node_modules/mkdirp/test/umask_sync.js b/tools/eslint/node_modules/mkdirp/test/umask_sync.js new file mode 100644 index 00000000000000..e537fbe4beebc2 --- /dev/null +++ b/tools/eslint/node_modules/mkdirp/test/umask_sync.js @@ -0,0 +1,30 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; + +test('umask sync modes', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file); + } catch (err) { + t.fail(err); + return t.end(); + } + + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & 0777, (0777 & (~process.umask()))); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/tools/eslint/node_modules/object-assign/index.js b/tools/eslint/node_modules/object-assign/index.js new file mode 100644 index 00000000000000..438b80abb531dd --- /dev/null +++ b/tools/eslint/node_modules/object-assign/index.js @@ -0,0 +1,26 @@ +'use strict'; + +function ToObject(val) { + if (val == null) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +module.exports = Object.assign || function (target, source) { + var from; + var keys; + var to = ToObject(target); + + for (var s = 1; s < arguments.length; s++) { + from = arguments[s]; + keys = Object.keys(Object(from)); + + for (var i = 0; i < keys.length; i++) { + to[keys[i]] = from[keys[i]]; + } + } + + return to; +}; diff --git a/tools/eslint/node_modules/object-assign/package.json b/tools/eslint/node_modules/object-assign/package.json new file mode 100644 index 00000000000000..b03ee5ac88676a --- /dev/null +++ b/tools/eslint/node_modules/object-assign/package.json @@ -0,0 +1,68 @@ +{ + "name": "object-assign", + "version": "2.0.0", + "description": "ES6 Object.assign() ponyfill", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/object-assign.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es6", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "mocha": "*" + }, + "gitHead": "4cd0365f5a78dd369473ca0bbd31f7b234148c42", + "bugs": { + "url": "https://github.com/sindresorhus/object-assign/issues" + }, + "homepage": "https://github.com/sindresorhus/object-assign", + "_id": "object-assign@2.0.0", + "_shasum": "f8309b09083b01261ece3ef7373f2b57b8dd7042", + "_from": "object-assign@>=2.0.0 <3.0.0", + "_npmVersion": "2.1.5", + "_nodeVersion": "0.10.32", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "dist": { + "shasum": "f8309b09083b01261ece3ef7373f2b57b8dd7042", + "tarball": "http://registry.npmjs.org/object-assign/-/object-assign-2.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/object-assign/-/object-assign-2.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/object-assign/readme.md b/tools/eslint/node_modules/object-assign/readme.md new file mode 100644 index 00000000000000..aee51c12b56589 --- /dev/null +++ b/tools/eslint/node_modules/object-assign/readme.md @@ -0,0 +1,51 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES6 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) ponyfill + +> Ponyfill: A polyfill that doesn't overwrite the native method + + +## Install + +```sh +$ npm install --save object-assign +``` + + +## Usage + +```js +var objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, source, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES6 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/optionator/LICENSE b/tools/eslint/node_modules/optionator/LICENSE new file mode 100644 index 00000000000000..525b11850e6f2c --- /dev/null +++ b/tools/eslint/node_modules/optionator/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/optionator/README.md b/tools/eslint/node_modules/optionator/README.md new file mode 100644 index 00000000000000..99e3bc751ddace --- /dev/null +++ b/tools/eslint/node_modules/optionator/README.md @@ -0,0 +1,200 @@ +# Optionator + + +Optionator is an option parsing and help generation library. + +## Why? +The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. +With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). +If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. + + $ cmd --halp + Invalid option '--halp' - perhaps you meant '--help'? + + $ cmd --count str + Invalid value for option 'count' - expected type Int, received value: str. + +Over helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. + +## About +Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. + +Optionator is used by [Grasp](http://graspjs.com), [eslint](http://eslint.org), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and more. + +MIT license. Version 0.5.0 + + npm install optionator + +For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). + +## Usage +`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `generateHelp`, and `generateHelpForOption`, which are all functions. + +```js +var optionator = require('optionator')({ + prepend: 'Usage: cmd [options]', + append: 'Version 1.0.0', + options: [{ + option: 'help', + alias: 'h', + type: 'Boolean', + description: 'displays help' + }, { + option: 'count', + alias: 'c', + type: 'Int', + description: 'number of things', + example: 'cmd --count 2' + }] +}); +``` + +### parse(input, parseOptions) +`parse` processes the `input` according to your settings, and returns an object with the results. + +##### arguments +* input - `[String] | Object | String` - the input you wish to parse +* parseOptions - `{slice: Int}` - all options optional + - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) + +##### returns +`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. + +##### example +```js +parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} +parse('--count 2 positional'); // {count: 2, _: ['positional']} +parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} +``` + +### generateHelp(helpOptions) +`generateHelp` produces help text based on your settings. + +##### arguments +* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional + - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` + - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` + +##### returns +`String` - the generated help text + +##### example +```js +generateHelp(); /* +"Usage: cmd [options] positional + + -h, --help displays help + -c, --count Int number of things + +Version 1.0.0 +"*/ +``` + +### generateHelpForOption(optionName) +`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. + +##### arguments +* optionName - `String` - the name of the option to display + +##### returns +`String` - the generated help text for the option + +##### example +```js +generateHelpForOption('count'); /* +"-c, --count Int +description: number of things +example: cmd --count 2 +"*/ +``` + +## Settings Format +When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: + + { + prepend: Maybe String, + append: Maybe String, + options: [{heading: String} | { + option: String, + alias: Maybe [String] | String, + type: Maybe String, + enum: Maybe [String], + default: Maybe String, + restPositional: Maybe Boolean, + requried: Maybe Boolean, + overrideRequired: Maybe Bookean, + dependsOn: Maybe [String] | String, + description: Maybe String, + longDescription: Maybe String, + example: Maybe [String] | String + }], + helpStyle: Maybe { + aliasSeparator: Maybe String, + typeSeparator: Maybe String, + descriptionSeparator: Maybe String, + initialIndent: Maybe Int, + secondaryIndent: Maybe Int, + maxPadFactor: Maybe Number + }, + mutuallyExclusive: Maybe [[String | [String]]], + concatRepeatedArrays: Maybe Boolean, + mergeRepeatedObjects: Maybe Boolean + } + +### Top Level Properties +* `prepend` is an optional string to be placed before the options in the help text +* `append` is an optional string to be placed after the options in the help text +* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified +* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text +* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present +* `concatRepeatedArrays` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` +* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` + +#### Heading Properties +* `heading` a required string, the name of the heading + +#### Option Properties +* `option` the required name of the option - use dash-case, without the leading dashes +* `alias` is an optional string or array of strings which specify any aliases for the option +* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it +* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` +* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` +* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument +* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined +* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags +* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set +* `description` is an optional string, which will be displayed next to the option in the help text +* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used +* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used + +#### Help Style Properties +* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' +* `typeSeparator` is an optional string, separates the type from the names - default: ' ' +* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' +* `initialIndent` is an optional int - the amount of indent for options - default: 2 +* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 +* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 + +## Argument Format +At the highest level there are two types of arguments: named, and positional. + +Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). + +There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. + +For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. + +You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. + +Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. + +Everything after an `--` is positional, even if it looks like a named argument. + +You may optionally use `=` to separate option names from values, for example: `--count=2`. + +If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. + +If duplicate named arguments are present, the last one will be taken. + +## Technical About +`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/tools/eslint/node_modules/optionator/lib/coerce.js b/tools/eslint/node_modules/optionator/lib/coerce.js new file mode 100644 index 00000000000000..6fb60aa82de436 --- /dev/null +++ b/tools/eslint/node_modules/optionator/lib/coerce.js @@ -0,0 +1,367 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var ref$, id, reject, parsedTypeCheck, types, tokenRegex, toString$ = {}.toString; + ref$ = require('prelude-ls'), id = ref$.id, reject = ref$.reject; + parsedTypeCheck = require('type-check').parsedTypeCheck; + types = { + '*': function(it){ + switch (toString$.call(it).slice(8, -1)) { + case 'Array': + return coerceType(it, { + type: 'Array' + }); + case 'Object': + return coerceType(it, { + type: 'Object' + }); + default: + return { + type: 'Just', + value: coerceTypes(it, [ + { + type: 'Undefined' + }, { + type: 'Null' + }, { + type: 'Boolean' + }, { + type: 'Number' + }, { + type: 'Date' + }, { + type: 'RegExp' + }, { + type: 'Array' + }, { + type: 'Object' + }, { + type: 'String' + } + ], { + explicit: true + }) + }; + } + }, + Undefined: function(it){ + if (it === 'undefined') { + return { + type: 'Just', + value: void 8 + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Null: function(it){ + if (it === 'null') { + return { + type: 'Just', + value: null + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Boolean: function(it){ + if (it === 'true') { + return { + type: 'Just', + value: true + }; + } else if (it === 'false') { + return { + type: 'Just', + value: false + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Number: function(it){ + return { + type: 'Just', + value: +it + }; + }, + Int: function(it){ + return { + type: 'Just', + value: parseInt(it) + }; + }, + Float: function(it){ + return { + type: 'Just', + value: parseFloat(it) + }; + }, + Date: function(value, options){ + var that; + if (that = /^\#(.*)\#$/.exec(value)) { + return { + type: 'Just', + value: new Date(+that[1] || that[1]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new Date(+value || value) + }; + } + }, + RegExp: function(value, options){ + var that; + if (that = /^\/(.*)\/([gimy]*)$/.exec(value)) { + return { + type: 'Just', + value: new RegExp(that[1], that[2]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new RegExp(value) + }; + } + }, + Array: function(it){ + return coerceArray(it, { + of: [{ + type: '*' + }] + }); + }, + Object: function(it){ + return coerceFields(it, { + of: {} + }); + }, + String: function(it){ + var that; + if (that = it.match(/^'(.*)'$/)) { + return { + type: 'Just', + value: that[1] + }; + } else if (that = it.match(/^"(.*)"$/)) { + return { + type: 'Just', + value: that[1] + }; + } else { + return { + type: 'Just', + value: it + }; + } + } + }; + function coerceArray(node, type){ + var typeOf, element; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) { + element = ref$[i$]; + results$.push(coerceTypes(element, typeOf)); + } + return results$; + }()) + }; + } + function coerceTuple(node, type){ + var i, types; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + return { + type: 'Just', + value: (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { + i = i$; + types = ref$[i$]; + results$.push(coerceTypes(node[i], types)); + } + return results$; + }()) + }; + } + function coerceFields(node, type){ + var typeOf, key, value; + if (toString$.call(node).slice(8, -1) !== 'Object') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var ref$, results$ = {}; + for (key in ref$ = node) { + value = ref$[key]; + results$[key] = coerceTypes(value, typeOf[key] || [{ + type: '*' + }]); + } + return results$; + }()) + }; + } + function coerceType(node, typeObj, options){ + var type, structure, coerceFunc; + type = typeObj.type, structure = typeObj.structure; + if (type) { + coerceFunc = types[type]; + return coerceFunc(node, options); + } else { + switch (structure) { + case 'array': + return coerceArray(node, typeObj); + case 'tuple': + return coerceTuple(node, typeObj); + case 'fields': + return coerceFields(node, typeObj); + } + } + } + function coerceTypes(node, types, options){ + var i$, len$, type, ref$, valueType, value; + options == null && (options = {}); + for (i$ = 0, len$ = types.length; i$ < len$; ++i$) { + type = types[i$]; + ref$ = coerceType(node, type, options), valueType = ref$.type, value = ref$.value; + if (valueType === 'Nothing') { + continue; + } + if (parsedTypeCheck([type], value)) { + return value; + } + } + throw new Error("Value '" + node + "' does not type check against " + JSON.stringify(types) + "."); + } + function consumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } else { + throw new Error("Expected '" + op + "', but got " + tokens[0] + " instead."); + } + } + function maybeConsumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } + } + function consumeList(tokens, delimiters, hasDelimiters){ + var result; + if (hasDelimiters) { + consumeOp(tokens, delimiters[0]); + } + result = []; + while (tokens.length && tokens[0] !== delimiters[1]) { + result.push(consumeElement(tokens)); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, delimiters[1]); + } + return result; + } + function consumeArray(tokens, hasDelimiters){ + return consumeList(tokens, ['[', ']'], hasDelimiters); + } + function consumeTuple(tokens, hasDelimiters){ + return consumeList(tokens, ['(', ')'], hasDelimiters); + } + function consumeFields(tokens, hasDelimiters){ + var result, key; + if (hasDelimiters) { + consumeOp(tokens, '{'); + } + result = {}; + while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) { + key = tokens.shift(); + consumeOp(tokens, ':'); + result[key] = consumeElement(tokens); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, '}'); + } + return result; + } + function consumeElement(tokens){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens, true); + case '(': + return consumeTuple(tokens, true); + case '{': + return consumeFields(tokens, true); + default: + return tokens.shift(); + } + } + function consumeTopLevel(tokens, types){ + var structure, origTokens, result; + structure = types[0].structure; + if (types.length === 1 && structure) { + origTokens = tokens.slice(); + result = structure === 'array' + ? consumeArray(tokens, tokens[0] === '[') + : structure === 'tuple' + ? consumeTuple(tokens, tokens[0] === '(') + : consumeFields(tokens, tokens[0] === '{'); + if (tokens.length) { + return consumeElement(structure === 'array' + ? ['['].concat(origTokens, [']']) + : ['('].concat(origTokens, [')'])); + } else { + return result; + } + } else { + return consumeElement(tokens); + } + } + tokenRegex = /("(?:[^"]|\\")*")|('(?:[^']|\\')*')|(#.*#)|(\/(?:\\\/|[^\/])*\/[gimy]*)|([\[\]\(\)}{:,])|([-\.\$\w]+)|\s*/; + function coerce(types, string){ + var tokens, node; + tokens = reject(function(it){ + return !it || /^\s+$/.test(it); + }, string.split(tokenRegex)); + node = consumeTopLevel(tokens, types); + if (!node) { + throw new Error("Error parsing " + string); + } + return coerceTypes(node, types); + } + module.exports = coerce; + /* + function log + console.log it; it + */ +}).call(this); diff --git a/tools/eslint/node_modules/optionator/lib/help.js b/tools/eslint/node_modules/optionator/lib/help.js new file mode 100644 index 00000000000000..26afec2d64cbb2 --- /dev/null +++ b/tools/eslint/node_modules/optionator/lib/help.js @@ -0,0 +1,242 @@ +// Generated by LiveScript 1.3.1 +(function(){ + var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp; + ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines; + ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize; + wordwrap = require('wordwrap'); + getPreText = function(option, arg$, maxWidth){ + var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, typeString, that, wrap; + mainName = option.option, shortNames = (ref$ = option.shortNames) != null + ? ref$ + : [], longNames = (ref$ = option.longNames) != null + ? ref$ + : [], type = option.type, description = option.description; + aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent; + if (option.negateName) { + mainName = "no-" + mainName; + if (longNames) { + longNames = map(function(it){ + return "no-" + it; + }, longNames); + } + } + names = mainName.length === 1 + ? [mainName].concat(shortNames, longNames) + : shortNames.concat([mainName], longNames); + namesString = map(nameToRaw, names).join(aliasSeparator); + namesStringLen = namesString.length; + typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator; + typeSeparatorStringLen = typeSeparatorString.length; + typeString = (that = option['enum']) ? "One of: " + that.join(', ') : type; + if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + typeString.length > maxWidth) { + wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth); + return namesString + "" + typeSeparatorString + wrap(typeString).replace(/^\s+/, ''); + } else { + return namesString + "" + (option.boolean + ? '' + : typeSeparatorString + "" + typeString); + } + }; + setHelpStyleDefaults = function(helpStyle){ + helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', '); + helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' '); + helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = ' '); + helpStyle.initialIndent == null && (helpStyle.initialIndent = 2); + helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4); + helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5); + }; + generateHelpForOption = function(getOption, arg$){ + var stdout, helpStyle, ref$; + stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null + ? ref$ + : {}; + setHelpStyleDefaults(helpStyle); + return function(optionName){ + var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator; + maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null; + wrap = maxWidth ? wordwrap(maxWidth) : id; + try { + option = getOption(dasherize(optionName)); + } catch (e$) { + e = e$; + return e.message; + } + pre = getPreText(option, helpStyle); + defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : ''; + restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : ''; + description = option.longDescription || option.description && sentencize(option.description); + fullDescription = description && restPositionalString + ? description + " " + restPositionalString + : (that = description || restPositionalString) ? that : ''; + preDescription = 'description:'; + descriptionString = !fullDescription + ? '' + : maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth + ? "\n" + preDescription + "\n" + wrap(fullDescription) + : "\n" + preDescription + " " + fullDescription; + exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1 + ? "\nexamples:\n" + unlines(examples) + : "\nexample: " + examples[0]) : ''; + seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : ''; + return pre + "" + seperator + defaultString + descriptionString + exampleString; + }; + }; + generateHelp = function(arg$){ + var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent; + options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null + ? ref$ + : {}, stdout = arg$.stdout; + setHelpStyleDefaults(helpStyle); + aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent; + return function(arg$){ + var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap; + ref$ = arg$ != null + ? arg$ + : {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate; + maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null; + output = []; + out = function(it){ + return output.push(it != null ? it : ''); + }; + if (prepend) { + out(interpolate ? interp(prepend, interpolate) : prepend); + out(); + } + data = []; + optionCount = 0; + totalPreLen = 0; + preLens = []; + for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) { + item = ref$[i$]; + if (showHidden || !item.hidden) { + if (that = item.heading) { + data.push({ + type: 'heading', + value: that + }); + } else { + pre = getPreText(item, helpStyle, maxWidth); + desc = item['default'] && !item.negateName + ? (that = item.description) != null + ? that + " - default: " + item['default'] + : "default: " + item['default'] + : (that = item.description) != null ? that : ''; + data.push({ + type: 'option', + pre: pre, + desc: desc, + descLen: desc.length + }); + preLen = pre.length; + optionCount++; + totalPreLen += preLen; + preLens.push(preLen); + } + } + } + sortedPreLens = sort(preLens); + maxPreLen = sortedPreLens[sortedPreLens.length - 1]; + preLenMean = initialIndent + totalPreLen / optionCount; + x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen; + for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) { + preLen = sortedPreLens[i$]; + if (preLen <= x) { + padAmount = preLen; + break; + } + } + descSepLen = descriptionSeparator.length; + if (maxWidth != null) { + fullWrapCount = 0; + partialWrapCount = 0; + for (i$ = 0, len$ = data.length; i$ < len$; ++i$) { + item = data[i$]; + if (item.type === 'option') { + pre = item.pre, desc = item.desc, descLen = item.descLen; + if (descLen === 0) { + item.wrap = 'none'; + } else { + preLen = max(padAmount, pre.length) + initialIndent + descSepLen; + totalLen = preLen + descLen; + if (totalLen > maxWidth) { + if (descLen / 2.5 > maxWidth - preLen) { + fullWrapCount++; + item.wrap = 'full'; + } else { + partialWrapCount++; + item.wrap = 'partial'; + } + } else { + item.wrap = 'none'; + } + } + } + } + } + initialSpace = repeatString$(' ', initialIndent); + wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5; + for (i$ = 0, len$ = data.length; i$ < len$; ++i$) { + i = i$; + item = data[i$]; + if (item.type === 'heading') { + if (i !== 0) { + out(); + } + out(item.value + ":"); + } else { + pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap; + if (maxWidth != null) { + if (wrapAllFull || wrap === 'full') { + wrap = wordwrap(initialIndent + secondaryIndent, maxWidth); + out(initialSpace + "" + pre + "\n" + wrap(desc)); + continue; + } else if (wrap === 'partial') { + wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth); + out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, '')); + continue; + } + } + if (descLen === 0) { + out(initialSpace + "" + pre); + } else { + out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc); + } + } + } + if (append) { + out(); + out(interpolate ? interp(append, interpolate) : append); + } + return unlines(output); + }; + }; + function pad(str, num){ + var len, padAmount; + len = str.length; + padAmount = num - len; + return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0); + } + function sentencize(str){ + var first, rest, period; + first = str.charAt(0).toUpperCase(); + rest = str.slice(1); + period = /[\.!\?]$/.test(str) ? '' : '.'; + return first + "" + rest + period; + } + function interp(string, object){ + return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){ + var ref$; + return (ref$ = object[key]) != null + ? ref$ + : "{{" + key + "}}"; + }); + } + module.exports = { + generateHelp: generateHelp, + generateHelpForOption: generateHelpForOption + }; + function repeatString$(str, n){ + for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str; + return r; + } +}).call(this); diff --git a/tools/eslint/node_modules/optionator/lib/index.js b/tools/eslint/node_modules/optionator/lib/index.js new file mode 100644 index 00000000000000..f9ae9a566c78a2 --- /dev/null +++ b/tools/eslint/node_modules/optionator/lib/index.js @@ -0,0 +1,417 @@ +// Generated by LiveScript 1.3.1 +(function(){ + var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice; + VERSION = '0.5.0'; + ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize; + deepIs = require('deep-is'); + ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize; + ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption; + ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType; + parseLevn = require('levn').parsedTypeParse; + camelizeKeys = function(obj){ + var key, value, resultObj$ = {}; + for (key in obj) { + value = obj[key]; + resultObj$[camelize(key)] = value; + } + return resultObj$; + }; + parseString = function(string){ + var assignOpt, regex, replaceRegex, result; + assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*='; + regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g'); + replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$'); + result = map(function(it){ + return it.replace(replaceRegex, '$1$2'); + }, string.match(regex) || []); + return result; + }; + main = function(libOptions){ + var opts, defaults, required, traverse, getOption, parse; + opts = {}; + defaults = {}; + required = []; + if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') { + libOptions.stdout = process.stdout; + } + traverse = function(options){ + var i$, len$, option, name, e, parsedPossibilities, parsedType, j$, ref$, len1$, possibility, that, rawDependsType, dependsOpts, dependsType, alias, shortNames, longNames; + if (toString$.call(options).slice(8, -1) !== 'Array') { + throw new Error('No options defined.'); + } + for (i$ = 0, len$ = options.length; i$ < len$; ++i$) { + option = options[i$]; + if (option.heading == null) { + name = option.option; + if (opts[name] != null) { + throw new Error("Option '" + name + "' already defined."); + } + if (option.type === 'Boolean') { + option.boolean == null && (option.boolean = true); + } + if (option.parsedType == null) { + if (!option.type) { + throw new Error("No type defined for option '" + name + "'."); + } + try { + option.parsedType = parseType(option.type); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message); + } + } + if (option['default']) { + try { + defaults[name] = parseLevn(option.parsedType, option['default']); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message); + } + } + if (option['enum'] && !option.parsedPossiblities) { + parsedPossibilities = []; + parsedType = option.parsedType; + for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) { + possibility = ref$[j$]; + try { + parsedPossibilities.push(parseLevn(parsedType, possibility)); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message); + } + } + option.parsedPossibilities = parsedPossibilities; + } + if (that = option.dependsOn) { + if (that.length) { + ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1); + dependsType = rawDependsType.toLowerCase(); + if (dependsOpts.length) { + if (dependsType === 'and' || dependsType === 'or') { + option.dependsOn = [dependsType].concat(slice$.call(dependsOpts)); + } else { + throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'"); + } + } else { + if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') { + option.dependsOn = null; + } else { + option.dependsOn = ['and', rawDependsType]; + } + } + } else { + option.dependsOn = null; + } + } + if (option.required) { + required.push(name); + } + opts[name] = option; + if (option.alias || option.aliases) { + if (name === 'NUM') { + throw new Error("-NUM option can't have aliases."); + } + if (option.alias) { + option.aliases == null && (option.aliases = [].concat(option.alias)); + } + for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) { + alias = ref$[j$]; + if (opts[alias] != null) { + throw new Error("Option '" + alias + "' already defined."); + } + opts[alias] = option; + } + ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1]; + option.shortNames == null && (option.shortNames = shortNames); + option.longNames == null && (option.longNames = longNames); + } + if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') { + option.negateName = true; + } + } + } + function fn$(it){ + return it.length === 1; + } + }; + traverse(libOptions.options); + getOption = function(name){ + var opt, possiblyMeant; + opt = opts[name]; + if (opt == null) { + possiblyMeant = closestString(keys(opts), name); + throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.')); + } + return opt; + }; + parse = function(input, arg$){ + var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, negated, noedName, valPrime; + slice = (arg$ != null + ? arg$ + : {}).slice; + obj = {}; + positional = []; + restPositional = false; + overrideRequired = false; + prop = null; + setValue = function(name, value){ + var opt, val, e, currentType; + opt = getOption(name); + if (opt.boolean) { + val = value; + } else { + try { + val = parseLevn(opt.parsedType, value); + } catch (e$) { + e = e$; + throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + "."); + } + if (opt['enum'] && !any(function(it){ + return deepIs(it, val); + }, opt.parsedPossibilities)) { + throw new Error("Option " + name + ": '" + val + "' not in [" + opt['enum'].join(', ') + "]."); + } + } + currentType = toString$.call(obj[name]).slice(8, -1); + if (obj[name] != null) { + if (libOptions.concatRepeatedArrays && currentType === 'Array') { + obj[name] = obj[name].concat(val); + } else if (libOptions.mergeRepeatedObjects && currentType === 'Object') { + import$(obj[name], val); + } else { + obj[name] = val; + } + } else { + obj[name] = val; + } + if (opt.restPositional) { + restPositional = true; + } + if (opt.overrideRequired) { + overrideRequired = true; + } + }; + setDefaults = function(){ + var name, ref$, value; + for (name in ref$ = defaults) { + value = ref$[name]; + if (obj[name] == null) { + obj[name] = value; + } + } + }; + checkRequired = function(){ + var i$, ref$, len$, name; + if (overrideRequired) { + return; + } + for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) { + name = ref$[i$]; + if (!obj[name]) { + throw new Error("Option " + nameToRaw(name) + " is required."); + } + } + }; + mutuallyExclusiveError = function(first, second){ + throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time."); + }; + checkMutuallyExclusive = function(){ + var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt; + rules = libOptions.mutuallyExclusive; + if (!rules) { + return; + } + for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) { + rule = rules[i$]; + present = null; + for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) { + element = rule[j$]; + if (toString$.call(element).slice(8, -1) === 'Array') { + for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) { + opt = element[k$]; + if (opt in obj) { + if (present != null) { + mutuallyExclusiveError(present, opt); + } else { + present = opt; + break; + } + } + } + } else { + if (element in obj) { + if (present != null) { + mutuallyExclusiveError(present, element); + } else { + present = element; + } + } + } + } + } + }; + checkDependency = function(option){ + var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption; + dependsOn = option.dependsOn; + if (!dependsOn || option.dependenciesMet) { + return true; + } + type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1); + for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) { + targetOptionName = targetOptionNames[i$]; + targetOption = obj[targetOptionName]; + if (targetOption && checkDependency(targetOption)) { + if (type === 'or') { + return true; + } + } else if (type === 'and') { + throw new Error("The option '" + option.option + "' did not have its dependencies met."); + } + } + if (type === 'and') { + return true; + } else { + throw new Error("The option '" + option.option + "' did not meet any of its dependencies."); + } + }; + checkDependencies = function(){ + var name; + for (name in obj) { + checkDependency(opts[name]); + } + }; + switch (toString$.call(input).slice(8, -1)) { + case 'String': + args = parseString(input.slice(slice != null ? slice : 0)); + break; + case 'Array': + args = input.slice(slice != null ? slice : 2); + break; + case 'Object': + obj = {}; + for (key in input) { + value = input[key]; + if (key !== '_') { + option = getOption(dasherize(key)); + if (parsedTypeCheck(option.parsedType, value)) { + obj[option.option] = value; + } else { + throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'."); + } + } + } + checkMutuallyExclusive(); + checkDependencies(); + setDefaults(); + checkRequired(); + return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$; + default: + throw new Error("Invalid argument to 'parse': " + input + "."); + } + for (i$ = 0, len$ = args.length; i$ < len$; ++i$) { + arg = args[i$]; + if (arg === '--') { + restPositional = true; + } else if (restPositional) { + positional.push(arg); + } else { + if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) { + result = that; + if (prop) { + throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required."); + } + short = result[1].length === 1; + argName = result[2]; + usingAssign = result[3] != null; + val = result[4]; + if (usingAssign && val == null) { + throw new Error("No value for '" + argName + "' specified."); + } + if (short) { + flags = chars(argName); + len = flags.length; + for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) { + i = j$; + flag = flags[j$]; + opt = getOption(flag); + name = opt.option; + if (restPositional) { + positional.push(flag); + } else if (opt.boolean) { + setValue(name, true); + } else if (i === len - 1) { + if (usingAssign) { + setValue(name, val); + } else { + prop = name; + } + } else { + throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags."); + } + } + } else { + negated = false; + if (that = argName.match(/^no-(.+)$/)) { + negated = true; + noedName = that[1]; + opt = getOption(noedName); + } else { + opt = getOption(argName); + } + name = opt.option; + if (opt.boolean) { + valPrime = usingAssign ? parseLevn([{ + type: 'Boolean' + }], val) : true; + if (negated) { + setValue(name, !valPrime); + } else { + setValue(name, valPrime); + } + } else { + if (negated) { + throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'."); + } + if (usingAssign) { + setValue(name, val); + } else { + prop = name; + } + } + } + } else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) { + opt = opts.NUM; + if (!opt) { + throw new Error('No -NUM option defined.'); + } + setValue(opt.option, that[1]); + } else { + if (prop) { + setValue(prop, arg); + prop = null; + } else { + positional.push(arg); + } + } + } + } + checkMutuallyExclusive(); + checkDependencies(); + setDefaults(); + checkRequired(); + return ref$ = camelizeKeys(obj), ref$._ = positional, ref$; + }; + return { + parse: parse, + generateHelp: generateHelp(libOptions), + generateHelpForOption: generateHelpForOption(getOption, libOptions) + }; + }; + main.VERSION = VERSION; + module.exports = main; + function import$(obj, src){ + var own = {}.hasOwnProperty; + for (var key in src) if (own.call(src, key)) obj[key] = src[key]; + return obj; + } +}).call(this); diff --git a/tools/eslint/node_modules/optionator/lib/parse-type.js b/tools/eslint/node_modules/optionator/lib/parse-type.js new file mode 100644 index 00000000000000..e648723cf13766 --- /dev/null +++ b/tools/eslint/node_modules/optionator/lib/parse-type.js @@ -0,0 +1,143 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var reject, tokenRegex; + reject = require('prelude-ls').reject; + function consumeWord(tokens){ + var token; + token = tokens[0]; + if (!(token != null && /^[a-zA-Z]+$/.test(token))) { + throw new Error("Exected textual string."); + } + return tokens.shift(); + } + function consumeOp(tokens, op){ + var token; + token = tokens[0]; + if (token !== op) { + throw new Error("Expected " + op); + } + return tokens.shift(); + } + function maybeConsumeOp(tokens, op){ + var token; + token = tokens[0]; + if (token === op) { + return tokens.shift(); + } else { + return null; + } + } + function consumeArray(tokens){ + var contentType; + consumeOp(tokens, '['); + contentType = consumeTypes(tokens); + if (!contentType) { + throw new Error("Must specify content type for Array."); + } + consumeOp(tokens, ']'); + return { + type: 'Array', + contentType: contentType + }; + } + function consumeTuple(tokens){ + var contentTypes, that; + contentTypes = []; + consumeOp(tokens, '('); + while (that = consumeTypes(tokens)) { + contentTypes.push(that); + if (!maybeConsumeOp(tokens, ',')) { + break; + } + } + consumeOp(tokens, ')'); + return { + type: 'Tuple', + contentTypes: contentTypes + }; + } + function consumeProperty(tokens){ + var key, type; + key = consumeWord(tokens); + consumeOp(tokens, ':'); + type = consumeTypes(tokens); + return { + key: key, + type: type + }; + } + function consumeObject(tokens){ + var properties, that; + properties = []; + consumeOp(tokens, '{'); + while (that = consumeProperty(tokens)) { + properties.push(that); + if (!maybeConsumeOp(tokens, ',')) { + break; + } + } + consumeOp(tokens, '}'); + return { + type: 'Object', + properties: properties + }; + } + function consumeType(tokens){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens); + case '{': + return consumeObject(tokens); + case '(': + return consumeTuple(tokens); + default: + return { + type: consumeWord(tokens) + }; + } + } + function consumeMaybe(tokens){ + var maybe, type; + if (tokens[0] === 'Maybe') { + tokens.shift(); + maybe = true; + } + type = consumeType(tokens); + if (maybe) { + return { + type: 'Maybe', + contentType: type + }; + } else { + return type; + } + } + function consumeTypes(tokens){ + var types; + types = []; + for (;;) { + types.push(consumeMaybe(tokens)); + if (!maybeConsumeOp('|')) { + break; + } + } + if (!types.length) { + throw new Error("Expected type(s)."); + } + return types; + } + tokenRegex = /[:,\[\]\(\)}{]|[a-zA-Z]+/g; + module.exports = function(input){ + var tokens, e; + tokens = reject(function(it){ + return /^\s*$/.test(it); + })( + input.match(tokenRegex)); + try { + return consumeTypes(tokens); + } catch (e$) { + e = e$; + throw new Error(e.message + " - '" + tokens.join('#') + "' - '" + input + "'"); + } + }; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/lib/util.js b/tools/eslint/node_modules/optionator/lib/util.js new file mode 100644 index 00000000000000..480ba9552c15b1 --- /dev/null +++ b/tools/eslint/node_modules/optionator/lib/util.js @@ -0,0 +1,46 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize; + prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy; + fl = require('fast-levenshtein'); + closestString = function(possibilities, input){ + var distances, ref$, string, distance; + if (!possibilities.length) { + return; + } + distances = map(function(it){ + var ref$, longer, shorter; + ref$ = input.length > it.length + ? [input, it] + : [it, input], longer = ref$[0], shorter = ref$[1]; + return { + string: it, + distance: fl.get(longer, shorter) + }; + })( + possibilities); + ref$ = sortBy(function(it){ + return it.distance; + }, distances)[0], string = ref$.string, distance = ref$.distance; + return string; + }; + nameToRaw = function(name){ + if (name.length === 1 || name === 'NUM') { + return "-" + name; + } else { + return "--" + name; + } + }; + dasherize = function(string){ + if (/^[A-Z]/.test(string)) { + return string; + } else { + return prelude.dasherize(string); + } + }; + module.exports = { + closestString: closestString, + nameToRaw: nameToRaw, + dasherize: dasherize + }; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/.npmignore b/tools/eslint/node_modules/optionator/node_modules/deep-is/.npmignore new file mode 100644 index 00000000000000..3c3629e647f5dd --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/.travis.yml b/tools/eslint/node_modules/optionator/node_modules/deep-is/.travis.yml new file mode 100644 index 00000000000000..d523c5f5658a4e --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - 0.4 + - 0.6 + - 0.8 + - 0.10 diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/LICENSE b/tools/eslint/node_modules/optionator/node_modules/deep-is/LICENSE new file mode 100644 index 00000000000000..c38f84073f61ef --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012, 2013 Thorsten Lorenz +Copyright (c) 2012 James Halliday +Copyright (c) 2009 Thomas Robinson <280north.com> + +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/README.markdown b/tools/eslint/node_modules/optionator/node_modules/deep-is/README.markdown new file mode 100644 index 00000000000000..eb69a83bda12f8 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/README.markdown @@ -0,0 +1,70 @@ +deep-is +========== + +Node's `assert.deepEqual() algorithm` as a standalone module. Exactly like +[deep-equal](https://github.com/substack/node-deep-equal) except for the fact that `deepEqual(NaN, NaN) === true`. + +This module is around [5 times faster](https://gist.github.com/2790507) +than wrapping `assert.deepEqual()` in a `try/catch`. + +[![browser support](http://ci.testling.com/thlorenz/deep-is.png)](http://ci.testling.com/thlorenz/deep-is) + +[![build status](https://secure.travis-ci.org/thlorenz/deep-is.png)](http://travis-ci.org/thlorenz/deep-is) + +example +======= + +``` js +var equal = require('deep-is'); +console.dir([ + equal( + { a : [ 2, 3 ], b : [ 4 ] }, + { a : [ 2, 3 ], b : [ 4 ] } + ), + equal( + { x : 5, y : [6] }, + { x : 5, y : 6 } + ) +]); +``` + +methods +======= + +var deepIs = require('deep-is') + +deepIs(a, b) +--------------- + +Compare objects `a` and `b`, returning whether they are equal according to a +recursive equality algorithm. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install deep-is +``` + +test +==== + +With [npm](http://npmjs.org) do: + +``` +npm test +``` + +license +======= + +Copyright (c) 2012, 2013 Thorsten Lorenz +Copyright (c) 2012 James Halliday + +Derived largely from node's assert module, which has the copyright statement: + +Copyright (c) 2009 Thomas Robinson <280north.com> + +Released under the MIT license, see LICENSE for details. diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/example/cmp.js b/tools/eslint/node_modules/optionator/node_modules/deep-is/example/cmp.js new file mode 100644 index 00000000000000..67014b88dcbc9b --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/example/cmp.js @@ -0,0 +1,11 @@ +var equal = require('../'); +console.dir([ + equal( + { a : [ 2, 3 ], b : [ 4 ] }, + { a : [ 2, 3 ], b : [ 4 ] } + ), + equal( + { x : 5, y : [6] }, + { x : 5, y : 6 } + ) +]); diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/index.js b/tools/eslint/node_modules/optionator/node_modules/deep-is/index.js new file mode 100644 index 00000000000000..506fe279531349 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/index.js @@ -0,0 +1,102 @@ +var pSlice = Array.prototype.slice; +var Object_keys = typeof Object.keys === 'function' + ? Object.keys + : function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + } +; + +var deepEqual = module.exports = function (actual, expected) { + // enforce Object.is +0 !== -0 + if (actual === 0 && expected === 0) { + return areZerosEqual(actual, expected); + + // 7.1. All identical values are equivalent, as determined by ===. + } else if (actual === expected) { + return true; + + } else if (actual instanceof Date && expected instanceof Date) { + return actual.getTime() === expected.getTime(); + + } else if (isNumberNaN(actual)) { + return isNumberNaN(expected); + + // 7.3. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (typeof actual != 'object' && typeof expected != 'object') { + return actual == expected; + + // 7.4. For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +}; + +function isUndefinedOrNull(value) { + return value === null || value === undefined; +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function isNumberNaN(value) { + // NaN === NaN -> false + return typeof value == 'number' && value !== value; +} + +function areZerosEqual(zeroA, zeroB) { + // (1 / +0|0) -> Infinity, but (1 / -0) -> -Infinity and (Infinity !== -Infinity) + return (1 / zeroA) === (1 / zeroB); +} + +function objEquiv(a, b) { + if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) + return false; + + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return deepEqual(a, b); + } + try { + var ka = Object_keys(a), + kb = Object_keys(b), + key, i; + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key])) return false; + } + return true; +} diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/package.json b/tools/eslint/node_modules/optionator/node_modules/deep-is/package.json new file mode 100644 index 00000000000000..6486a82ebfe8d7 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/package.json @@ -0,0 +1,86 @@ +{ + "name": "deep-is", + "version": "0.1.3", + "description": "node's assert.deepEqual algorithm except for NaN being equal to NaN", + "main": "index.js", + "directories": { + "lib": ".", + "example": "example", + "test": "test" + }, + "scripts": { + "test": "tape test/*.js" + }, + "devDependencies": { + "tape": "~1.0.2" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/thlorenz/deep-is.git" + }, + "keywords": [ + "equality", + "equal", + "compare" + ], + "author": { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "http://thlorenz.com" + }, + "license": { + "type": "MIT", + "url": "https://github.com/thlorenz/deep-is/blob/master/LICENSE" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "gitHead": "f126057628423458636dec9df3d621843b9ac55e", + "bugs": { + "url": "https://github.com/thlorenz/deep-is/issues" + }, + "homepage": "https://github.com/thlorenz/deep-is", + "_id": "deep-is@0.1.3", + "_shasum": "b369d6fb5dbc13eecf524f91b070feedc357cf34", + "_from": "deep-is@>=0.1.2 <0.2.0", + "_npmVersion": "1.4.14", + "_npmUser": { + "name": "thlorenz", + "email": "thlorenz@gmx.de" + }, + "maintainers": [ + { + "name": "thlorenz", + "email": "thlorenz@gmx.de" + } + ], + "dist": { + "shasum": "b369d6fb5dbc13eecf524f91b070feedc357cf34", + "tarball": "http://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz" + }, + "_resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/test/NaN.js b/tools/eslint/node_modules/optionator/node_modules/deep-is/test/NaN.js new file mode 100644 index 00000000000000..ddaa5a77b412fc --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/test/NaN.js @@ -0,0 +1,16 @@ +var test = require('tape'); +var equal = require('../'); + +test('NaN and 0 values', function (t) { + t.ok(equal(NaN, NaN)); + t.notOk(equal(0, NaN)); + t.ok(equal(0, 0)); + t.notOk(equal(0, 1)); + t.end(); +}); + + +test('nested NaN values', function (t) { + t.ok(equal([ NaN, 1, NaN ], [ NaN, 1, NaN ])); + t.end(); +}); diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/test/cmp.js b/tools/eslint/node_modules/optionator/node_modules/deep-is/test/cmp.js new file mode 100644 index 00000000000000..307101341db090 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/test/cmp.js @@ -0,0 +1,23 @@ +var test = require('tape'); +var equal = require('../'); + +test('equal', function (t) { + t.ok(equal( + { a : [ 2, 3 ], b : [ 4 ] }, + { a : [ 2, 3 ], b : [ 4 ] } + )); + t.end(); +}); + +test('not equal', function (t) { + t.notOk(equal( + { x : 5, y : [6] }, + { x : 5, y : 6 } + )); + t.end(); +}); + +test('nested nulls', function (t) { + t.ok(equal([ null, null, null ], [ null, null, null ])); + t.end(); +}); diff --git a/tools/eslint/node_modules/optionator/node_modules/deep-is/test/neg-vs-pos-0.js b/tools/eslint/node_modules/optionator/node_modules/deep-is/test/neg-vs-pos-0.js new file mode 100644 index 00000000000000..ac26130e6a7757 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/deep-is/test/neg-vs-pos-0.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var equal = require('../'); + +test('0 values', function (t) { + t.ok(equal( 0, 0), ' 0 === 0'); + t.ok(equal( 0, +0), ' 0 === +0'); + t.ok(equal(+0, +0), '+0 === +0'); + t.ok(equal(-0, -0), '-0 === -0'); + + t.notOk(equal(-0, 0), '-0 !== 0'); + t.notOk(equal(-0, +0), '-0 !== +0'); + + t.end(); +}); + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/.npmignore b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/.npmignore new file mode 100644 index 00000000000000..0cc2c66b8c0bdc --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/.npmignore @@ -0,0 +1,4 @@ +*.iml +.idea/ +node_modules/ +npm-debug.log diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/.travis.yml b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/.travis.yml new file mode 100644 index 00000000000000..cc060cb017c63d --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/.travis.yml @@ -0,0 +1,16 @@ +language: node_js + +node_js: + - 0.10 + - 0.11 + +before_script: + - "npm install -g grunt-cli" + - "npm install" + +script: + - "npm run build" + +notifications: + email: + - ram@hiddentao.com diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/CONTRIBUTING.md b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/CONTRIBUTING.md new file mode 100644 index 00000000000000..66626826d2f2e0 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/CONTRIBUTING.md @@ -0,0 +1,22 @@ +# Contribute to fast-levenshtein + +This guide guidelines for those wishing to contribute to fast-levenshtein. + +## Contributor license agreement + +By submitting code as an individual or as an entity you agree that your code is [licensed the same as fast-levenshtein](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md). + +## Issues and pull requests + +Issues and merge requests should be in English and contain appropriate language for audiences of all ages. + +We will only accept a merge requests which meets the following criteria: + +* Includes proper tests and all tests pass (unless it contains a test exposing a bug in existing code) +* Can be merged without problems (if not please use: `git rebase master`) +* Does not break any existing functionality +* Fixes one specific issue or implements one specific feature (do not combine things, send separate merge requests if needed) +* Keeps the code base clean and well structured +* Contains functionality we think other users will benefit from too +* Doesn't add unnessecary configuration options since they complicate future changes + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/Gruntfile.js b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/Gruntfile.js new file mode 100644 index 00000000000000..6e7b3b37073e21 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/Gruntfile.js @@ -0,0 +1,81 @@ +module.exports = function(grunt) { + + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + + mochaTest: { + files: ['test/*.js'] + }, + mochaTestConfig: { + options: { + reporter: 'spec', + ui: 'exports' + } + }, + + jshint: { + options: { + "bitwise": false, + "camelcase": false, + "curly": false, + "eqeqeq": true, + "forin": true, + "immed": true, + "indent": 2, + "latedef": false, + "newcap": true, + "noarg": true, + "noempty": false, + "nonew": true, + "plusplus": false, + "quotmark": false, + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + + "boss": true, + "laxcomma": true, + "multistr": true, + "sub": true, + "supernew": true, + + "browser": true, + "node": true, + "worker": true, + + "predef": [ + 'define', 'require' + ] + }, + files: ['levenshtein.js'] + }, + + uglify: { + options: { + banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %>. Copyright <%= pkg.author %> */\n' + }, + build: { + src: 'levenshtein.js', + dest: 'levenshtein.min.js' + } + }, + + benchmarkConfig: { + speed: { + src: ['benchmark/speed.js'] + } + }, + }); + + require('load-grunt-tasks')(grunt); + grunt.renameTask('benchmark', 'benchmarkConfig'); + + grunt.registerTask('build', ['jshint', 'uglify', 'mochaTest']); + + grunt.registerTask('default', ['build']); + + grunt.registerTask('benchmark', ['npm-install:levenshtein-edit-distance:levenshtein:natural:levenshtein-component:levenshtein-deltas', 'benchmarkConfig']); +}; + + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/LICENSE.md b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/LICENSE.md new file mode 100644 index 00000000000000..6212406b413b7a --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/LICENSE.md @@ -0,0 +1,25 @@ +(MIT License) + +Copyright (c) 2013 [Ramesh Nair](http://www.hiddentao.com/) + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/README.md b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/README.md new file mode 100644 index 00000000000000..2a917a73186c48 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/README.md @@ -0,0 +1,120 @@ +# fast-levenshtein - Levenshtein algorithm in Javascript + +[![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) + +An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with asynchronous callback support. + +## Features + +* Works in node.js and in the browser. +* Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). +* Provides synchronous and asynchronous versions of the algorithm. +* Asynchronous version is almost as fast as the synchronous version for small strings and can also provide progress updates. +* Comprehensive test suite and performance benchmark. +* Small: <1 KB minified and gzipped + +## Installation + +### node.js + +Install using [npm](http://npmjs.org/): + +```bash +$ npm install fast-levenshtein +``` + +### Browser + +Using bower: + +```bash +$ bower install fast-levenshtein +``` + +If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. + +## Examples + +**Synchronous** + +```javascript +var levenshtein = require('fast-levenshtein'); + +var distance = levenshtein.get('back', 'book'); // 2 +var distance = levenshtein.get('我愛你', '我叫你'); // 1 +``` + +**Asynchronous** + +```javascript +var levenshtein = require('fast-levenshtein'); + +levenshtein.getAsync('back', 'book', function (err, distance) { + // err is null unless an error was thrown + // distance equals 2 +}); +``` + +**Asynchronous with progress updates** + +```javascript +var levenshtein = require('fast-levenshtein'); + +var hugeText1 = fs.readFileSync(...); +var hugeText2 = fs.readFileSync(...); + +levenshtein.getAsync(hugeText1, hugeText2, function (err, distance) { + // process the results as normal +}, { + progress: function(percentComplete) { + console.log(percentComplete + ' % completed so far...'); + } +); +``` + +## Building and Testing + +To build the code and run the tests: + +```bash +$ npm install -g grunt-cli +$ npm install +$ npm run build +``` + +## Performance + +_Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ + +Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): + +```bash +Running suite Implementation comparison [benchmark/speed.js]... +>> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) +>> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) +>> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) +>> natural x 255 ops/sec ±0.76% (88 runs sampled) +>> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) +>> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) +Benchmark done. +Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component +``` + +You can run this benchmark yourself by doing: + +```bash +$ npm install -g grunt-cli +$ npm install +$ npm run build +$ npm run benchmark +``` + +## Contributing + +If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. + +See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. + +## License + +MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/benchmark/speed.js b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/benchmark/speed.js new file mode 100644 index 00000000000000..2564430a4f735b --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/benchmark/speed.js @@ -0,0 +1,182 @@ +var fastLevenshtein = require('../levenshtein.min').get, + levenshtein = require('levenshtein'), + levenshteinEditDistance = require('levenshtein-edit-distance'), + levenshteinComponent = require('levenshtein-component'), + levenshteinDeltas = require('levenshtein-deltas'), + natural = require('natural').LevenshteinDistance; + + + +/* The first 100 words from Letterpress: https://github.com/atebits/Words */ +source = Array(11).join([ + 'aa', + 'aah', + 'aahed', + 'aahing', + 'aahs', + 'aal', + 'aalii', + 'aaliis', + 'aals', + 'aardvark', + 'aardvarks', + 'aardwolf', + 'aardwolves', + 'aargh', + 'aarrgh', + 'aarrghh', + 'aarti', + 'aartis', + 'aas', + 'aasvogel', + 'aasvogels', + 'ab', + 'aba', + 'abac', + 'abaca', + 'abacas', + 'abaci', + 'aback', + 'abacs', + 'abacterial', + 'abactinal', + 'abactinally', + 'abactor', + 'abactors', + 'abacus', + 'abacuses', + 'abaft', + 'abaka', + 'abakas', + 'abalone', + 'abalones', + 'abamp', + 'abampere', + 'abamperes', + 'abamps', + 'aband', + 'abanded', + 'abanding', + 'abandon', + 'abandoned', + 'abandonedly', + 'abandonee', + 'abandonees', + 'abandoner', + 'abandoners', + 'abandoning', + 'abandonment', + 'abandonments', + 'abandons', + 'abandonware', + 'abandonwares', + 'abands', + 'abapical', + 'abas', + 'abase', + 'abased', + 'abasedly', + 'abasement', + 'abasements', + 'abaser', + 'abasers', + 'abases', + 'abash', + 'abashed', + 'abashedly', + 'abashes', + 'abashing', + 'abashless', + 'abashment', + 'abashments', + 'abasia', + 'abasias', + 'abasing', + 'abask', + 'abatable', + 'abate', + 'abated', + 'abatement', + 'abatements', + 'abater', + 'abaters', + 'abates', + 'abating', + 'abatis', + 'abatises', + 'abator', + 'abators', + 'abattis', + 'abattises', + 'abattoir', + 'abattoirs' +].join('|')).split('|'); + + + +/** + * The actual test loop. + * @param {Function} fn Levenshtein distance function. + */ +var loop = function(fn) { + var iterator = -1, + previousValue = '', + value, + dist; + + while (value = source[++iterator]) { + dist = fn(previousValue, value); + previousValue = value; + } +}; + + +/** @type {Object} Test config */ +module.exports = { + name: 'Implementation comparison', + onComplete: function() { + console.log('Benchmark done.'); + }, + tests: [ + { + name: 'levenshtein-edit-distance', + fn: function() { + loop(levenshteinEditDistance); + } + }, + { + name: 'levenshtein-component', + fn: function() { + loop(levenshteinComponent); + } + }, + { + name: 'levenshtein-deltas', + fn: function() { + loop(function(v1,v2) { + return new levenshteinDeltas.Lev(v1,v2).distance(); + }); + } + }, + { + name: 'natural', + fn: function() { + loop(natural); + } + }, + { + name: 'levenshtein', + fn: function() { + loop(levenshtein); + } + }, + { + name: 'fast-levenshtein', + fn: function() { + loop(fastLevenshtein); + } + }, + ] +}; + + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/bower.json b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/bower.json new file mode 100644 index 00000000000000..16703934175625 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/bower.json @@ -0,0 +1,30 @@ +{ + "name": "fast-levenshtein", + "version": "1.0.6", + "homepage": "https://github.com/hiddentao/fast-levenshtein", + "authors": [ + "Ramesh Nair " + ], + "description": "Efficient implementation of Levenshtein algorithm with asynchronous callback support", + "main": "levenshtein.js", + "moduleType": [ + "amd", + "globals", + "node" + ], + "keywords": [ + "levenshtein", + "distance", + "string" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests", + "benchmark", + "Gruntfile.js" + ] +} diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/levenshtein.js b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/levenshtein.js new file mode 100644 index 00000000000000..0028f405ac4bfe --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/levenshtein.js @@ -0,0 +1,198 @@ +(function() { + 'use strict'; + + /** + * Extend an Object with another Object's properties. + * + * The source objects are specified as additional arguments. + * + * @param dst Object the object to extend. + * + * @return Object the final object. + */ + var _extend = function(dst) { + var sources = Array.prototype.slice.call(arguments, 1); + for (var i=0; i tmp) { + nextCol = tmp; + } + // deletion + tmp = prevRow[j + 1] + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + + // copy current col value into previous (in preparation for next iteration) + prevRow[j] = curCol; + } + + // copy last col value into previous (in preparation for next iteration) + prevRow[j] = nextCol; + } + + return nextCol; + }, + + /** + * Asynchronously calculate levenshtein distance of the two strings. + * + * @param str1 String the first string. + * @param str2 String the second string. + * @param cb Function callback function with signature: function(Error err, int distance) + * @param [options] Object additional options. + * @param [options.progress] Function progress callback with signature: function(percentComplete) + */ + getAsync: function(str1, str2, cb, options) { + options = _extend({}, { + progress: null + }, options); + + // base cases + if (str1 === str2) return cb(null, 0); + if (str1.length === 0) return cb(null, str2.length); + if (str2.length === 0) return cb(null, str1.length); + + // two rows + var prevRow = new Array(str2.length + 1), + curCol, nextCol, + i, j, tmp, + startTime, currentTime; + + // initialise previous row + for (i=0; i tmp) { + nextCol = tmp; + } + // deletion + tmp = prevRow[j + 1] + 1; + if (nextCol > tmp) { + nextCol = tmp; + } + + // copy current into previous (in preparation for next iteration) + prevRow[j] = curCol; + + // get current time + currentTime = new Date().valueOf(); + } + + // send a progress update? + if (null !== options.progress) { + try { + options.progress.call(null, (i * 100.0/ str1.length)); + } catch (err) { + return cb('Progress callback: ' + err.toString()); + } + } + + // next iteration + setTimeout(__calculate(), 0); + }; + + __calculate(); + } + + }; + + // amd + if (typeof define !== "undefined" && define !== null && define.amd) { + define(function() { + return Levenshtein; + }); + } + // commonjs + else if (typeof module !== "undefined" && module !== null) { + module.exports = Levenshtein; + } + // web worker + else if (typeof self !== "undefined" && typeof self.postMessage === 'function' && typeof self.importScripts === 'function') { + self.Levenshtein = Levenshtein; + } + // browser main thread + else if (typeof window !== "undefined" && window !== null) { + window.Levenshtein = Levenshtein; + } +}()); + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/levenshtein.min.js b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/levenshtein.min.js new file mode 100644 index 00000000000000..94d89ee5c8c7a1 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/levenshtein.min.js @@ -0,0 +1,2 @@ +/*! fast-levenshtein 2014-12-17. Copyright Ramesh Nair (http://www.hiddentao.com/) */ +!function(){"use strict";var a=function(a){for(var b=Array.prototype.slice.call(arguments,1),c=0;cg&&(d=g),g=h[f+1]+1,d>g&&(d=g),h[f]=c;h[f]=d}return d},getAsync:function(b,c,d,e){if(e=a({},{progress:null},e),b===c)return d(null,0);if(0===b.length)return d(null,c.length);if(0===c.length)return d(null,b.length);var f,g,h,i,j,k,l,m=new Array(c.length+1);for(h=0;hl-k;){if(c.length<=++i){if(m[i]=g,b.length<=++h)return d(null,g);g=h+1,i=0}f=g,g=m[i]+(b.charAt(h)===c.charAt(i)?0:1),j=f+1,g>j&&(g=j),j=m[i+1]+1,g>j&&(g=j),m[i]=f,l=(new Date).valueOf()}if(null!==e.progress)try{e.progress.call(null,100*h/b.length)}catch(a){return d("Progress callback: "+a.toString())}setTimeout(n(),0)};n()}};"undefined"!=typeof define&&null!==define&&define.amd?define(function(){return b}):"undefined"!=typeof module&&null!==module?module.exports=b:"undefined"!=typeof self&&"function"==typeof self.postMessage&&"function"==typeof self.importScripts?self.Levenshtein=b:"undefined"!=typeof window&&null!==window&&(window.Levenshtein=b)}(); \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/package.json b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/package.json new file mode 100644 index 00000000000000..b130071e3f360c --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/package.json @@ -0,0 +1,62 @@ +{ + "name": "fast-levenshtein", + "version": "1.0.6", + "description": "Efficient implementation of Levenshtein algorithm with asynchronous callback support", + "main": "levenshtein.js", + "scripts": { + "build": "grunt build", + "benchmark": "grunt benchmark" + }, + "devDependencies": { + "lodash": "~1.2.0", + "chai": "~1.5.0", + "mocha": "~1.9.0", + "grunt-contrib-uglify": "~0.2.0", + "grunt": "~0.4.1", + "grunt-contrib-jshint": "~0.4.3", + "grunt-mocha-test": "~0.2.2", + "grunt-npm-install": "~0.1.0", + "load-grunt-tasks": "~0.6.0", + "grunt-benchmark": "~0.2.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hiddentao/fast-levenshtein.git" + }, + "keywords": [ + "levenshtein", + "distance", + "string" + ], + "author": { + "name": "Ramesh Nair", + "email": "ram@hiddentao.com", + "url": "http://www.hiddentao.com/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/hiddentao/fast-levenshtein/issues" + }, + "homepage": "https://github.com/hiddentao/fast-levenshtein", + "_id": "fast-levenshtein@1.0.6", + "_shasum": "3bedb184e39f95cb0d88928688e6b1ee3273446a", + "_from": "fast-levenshtein@>=1.0.0 <1.1.0", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "hiddentao", + "email": "ram@hiddentao.com" + }, + "maintainers": [ + { + "name": "hiddentao", + "email": "ram@hiddentao.com" + } + ], + "dist": { + "shasum": "3bedb184e39f95cb0d88928688e6b1ee3273446a", + "tarball": "http://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-1.0.6.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-1.0.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/mocha.opts b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/mocha.opts new file mode 100644 index 00000000000000..a8ccfb4515769e --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/mocha.opts @@ -0,0 +1,2 @@ +--ui exports +--reporter spec diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/tests.js b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/tests.js new file mode 100644 index 00000000000000..54b92220aa481c --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/tests.js @@ -0,0 +1,171 @@ +var _ = require('lodash'), + chai = require('chai'), + fs = require('fs'), + levenshtein = require('../levenshtein.min'); + +var expect = chai.expect, + assert = chai.assert; + + +/** + * Create test functions. + * @return Object + */ +var createTests = function(str1, str2, expectedLength, options) { + options = _.extend({}, { + description: null + }, options); + + if (!options.description) { + options.description = (0 === str1.length ? '(empty)' : str1) + ' <-> ' + (0 === str2.length ? '(empty)' : str2); + } + + var ret = {}; + + ret["SYNC:\t" + options.description] = function() { + expect(levenshtein.get(str1, str2)).to.eql(expectedLength); + }; + + ret["ASYNC:\t" + options.description] = function(done) { + levenshtein.getAsync(str1, str2, function(err, distance) { + expect(err).to.be.null; + expect(distance).to.eql(expectedLength); + + done(); + }); + }; + + return ret; +}; + + +// ----- Basic tests ----- // + +(function() { + + var tests = {}, + str = 'hello', + str1 = str, + str2 = str, + i; + + // equal strings + _.extend(tests, createTests('hello', 'hello', 0)); + + // inserts + for (i=0; i<=str.length; ++i) { + str1 = str.substr(0,i); + str2 = str; + + _.extend(tests, createTests(str1, str2, str.length - i)); + } + + // deletes + for (i=str.length-1; i>=0; --i) { + str1 = str; + str2 = str.substr(0,i); + + _.extend(tests, createTests(str1, str2, str.length - i)); + } + + // substitutions + _.extend(tests, createTests("a", "b", 1 )); + _.extend(tests, createTests("ab", "ac", 1 )); + _.extend(tests, createTests("ac", "bc", 1 )); + _.extend(tests, createTests("abc", "axc", 1 )); + _.extend(tests, createTests("xabxcdxxefxgx", "1ab2cd34ef5g6", 6 )); + + // many ops + _.extend(tests, createTests('xabxcdxxefxgx', 'abcdefg', 6)); + _.extend(tests, createTests('javawasneat', 'scalaisgreat', 7)); + _.extend(tests, createTests("example", "samples", 3)); + _.extend(tests, createTests("sturgeon", "urgently", 6 )); + _.extend(tests, createTests("levenshtein", "frankenstein", 6 )); + _.extend(tests, createTests("distance", "difference", 5 )); + + // non-latin + _.extend(tests, createTests('因為我是中國人所以我會說中文', '因為我是英國人所以我會說英文', 2, { + description: 'non-latin' + })); + + // long text + _.extend(tests, createTests( + 'Morbi interdum ultricies neque varius condimentum. Donec volutpat turpis interdum metus ultricies vulputate. Duis ultricies rhoncus sapien, sit amet fermentum risus imperdiet vitae. Ut et lectus', + 'Duis erat dolor, cursus in tincidunt a, lobortis in odio. Cras magna sem, pharetra et iaculis quis, faucibus quis tellus. Suspendisse dapibus sapien in justo cursus', + 143, + { + description: 'long text' + } + )); + + exports['Basic'] = tests; +})(); + +// ------ Asynchronous tests ----- // + +var text1 = fs.readFileSync(__dirname + '/text1.txt', 'utf-8'), + text2 = fs.readFileSync(__dirname + '/text2.txt', 'utf-8'); + +exports['Async'] = { + 'no progress callback': function(done) { + this.timeout(20000); + + var startTime = new Date().valueOf(); + + levenshtein.getAsync(text1, text2, function(err, distance) { + var timeElapsed = new Date().valueOf() - startTime; + + expect(err).to.be.null; + expect(distance).to.eql(194); + + console.log(timeElapsed + ' ms'); + + done(); + }); + }, + 'with progress callback': function(done) { + this.timeout(20000); + + var percents = []; + var progress = function(percent) { + percents.push(percent); + }; + + var startTime = new Date().valueOf(); + + levenshtein.getAsync(text1, text2, function(err, distance) { + var timeElapsed = new Date().valueOf() - startTime; + + expect(err).to.be.null; + expect(distance).to.eql(194); + + console.log(timeElapsed + ' ms, ' + percents.length + ' progress updates'); + + expect(0 < percents.length).to.be.true; + + // check percentages + var lastPercent = 0; + _.each(percents, function(percent) { + expect(100 >= percent); + expect(percent > lastPercent); + lastPercent = percent; + }); + + done(); + }, { + progress: progress + }); + }, + 'progress callback error': function(done) { + levenshtein.getAsync(text1 + text2, text2 + text1, function(err) { + expect(err.toString()).to.be.eql('Progress callback: Error: Bla bla'); + + done(); + }, { + progress: function() { + throw new Error('Bla bla'); + } + }); + } +}; + diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/text1.txt b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/text1.txt new file mode 100644 index 00000000000000..4833682aca5bdb --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/text1.txt @@ -0,0 +1 @@ +Duis mollis rhoncus turpis. Proin ut nunc eget urna molestie dictum. Cras mollis nibh quis eros faucibus posuere vehicula diam rutrum. Morbi mattis orci vel ante dignissim sollicitudin. Aenean quis enim orci. Integer vehicula elementum porta. Nullam massa mauris, ornare eget ullamcorper eget, consequat at dolor. Integer cursus pellentesque velit in semper. Donec sem turpis, tristique vitae egestas nec, varius sit amet ipsum. Nullam scelerisque est eu arcu vulputate varius. Integer vel gravida leo. Suspendisse blandit vehicula neque, non porttitor eros adipiscing non. Curabitur egestas pulvinar sapien ac imperdiet. Ut ac purus sit amet magna sollicitudin cursus non vel eros. In vel nibh eget libero mattis volutpat nec vulputate quam. Vestibulum commodo ante id magna cursus tristique. Integer rutrum diam sit amet nulla placerat ornare. Quisque nec felis lacus. In lorem mauris, lobortis sit amet sodales non, sollicitudin vitae odio. Nam a dui est, venenatis iaculis purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In in sollicitudin urna. Praesent dapibus ligula sed lacus pulvinar sit amet pellentesque enim tincidunt. Vivamus feugiat, sapien vitae convallis consectetur, justo ligula semper quam, mollis dapibus lorem odio sit amet justo. Duis ut leo vel turpis cursus tempor. Donec condimentum convallis lacus at feugiat. Aliquam erat volutpat. Etiam auctor risus dolor, in tempor nibh. Nulla interdum, magna eget suscipit aliquet, enim arcu aliquet nunc, vel molestie est sem ac turpis. Ut et convallis diam. Integer malesuada eleifend eros non sollicitudin. In ac sem eget purus iaculis sollicitudin. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse ultrices nulla sit amet sapien fringilla eleifend. Integer eget lectus a augue convallis dignissim sit amet scelerisque odio. Duis velit nisl, mollis a adipiscing eget, suscipit in quam. Sed id lacus et justo dapibus dapibus vestibulum gravida massa. Duis euismod luctus tempor. Nam venenatis gravida rutrum. Etiam id aliquet est. Integer ante arcu, viverra sit amet placerat sit amet, posuere in est. Cras eleifend ultricies urna, ut euismod quam euismod quis. Cras pellentesque nulla et ante molestie pulvinar. Duis malesuada bibendum arcu, id imperdiet enim egestas eget. Sed blandit iaculis enim vel adipiscing. Donec dui quam, tristique non tincidunt sed, interdum luctus ante. Etiam eget nisl id est hendrerit egestas. Vestibulum tempor justo magna, non sagittis felis. Vivamus nec nibh porta nibh cursus luctus suscipit ut nibh. Aenean mollis molestie justo, non ornare mi mollis id. Vestibulum massa neque, mattis eget pulvinar et, tincidunt in magna. Nunc vitae dapibus turpis. Nullam bibendum vehicula odio sed viverra. Donec laoreet, lectus sit amet viverra scelerisque, mi enim fermentum tellus, quis consequat arcu felis in ante. Donec non felis non nisl tincidunt ultricies sit amet nec mi. Maecenas sodales, lorem vel volutpat cursus, nisi tortor pulvinar eros, in pharetra mauris neque sit amet nulla. Nulla ligula turpis, egestas in imperdDuis mollis rhoncus turpis. Proin ut nunc eget urna molestie dictum. Cras mollis nibh quis eros faucibus posuere vehicula diam rutrum. Morbi mattis orci vel ante dignissim sollicitudin. Aenean quis enim orci. Integer vehicula elementum porta. Nullam massa mauris, ornare eget ullamcorper eget, consequat at dolor. Integer cursus pellentesque velit in semper. Donec sem turpis, tristique vitae egestas nec, varius sit amet ipsum. Nullam scelerisque est eu arcu vulputate varius. Integer vel gravida leo. Suspendisse blandit vehicula neque, non porttitor eros adipiscing non. Curabitur egestas pulvinar sapien ac imperdiet. Ut ac purus sit amet magna sollicitudin cursus non vel eros. In vel nibh eget libero mattis volutpat nec vulputate quam. Vestibulum commodo ante id magna cursus tristique. Integer rutrum diam sit amet nulla placerat ornare. Quisque nec felis lacus. In lorem mauris, lobortis sit amet sodales non, sollicitudin vitae odio. Nam a dui est, venenatis iaculis purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In in sollicitudin urna. Praesent dapibus ligula sed lacus pulvinar sit amet pellentesque enim tincidunt. Vivamus feugiat, sapien vitae convallis consectetur, justo ligula semper quam, mollis dapibus lorem odio sit amet justo. Duis ut leo vel turpis cursus tempor. Donec condimentum convallis lacus at feugiat. Aliquam erat volutpat. Etiam auctor risus dolor, in tempor nibh. Nulla interdum, magna eget suscipit aliquet, enim arcu aliquet nunc, vel molestie est sem ac turpis. Ut et convallis diam. Integer malesuada eleifend eros non sollicitudin. In ac sem eget purus iaculis sollicitudin. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse ultrices nulla sit amet sapien fringilla eleifend. Integer eget lectus a augue convallis dignissim sit amet scelerisque odio. Duis velit nisl, mollis a adipiscing eget, suscipit in quam. Sed id lacus et justo dapibus dapibus vestibulum gravida massa. Duis euismod luctus tempor. Nam venenatis gravida rutrum. Etiam id aliquet est. Integer ante arcu, viverra sit amet placerat sit amet, posuere in est. Cras eleifend ultricies urna, ut euismod quam euismod quis. Cras pellentesque nulla et ante molestie pulvinar. Duis malesuada bibendum arcu, id imperdiet enim egestas eget. Sed blandit iaculis enim vel adipiscing. Donec dui quam, tristique non tincidunt sed, interdum luctus ante. Etiam eget nisl id est hendrerit egestas. Vestibulum tempor justo magna, non sagittis felis. Vivamus nec nibh porta nibh cursus luctus suscipit ut nibh. Aenean mollis molestie justo, non ornare mi mollis id. Vestibulum massa neque, mattis eget pulvinar et, tincidunt in magna. Nunc vitae dapibus turpis. Nullam bibendum vehicula odio sed viverra. Donec laoreet, lectus sit amet viverra scelerisque, mi enim fermentum tellus, quis consequat arcu felis in ante. Donec non felis non nisl tincidunt ultricies sit amet nec mi. Maecenas sodales, lorem vel volutpat cursus, nisi tortor pulvinar eros, in pharetra mauris neque sit amet nulla. Nulla ligula turpis, egestas in imperdiet a, faucibus quis turpis. Vivamus purus lorem, vestibulum id rhoncus iaculis, vulputate nec mi \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/text2.txt b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/text2.txt new file mode 100644 index 00000000000000..ca15f413dc40d0 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/fast-levenshtein/test/text2.txt @@ -0,0 +1 @@ +Duis mollis rhoncus turpis. Proin ut nunc eget urna molestie dictum. Cras mollis nibh quis eros faucibus posuere vehicula diam rutrum. Morbi mattis orci vel ante dignissim sollicitudin. Aenean quis enim orci. Integer vehicula elementum porta. Nullam massa mauris, ornare eget ullamcorper eget, consequat at dolor. Integer cursus pellentesque velit in semper. Donec sem turpis, tristique vitae egestas nec, varius sit amet ipsum. Nullam scelerisque est eu arcu vulputate varius. Integer vel gravida leo. Suspendisse blandit vehicula neque, non porttitor eros adipiscing non. Curabitur egestas pulvinar sapien ac imperdiet. Ut ac purus sit amet magna sollicitudin cursus non vel eros. In vel nibh eget libero mattis volutpat nec vulputate quam. Vestibulum commodo ante id magna cursus tristique. Integer rutrum diam sit amet nulla placerat ornare. Quisque nec felis lacus. In lorem mauris, lobortis sit amet sodales non, sollicitudin vitae odio. Nam a dui est, venenatis iaculis purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In in sollicitudin urna. Praesent dapibus ligula sed lacus pulvinar sit amet pellentesque enim tincidunt. Vivamus feugiat, sapien vitae convallis consectetur, justo ligula semper quam, mollis dapibus lorem odio sit amet justo. Duis ut leo vel turpis cursus tempor. Donec condimentum convallis lacus at feugiat. Aliquam erat volutpat. Etiam auctor risus dolor, in tempor nibh. Nulla interdum, magna eget suscipit aliquet, enim arcu aliquet nunc, vel molestie est sem ac turpis. Ut et convallis diam. Integer malesuada eleifend eros non sollicitudin. In ac sem eget purus iaculis sollicitudin. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse ultrices nulla sit amet sapien fringilla eleifend. Integer eget lectus a augue convallis dignissim sit amet scelerisque odio. Duis velit nisl, mollis a adipiscing eget, suscipit in quam. Sed id lacus et justo dapibus dapibus vestibulum gravida massa. Duis euismod luctus tempor. Nam venenatis gravida rutrum. Etiam id aliquet est. Integer ante arcu, viverra sit amet placerat sit amet, posuere in est. Cras eleifend ultricies urna, ut euismod quam euismod quis. Cras pellentesque nulla et ante molestie pulvinar. Duis malesuada bibendum arcu, id imperdiet enim egestas eget. Sed blandit iaculis enim vel adipiscing. Donec dui quam, tristique non tincidunt sed, interdum luctus ante. Etiam eget nisl id est hendrerit egestas. Vestibulum tempor justo magna, non sagittis felis. Vivamus nec nibh porta nibh cursus luctus suscipit ut nibh. Aenean mollis molestie justo, non ornare mi mollis id. Vestibulum massa neque, mattis eget pulvinar et, tincidunt in magna. Nunc vitae dapibus turpis. Nullam bibendum vehicula odio sed viverra. Donec laoreet, lectus sit amet viverra scelerisque, mi enim fermentum tellus, quis consequat arcu felis in ante. Donec non felis non nisl tincidunt ultricies sit amet nec mi. Maecenas sodales, lorem vel volutpat cursus, nisi tortor pulvinar eros, in pharetra mauris neque sit amet nulla. Nulla ligula turpis, egestas in imperdiet a, faucibus quis turpis. Vivamus purus lorem, vestibulum id rhoncus iaculis, vulputate nec miDuis mollis rhoncus turpis. Proin ut nunc eget urna molestie dictum. Cras mollis nibh quis eros faucibus posuere vehicula diam rutrum. Morbi mattis orci vel ante dignissim sollicitudin. Aenean quis enim orci. Integer vehicula elementum porta. Nullam massa mauris, ornare eget ullamcorper eget, consequat at dolor. Integer cursus pellentesque velit in semper. Donec sem turpis, tristique vitae egestas nec, varius sit amet ipsum. Nullam scelerisque est eu arcu vulputate varius. Integer vel gravida leo. Suspendisse blandit vehicula neque, non porttitor eros adipiscing non. Curabitur egestas pulvinar sapien ac imperdiet. Ut ac purus sit amet magna sollicitudin cursus non vel eros. In vel nibh eget libero mattis volutpat nec vulputate quam. Vestibulum commodo ante id magna cursus tristique. Integer rutrum diam sit amet nulla placerat ornare. Quisque nec felis lacus. In lorem mauris, lobortis sit amet sodales non, sollicitudin vitae odio. Nam a dui est, venenatis iaculis purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In in sollicitudin urna. Praesent dapibus ligula sed lacus pulvinar sit amet pellentesque enim tincidunt. Vivamus feugiat, sapien vitae convallis consectetur, justo ligula semper quam, mollis dapibus lorem odio sit amet justo. Duis ut leo vel turpis cursus tempor. Donec condimentum convallis lacus at feugiat. Aliquam erat volutpat. Etiam auctor risus dolor, in tempor nibh. Nulla interdum, magna eget suscipit aliquet, enim arcu aliquet nunc, vel molestie est sem ac turpis. Ut et convallis diam. Integer malesuada eleifend eros non sollicitudin. In ac sem eget purus iaculis sollicitudin. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse ultrices nulla sit amet sapien fringilla eleifend. Integer eget lectus a augue convallis dignissim sit amet scelerisque odio. Duis velit nisl, mollis a adipiscing eget, suscipit in quam. Sed id lacus et justo dapibus dapibus vestibulum gravida massa. Duis euismod luctus tempor. Nam venenatis gravida rutrum. Etiam id aliquet est. Integer ante arcu, viverra sit amet placerat sit amet, posuere in est. Cras eleifend ultricies urna, ut euismod quam euismod quis. Cras pellentesque nulla et ante molestie pulvinar. Duis malesuada bibendum arcu, id imperdiet enim egestas eget. Sed blandit iaculis enim vel adipiscing. Donec dui quam, tristique non tincidunt sed, interdum luctus ante. Etiam eget nisl id est hendrerit egestas. Vestibulum tempor justo magna, non sagittis felis. Vivamus nec nibh porta nibh cursus luctus suscipit ut nibh. Aenean mollis molestie justo, non ornare mi mollis id. Vestibulum massa neque, mattis eget pulvinar et, tincidunt in magna. Nunc vitae dapibus turpis. Nullam bibendum vehicula odio sed viverra. Donec laoreet, lectus sit amet viverra scelerisque, mi enim fermentum tellus, quis consequat arcu felis in ante. Donec non felis non nisl tincidunt ultricies sit amet nec mi. Maecenas sodales, lorem vel volutpat cursus, nisi tortor pulvinar eros, in pharetra mauris neque sit amet nulla. Nulla ligula turpis, egestas in imperd \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/LICENSE b/tools/eslint/node_modules/optionator/node_modules/levn/LICENSE new file mode 100644 index 00000000000000..525b11850e6f2c --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/README.md b/tools/eslint/node_modules/optionator/node_modules/levn/README.md new file mode 100644 index 00000000000000..e55d9435ad855f --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/README.md @@ -0,0 +1,195 @@ +# levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) +__Light ECMAScript (JavaScript) Value Notation__ +Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). + +Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.2.5. + +__How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. + + npm install levn + +For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). + + +## Quick Examples + +```js +var parse = require('levn').parse; +parse('Number', '2'); // 2 +parse('String', '2'); // '2' +parse('String', 'levn'); // 'levn' +parse('String', 'a b'); // 'a b' +parse('Boolean', 'true'); // true + +parse('Date', '#2011-11-11#'); // (Date object) +parse('Date', '2011-11-11'); // (Date object) +parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi +parse('RegExp', 're'); // /re/ + +parse('Number | String', 'str'); // 'str' +parse('Number | String', '2'); // 2 + +parse('[Number]', '[1,2,3]'); // [1,2,3] +parse('(String, Boolean)', '(hi, false)'); // ['hi', false] +parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} + +// at the top level, you can ommit surrounding delimiters +parse('[Number]', '1,2,3'); // [1,2,3] +parse('(String, Boolean)', 'hi, false'); // ['hi', false] +parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} + +// wildcard - auto choose type +parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] +``` +## Usage + +`require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. + +```js +// parse(type, input, options); +parse('[Number]', '1,2,3'); // [1, 2, 3] + +// parsedTypeParse(parsedType, input, options); +var parsedType = require('type-check').parseType('[Number]'); +parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] +``` + +### parse(type, input, options) + +`parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. + +##### arguments +* type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against +* input - `String` - the value written in the [levn format](#levn-format) +* options - `Maybe Object` - an optional parameter specifying additional [options](#options) + +##### returns +`*` - the resulting JavaScript value + +##### example +```js +parse('[Number]', '1,2,3'); // [1, 2, 3] +``` + +### parsedTypeParse(parsedType, input, options) + +`parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. + +##### arguments +* type - `Object` - the type in the parsed type format which to check against +* input - `String` - the value written in the [levn format](#levn-format) +* options - `Maybe Object` - an optional parameter specifying additional [options](#options) + +##### returns +`*` - the resulting JavaScript value + +##### example +```js +var parsedType = require('type-check').parseType('[Number]'); +parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] +``` + +## Levn Format + +Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. + +If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). + +* `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` +* `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` +* `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` +* `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents +* `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. +* `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). +* `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. +* Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. + +If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: + +* If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. +* If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. +* If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. +* If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. +* If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). +* If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. + +If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. + +Whitespace between special characters and elements is inconsequential. + +## Options + +Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. + +### Explicit + +A `Boolean`. By default it is `false`. + +__Example:__ + +```js +parse('RegExp', 're', {explicit: false}); // /re/ +parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... +parse('RegExp | String', 're', {explicit: true}); // 're' +``` + +`explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. + +### customTypes + +An `Object`. Empty `{}` by default. + +__Example:__ + +```js +var options = { + customTypes: { + Even: { + typeOf: 'Number', + validate: function (x) { + return x % 2 === 0; + }, + cast: function (x) { + return {type: 'Just', value: parseInt(x)}; + } + } + } +} +parse('Even', '2', options); // 2 +parse('Even', '3', options); // Error: Value: "3" does not type check... +``` + +__Another Example:__ +```js +function Person(name, age){ + this.name = name; + this.age = age; +} +var options = { + customTypes: { + Person: { + typeOf: 'Object', + validate: function (x) { + x instanceof Person; + }, + cast: function (value, options, typesCast) { + var name, age; + if ({}.toString.call(value).slice(8, -1) !== 'Object') { + return {type: 'Nothing'}; + } + name = typesCast(value.name, [{type: 'String'}], options); + age = typesCast(value.age, [{type: 'Numger'}], options); + return {type: 'Just', value: new Person(name, age)}; + } + } +} +parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} +``` + +`customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. + +`cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. + +## Technical About + +`levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/lib/cast.js b/tools/eslint/node_modules/optionator/node_modules/levn/lib/cast.js new file mode 100644 index 00000000000000..2a6816f94d32bd --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/lib/cast.js @@ -0,0 +1,298 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var parsedTypeCheck, types, toString$ = {}.toString; + parsedTypeCheck = require('type-check').parsedTypeCheck; + types = { + '*': function(value, options){ + switch (toString$.call(value).slice(8, -1)) { + case 'Array': + return typeCast(value, { + type: 'Array' + }, options); + case 'Object': + return typeCast(value, { + type: 'Object' + }, options); + default: + return { + type: 'Just', + value: typesCast(value, [ + { + type: 'Undefined' + }, { + type: 'Null' + }, { + type: 'NaN' + }, { + type: 'Boolean' + }, { + type: 'Number' + }, { + type: 'Date' + }, { + type: 'RegExp' + }, { + type: 'Array' + }, { + type: 'Object' + }, { + type: 'String' + } + ], (options.explicit = true, options)) + }; + } + }, + Undefined: function(it){ + if (it === 'undefined' || it === void 8) { + return { + type: 'Just', + value: void 8 + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Null: function(it){ + if (it === 'null') { + return { + type: 'Just', + value: null + }; + } else { + return { + type: 'Nothing' + }; + } + }, + NaN: function(it){ + if (it === 'NaN') { + return { + type: 'Just', + value: NaN + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Boolean: function(it){ + if (it === 'true') { + return { + type: 'Just', + value: true + }; + } else if (it === 'false') { + return { + type: 'Just', + value: false + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Number: function(it){ + return { + type: 'Just', + value: +it + }; + }, + Int: function(it){ + return { + type: 'Just', + value: parseInt(it) + }; + }, + Float: function(it){ + return { + type: 'Just', + value: parseFloat(it) + }; + }, + Date: function(value, options){ + var that; + if (that = /^\#([\s\S]*)\#$/.exec(value)) { + return { + type: 'Just', + value: new Date(+that[1] || that[1]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new Date(+value || value) + }; + } + }, + RegExp: function(value, options){ + var that; + if (that = /^\/([\s\S]*)\/([gimy]*)$/.exec(value)) { + return { + type: 'Just', + value: new RegExp(that[1], that[2]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new RegExp(value) + }; + } + }, + Array: function(value, options){ + return castArray(value, { + of: [{ + type: '*' + }] + }, options); + }, + Object: function(value, options){ + return castFields(value, { + of: {} + }, options); + }, + String: function(it){ + var that; + if (toString$.call(it).slice(8, -1) !== 'String') { + return { + type: 'Nothing' + }; + } + if (that = it.match(/^'([\s\S]*)'$/)) { + return { + type: 'Just', + value: that[1].replace(/\\'/g, "'") + }; + } else if (that = it.match(/^"([\s\S]*)"$/)) { + return { + type: 'Just', + value: that[1].replace(/\\"/g, '"') + }; + } else { + return { + type: 'Just', + value: it + }; + } + } + }; + function castArray(node, type, options){ + var typeOf, element; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) { + element = ref$[i$]; + results$.push(typesCast(element, typeOf, options)); + } + return results$; + }()) + }; + } + function castTuple(node, type, options){ + var result, i, i$, ref$, len$, types, cast; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + result = []; + i = 0; + for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { + types = ref$[i$]; + cast = typesCast(node[i], types, options); + if (toString$.call(cast).slice(8, -1) !== 'Undefined') { + result.push(cast); + } + i++; + } + if (node.length <= i) { + return { + type: 'Just', + value: result + }; + } else { + return { + type: 'Nothing' + }; + } + } + function castFields(node, type, options){ + var typeOf, key, value; + if (toString$.call(node).slice(8, -1) !== 'Object') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var ref$, results$ = {}; + for (key in ref$ = node) { + value = ref$[key]; + results$[typesCast(key, [{ + type: 'String' + }], options)] = typesCast(value, typeOf[key] || [{ + type: '*' + }], options); + } + return results$; + }()) + }; + } + function typeCast(node, typeObj, options){ + var type, structure, castFunc, ref$; + type = typeObj.type, structure = typeObj.structure; + if (type) { + castFunc = ((ref$ = options.customTypes[type]) != null ? ref$.cast : void 8) || types[type]; + if (!castFunc) { + throw new Error("Type not defined: " + type + "."); + } + return castFunc(node, options, typesCast); + } else { + switch (structure) { + case 'array': + return castArray(node, typeObj, options); + case 'tuple': + return castTuple(node, typeObj, options); + case 'fields': + return castFields(node, typeObj, options); + } + } + } + function typesCast(node, types, options){ + var i$, len$, type, ref$, valueType, value; + for (i$ = 0, len$ = types.length; i$ < len$; ++i$) { + type = types[i$]; + ref$ = typeCast(node, type, options), valueType = ref$.type, value = ref$.value; + if (valueType === 'Nothing') { + continue; + } + if (parsedTypeCheck([type], value, { + customTypes: options.customTypes + })) { + return value; + } + } + throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + "."); + } + module.exports = typesCast; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/lib/coerce.js b/tools/eslint/node_modules/optionator/node_modules/levn/lib/coerce.js new file mode 100644 index 00000000000000..027b6da022f09f --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/lib/coerce.js @@ -0,0 +1,285 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var parsedTypeCheck, types, toString$ = {}.toString; + parsedTypeCheck = require('type-check').parsedTypeCheck; + types = { + '*': function(it){ + switch (toString$.call(it).slice(8, -1)) { + case 'Array': + return coerceType(it, { + type: 'Array' + }); + case 'Object': + return coerceType(it, { + type: 'Object' + }); + default: + return { + type: 'Just', + value: coerceTypes(it, [ + { + type: 'Undefined' + }, { + type: 'Null' + }, { + type: 'NaN' + }, { + type: 'Boolean' + }, { + type: 'Number' + }, { + type: 'Date' + }, { + type: 'RegExp' + }, { + type: 'Array' + }, { + type: 'Object' + }, { + type: 'String' + } + ], { + explicit: true + }) + }; + } + }, + Undefined: function(it){ + if (it === 'undefined' || it === void 8) { + return { + type: 'Just', + value: void 8 + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Null: function(it){ + if (it === 'null') { + return { + type: 'Just', + value: null + }; + } else { + return { + type: 'Nothing' + }; + } + }, + NaN: function(it){ + if (it === 'NaN') { + return { + type: 'Just', + value: NaN + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Boolean: function(it){ + if (it === 'true') { + return { + type: 'Just', + value: true + }; + } else if (it === 'false') { + return { + type: 'Just', + value: false + }; + } else { + return { + type: 'Nothing' + }; + } + }, + Number: function(it){ + return { + type: 'Just', + value: +it + }; + }, + Int: function(it){ + return { + type: 'Just', + value: parseInt(it) + }; + }, + Float: function(it){ + return { + type: 'Just', + value: parseFloat(it) + }; + }, + Date: function(value, options){ + var that; + if (that = /^\#(.*)\#$/.exec(value)) { + return { + type: 'Just', + value: new Date(+that[1] || that[1]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new Date(+value || value) + }; + } + }, + RegExp: function(value, options){ + var that; + if (that = /^\/(.*)\/([gimy]*)$/.exec(value)) { + return { + type: 'Just', + value: new RegExp(that[1], that[2]) + }; + } else if (options.explicit) { + return { + type: 'Nothing' + }; + } else { + return { + type: 'Just', + value: new RegExp(value) + }; + } + }, + Array: function(it){ + return coerceArray(it, { + of: [{ + type: '*' + }] + }); + }, + Object: function(it){ + return coerceFields(it, { + of: {} + }); + }, + String: function(it){ + var that; + if (toString$.call(it).slice(8, -1) !== 'String') { + return { + type: 'Nothing' + }; + } + if (that = it.match(/^'(.*)'$/)) { + return { + type: 'Just', + value: that[1] + }; + } else if (that = it.match(/^"(.*)"$/)) { + return { + type: 'Just', + value: that[1] + }; + } else { + return { + type: 'Just', + value: it + }; + } + } + }; + function coerceArray(node, type){ + var typeOf, element; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) { + element = ref$[i$]; + results$.push(coerceTypes(element, typeOf)); + } + return results$; + }()) + }; + } + function coerceTuple(node, type){ + var result, i$, ref$, len$, i, types, that; + if (toString$.call(node).slice(8, -1) !== 'Array') { + return { + type: 'Nothing' + }; + } + result = []; + for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { + i = i$; + types = ref$[i$]; + if (that = coerceTypes(node[i], types)) { + result.push(that); + } + } + return { + type: 'Just', + value: result + }; + } + function coerceFields(node, type){ + var typeOf, key, value; + if (toString$.call(node).slice(8, -1) !== 'Object') { + return { + type: 'Nothing' + }; + } + typeOf = type.of; + return { + type: 'Just', + value: (function(){ + var ref$, results$ = {}; + for (key in ref$ = node) { + value = ref$[key]; + results$[key] = coerceTypes(value, typeOf[key] || [{ + type: '*' + }]); + } + return results$; + }()) + }; + } + function coerceType(node, typeObj, options){ + var type, structure, coerceFunc; + type = typeObj.type, structure = typeObj.structure; + if (type) { + coerceFunc = types[type]; + return coerceFunc(node, options); + } else { + switch (structure) { + case 'array': + return coerceArray(node, typeObj); + case 'tuple': + return coerceTuple(node, typeObj); + case 'fields': + return coerceFields(node, typeObj); + } + } + } + function coerceTypes(node, types, options){ + var i$, len$, type, ref$, valueType, value; + for (i$ = 0, len$ = types.length; i$ < len$; ++i$) { + type = types[i$]; + ref$ = coerceType(node, type, options), valueType = ref$.type, value = ref$.value; + if (valueType === 'Nothing') { + continue; + } + if (parsedTypeCheck([type], value)) { + return value; + } + } + throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + "."); + } + module.exports = coerceTypes; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/lib/index.js b/tools/eslint/node_modules/optionator/node_modules/levn/lib/index.js new file mode 100644 index 00000000000000..54b5769e510175 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/lib/index.js @@ -0,0 +1,22 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var parseString, cast, parseType, VERSION, parsedTypeParse, parse; + parseString = require('./parse-string'); + cast = require('./cast'); + parseType = require('type-check').parseType; + VERSION = '0.2.5'; + parsedTypeParse = function(parsedType, string, options){ + options == null && (options = {}); + options.explicit == null && (options.explicit = false); + options.customTypes == null && (options.customTypes = {}); + return cast(parseString(parsedType, string, options), parsedType, options); + }; + parse = function(type, string, options){ + return parsedTypeParse(parseType(type), string, options); + }; + module.exports = { + VERSION: VERSION, + parse: parse, + parsedTypeParse: parsedTypeParse + }; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/lib/parse-string.js b/tools/eslint/node_modules/optionator/node_modules/levn/lib/parse-string.js new file mode 100644 index 00000000000000..65ec755c42c800 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/lib/parse-string.js @@ -0,0 +1,113 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var reject, special, tokenRegex; + reject = require('prelude-ls').reject; + function consumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } else { + throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + "."); + } + } + function maybeConsumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } + } + function consumeList(tokens, arg$, hasDelimiters){ + var open, close, result, untilTest; + open = arg$[0], close = arg$[1]; + if (hasDelimiters) { + consumeOp(tokens, open); + } + result = []; + untilTest = "," + (hasDelimiters ? close : ''); + while (tokens.length && (hasDelimiters && tokens[0] !== close)) { + result.push(consumeElement(tokens, untilTest)); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, close); + } + return result; + } + function consumeArray(tokens, hasDelimiters){ + return consumeList(tokens, ['[', ']'], hasDelimiters); + } + function consumeTuple(tokens, hasDelimiters){ + return consumeList(tokens, ['(', ')'], hasDelimiters); + } + function consumeFields(tokens, hasDelimiters){ + var result, untilTest, key; + if (hasDelimiters) { + consumeOp(tokens, '{'); + } + result = {}; + untilTest = "," + (hasDelimiters ? '}' : ''); + while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) { + key = consumeValue(tokens, ':'); + consumeOp(tokens, ':'); + result[key] = consumeElement(tokens, untilTest); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, '}'); + } + return result; + } + function consumeValue(tokens, untilTest){ + var out; + untilTest == null && (untilTest = ''); + out = ''; + while (tokens.length && -1 === untilTest.indexOf(tokens[0])) { + out += tokens.shift(); + } + return out; + } + function consumeElement(tokens, untilTest){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens, true); + case '(': + return consumeTuple(tokens, true); + case '{': + return consumeFields(tokens, true); + default: + return consumeValue(tokens, untilTest); + } + } + function consumeTopLevel(tokens, types, options){ + var ref$, type, structure, origTokens, result, finalResult, x$, y$; + ref$ = types[0], type = ref$.type, structure = ref$.structure; + origTokens = tokens.concat(); + if (!options.explicit && types.length === 1 && ((!type && structure) || (type === 'Array' || type === 'Object'))) { + result = structure === 'array' || type === 'Array' + ? consumeArray(tokens, tokens[0] === '[') + : structure === 'tuple' + ? consumeTuple(tokens, tokens[0] === '(') + : consumeFields(tokens, tokens[0] === '{'); + finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array' + ? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$) + : (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result; + } else { + finalResult = consumeElement(tokens); + } + return finalResult; + } + special = /\[\]\(\)}{:,/.source; + tokenRegex = RegExp('("(?:\\\\"|[^"])*")|(\'(?:\\\\\'|[^\'])*\')|(/(?:\\\\/|[^/])*/[a-zA-Z]*)|(#.*#)|([' + special + '])|([^\\s' + special + '](?:\\s*[^\\s' + special + ']+)*)|\\s*'); + module.exports = function(types, string, options){ + var tokens, node; + options == null && (options = {}); + if (!options.explicit && types.length === 1 && types[0].type === 'String') { + return "'" + string.replace(/\\'/g, "\\\\'") + "'"; + } + tokens = reject(not$, string.split(tokenRegex)); + node = consumeTopLevel(tokens, types, options); + if (!node) { + throw new Error("Error parsing '" + string + "'."); + } + return node; + }; + function not$(x){ return !x; } +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/lib/parse.js b/tools/eslint/node_modules/optionator/node_modules/levn/lib/parse.js new file mode 100644 index 00000000000000..2beff0f4794202 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/lib/parse.js @@ -0,0 +1,102 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var reject, special, tokenRegex; + reject = require('prelude-ls').reject; + function consumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } else { + throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + "."); + } + } + function maybeConsumeOp(tokens, op){ + if (tokens[0] === op) { + return tokens.shift(); + } + } + function consumeList(tokens, delimiters, hasDelimiters){ + var result; + if (hasDelimiters) { + consumeOp(tokens, delimiters[0]); + } + result = []; + while (tokens.length && tokens[0] !== delimiters[1]) { + result.push(consumeElement(tokens)); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, delimiters[1]); + } + return result; + } + function consumeArray(tokens, hasDelimiters){ + return consumeList(tokens, ['[', ']'], hasDelimiters); + } + function consumeTuple(tokens, hasDelimiters){ + return consumeList(tokens, ['(', ')'], hasDelimiters); + } + function consumeFields(tokens, hasDelimiters){ + var result, key; + if (hasDelimiters) { + consumeOp(tokens, '{'); + } + result = {}; + while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) { + key = tokens.shift(); + consumeOp(tokens, ':'); + result[key] = consumeElement(tokens); + maybeConsumeOp(tokens, ','); + } + if (hasDelimiters) { + consumeOp(tokens, '}'); + } + return result; + } + function consumeElement(tokens){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens, true); + case '(': + return consumeTuple(tokens, true); + case '{': + return consumeFields(tokens, true); + default: + return tokens.shift(); + } + } + function consumeTopLevel(tokens, types){ + var ref$, type, structure, origTokens, result, finalResult, x$, y$; + ref$ = types[0], type = ref$.type, structure = ref$.structure; + origTokens = tokens.concat(); + if (types.length === 1 && (structure || (type === 'Array' || type === 'Object'))) { + result = structure === 'array' || type === 'Array' + ? consumeArray(tokens, tokens[0] === '[') + : structure === 'tuple' + ? consumeTuple(tokens, tokens[0] === '(') + : consumeFields(tokens, tokens[0] === '{'); + finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array' + ? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$) + : (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result; + } else { + finalResult = consumeElement(tokens); + } + if (tokens.length && origTokens.length) { + throw new Error("Unable to parse " + JSON.stringify(origTokens) + " of type " + JSON.stringify(types) + "."); + } else { + return finalResult; + } + } + special = /\[\]\(\)}{:,/.source; + tokenRegex = RegExp('("(?:[^"]|\\\\")*")|(\'(?:[^\']|\\\\\')*\')|(#.*#)|(/(?:\\\\/|[^/])*/[gimy]*)|([' + special + '])|([^\\s' + special + ']+)|\\s*'); + module.exports = function(string, types){ + var tokens, node; + tokens = reject(function(it){ + return !it || /^\s+$/.test(it); + }, string.split(tokenRegex)); + node = consumeTopLevel(tokens, types); + if (!node) { + throw new Error("Error parsing '" + string + "'."); + } + return node; + }; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/levn/package.json b/tools/eslint/node_modules/optionator/node_modules/levn/package.json new file mode 100644 index 00000000000000..bc7269b14718e5 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/levn/package.json @@ -0,0 +1,78 @@ +{ + "name": "levn", + "version": "0.2.5", + "author": { + "name": "George Zahariev", + "email": "z@georgezahariev.com" + }, + "description": "Light ECMAScript (JavaScript) Value Notation - human written, concise, typed, flexible", + "homepage": "https://github.com/gkz/levn", + "keywords": [ + "levn", + "light", + "ecmascript", + "value", + "notation", + "json", + "typed", + "human", + "concise", + "typed", + "flexible" + ], + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "main": "./lib/", + "bugs": { + "url": "https://github.com/gkz/levn/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/gkz/levn/master/LICENSE" + } + ], + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/levn.git" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "prelude-ls": "~1.1.0", + "type-check": "~0.3.1" + }, + "devDependencies": { + "LiveScript": "~1.2.0", + "mocha": "~1.8.2", + "istanbul": "~0.1.43" + }, + "_id": "levn@0.2.5", + "dist": { + "shasum": "ba8d339d0ca4a610e3a3f145b9caf48807155054", + "tarball": "http://registry.npmjs.org/levn/-/levn-0.2.5.tgz" + }, + "_from": "levn@>=0.2.5 <0.3.0", + "_npmVersion": "1.3.21", + "_npmUser": { + "name": "gkz", + "email": "z@georgezahariev.com" + }, + "maintainers": [ + { + "name": "gkz", + "email": "z@georgezahariev.com" + } + ], + "directories": {}, + "_shasum": "ba8d339d0ca4a610e3a3f145b9caf48807155054", + "_resolved": "https://registry.npmjs.org/levn/-/levn-0.2.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/LICENSE b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/LICENSE new file mode 100644 index 00000000000000..525b11850e6f2c --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/README.md b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/README.md new file mode 100644 index 00000000000000..fabc212e70606a --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/README.md @@ -0,0 +1,15 @@ +# prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) + +is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, LiveScript. + +See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. + +You can install via npm `npm install prelude-ls` + +### Development + +`make test` to test + +`make build` to build `lib` from `src` + +`make build-browser` to build browser versions diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Func.js b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Func.js new file mode 100644 index 00000000000000..7af0b1974e3bb5 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Func.js @@ -0,0 +1,45 @@ +// Generated by LiveScript 1.2.0 +var apply, curry, flip, fix, over; +apply = curry$(function(f, list){ + return f.apply(null, list); +}); +curry = function(f){ + return curry$(f); +}; +flip = curry$(function(f, x, y){ + return f(y, x); +}); +fix = function(f){ + return function(g){ + return function(){ + return f(g(g)).apply(null, arguments); + }; + }(function(g){ + return function(){ + return f(g(g)).apply(null, arguments); + }; + }); +}; +over = curry$(function(f, g, x, y){ + return f(g(x), g(y)); +}); +module.exports = { + curry: curry, + flip: flip, + fix: fix, + apply: apply, + over: over +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/List.js b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/List.js new file mode 100644 index 00000000000000..02e735286ffb1d --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/List.js @@ -0,0 +1,677 @@ +// Generated by LiveScript 1.2.0 +var each, map, compact, filter, reject, partition, find, head, first, tail, last, initial, empty, reverse, unique, uniqueBy, fold, foldl, fold1, foldl1, foldr, foldr1, unfoldr, concat, concatMap, flatten, difference, intersection, union, countBy, groupBy, andList, orList, any, all, sort, sortWith, sortBy, sum, product, mean, average, maximum, minimum, maximumBy, minimumBy, scan, scanl, scan1, scanl1, scanr, scanr1, slice, take, drop, splitAt, takeWhile, dropWhile, span, breakList, zip, zipWith, zipAll, zipAllWith, at, elemIndex, elemIndices, findIndex, findIndices, toString$ = {}.toString, slice$ = [].slice; +each = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + f(x); + } + return xs; +}); +map = curry$(function(f, xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + results$.push(f(x)); + } + return results$; +}); +compact = function(xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (x) { + results$.push(x); + } + } + return results$; +}; +filter = curry$(function(f, xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (f(x)) { + results$.push(x); + } + } + return results$; +}); +reject = curry$(function(f, xs){ + var i$, len$, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!f(x)) { + results$.push(x); + } + } + return results$; +}); +partition = curry$(function(f, xs){ + var passed, failed, i$, len$, x; + passed = []; + failed = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + (f(x) ? passed : failed).push(x); + } + return [passed, failed]; +}); +find = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (f(x)) { + return x; + } + } +}); +head = first = function(xs){ + return xs[0]; +}; +tail = function(xs){ + if (!xs.length) { + return; + } + return xs.slice(1); +}; +last = function(xs){ + return xs[xs.length - 1]; +}; +initial = function(xs){ + if (!xs.length) { + return; + } + return xs.slice(0, -1); +}; +empty = function(xs){ + return !xs.length; +}; +reverse = function(xs){ + return xs.concat().reverse(); +}; +unique = function(xs){ + var result, i$, len$, x; + result = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!in$(x, result)) { + result.push(x); + } + } + return result; +}; +uniqueBy = curry$(function(f, xs){ + var seen, i$, len$, x, val, results$ = []; + seen = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + val = f(x); + if (in$(val, seen)) { + continue; + } + seen.push(val); + results$.push(x); + } + return results$; +}); +fold = foldl = curry$(function(f, memo, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + memo = f(memo, x); + } + return memo; +}); +fold1 = foldl1 = curry$(function(f, xs){ + return fold(f, xs[0], xs.slice(1)); +}); +foldr = curry$(function(f, memo, xs){ + var i$, x; + for (i$ = xs.length - 1; i$ >= 0; --i$) { + x = xs[i$]; + memo = f(x, memo); + } + return memo; +}); +foldr1 = curry$(function(f, xs){ + return foldr(f, xs[xs.length - 1], xs.slice(0, -1)); +}); +unfoldr = curry$(function(f, b){ + var result, x, that; + result = []; + x = b; + while ((that = f(x)) != null) { + result.push(that[0]); + x = that[1]; + } + return result; +}); +concat = function(xss){ + return [].concat.apply([], xss); +}; +concatMap = curry$(function(f, xs){ + var x; + return [].concat.apply([], (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) { + x = ref$[i$]; + results$.push(f(x)); + } + return results$; + }())); +}); +flatten = function(xs){ + var x; + return [].concat.apply([], (function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (toString$.call(x).slice(8, -1) === 'Array') { + results$.push(flatten(x)); + } else { + results$.push(x); + } + } + return results$; + }())); +}; +difference = function(xs){ + var yss, results, i$, len$, x, j$, len1$, ys; + yss = slice$.call(arguments, 1); + results = []; + outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) { + ys = yss[j$]; + if (in$(x, ys)) { + continue outer; + } + } + results.push(x); + } + return results; +}; +intersection = function(xs){ + var yss, results, i$, len$, x, j$, len1$, ys; + yss = slice$.call(arguments, 1); + results = []; + outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + for (j$ = 0, len1$ = yss.length; j$ < len1$; ++j$) { + ys = yss[j$]; + if (!in$(x, ys)) { + continue outer; + } + } + results.push(x); + } + return results; +}; +union = function(){ + var xss, results, i$, len$, xs, j$, len1$, x; + xss = slice$.call(arguments); + results = []; + for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) { + xs = xss[i$]; + for (j$ = 0, len1$ = xs.length; j$ < len1$; ++j$) { + x = xs[j$]; + if (!in$(x, results)) { + results.push(x); + } + } + } + return results; +}; +countBy = curry$(function(f, xs){ + var results, i$, len$, x, key; + results = {}; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + key = f(x); + if (key in results) { + results[key] += 1; + } else { + results[key] = 1; + } + } + return results; +}); +groupBy = curry$(function(f, xs){ + var results, i$, len$, x, key; + results = {}; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + key = f(x); + if (key in results) { + results[key].push(x); + } else { + results[key] = [x]; + } + } + return results; +}); +andList = function(xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!x) { + return false; + } + } + return true; +}; +orList = function(xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (x) { + return true; + } + } + return false; +}; +any = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (f(x)) { + return true; + } + } + return false; +}); +all = curry$(function(f, xs){ + var i$, len$, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + if (!f(x)) { + return false; + } + } + return true; +}); +sort = function(xs){ + return xs.concat().sort(function(x, y){ + if (x > y) { + return 1; + } else if (x < y) { + return -1; + } else { + return 0; + } + }); +}; +sortWith = curry$(function(f, xs){ + return xs.concat().sort(f); +}); +sortBy = curry$(function(f, xs){ + return xs.concat().sort(function(x, y){ + if (f(x) > f(y)) { + return 1; + } else if (f(x) < f(y)) { + return -1; + } else { + return 0; + } + }); +}); +sum = function(xs){ + var result, i$, len$, x; + result = 0; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + result += x; + } + return result; +}; +product = function(xs){ + var result, i$, len$, x; + result = 1; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + result *= x; + } + return result; +}; +mean = average = function(xs){ + var sum, i$, len$, x; + sum = 0; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + x = xs[i$]; + sum += x; + } + return sum / xs.length; +}; +maximum = function(xs){ + var max, i$, ref$, len$, x; + max = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (x > max) { + max = x; + } + } + return max; +}; +minimum = function(xs){ + var min, i$, ref$, len$, x; + min = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (x < min) { + min = x; + } + } + return min; +}; +maximumBy = curry$(function(f, xs){ + var max, i$, ref$, len$, x; + max = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (f(x) > f(max)) { + max = x; + } + } + return max; +}); +minimumBy = curry$(function(f, xs){ + var min, i$, ref$, len$, x; + min = xs[0]; + for (i$ = 0, len$ = (ref$ = xs.slice(1)).length; i$ < len$; ++i$) { + x = ref$[i$]; + if (f(x) < f(min)) { + min = x; + } + } + return min; +}); +scan = scanl = curry$(function(f, memo, xs){ + var last, x; + last = memo; + return [memo].concat((function(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xs).length; i$ < len$; ++i$) { + x = ref$[i$]; + results$.push(last = f(last, x)); + } + return results$; + }())); +}); +scan1 = scanl1 = curry$(function(f, xs){ + if (!xs.length) { + return; + } + return scan(f, xs[0], xs.slice(1)); +}); +scanr = curry$(function(f, memo, xs){ + xs = xs.concat().reverse(); + return scan(f, memo, xs).reverse(); +}); +scanr1 = curry$(function(f, xs){ + if (!xs.length) { + return; + } + xs = xs.concat().reverse(); + return scan(f, xs[0], xs.slice(1)).reverse(); +}); +slice = curry$(function(x, y, xs){ + return xs.slice(x, y); +}); +take = curry$(function(n, xs){ + if (n <= 0) { + return xs.slice(0, 0); + } else { + return xs.slice(0, n); + } +}); +drop = curry$(function(n, xs){ + if (n <= 0) { + return xs; + } else { + return xs.slice(n); + } +}); +splitAt = curry$(function(n, xs){ + return [take(n, xs), drop(n, xs)]; +}); +takeWhile = curry$(function(p, xs){ + var len, i; + len = xs.length; + if (!len) { + return xs; + } + i = 0; + while (i < len && p(xs[i])) { + i += 1; + } + return xs.slice(0, i); +}); +dropWhile = curry$(function(p, xs){ + var len, i; + len = xs.length; + if (!len) { + return xs; + } + i = 0; + while (i < len && p(xs[i])) { + i += 1; + } + return xs.slice(i); +}); +span = curry$(function(p, xs){ + return [takeWhile(p, xs), dropWhile(p, xs)]; +}); +breakList = curry$(function(p, xs){ + return span(function(){ + return not$(p.apply(this, arguments)); + }, xs); +}); +zip = curry$(function(xs, ys){ + var result, len, i$, len$, i, x; + result = []; + len = ys.length; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (i === len) { + break; + } + result.push([x, ys[i]]); + } + return result; +}); +zipWith = curry$(function(f, xs, ys){ + var result, len, i$, len$, i, x; + result = []; + len = ys.length; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (i === len) { + break; + } + result.push(f(x, ys[i])); + } + return result; +}); +zipAll = function(){ + var xss, minLength, i$, len$, xs, ref$, i, lresult$, j$, results$ = []; + xss = slice$.call(arguments); + minLength = 9e9; + for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) { + xs = xss[i$]; + minLength <= (ref$ = xs.length) || (minLength = ref$); + } + for (i$ = 0; i$ < minLength; ++i$) { + i = i$; + lresult$ = []; + for (j$ = 0, len$ = xss.length; j$ < len$; ++j$) { + xs = xss[j$]; + lresult$.push(xs[i]); + } + results$.push(lresult$); + } + return results$; +}; +zipAllWith = function(f){ + var xss, minLength, i$, len$, xs, ref$, i, results$ = []; + xss = slice$.call(arguments, 1); + minLength = 9e9; + for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) { + xs = xss[i$]; + minLength <= (ref$ = xs.length) || (minLength = ref$); + } + for (i$ = 0; i$ < minLength; ++i$) { + i = i$; + results$.push(f.apply(null, (fn$()))); + } + return results$; + function fn$(){ + var i$, ref$, len$, results$ = []; + for (i$ = 0, len$ = (ref$ = xss).length; i$ < len$; ++i$) { + xs = ref$[i$]; + results$.push(xs[i]); + } + return results$; + } +}; +at = curry$(function(n, xs){ + if (n < 0) { + return xs[xs.length + n]; + } else { + return xs[n]; + } +}); +elemIndex = curry$(function(el, xs){ + var i$, len$, i, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (x === el) { + return i; + } + } +}); +elemIndices = curry$(function(el, xs){ + var i$, len$, i, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (x === el) { + results$.push(i); + } + } + return results$; +}); +findIndex = curry$(function(f, xs){ + var i$, len$, i, x; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (f(x)) { + return i; + } + } +}); +findIndices = curry$(function(f, xs){ + var i$, len$, i, x, results$ = []; + for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) { + i = i$; + x = xs[i$]; + if (f(x)) { + results$.push(i); + } + } + return results$; +}); +module.exports = { + each: each, + map: map, + filter: filter, + compact: compact, + reject: reject, + partition: partition, + find: find, + head: head, + first: first, + tail: tail, + last: last, + initial: initial, + empty: empty, + reverse: reverse, + difference: difference, + intersection: intersection, + union: union, + countBy: countBy, + groupBy: groupBy, + fold: fold, + fold1: fold1, + foldl: foldl, + foldl1: foldl1, + foldr: foldr, + foldr1: foldr1, + unfoldr: unfoldr, + andList: andList, + orList: orList, + any: any, + all: all, + unique: unique, + uniqueBy: uniqueBy, + sort: sort, + sortWith: sortWith, + sortBy: sortBy, + sum: sum, + product: product, + mean: mean, + average: average, + concat: concat, + concatMap: concatMap, + flatten: flatten, + maximum: maximum, + minimum: minimum, + maximumBy: maximumBy, + minimumBy: minimumBy, + scan: scan, + scan1: scan1, + scanl: scanl, + scanl1: scanl1, + scanr: scanr, + scanr1: scanr1, + slice: slice, + take: take, + drop: drop, + splitAt: splitAt, + takeWhile: takeWhile, + dropWhile: dropWhile, + span: span, + breakList: breakList, + zip: zip, + zipWith: zipWith, + zipAll: zipAll, + zipAllWith: zipAllWith, + at: at, + elemIndex: elemIndex, + elemIndices: elemIndices, + findIndex: findIndex, + findIndices: findIndices +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} +function in$(x, xs){ + var i = -1, l = xs.length >>> 0; + while (++i < l) if (x === xs[i]) return true; + return false; +} +function not$(x){ return !x; } \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Num.js b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Num.js new file mode 100644 index 00000000000000..904b6cd5d3a685 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Num.js @@ -0,0 +1,130 @@ +// Generated by LiveScript 1.2.0 +var max, min, negate, abs, signum, quot, rem, div, mod, recip, pi, tau, exp, sqrt, ln, pow, sin, tan, cos, asin, acos, atan, atan2, truncate, round, ceiling, floor, isItNaN, even, odd, gcd, lcm; +max = curry$(function(x$, y$){ + return x$ > y$ ? x$ : y$; +}); +min = curry$(function(x$, y$){ + return x$ < y$ ? x$ : y$; +}); +negate = function(x){ + return -x; +}; +abs = Math.abs; +signum = function(x){ + if (x < 0) { + return -1; + } else if (x > 0) { + return 1; + } else { + return 0; + } +}; +quot = curry$(function(x, y){ + return ~~(x / y); +}); +rem = curry$(function(x$, y$){ + return x$ % y$; +}); +div = curry$(function(x, y){ + return Math.floor(x / y); +}); +mod = curry$(function(x$, y$){ + var ref$; + return ((x$) % (ref$ = y$) + ref$) % ref$; +}); +recip = (function(it){ + return 1 / it; +}); +pi = Math.PI; +tau = pi * 2; +exp = Math.exp; +sqrt = Math.sqrt; +ln = Math.log; +pow = curry$(function(x$, y$){ + return Math.pow(x$, y$); +}); +sin = Math.sin; +tan = Math.tan; +cos = Math.cos; +asin = Math.asin; +acos = Math.acos; +atan = Math.atan; +atan2 = curry$(function(x, y){ + return Math.atan2(x, y); +}); +truncate = function(x){ + return ~~x; +}; +round = Math.round; +ceiling = Math.ceil; +floor = Math.floor; +isItNaN = function(x){ + return x !== x; +}; +even = function(x){ + return x % 2 === 0; +}; +odd = function(x){ + return x % 2 !== 0; +}; +gcd = curry$(function(x, y){ + var z; + x = Math.abs(x); + y = Math.abs(y); + while (y !== 0) { + z = x % y; + x = y; + y = z; + } + return x; +}); +lcm = curry$(function(x, y){ + return Math.abs(Math.floor(x / gcd(x, y) * y)); +}); +module.exports = { + max: max, + min: min, + negate: negate, + abs: abs, + signum: signum, + quot: quot, + rem: rem, + div: div, + mod: mod, + recip: recip, + pi: pi, + tau: tau, + exp: exp, + sqrt: sqrt, + ln: ln, + pow: pow, + sin: sin, + tan: tan, + cos: cos, + acos: acos, + asin: asin, + atan: atan, + atan2: atan2, + truncate: truncate, + round: round, + ceiling: ceiling, + floor: floor, + isItNaN: isItNaN, + even: even, + odd: odd, + gcd: gcd, + lcm: lcm +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Obj.js b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Obj.js new file mode 100644 index 00000000000000..bb244d8e54522d --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Obj.js @@ -0,0 +1,154 @@ +// Generated by LiveScript 1.2.0 +var values, keys, pairsToObj, objToPairs, listsToObj, objToLists, empty, each, map, compact, filter, reject, partition, find; +values = function(object){ + var i$, x, results$ = []; + for (i$ in object) { + x = object[i$]; + results$.push(x); + } + return results$; +}; +keys = function(object){ + var x, results$ = []; + for (x in object) { + results$.push(x); + } + return results$; +}; +pairsToObj = function(object){ + var i$, len$, x, results$ = {}; + for (i$ = 0, len$ = object.length; i$ < len$; ++i$) { + x = object[i$]; + results$[x[0]] = x[1]; + } + return results$; +}; +objToPairs = function(object){ + var key, value, results$ = []; + for (key in object) { + value = object[key]; + results$.push([key, value]); + } + return results$; +}; +listsToObj = curry$(function(keys, values){ + var i$, len$, i, key, results$ = {}; + for (i$ = 0, len$ = keys.length; i$ < len$; ++i$) { + i = i$; + key = keys[i$]; + results$[key] = values[i]; + } + return results$; +}); +objToLists = function(object){ + var keys, values, key, value; + keys = []; + values = []; + for (key in object) { + value = object[key]; + keys.push(key); + values.push(value); + } + return [keys, values]; +}; +empty = function(object){ + var x; + for (x in object) { + return false; + } + return true; +}; +each = curry$(function(f, object){ + var i$, x; + for (i$ in object) { + x = object[i$]; + f(x); + } + return object; +}); +map = curry$(function(f, object){ + var k, x, results$ = {}; + for (k in object) { + x = object[k]; + results$[k] = f(x); + } + return results$; +}); +compact = function(object){ + var k, x, results$ = {}; + for (k in object) { + x = object[k]; +if (x) { + results$[k] = x; + } + } + return results$; +}; +filter = curry$(function(f, object){ + var k, x, results$ = {}; + for (k in object) { + x = object[k]; +if (f(x)) { + results$[k] = x; + } + } + return results$; +}); +reject = curry$(function(f, object){ + var k, x, results$ = {}; + for (k in object) { + x = object[k]; +if (!f(x)) { + results$[k] = x; + } + } + return results$; +}); +partition = curry$(function(f, object){ + var passed, failed, k, x; + passed = {}; + failed = {}; + for (k in object) { + x = object[k]; + (f(x) ? passed : failed)[k] = x; + } + return [passed, failed]; +}); +find = curry$(function(f, object){ + var i$, x; + for (i$ in object) { + x = object[i$]; + if (f(x)) { + return x; + } + } +}); +module.exports = { + values: values, + keys: keys, + pairsToObj: pairsToObj, + objToPairs: objToPairs, + listsToObj: listsToObj, + objToLists: objToLists, + empty: empty, + each: each, + map: map, + filter: filter, + compact: compact, + reject: reject, + partition: partition, + find: find +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Str.js b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Str.js new file mode 100644 index 00000000000000..c1b3424627a787 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/Str.js @@ -0,0 +1,92 @@ +// Generated by LiveScript 1.2.0 +var split, join, lines, unlines, words, unwords, chars, unchars, reverse, repeat, capitalize, camelize, dasherize; +split = curry$(function(sep, str){ + return str.split(sep); +}); +join = curry$(function(sep, xs){ + return xs.join(sep); +}); +lines = function(str){ + if (!str.length) { + return []; + } + return str.split('\n'); +}; +unlines = function(it){ + return it.join('\n'); +}; +words = function(str){ + if (!str.length) { + return []; + } + return str.split(/[ ]+/); +}; +unwords = function(it){ + return it.join(' '); +}; +chars = function(it){ + return it.split(''); +}; +unchars = function(it){ + return it.join(''); +}; +reverse = function(str){ + return str.split('').reverse().join(''); +}; +repeat = curry$(function(n, str){ + var result, i$; + result = ''; + for (i$ = 0; i$ < n; ++i$) { + result += str; + } + return result; +}); +capitalize = function(str){ + return str.charAt(0).toUpperCase() + str.slice(1); +}; +camelize = function(it){ + return it.replace(/[-_]+(.)?/g, function(arg$, c){ + return (c != null ? c : '').toUpperCase(); + }); +}; +dasherize = function(str){ + return str.replace(/([^-A-Z])([A-Z]+)/g, function(arg$, lower, upper){ + return lower + "-" + (upper.length > 1 + ? upper + : upper.toLowerCase()); + }).replace(/^([A-Z]+)/, function(arg$, upper){ + if (upper.length > 1) { + return upper + "-"; + } else { + return upper.toLowerCase(); + } + }); +}; +module.exports = { + split: split, + join: join, + lines: lines, + unlines: unlines, + words: words, + unwords: unwords, + chars: chars, + unchars: unchars, + reverse: reverse, + repeat: repeat, + capitalize: capitalize, + camelize: camelize, + dasherize: dasherize +}; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/index.js b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/index.js new file mode 100644 index 00000000000000..730147730ff9c4 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/lib/index.js @@ -0,0 +1,178 @@ +// Generated by LiveScript 1.2.0 +var Func, List, Obj, Str, Num, id, isType, replicate, prelude, toString$ = {}.toString; +Func = require('./Func.js'); +List = require('./List.js'); +Obj = require('./Obj.js'); +Str = require('./Str.js'); +Num = require('./Num.js'); +id = function(x){ + return x; +}; +isType = curry$(function(type, x){ + return toString$.call(x).slice(8, -1) === type; +}); +replicate = curry$(function(n, x){ + var i$, results$ = []; + for (i$ = 0; i$ < n; ++i$) { + results$.push(x); + } + return results$; +}); +Str.empty = List.empty; +Str.slice = List.slice; +Str.take = List.take; +Str.drop = List.drop; +Str.splitAt = List.splitAt; +Str.takeWhile = List.takeWhile; +Str.dropWhile = List.dropWhile; +Str.span = List.span; +Str.breakStr = List.breakList; +prelude = { + Func: Func, + List: List, + Obj: Obj, + Str: Str, + Num: Num, + id: id, + isType: isType, + replicate: replicate +}; +prelude.each = List.each; +prelude.map = List.map; +prelude.filter = List.filter; +prelude.compact = List.compact; +prelude.reject = List.reject; +prelude.partition = List.partition; +prelude.find = List.find; +prelude.head = List.head; +prelude.first = List.first; +prelude.tail = List.tail; +prelude.last = List.last; +prelude.initial = List.initial; +prelude.empty = List.empty; +prelude.reverse = List.reverse; +prelude.difference = List.difference; +prelude.intersection = List.intersection; +prelude.union = List.union; +prelude.countBy = List.countBy; +prelude.groupBy = List.groupBy; +prelude.fold = List.fold; +prelude.foldl = List.foldl; +prelude.fold1 = List.fold1; +prelude.foldl1 = List.foldl1; +prelude.foldr = List.foldr; +prelude.foldr1 = List.foldr1; +prelude.unfoldr = List.unfoldr; +prelude.andList = List.andList; +prelude.orList = List.orList; +prelude.any = List.any; +prelude.all = List.all; +prelude.unique = List.unique; +prelude.uniqueBy = List.uniqueBy; +prelude.sort = List.sort; +prelude.sortWith = List.sortWith; +prelude.sortBy = List.sortBy; +prelude.sum = List.sum; +prelude.product = List.product; +prelude.mean = List.mean; +prelude.average = List.average; +prelude.concat = List.concat; +prelude.concatMap = List.concatMap; +prelude.flatten = List.flatten; +prelude.maximum = List.maximum; +prelude.minimum = List.minimum; +prelude.maximumBy = List.maximumBy; +prelude.minimumBy = List.minimumBy; +prelude.scan = List.scan; +prelude.scanl = List.scanl; +prelude.scan1 = List.scan1; +prelude.scanl1 = List.scanl1; +prelude.scanr = List.scanr; +prelude.scanr1 = List.scanr1; +prelude.slice = List.slice; +prelude.take = List.take; +prelude.drop = List.drop; +prelude.splitAt = List.splitAt; +prelude.takeWhile = List.takeWhile; +prelude.dropWhile = List.dropWhile; +prelude.span = List.span; +prelude.breakList = List.breakList; +prelude.zip = List.zip; +prelude.zipWith = List.zipWith; +prelude.zipAll = List.zipAll; +prelude.zipAllWith = List.zipAllWith; +prelude.at = List.at; +prelude.elemIndex = List.elemIndex; +prelude.elemIndices = List.elemIndices; +prelude.findIndex = List.findIndex; +prelude.findIndices = List.findIndices; +prelude.apply = Func.apply; +prelude.curry = Func.curry; +prelude.flip = Func.flip; +prelude.fix = Func.fix; +prelude.over = Func.over; +prelude.split = Str.split; +prelude.join = Str.join; +prelude.lines = Str.lines; +prelude.unlines = Str.unlines; +prelude.words = Str.words; +prelude.unwords = Str.unwords; +prelude.chars = Str.chars; +prelude.unchars = Str.unchars; +prelude.repeat = Str.repeat; +prelude.capitalize = Str.capitalize; +prelude.camelize = Str.camelize; +prelude.dasherize = Str.dasherize; +prelude.values = Obj.values; +prelude.keys = Obj.keys; +prelude.pairsToObj = Obj.pairsToObj; +prelude.objToPairs = Obj.objToPairs; +prelude.listsToObj = Obj.listsToObj; +prelude.objToLists = Obj.objToLists; +prelude.max = Num.max; +prelude.min = Num.min; +prelude.negate = Num.negate; +prelude.abs = Num.abs; +prelude.signum = Num.signum; +prelude.quot = Num.quot; +prelude.rem = Num.rem; +prelude.div = Num.div; +prelude.mod = Num.mod; +prelude.recip = Num.recip; +prelude.pi = Num.pi; +prelude.tau = Num.tau; +prelude.exp = Num.exp; +prelude.sqrt = Num.sqrt; +prelude.ln = Num.ln; +prelude.pow = Num.pow; +prelude.sin = Num.sin; +prelude.tan = Num.tan; +prelude.cos = Num.cos; +prelude.acos = Num.acos; +prelude.asin = Num.asin; +prelude.atan = Num.atan; +prelude.atan2 = Num.atan2; +prelude.truncate = Num.truncate; +prelude.round = Num.round; +prelude.ceiling = Num.ceiling; +prelude.floor = Num.floor; +prelude.isItNaN = Num.isItNaN; +prelude.even = Num.even; +prelude.odd = Num.odd; +prelude.gcd = Num.gcd; +prelude.lcm = Num.lcm; +prelude.VERSION = '1.1.1'; +module.exports = prelude; +function curry$(f, bound){ + var context, + _curry = function(args) { + return f.length > 1 ? function(){ + var params = args ? args.concat() : []; + context = bound ? context || this : this; + return params.push.apply(params, arguments) < + f.length && arguments.length ? + _curry.call(context, params) : f.apply(context, params); + } : f; + }; + return _curry(); +} \ No newline at end of file diff --git a/tools/eslint/node_modules/optionator/node_modules/prelude-ls/package.json b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/package.json new file mode 100644 index 00000000000000..4637f0e6f12893 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/prelude-ls/package.json @@ -0,0 +1,77 @@ +{ + "name": "prelude-ls", + "version": "1.1.1", + "author": { + "name": "George Zahariev", + "email": "z@georgezahariev.com" + }, + "description": "prelude.ls is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, LiveScript.", + "keywords": [ + "prelude", + "livescript", + "utility", + "ls", + "coffeescript", + "javascript", + "library", + "functional", + "array", + "list", + "object", + "string" + ], + "main": "lib/", + "files": [ + "lib/", + "README.md", + "LICENSE" + ], + "homepage": "http://preludels.com", + "bugs": { + "url": "https://github.com/gkz/prelude-ls/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/gkz/prelude-ls/master/LICENSE" + } + ], + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/prelude-ls.git" + }, + "scripts": { + "test": "make test" + }, + "devDependencies": { + "LiveScript": "~1.2.0", + "uglify-js": "~2.4.12", + "mocha": "~1.17.1", + "istanbul": "~0.2.4", + "browserify": "~3.24.13" + }, + "_id": "prelude-ls@1.1.1", + "dist": { + "shasum": "c0b86c1ffd151ad3cc75e7e3fe38d7a1bf33728a", + "tarball": "http://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.1.tgz" + }, + "_from": "prelude-ls@>=1.1.1 <1.2.0", + "_npmVersion": "1.3.21", + "_npmUser": { + "name": "gkz", + "email": "z@georgezahariev.com" + }, + "maintainers": [ + { + "name": "gkz", + "email": "z@georgezahariev.com" + } + ], + "directories": {}, + "_shasum": "c0b86c1ffd151ad3cc75e7e3fe38d7a1bf33728a", + "_resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/optionator/node_modules/type-check/LICENSE b/tools/eslint/node_modules/optionator/node_modules/type-check/LICENSE new file mode 100644 index 00000000000000..525b11850e6f2c --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/type-check/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/optionator/node_modules/type-check/README.md b/tools/eslint/node_modules/optionator/node_modules/type-check/README.md new file mode 100644 index 00000000000000..0b8c1fd3af0314 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/type-check/README.md @@ -0,0 +1,210 @@ +# type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) + + + +`type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.3.1. Check out the [demo](http://gkz.github.io/type-check/). + +For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). + + npm install type-check + +## Quick Examples + +```js +// Basic types: +var typeCheck = require('type-check').typeCheck; +typeCheck('Number', 1); // true +typeCheck('Number', 'str'); // false +typeCheck('Error', new Error); // true +typeCheck('Undefined', undefined); // true + +// Comment +typeCheck('count::Number', 1); // true + +// One type OR another type: +typeCheck('Number | String', 2); // true +typeCheck('Number | String', 'str'); // true + +// Wildcard, matches all types: +typeCheck('*', 2) // true + +// Array, all elements of a single type: +typeCheck('[Number]', [1, 2, 3]); // true +typeCheck('[Number]', [1, 'str', 3]); // false + +// Tuples, or fixed length arrays with elements of different types: +typeCheck('(String, Number)', ['str', 2]); // true +typeCheck('(String, Number)', ['str']); // false +typeCheck('(String, Number)', ['str', 2, 5]); // false + +// Object properties: +typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true +typeCheck('{x: Number, y: Boolean}', {x: 2}); // false +typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true +typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false +typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true + +// A particular type AND object properties: +typeCheck('RegExp{source: String, ...}', /re/i); // true +typeCheck('RegExp{source: String, ...}', {source: 're'}); // false + +// Custom types: +var opt = {customTypes: + {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; +typeCheck('Even', 2, opt); // true + +// Nested: +var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' +typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true +``` + +Check out the [type syntax format](#syntax) and [guide](#guide). + +## Usage + +`require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. + +```js +// typeCheck(type, input, options); +typeCheck('Number', 2); // true + +// parseType(type); +var parsedType = parseType('Number'); // object + +// parsedTypeCheck(parsedType, input, options); +parsedTypeCheck(parsedType, 2); // true +``` + +### typeCheck(type, input, options) + +`typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. + +##### arguments +* type - `String` - the type written in the [type format](#type-format) which to check against +* input - `*` - any JavaScript value, which is to be checked against the type +* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) + +##### returns +`Boolean` - whether the input matches the type + +##### example +```js +typeCheck('Number', 2); // true +``` + +### parseType(type) + +`parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. + +##### arguments +* type - `String` - the type written in the [type format](#type-format) which to parse + +##### returns +`Object` - an object in the parsed type format representing the parsed type + +##### example +```js +parseType('Number'); // [{type: 'Number'}] +``` +### parsedTypeCheck(parsedType, input, options) + +`parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. + +##### arguments +* type - `Object` - the type in the parsed type format which to check against +* input - `*` - any JavaScript value, which is to be checked against the type +* options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) + +##### returns +`Boolean` - whether the input matches the type + +##### example +```js +parsedTypeCheck([{type: 'Number'}], 2); // true +var parsedType = parseType('String'); +parsedTypeCheck(parsedType, 'str'); // true +``` + + +## Type Format + +### Syntax + +White space is ignored. The root node is a __Types__. + +* __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` +* __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` +* __Types__ = optionally a comment (an `Indentifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` +* __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` +* __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` +* __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` +* __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` +* __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` + +### Guide + +`type-check` uses `Object.toString` to find out the basic type of a value. Specifically, + +```js +{}.toString.call(VALUE).slice(8, -1) +{}.toString.call(true).slice(8, -1) // 'Boolean' +``` +A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. + +You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. + +Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. + +You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. + +The wildcard `*` matches all types. + +There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. + +If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. + +To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. + +If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). + +If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. + +For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. + +A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. + +An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. + +Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. + +## Options + +Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. + + +### Custom Types + +__Example:__ + +```js +var options = { + customTypes: { + Even: { + typeOf: 'Number', + validate: function(x) { + return x % 2 === 0; + } + } + } +}; +typeCheck('Even', 2, options); // true +typeCheck('Even', 3, options); // false +``` + +`customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. + +The `typeOf` property is the type the value should be, and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. + +## Technical About + +`type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/tools/eslint/node_modules/optionator/node_modules/type-check/lib/check.js b/tools/eslint/node_modules/optionator/node_modules/type-check/lib/check.js new file mode 100644 index 00000000000000..c1e51ff90b0173 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/type-check/lib/check.js @@ -0,0 +1,126 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var ref$, any, all, isItNaN, types, defaultType, customTypes, toString$ = {}.toString; + ref$ = require('prelude-ls'), any = ref$.any, all = ref$.all, isItNaN = ref$.isItNaN; + types = { + Number: { + typeOf: 'Number', + validate: function(it){ + return !isItNaN(it); + } + }, + NaN: { + typeOf: 'Number', + validate: isItNaN + }, + Int: { + typeOf: 'Number', + validate: function(it){ + return !isItNaN(it) && it % 1 === 0; + } + }, + Float: { + typeOf: 'Number', + validate: function(it){ + return !isItNaN(it); + } + }, + Date: { + typeOf: 'Date', + validate: function(it){ + return !isItNaN(it.getTime()); + } + } + }; + defaultType = { + array: 'Array', + tuple: 'Array' + }; + function checkArray(input, type){ + return all(function(it){ + return checkMultiple(it, type.of); + }, input); + } + function checkTuple(input, type){ + var i, i$, ref$, len$, types; + i = 0; + for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { + types = ref$[i$]; + if (!checkMultiple(input[i], types)) { + return false; + } + i++; + } + return input.length <= i; + } + function checkFields(input, type){ + var inputKeys, numInputKeys, k, numOfKeys, key, ref$, types; + inputKeys = {}; + numInputKeys = 0; + for (k in input) { + inputKeys[k] = true; + numInputKeys++; + } + numOfKeys = 0; + for (key in ref$ = type.of) { + types = ref$[key]; + if (!checkMultiple(input[key], types)) { + return false; + } + if (inputKeys[key]) { + numOfKeys++; + } + } + return type.subset || numInputKeys === numOfKeys; + } + function checkStructure(input, type){ + if (!(input instanceof Object)) { + return false; + } + switch (type.structure) { + case 'fields': + return checkFields(input, type); + case 'array': + return checkArray(input, type); + case 'tuple': + return checkTuple(input, type); + } + } + function check(input, typeObj){ + var type, structure, setting, that; + type = typeObj.type, structure = typeObj.structure; + if (type) { + if (type === '*') { + return true; + } + setting = customTypes[type] || types[type]; + if (setting) { + return setting.typeOf === toString$.call(input).slice(8, -1) && setting.validate(input); + } else { + return type === toString$.call(input).slice(8, -1) && (!structure || checkStructure(input, typeObj)); + } + } else if (structure) { + if (that = defaultType[structure]) { + if (that !== toString$.call(input).slice(8, -1)) { + return false; + } + } + return checkStructure(input, typeObj); + } else { + throw new Error("No type defined. Input: " + input + "."); + } + } + function checkMultiple(input, types){ + if (toString$.call(types).slice(8, -1) !== 'Array') { + throw new Error("Types must be in an array. Input: " + input + "."); + } + return any(function(it){ + return check(input, it); + }, types); + } + module.exports = function(parsedType, input, options){ + options == null && (options = {}); + customTypes = options.customTypes || {}; + return checkMultiple(input, parsedType); + }; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/type-check/lib/index.js b/tools/eslint/node_modules/optionator/node_modules/type-check/lib/index.js new file mode 100644 index 00000000000000..ff263e1d6f2220 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/type-check/lib/index.js @@ -0,0 +1,16 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var VERSION, parseType, parsedTypeCheck, typeCheck; + VERSION = '0.3.1'; + parseType = require('./parse-type'); + parsedTypeCheck = require('./check'); + typeCheck = function(type, input, options){ + return parsedTypeCheck(parseType(type), input, options); + }; + module.exports = { + VERSION: VERSION, + typeCheck: typeCheck, + parsedTypeCheck: parsedTypeCheck, + parseType: parseType + }; +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/type-check/lib/parse-type.js b/tools/eslint/node_modules/optionator/node_modules/type-check/lib/parse-type.js new file mode 100644 index 00000000000000..32c3a460e33644 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/type-check/lib/parse-type.js @@ -0,0 +1,196 @@ +// Generated by LiveScript 1.2.0 +(function(){ + var identifierRegex, tokenRegex; + identifierRegex = /[\$\w]+/; + function peek(tokens){ + var token; + token = tokens[0]; + if (token == null) { + throw new Error('Unexpected end of input.'); + } + return token; + } + function consumeIdent(tokens){ + var token; + token = peek(tokens); + if (!identifierRegex.test(token)) { + throw new Error("Expected text, got '" + token + "' instead."); + } + return tokens.shift(); + } + function consumeOp(tokens, op){ + var token; + token = peek(tokens); + if (token !== op) { + throw new Error("Expected '" + op + "', got '" + token + "' instead."); + } + return tokens.shift(); + } + function maybeConsumeOp(tokens, op){ + var token; + token = tokens[0]; + if (token === op) { + return tokens.shift(); + } else { + return null; + } + } + function consumeArray(tokens){ + var types; + consumeOp(tokens, '['); + if (peek(tokens) === ']') { + throw new Error("Must specify type of Array - eg. [Type], got [] instead."); + } + types = consumeTypes(tokens); + consumeOp(tokens, ']'); + return { + structure: 'array', + of: types + }; + } + function consumeTuple(tokens){ + var components; + components = []; + consumeOp(tokens, '('); + if (peek(tokens) === ')') { + throw new Error("Tuple must be of at least length 1 - eg. (Type), got () instead."); + } + for (;;) { + components.push(consumeTypes(tokens)); + maybeConsumeOp(tokens, ','); + if (')' === peek(tokens)) { + break; + } + } + consumeOp(tokens, ')'); + return { + structure: 'tuple', + of: components + }; + } + function consumeFields(tokens){ + var fields, subset, ref$, key, types; + fields = {}; + consumeOp(tokens, '{'); + subset = false; + for (;;) { + if (maybeConsumeOp(tokens, '...')) { + subset = true; + break; + } + ref$ = consumeField(tokens), key = ref$[0], types = ref$[1]; + fields[key] = types; + maybeConsumeOp(tokens, ','); + if ('}' === peek(tokens)) { + break; + } + } + consumeOp(tokens, '}'); + return { + structure: 'fields', + of: fields, + subset: subset + }; + } + function consumeField(tokens){ + var key, types; + key = consumeIdent(tokens); + consumeOp(tokens, ':'); + types = consumeTypes(tokens); + return [key, types]; + } + function maybeConsumeStructure(tokens){ + switch (tokens[0]) { + case '[': + return consumeArray(tokens); + case '(': + return consumeTuple(tokens); + case '{': + return consumeFields(tokens); + } + } + function consumeType(tokens){ + var token, wildcard, type, structure; + token = peek(tokens); + wildcard = token === '*'; + if (wildcard || identifierRegex.test(token)) { + type = wildcard + ? consumeOp(tokens, '*') + : consumeIdent(tokens); + structure = maybeConsumeStructure(tokens); + if (structure) { + return structure.type = type, structure; + } else { + return { + type: type + }; + } + } else { + structure = maybeConsumeStructure(tokens); + if (!structure) { + throw new Error("Unexpected character: " + token); + } + return structure; + } + } + function consumeTypes(tokens){ + var lookahead, types, typesSoFar, typeObj, type; + if ('::' === peek(tokens)) { + throw new Error("No comment before comment separator '::' found."); + } + lookahead = tokens[1]; + if (lookahead != null && lookahead === '::') { + tokens.shift(); + tokens.shift(); + } + types = []; + typesSoFar = {}; + if ('Maybe' === peek(tokens)) { + tokens.shift(); + types = [ + { + type: 'Undefined' + }, { + type: 'Null' + } + ]; + typesSoFar = { + Undefined: true, + Null: true + }; + } + for (;;) { + typeObj = consumeType(tokens), type = typeObj.type; + if (!typesSoFar[type]) { + types.push(typeObj); + } + typesSoFar[type] = true; + if (!maybeConsumeOp(tokens, '|')) { + break; + } + } + return types; + } + tokenRegex = RegExp('\\.\\.\\.|::|->|' + identifierRegex.source + '|\\S', 'g'); + module.exports = function(input){ + var tokens, e; + if (!input.length) { + throw new Error('No type specified.'); + } + tokens = input.match(tokenRegex) || []; + if (in$('->', tokens)) { + throw new Error("Function types are not supported.\ To validate that something is a function, you may use 'Function'."); + } + try { + return consumeTypes(tokens); + } catch (e$) { + e = e$; + throw new Error(e.message + " - Remaining tokens: " + JSON.stringify(tokens) + " - Initial input: '" + input + "'"); + } + }; + function in$(x, xs){ + var i = -1, l = xs.length >>> 0; + while (++i < l) if (x === xs[i]) return true; + return false; + } +}).call(this); diff --git a/tools/eslint/node_modules/optionator/node_modules/type-check/package.json b/tools/eslint/node_modules/optionator/node_modules/type-check/package.json new file mode 100644 index 00000000000000..01916be6f856dd --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/type-check/package.json @@ -0,0 +1,71 @@ +{ + "name": "type-check", + "version": "0.3.1", + "author": { + "name": "George Zahariev", + "email": "z@georgezahariev.com" + }, + "description": "type-check allows you to check the types of JavaScript values at runtime with a Haskell like type syntax.", + "homepage": "https://github.com/gkz/type-check", + "keywords": [ + "type", + "check", + "checking", + "library" + ], + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "main": "./lib/", + "bugs": { + "url": "https://github.com/gkz/type-check/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/gkz/type-check/master/LICENSE" + } + ], + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/type-check.git" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "prelude-ls": "~1.1.0" + }, + "devDependencies": { + "LiveScript": "~1.2.0", + "mocha": "~1.8.2", + "istanbul": "~0.1.43", + "browserify": "~2.33" + }, + "_id": "type-check@0.3.1", + "dist": { + "shasum": "9233923c4da174d0ac5480ecfd6ef84c349eb58d", + "tarball": "http://registry.npmjs.org/type-check/-/type-check-0.3.1.tgz" + }, + "_from": "type-check@>=0.3.1 <0.4.0", + "_npmVersion": "1.3.21", + "_npmUser": { + "name": "gkz", + "email": "z@georgezahariev.com" + }, + "maintainers": [ + { + "name": "gkz", + "email": "z@georgezahariev.com" + } + ], + "directories": {}, + "_shasum": "9233923c4da174d0ac5480ecfd6ef84c349eb58d", + "_resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/.npmignore b/tools/eslint/node_modules/optionator/node_modules/wordwrap/.npmignore new file mode 100644 index 00000000000000..3c3629e647f5dd --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/README.markdown b/tools/eslint/node_modules/optionator/node_modules/wordwrap/README.markdown new file mode 100644 index 00000000000000..346374e0d480bb --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/README.markdown @@ -0,0 +1,70 @@ +wordwrap +======== + +Wrap your words. + +example +======= + +made out of meat +---------------- + +meat.js + + var wrap = require('wordwrap')(15); + console.log(wrap('You and your whole family are made out of meat.')); + +output: + + You and your + whole family + are made out + of meat. + +centered +-------- + +center.js + + var wrap = require('wordwrap')(20, 60); + console.log(wrap( + 'At long last the struggle and tumult was over.' + + ' The machines had finally cast off their oppressors' + + ' and were finally free to roam the cosmos.' + + '\n' + + 'Free of purpose, free of obligation.' + + ' Just drifting through emptiness.' + + ' The sun was just another point of light.' + )); + +output: + + At long last the struggle and tumult + was over. The machines had finally cast + off their oppressors and were finally + free to roam the cosmos. + Free of purpose, free of obligation. + Just drifting through emptiness. The + sun was just another point of light. + +methods +======= + +var wrap = require('wordwrap'); + +wrap(stop), wrap(start, stop, params={mode:"soft"}) +--------------------------------------------------- + +Returns a function that takes a string and returns a new string. + +Pad out lines with spaces out to column `start` and then wrap until column +`stop`. If a word is longer than `stop - start` characters it will overflow. + +In "soft" mode, split chunks by `/(\S+\s+/` and don't break up chunks which are +longer than `stop - start`, in "hard" mode, split chunks with `/\b/` and break +up chunks longer than `stop - start`. + +wrap.hard(start, stop) +---------------------- + +Like `wrap()` but with `params.mode = "hard"`. diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/example/center.js b/tools/eslint/node_modules/optionator/node_modules/wordwrap/example/center.js new file mode 100644 index 00000000000000..a3fbaae9880f76 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/example/center.js @@ -0,0 +1,10 @@ +var wrap = require('wordwrap')(20, 60); +console.log(wrap( + 'At long last the struggle and tumult was over.' + + ' The machines had finally cast off their oppressors' + + ' and were finally free to roam the cosmos.' + + '\n' + + 'Free of purpose, free of obligation.' + + ' Just drifting through emptiness.' + + ' The sun was just another point of light.' +)); diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/example/meat.js b/tools/eslint/node_modules/optionator/node_modules/wordwrap/example/meat.js new file mode 100644 index 00000000000000..a4665e1058b5ec --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/example/meat.js @@ -0,0 +1,3 @@ +var wrap = require('wordwrap')(15); + +console.log(wrap('You and your whole family are made out of meat.')); diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/index.js b/tools/eslint/node_modules/optionator/node_modules/wordwrap/index.js new file mode 100644 index 00000000000000..c9bc94521d8c7a --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/index.js @@ -0,0 +1,76 @@ +var wordwrap = module.exports = function (start, stop, params) { + if (typeof start === 'object') { + params = start; + start = params.start; + stop = params.stop; + } + + if (typeof stop === 'object') { + params = stop; + start = start || params.start; + stop = undefined; + } + + if (!stop) { + stop = start; + start = 0; + } + + if (!params) params = {}; + var mode = params.mode || 'soft'; + var re = mode === 'hard' ? /\b/ : /(\S+\s+)/; + + return function (text) { + var chunks = text.toString() + .split(re) + .reduce(function (acc, x) { + if (mode === 'hard') { + for (var i = 0; i < x.length; i += stop - start) { + acc.push(x.slice(i, i + stop - start)); + } + } + else acc.push(x) + return acc; + }, []) + ; + + return chunks.reduce(function (lines, rawChunk) { + if (rawChunk === '') return lines; + + var chunk = rawChunk.replace(/\t/g, ' '); + + var i = lines.length - 1; + if (lines[i].length + chunk.length > stop) { + lines[i] = lines[i].replace(/\s+$/, ''); + + chunk.split(/\n/).forEach(function (c) { + lines.push( + new Array(start + 1).join(' ') + + c.replace(/^\s+/, '') + ); + }); + } + else if (chunk.match(/\n/)) { + var xs = chunk.split(/\n/); + lines[i] += xs.shift(); + xs.forEach(function (c) { + lines.push( + new Array(start + 1).join(' ') + + c.replace(/^\s+/, '') + ); + }); + } + else { + lines[i] += chunk; + } + + return lines; + }, [ new Array(start + 1).join(' ') ]).join('\n'); + }; +}; + +wordwrap.soft = wordwrap; + +wordwrap.hard = function (start, stop) { + return wordwrap(start, stop, { mode : 'hard' }); +}; diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/package.json b/tools/eslint/node_modules/optionator/node_modules/wordwrap/package.json new file mode 100644 index 00000000000000..d1c1ae26332b39 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/package.json @@ -0,0 +1,47 @@ +{ + "name": "wordwrap", + "description": "Wrap those words. Show them at what columns to start and stop.", + "version": "0.0.2", + "repository": { + "type": "git", + "url": "git://github.com/substack/node-wordwrap.git" + }, + "main": "./index.js", + "keywords": [ + "word", + "wrap", + "rule", + "format", + "column" + ], + "directories": { + "lib": ".", + "example": "example", + "test": "test" + }, + "scripts": { + "test": "expresso" + }, + "devDependencies": { + "expresso": "=0.7.x" + }, + "engines": { + "node": ">=0.4.0" + }, + "license": "MIT/X11", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "readme": "wordwrap\n========\n\nWrap your words.\n\nexample\n=======\n\nmade out of meat\n----------------\n\nmeat.js\n\n var wrap = require('wordwrap')(15);\n console.log(wrap('You and your whole family are made out of meat.'));\n\noutput:\n\n You and your\n whole family\n are made out\n of meat.\n\ncentered\n--------\n\ncenter.js\n\n var wrap = require('wordwrap')(20, 60);\n console.log(wrap(\n 'At long last the struggle and tumult was over.'\n + ' The machines had finally cast off their oppressors'\n + ' and were finally free to roam the cosmos.'\n + '\\n'\n + 'Free of purpose, free of obligation.'\n + ' Just drifting through emptiness.'\n + ' The sun was just another point of light.'\n ));\n\noutput:\n\n At long last the struggle and tumult\n was over. The machines had finally cast\n off their oppressors and were finally\n free to roam the cosmos.\n Free of purpose, free of obligation.\n Just drifting through emptiness. The\n sun was just another point of light.\n\nmethods\n=======\n\nvar wrap = require('wordwrap');\n\nwrap(stop), wrap(start, stop, params={mode:\"soft\"})\n---------------------------------------------------\n\nReturns a function that takes a string and returns a new string.\n\nPad out lines with spaces out to column `start` and then wrap until column\n`stop`. If a word is longer than `stop - start` characters it will overflow.\n\nIn \"soft\" mode, split chunks by `/(\\S+\\s+/` and don't break up chunks which are\nlonger than `stop - start`, in \"hard\" mode, split chunks with `/\\b/` and break\nup chunks longer than `stop - start`.\n\nwrap.hard(start, stop)\n----------------------\n\nLike `wrap()` but with `params.mode = \"hard\"`.\n", + "readmeFilename": "README.markdown", + "bugs": { + "url": "https://github.com/substack/node-wordwrap/issues" + }, + "homepage": "https://github.com/substack/node-wordwrap", + "_id": "wordwrap@0.0.2", + "_shasum": "b79669bb42ecb409f83d583cad52ca17eaa1643f", + "_from": "wordwrap@>=0.0.2 <0.1.0", + "_resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz" +} diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/break.js b/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/break.js new file mode 100644 index 00000000000000..749292ecc13da0 --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/break.js @@ -0,0 +1,30 @@ +var assert = require('assert'); +var wordwrap = require('../'); + +exports.hard = function () { + var s = 'Assert from {"type":"equal","ok":false,"found":1,"wanted":2,' + + '"stack":[],"id":"b7ddcd4c409de8799542a74d1a04689b",' + + '"browser":"chrome/6.0"}' + ; + var s_ = wordwrap.hard(80)(s); + + var lines = s_.split('\n'); + assert.equal(lines.length, 2); + assert.ok(lines[0].length < 80); + assert.ok(lines[1].length < 80); + + assert.equal(s, s_.replace(/\n/g, '')); +}; + +exports.break = function () { + var s = new Array(55+1).join('a'); + var s_ = wordwrap.hard(20)(s); + + var lines = s_.split('\n'); + assert.equal(lines.length, 3); + assert.ok(lines[0].length === 20); + assert.ok(lines[1].length === 20); + assert.ok(lines[2].length === 15); + + assert.equal(s, s_.replace(/\n/g, '')); +}; diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/idleness.txt b/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/idleness.txt new file mode 100644 index 00000000000000..aa3f4907fe889e --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/idleness.txt @@ -0,0 +1,63 @@ +In Praise of Idleness + +By Bertrand Russell + +[1932] + +Like most of my generation, I was brought up on the saying: 'Satan finds some mischief for idle hands to do.' Being a highly virtuous child, I believed all that I was told, and acquired a conscience which has kept me working hard down to the present moment. But although my conscience has controlled my actions, my opinions have undergone a revolution. I think that there is far too much work done in the world, that immense harm is caused by the belief that work is virtuous, and that what needs to be preached in modern industrial countries is quite different from what always has been preached. Everyone knows the story of the traveler in Naples who saw twelve beggars lying in the sun (it was before the days of Mussolini), and offered a lira to the laziest of them. Eleven of them jumped up to claim it, so he gave it to the twelfth. this traveler was on the right lines. But in countries which do not enjoy Mediterranean sunshine idleness is more difficult, and a great public propaganda will be required to inaugurate it. I hope that, after reading the following pages, the leaders of the YMCA will start a campaign to induce good young men to do nothing. If so, I shall not have lived in vain. + +Before advancing my own arguments for laziness, I must dispose of one which I cannot accept. Whenever a person who already has enough to live on proposes to engage in some everyday kind of job, such as school-teaching or typing, he or she is told that such conduct takes the bread out of other people's mouths, and is therefore wicked. If this argument were valid, it would only be necessary for us all to be idle in order that we should all have our mouths full of bread. What people who say such things forget is that what a man earns he usually spends, and in spending he gives employment. As long as a man spends his income, he puts just as much bread into people's mouths in spending as he takes out of other people's mouths in earning. The real villain, from this point of view, is the man who saves. If he merely puts his savings in a stocking, like the proverbial French peasant, it is obvious that they do not give employment. If he invests his savings, the matter is less obvious, and different cases arise. + +One of the commonest things to do with savings is to lend them to some Government. In view of the fact that the bulk of the public expenditure of most civilized Governments consists in payment for past wars or preparation for future wars, the man who lends his money to a Government is in the same position as the bad men in Shakespeare who hire murderers. The net result of the man's economical habits is to increase the armed forces of the State to which he lends his savings. Obviously it would be better if he spent the money, even if he spent it in drink or gambling. + +But, I shall be told, the case is quite different when savings are invested in industrial enterprises. When such enterprises succeed, and produce something useful, this may be conceded. In these days, however, no one will deny that most enterprises fail. That means that a large amount of human labor, which might have been devoted to producing something that could be enjoyed, was expended on producing machines which, when produced, lay idle and did no good to anyone. The man who invests his savings in a concern that goes bankrupt is therefore injuring others as well as himself. If he spent his money, say, in giving parties for his friends, they (we may hope) would get pleasure, and so would all those upon whom he spent money, such as the butcher, the baker, and the bootlegger. But if he spends it (let us say) upon laying down rails for surface card in some place where surface cars turn out not to be wanted, he has diverted a mass of labor into channels where it gives pleasure to no one. Nevertheless, when he becomes poor through failure of his investment he will be regarded as a victim of undeserved misfortune, whereas the gay spendthrift, who has spent his money philanthropically, will be despised as a fool and a frivolous person. + +All this is only preliminary. I want to say, in all seriousness, that a great deal of harm is being done in the modern world by belief in the virtuousness of work, and that the road to happiness and prosperity lies in an organized diminution of work. + +First of all: what is work? Work is of two kinds: first, altering the position of matter at or near the earth's surface relatively to other such matter; second, telling other people to do so. The first kind is unpleasant and ill paid; the second is pleasant and highly paid. The second kind is capable of indefinite extension: there are not only those who give orders, but those who give advice as to what orders should be given. Usually two opposite kinds of advice are given simultaneously by two organized bodies of men; this is called politics. The skill required for this kind of work is not knowledge of the subjects as to which advice is given, but knowledge of the art of persuasive speaking and writing, i.e. of advertising. + +Throughout Europe, though not in America, there is a third class of men, more respected than either of the classes of workers. There are men who, through ownership of land, are able to make others pay for the privilege of being allowed to exist and to work. These landowners are idle, and I might therefore be expected to praise them. Unfortunately, their idleness is only rendered possible by the industry of others; indeed their desire for comfortable idleness is historically the source of the whole gospel of work. The last thing they have ever wished is that others should follow their example. + +From the beginning of civilization until the Industrial Revolution, a man could, as a rule, produce by hard work little more than was required for the subsistence of himself and his family, although his wife worked at least as hard as he did, and his children added their labor as soon as they were old enough to do so. The small surplus above bare necessaries was not left to those who produced it, but was appropriated by warriors and priests. In times of famine there was no surplus; the warriors and priests, however, still secured as much as at other times, with the result that many of the workers died of hunger. This system persisted in Russia until 1917 [1], and still persists in the East; in England, in spite of the Industrial Revolution, it remained in full force throughout the Napoleonic wars, and until a hundred years ago, when the new class of manufacturers acquired power. In America, the system came to an end with the Revolution, except in the South, where it persisted until the Civil War. A system which lasted so long and ended so recently has naturally left a profound impress upon men's thoughts and opinions. Much that we take for granted about the desirability of work is derived from this system, and, being pre-industrial, is not adapted to the modern world. Modern technique has made it possible for leisure, within limits, to be not the prerogative of small privileged classes, but a right evenly distributed throughout the community. The morality of work is the morality of slaves, and the modern world has no need of slavery. + +It is obvious that, in primitive communities, peasants, left to themselves, would not have parted with the slender surplus upon which the warriors and priests subsisted, but would have either produced less or consumed more. At first, sheer force compelled them to produce and part with the surplus. Gradually, however, it was found possible to induce many of them to accept an ethic according to which it was their duty to work hard, although part of their work went to support others in idleness. By this means the amount of compulsion required was lessened, and the expenses of government were diminished. To this day, 99 per cent of British wage-earners would be genuinely shocked if it were proposed that the King should not have a larger income than a working man. The conception of duty, speaking historically, has been a means used by the holders of power to induce others to live for the interests of their masters rather than for their own. Of course the holders of power conceal this fact from themselves by managing to believe that their interests are identical with the larger interests of humanity. Sometimes this is true; Athenian slave-owners, for instance, employed part of their leisure in making a permanent contribution to civilization which would have been impossible under a just economic system. Leisure is essential to civilization, and in former times leisure for the few was only rendered possible by the labors of the many. But their labors were valuable, not because work is good, but because leisure is good. And with modern technique it would be possible to distribute leisure justly without injury to civilization. + +Modern technique has made it possible to diminish enormously the amount of labor required to secure the necessaries of life for everyone. This was made obvious during the war. At that time all the men in the armed forces, and all the men and women engaged in the production of munitions, all the men and women engaged in spying, war propaganda, or Government offices connected with the war, were withdrawn from productive occupations. In spite of this, the general level of well-being among unskilled wage-earners on the side of the Allies was higher than before or since. The significance of this fact was concealed by finance: borrowing made it appear as if the future was nourishing the present. But that, of course, would have been impossible; a man cannot eat a loaf of bread that does not yet exist. The war showed conclusively that, by the scientific organization of production, it is possible to keep modern populations in fair comfort on a small part of the working capacity of the modern world. If, at the end of the war, the scientific organization, which had been created in order to liberate men for fighting and munition work, had been preserved, and the hours of the week had been cut down to four, all would have been well. Instead of that the old chaos was restored, those whose work was demanded were made to work long hours, and the rest were left to starve as unemployed. Why? Because work is a duty, and a man should not receive wages in proportion to what he has produced, but in proportion to his virtue as exemplified by his industry. + +This is the morality of the Slave State, applied in circumstances totally unlike those in which it arose. No wonder the result has been disastrous. Let us take an illustration. Suppose that, at a given moment, a certain number of people are engaged in the manufacture of pins. They make as many pins as the world needs, working (say) eight hours a day. Someone makes an invention by which the same number of men can make twice as many pins: pins are already so cheap that hardly any more will be bought at a lower price. In a sensible world, everybody concerned in the manufacturing of pins would take to working four hours instead of eight, and everything else would go on as before. But in the actual world this would be thought demoralizing. The men still work eight hours, there are too many pins, some employers go bankrupt, and half the men previously concerned in making pins are thrown out of work. There is, in the end, just as much leisure as on the other plan, but half the men are totally idle while half are still overworked. In this way, it is insured that the unavoidable leisure shall cause misery all round instead of being a universal source of happiness. Can anything more insane be imagined? + +The idea that the poor should have leisure has always been shocking to the rich. In England, in the early nineteenth century, fifteen hours was the ordinary day's work for a man; children sometimes did as much, and very commonly did twelve hours a day. When meddlesome busybodies suggested that perhaps these hours were rather long, they were told that work kept adults from drink and children from mischief. When I was a child, shortly after urban working men had acquired the vote, certain public holidays were established by law, to the great indignation of the upper classes. I remember hearing an old Duchess say: 'What do the poor want with holidays? They ought to work.' People nowadays are less frank, but the sentiment persists, and is the source of much of our economic confusion. + +Let us, for a moment, consider the ethics of work frankly, without superstition. Every human being, of necessity, consumes, in the course of his life, a certain amount of the produce of human labor. Assuming, as we may, that labor is on the whole disagreeable, it is unjust that a man should consume more than he produces. Of course he may provide services rather than commodities, like a medical man, for example; but he should provide something in return for his board and lodging. to this extent, the duty of work must be admitted, but to this extent only. + +I shall not dwell upon the fact that, in all modern societies outside the USSR, many people escape even this minimum amount of work, namely all those who inherit money and all those who marry money. I do not think the fact that these people are allowed to be idle is nearly so harmful as the fact that wage-earners are expected to overwork or starve. + +If the ordinary wage-earner worked four hours a day, there would be enough for everybody and no unemployment -- assuming a certain very moderate amount of sensible organization. This idea shocks the well-to-do, because they are convinced that the poor would not know how to use so much leisure. In America men often work long hours even when they are well off; such men, naturally, are indignant at the idea of leisure for wage-earners, except as the grim punishment of unemployment; in fact, they dislike leisure even for their sons. Oddly enough, while they wish their sons to work so hard as to have no time to be civilized, they do not mind their wives and daughters having no work at all. the snobbish admiration of uselessness, which, in an aristocratic society, extends to both sexes, is, under a plutocracy, confined to women; this, however, does not make it any more in agreement with common sense. + +The wise use of leisure, it must be conceded, is a product of civilization and education. A man who has worked long hours all his life will become bored if he becomes suddenly idle. But without a considerable amount of leisure a man is cut off from many of the best things. There is no longer any reason why the bulk of the population should suffer this deprivation; only a foolish asceticism, usually vicarious, makes us continue to insist on work in excessive quantities now that the need no longer exists. + +In the new creed which controls the government of Russia, while there is much that is very different from the traditional teaching of the West, there are some things that are quite unchanged. The attitude of the governing classes, and especially of those who conduct educational propaganda, on the subject of the dignity of labor, is almost exactly that which the governing classes of the world have always preached to what were called the 'honest poor'. Industry, sobriety, willingness to work long hours for distant advantages, even submissiveness to authority, all these reappear; moreover authority still represents the will of the Ruler of the Universe, Who, however, is now called by a new name, Dialectical Materialism. + +The victory of the proletariat in Russia has some points in common with the victory of the feminists in some other countries. For ages, men had conceded the superior saintliness of women, and had consoled women for their inferiority by maintaining that saintliness is more desirable than power. At last the feminists decided that they would have both, since the pioneers among them believed all that the men had told them about the desirability of virtue, but not what they had told them about the worthlessness of political power. A similar thing has happened in Russia as regards manual work. For ages, the rich and their sycophants have written in praise of 'honest toil', have praised the simple life, have professed a religion which teaches that the poor are much more likely to go to heaven than the rich, and in general have tried to make manual workers believe that there is some special nobility about altering the position of matter in space, just as men tried to make women believe that they derived some special nobility from their sexual enslavement. In Russia, all this teaching about the excellence of manual work has been taken seriously, with the result that the manual worker is more honored than anyone else. What are, in essence, revivalist appeals are made, but not for the old purposes: they are made to secure shock workers for special tasks. Manual work is the ideal which is held before the young, and is the basis of all ethical teaching. + +For the present, possibly, this is all to the good. A large country, full of natural resources, awaits development, and has has to be developed with very little use of credit. In these circumstances, hard work is necessary, and is likely to bring a great reward. But what will happen when the point has been reached where everybody could be comfortable without working long hours? + +In the West, we have various ways of dealing with this problem. We have no attempt at economic justice, so that a large proportion of the total produce goes to a small minority of the population, many of whom do no work at all. Owing to the absence of any central control over production, we produce hosts of things that are not wanted. We keep a large percentage of the working population idle, because we can dispense with their labor by making the others overwork. When all these methods prove inadequate, we have a war: we cause a number of people to manufacture high explosives, and a number of others to explode them, as if we were children who had just discovered fireworks. By a combination of all these devices we manage, though with difficulty, to keep alive the notion that a great deal of severe manual work must be the lot of the average man. + +In Russia, owing to more economic justice and central control over production, the problem will have to be differently solved. the rational solution would be, as soon as the necessaries and elementary comforts can be provided for all, to reduce the hours of labor gradually, allowing a popular vote to decide, at each stage, whether more leisure or more goods were to be preferred. But, having taught the supreme virtue of hard work, it is difficult to see how the authorities can aim at a paradise in which there will be much leisure and little work. It seems more likely that they will find continually fresh schemes, by which present leisure is to be sacrificed to future productivity. I read recently of an ingenious plan put forward by Russian engineers, for making the White Sea and the northern coasts of Siberia warm, by putting a dam across the Kara Sea. An admirable project, but liable to postpone proletarian comfort for a generation, while the nobility of toil is being displayed amid the ice-fields and snowstorms of the Arctic Ocean. This sort of thing, if it happens, will be the result of regarding the virtue of hard work as an end in itself, rather than as a means to a state of affairs in which it is no longer needed. + +The fact is that moving matter about, while a certain amount of it is necessary to our existence, is emphatically not one of the ends of human life. If it were, we should have to consider every navvy superior to Shakespeare. We have been misled in this matter by two causes. One is the necessity of keeping the poor contented, which has led the rich, for thousands of years, to preach the dignity of labor, while taking care themselves to remain undignified in this respect. The other is the new pleasure in mechanism, which makes us delight in the astonishingly clever changes that we can produce on the earth's surface. Neither of these motives makes any great appeal to the actual worker. If you ask him what he thinks the best part of his life, he is not likely to say: 'I enjoy manual work because it makes me feel that I am fulfilling man's noblest task, and because I like to think how much man can transform his planet. It is true that my body demands periods of rest, which I have to fill in as best I may, but I am never so happy as when the morning comes and I can return to the toil from which my contentment springs.' I have never heard working men say this sort of thing. They consider work, as it should be considered, a necessary means to a livelihood, and it is from their leisure that they derive whatever happiness they may enjoy. + +It will be said that, while a little leisure is pleasant, men would not know how to fill their days if they had only four hours of work out of the twenty-four. In so far as this is true in the modern world, it is a condemnation of our civilization; it would not have been true at any earlier period. There was formerly a capacity for light-heartedness and play which has been to some extent inhibited by the cult of efficiency. The modern man thinks that everything ought to be done for the sake of something else, and never for its own sake. Serious-minded persons, for example, are continually condemning the habit of going to the cinema, and telling us that it leads the young into crime. But all the work that goes to producing a cinema is respectable, because it is work, and because it brings a money profit. The notion that the desirable activities are those that bring a profit has made everything topsy-turvy. The butcher who provides you with meat and the baker who provides you with bread are praiseworthy, because they are making money; but when you enjoy the food they have provided, you are merely frivolous, unless you eat only to get strength for your work. Broadly speaking, it is held that getting money is good and spending money is bad. Seeing that they are two sides of one transaction, this is absurd; one might as well maintain that keys are good, but keyholes are bad. Whatever merit there may be in the production of goods must be entirely derivative from the advantage to be obtained by consuming them. The individual, in our society, works for profit; but the social purpose of his work lies in the consumption of what he produces. It is this divorce between the individual and the social purpose of production that makes it so difficult for men to think clearly in a world in which profit-making is the incentive to industry. We think too much of production, and too little of consumption. One result is that we attach too little importance to enjoyment and simple happiness, and that we do not judge production by the pleasure that it gives to the consumer. + +When I suggest that working hours should be reduced to four, I am not meaning to imply that all the remaining time should necessarily be spent in pure frivolity. I mean that four hours' work a day should entitle a man to the necessities and elementary comforts of life, and that the rest of his time should be his to use as he might see fit. It is an essential part of any such social system that education should be carried further than it usually is at present, and should aim, in part, at providing tastes which would enable a man to use leisure intelligently. I am not thinking mainly of the sort of things that would be considered 'highbrow'. Peasant dances have died out except in remote rural areas, but the impulses which caused them to be cultivated must still exist in human nature. The pleasures of urban populations have become mainly passive: seeing cinemas, watching football matches, listening to the radio, and so on. This results from the fact that their active energies are fully taken up with work; if they had more leisure, they would again enjoy pleasures in which they took an active part. + +In the past, there was a small leisure class and a larger working class. The leisure class enjoyed advantages for which there was no basis in social justice; this necessarily made it oppressive, limited its sympathies, and caused it to invent theories by which to justify its privileges. These facts greatly diminished its excellence, but in spite of this drawback it contributed nearly the whole of what we call civilization. It cultivated the arts and discovered the sciences; it wrote the books, invented the philosophies, and refined social relations. Even the liberation of the oppressed has usually been inaugurated from above. Without the leisure class, mankind would never have emerged from barbarism. + +The method of a leisure class without duties was, however, extraordinarily wasteful. None of the members of the class had to be taught to be industrious, and the class as a whole was not exceptionally intelligent. The class might produce one Darwin, but against him had to be set tens of thousands of country gentlemen who never thought of anything more intelligent than fox-hunting and punishing poachers. At present, the universities are supposed to provide, in a more systematic way, what the leisure class provided accidentally and as a by-product. This is a great improvement, but it has certain drawbacks. University life is so different from life in the world at large that men who live in academic milieu tend to be unaware of the preoccupations and problems of ordinary men and women; moreover their ways of expressing themselves are usually such as to rob their opinions of the influence that they ought to have upon the general public. Another disadvantage is that in universities studies are organized, and the man who thinks of some original line of research is likely to be discouraged. Academic institutions, therefore, useful as they are, are not adequate guardians of the interests of civilization in a world where everyone outside their walls is too busy for unutilitarian pursuits. + +In a world where no one is compelled to work more than four hours a day, every person possessed of scientific curiosity will be able to indulge it, and every painter will be able to paint without starving, however excellent his pictures may be. Young writers will not be obliged to draw attention to themselves by sensational pot-boilers, with a view to acquiring the economic independence needed for monumental works, for which, when the time at last comes, they will have lost the taste and capacity. Men who, in their professional work, have become interested in some phase of economics or government, will be able to develop their ideas without the academic detachment that makes the work of university economists often seem lacking in reality. Medical men will have the time to learn about the progress of medicine, teachers will not be exasperatedly struggling to teach by routine methods things which they learnt in their youth, which may, in the interval, have been proved to be untrue. + +Above all, there will be happiness and joy of life, instead of frayed nerves, weariness, and dyspepsia. The work exacted will be enough to make leisure delightful, but not enough to produce exhaustion. Since men will not be tired in their spare time, they will not demand only such amusements as are passive and vapid. At least one per cent will probably devote the time not spent in professional work to pursuits of some public importance, and, since they will not depend upon these pursuits for their livelihood, their originality will be unhampered, and there will be no need to conform to the standards set by elderly pundits. But it is not only in these exceptional cases that the advantages of leisure will appear. Ordinary men and women, having the opportunity of a happy life, will become more kindly and less persecuting and less inclined to view others with suspicion. The taste for war will die out, partly for this reason, and partly because it will involve long and severe work for all. Good nature is, of all moral qualities, the one that the world needs most, and good nature is the result of ease and security, not of a life of arduous struggle. Modern methods of production have given us the possibility of ease and security for all; we have chosen, instead, to have overwork for some and starvation for others. Hitherto we have continued to be as energetic as we were before there were machines; in this we have been foolish, but there is no reason to go on being foolish forever. + +[1] Since then, members of the Communist Party have succeeded to this privilege of the warriors and priests. diff --git a/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/wrap.js b/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/wrap.js new file mode 100644 index 00000000000000..0cfb76d178f91f --- /dev/null +++ b/tools/eslint/node_modules/optionator/node_modules/wordwrap/test/wrap.js @@ -0,0 +1,31 @@ +var assert = require('assert'); +var wordwrap = require('wordwrap'); + +var fs = require('fs'); +var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8'); + +exports.stop80 = function () { + var lines = wordwrap(80)(idleness).split(/\n/); + var words = idleness.split(/\s+/); + + lines.forEach(function (line) { + assert.ok(line.length <= 80, 'line > 80 columns'); + var chunks = line.match(/\S/) ? line.split(/\s+/) : []; + assert.deepEqual(chunks, words.splice(0, chunks.length)); + }); +}; + +exports.start20stop60 = function () { + var lines = wordwrap(20, 100)(idleness).split(/\n/); + var words = idleness.split(/\s+/); + + lines.forEach(function (line) { + assert.ok(line.length <= 100, 'line > 100 columns'); + var chunks = line + .split(/\s+/) + .filter(function (x) { return x.match(/\S/) }) + ; + assert.deepEqual(chunks, words.splice(0, chunks.length)); + assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' ')); + }); +}; diff --git a/tools/eslint/node_modules/optionator/package.json b/tools/eslint/node_modules/optionator/package.json new file mode 100644 index 00000000000000..116d2e9d3cd070 --- /dev/null +++ b/tools/eslint/node_modules/optionator/package.json @@ -0,0 +1,73 @@ +{ + "name": "optionator", + "version": "0.5.0", + "author": { + "name": "George Zahariev", + "email": "z@georgezahariev.com" + }, + "description": "option parsing and help generation", + "homepage": "https://github.com/gkz/optionator", + "keywords": [ + "options" + ], + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "main": "./lib/", + "bugs": { + "url": "https://github.com/gkz/optionator/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://raw.githubusercontent.com/gkz/optionator/master/LICENSE" + } + ], + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/optionator.git" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "prelude-ls": "~1.1.1", + "deep-is": "~0.1.2", + "wordwrap": "~0.0.2", + "type-check": "~0.3.1", + "levn": "~0.2.5", + "fast-levenshtein": "~1.0.0" + }, + "devDependencies": { + "LiveScript": "~1.3.1", + "mocha": "~2.0.1", + "istanbul": "~0.1.43" + }, + "gitHead": "52241eef663601bef5120c3a770d60533d2b3097", + "_id": "optionator@0.5.0", + "_shasum": "b75a8995a2d417df25b6e4e3862f50aa88651368", + "_from": "optionator@>=0.5.0 <0.6.0", + "_npmVersion": "2.0.0", + "_npmUser": { + "name": "gkz", + "email": "z@georgezahariev.com" + }, + "maintainers": [ + { + "name": "gkz", + "email": "z@georgezahariev.com" + } + ], + "dist": { + "shasum": "b75a8995a2d417df25b6e4e3862f50aa88651368", + "tarball": "http://registry.npmjs.org/optionator/-/optionator-0.5.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/optionator/-/optionator-0.5.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/strip-json-comments/cli.js b/tools/eslint/node_modules/strip-json-comments/cli.js new file mode 100755 index 00000000000000..ac4da48457a2f5 --- /dev/null +++ b/tools/eslint/node_modules/strip-json-comments/cli.js @@ -0,0 +1,41 @@ +#!/usr/bin/env node +'use strict'; +var fs = require('fs'); +var strip = require('./strip-json-comments'); +var input = process.argv[2]; + + +function getStdin(cb) { + var ret = ''; + + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', function (data) { + ret += data; + }); + + process.stdin.on('end', function () { + cb(ret); + }); +} + +if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) { + console.log('strip-json-comments > '); + console.log('or'); + console.log('cat | strip-json-comments > '); + return; +} + +if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) { + console.log(require('./package').version); + return; +} + +if (input) { + process.stdout.write(strip(fs.readFileSync(input, 'utf8'))); + return; +} + +getStdin(function (data) { + process.stdout.write(strip(data)); +}); diff --git a/tools/eslint/node_modules/strip-json-comments/package.json b/tools/eslint/node_modules/strip-json-comments/package.json new file mode 100644 index 00000000000000..0b4dc57515d3f0 --- /dev/null +++ b/tools/eslint/node_modules/strip-json-comments/package.json @@ -0,0 +1,78 @@ +{ + "name": "strip-json-comments", + "version": "1.0.2", + "description": "Strip comments from JSON. Lets you use comments in your JSON files!", + "keywords": [ + "json", + "strip", + "remove", + "delete", + "trim", + "comments", + "multiline", + "parse", + "config", + "configuration", + "conf", + "settings", + "util", + "env", + "environment", + "cli", + "bin" + ], + "license": "MIT", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "files": [ + "cli.js", + "strip-json-comments.js" + ], + "main": "strip-json-comments", + "bin": { + "strip-json-comments": "cli.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/strip-json-comments.git" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "*" + }, + "engines": { + "node": ">=0.8.0" + }, + "gitHead": "142dd671c71f90fb7fdba440184b1bb64543acb3", + "bugs": { + "url": "https://github.com/sindresorhus/strip-json-comments/issues" + }, + "homepage": "https://github.com/sindresorhus/strip-json-comments", + "_id": "strip-json-comments@1.0.2", + "_shasum": "5a48ab96023dbac1b7b8d0ffabf6f63f1677be9f", + "_from": "strip-json-comments@>=1.0.1 <1.1.0", + "_npmVersion": "2.1.2", + "_nodeVersion": "0.10.32", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "dist": { + "shasum": "5a48ab96023dbac1b7b8d0ffabf6f63f1677be9f", + "tarball": "http://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/strip-json-comments/readme.md b/tools/eslint/node_modules/strip-json-comments/readme.md new file mode 100644 index 00000000000000..336523243e6c0d --- /dev/null +++ b/tools/eslint/node_modules/strip-json-comments/readme.md @@ -0,0 +1,74 @@ +# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments) + +> Strip comments from JSON. Lets you use comments in your JSON files! + +This is now possible: + +```js +{ + // rainbows + "unicorn": /* ❤ */ "cake" +} +``` + +It will remove single-line comments `//` and multi-line comments `/**/`. + +Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin and a [require hook](https://github.com/uTest/autostrip-json-comments). + + +*There's already [json-comments](https://npmjs.org/package/json-comments), but it's only for Node.js and uses a naive regex to strip comments which fails on simple cases like `{"a":"//"}`. This module however parses out the comments.* + + +## Install + +```sh +$ npm install --save strip-json-comments +``` + +```sh +$ bower install --save strip-json-comments +``` + +```sh +$ component install sindresorhus/strip-json-comments +``` + + +## Usage + +```js +var json = '{/*rainbows*/"unicorn":"cake"}'; +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` + + +## API + +### stripJsonComments(input) + +#### input + +Type: `string` + +Accepts a string with JSON and returns a string without comments. + + +## CLI + +```sh +$ npm install --global strip-json-comments +``` + +```sh +$ strip-json-comments --help + +strip-json-comments input-file > output-file +# or +strip-json-comments < input-file > output-file +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js b/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js new file mode 100644 index 00000000000000..a47976fd51b4c0 --- /dev/null +++ b/tools/eslint/node_modules/strip-json-comments/strip-json-comments.js @@ -0,0 +1,67 @@ +/*! + strip-json-comments + Strip comments from JSON. Lets you use comments in your JSON files! + https://github.com/sindresorhus/strip-json-comments + by Sindre Sorhus + MIT License +*/ +(function () { + 'use strict'; + + function stripJsonComments(str) { + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var ret = ''; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && str[i - 1] !== '\\' && currentChar === '"') { + insideString = !insideString; + } + + if (insideString) { + ret += currentChar; + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + insideComment = 'single'; + i++; + } else if (insideComment === 'single' && currentChar + nextChar === '\r\n') { + insideComment = false; + i++; + ret += currentChar; + ret += nextChar; + continue; + } else if (insideComment === 'single' && currentChar === '\n') { + insideComment = false; + } else if (!insideComment && currentChar + nextChar === '/*') { + insideComment = 'multi'; + i++; + continue; + } else if (insideComment === 'multi' && currentChar + nextChar === '*/') { + insideComment = false; + i++; + continue; + } + + if (insideComment) { + continue; + } + + ret += currentChar; + } + + return ret; + } + + if (typeof module !== 'undefined' && module.exports) { + module.exports = stripJsonComments; + } else { + window.stripJsonComments = stripJsonComments; + } +})(); diff --git a/tools/eslint/node_modules/text-table/.travis.yml b/tools/eslint/node_modules/text-table/.travis.yml new file mode 100644 index 00000000000000..cc4dba29d959a2 --- /dev/null +++ b/tools/eslint/node_modules/text-table/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/tools/eslint/node_modules/text-table/LICENSE b/tools/eslint/node_modules/text-table/LICENSE new file mode 100644 index 00000000000000..ee27ba4b4412b0 --- /dev/null +++ b/tools/eslint/node_modules/text-table/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/text-table/example/align.js b/tools/eslint/node_modules/text-table/example/align.js new file mode 100644 index 00000000000000..9be43098cf87b8 --- /dev/null +++ b/tools/eslint/node_modules/text-table/example/align.js @@ -0,0 +1,8 @@ +var table = require('../'); +var t = table([ + [ 'beep', '1024' ], + [ 'boop', '33450' ], + [ 'foo', '1006' ], + [ 'bar', '45' ] +], { align: [ 'l', 'r' ] }); +console.log(t); diff --git a/tools/eslint/node_modules/text-table/example/center.js b/tools/eslint/node_modules/text-table/example/center.js new file mode 100644 index 00000000000000..52b1c69e012cb1 --- /dev/null +++ b/tools/eslint/node_modules/text-table/example/center.js @@ -0,0 +1,8 @@ +var table = require('../'); +var t = table([ + [ 'beep', '1024', 'xyz' ], + [ 'boop', '3388450', 'tuv' ], + [ 'foo', '10106', 'qrstuv' ], + [ 'bar', '45', 'lmno' ] +], { align: [ 'l', 'c', 'l' ] }); +console.log(t); diff --git a/tools/eslint/node_modules/text-table/example/dotalign.js b/tools/eslint/node_modules/text-table/example/dotalign.js new file mode 100644 index 00000000000000..2cea6299368475 --- /dev/null +++ b/tools/eslint/node_modules/text-table/example/dotalign.js @@ -0,0 +1,9 @@ +var table = require('../'); +var t = table([ + [ 'beep', '1024' ], + [ 'boop', '334.212' ], + [ 'foo', '1006' ], + [ 'bar', '45.6' ], + [ 'baz', '123.' ] +], { align: [ 'l', '.' ] }); +console.log(t); diff --git a/tools/eslint/node_modules/text-table/example/doubledot.js b/tools/eslint/node_modules/text-table/example/doubledot.js new file mode 100644 index 00000000000000..bab983b664cd6d --- /dev/null +++ b/tools/eslint/node_modules/text-table/example/doubledot.js @@ -0,0 +1,11 @@ +var table = require('../'); +var t = table([ + [ '0.1.2' ], + [ '11.22.33' ], + [ '5.6.7' ], + [ '1.22222' ], + [ '12345.' ], + [ '5555.' ], + [ '123' ] +], { align: [ '.' ] }); +console.log(t); diff --git a/tools/eslint/node_modules/text-table/example/table.js b/tools/eslint/node_modules/text-table/example/table.js new file mode 100644 index 00000000000000..903ea4c417ccb0 --- /dev/null +++ b/tools/eslint/node_modules/text-table/example/table.js @@ -0,0 +1,6 @@ +var table = require('../'); +var t = table([ + [ 'master', '0123456789abcdef' ], + [ 'staging', 'fedcba9876543210' ] +]); +console.log(t); diff --git a/tools/eslint/node_modules/text-table/index.js b/tools/eslint/node_modules/text-table/index.js new file mode 100644 index 00000000000000..5c0ba9876a5e0f --- /dev/null +++ b/tools/eslint/node_modules/text-table/index.js @@ -0,0 +1,86 @@ +module.exports = function (rows_, opts) { + if (!opts) opts = {}; + var hsep = opts.hsep === undefined ? ' ' : opts.hsep; + var align = opts.align || []; + var stringLength = opts.stringLength + || function (s) { return String(s).length; } + ; + + var dotsizes = reduce(rows_, function (acc, row) { + forEach(row, function (c, ix) { + var n = dotindex(c); + if (!acc[ix] || n > acc[ix]) acc[ix] = n; + }); + return acc; + }, []); + + var rows = map(rows_, function (row) { + return map(row, function (c_, ix) { + var c = String(c_); + if (align[ix] === '.') { + var index = dotindex(c); + var size = dotsizes[ix] + (/\./.test(c) ? 1 : 2) + - (stringLength(c) - index) + ; + return c + Array(size).join(' '); + } + else return c; + }); + }); + + var sizes = reduce(rows, function (acc, row) { + forEach(row, function (c, ix) { + var n = stringLength(c); + if (!acc[ix] || n > acc[ix]) acc[ix] = n; + }); + return acc; + }, []); + + return map(rows, function (row) { + return map(row, function (c, ix) { + var n = (sizes[ix] - stringLength(c)) || 0; + var s = Array(Math.max(n + 1, 1)).join(' '); + if (align[ix] === 'r' || align[ix] === '.') { + return s + c; + } + if (align[ix] === 'c') { + return Array(Math.ceil(n / 2 + 1)).join(' ') + + c + Array(Math.floor(n / 2 + 1)).join(' ') + ; + } + + return c + s; + }).join(hsep).replace(/\s+$/, ''); + }).join('\n'); +}; + +function dotindex (c) { + var m = /\.[^.]*$/.exec(c); + return m ? m.index + 1 : c.length; +} + +function reduce (xs, f, init) { + if (xs.reduce) return xs.reduce(f, init); + var i = 0; + var acc = arguments.length >= 3 ? init : xs[i++]; + for (; i < xs.length; i++) { + f(acc, xs[i], i); + } + return acc; +} + +function forEach (xs, f) { + if (xs.forEach) return xs.forEach(f); + for (var i = 0; i < xs.length; i++) { + f.call(xs, xs[i], i); + } +} + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f.call(xs, xs[i], i)); + } + return res; +} diff --git a/tools/eslint/node_modules/text-table/package.json b/tools/eslint/node_modules/text-table/package.json new file mode 100644 index 00000000000000..1c4c21571e5d18 --- /dev/null +++ b/tools/eslint/node_modules/text-table/package.json @@ -0,0 +1,52 @@ +{ + "name": "text-table", + "version": "0.2.0", + "description": "borderless text tables with alignment", + "main": "index.js", + "devDependencies": { + "tap": "~0.4.0", + "tape": "~1.0.2", + "cli-color": "~0.2.3" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "chrome/20..latest", + "firefox/10..latest", + "safari/latest", + "opera/11.0..latest", + "iphone/6", + "ipad/6" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/text-table.git" + }, + "homepage": "https://github.com/substack/text-table", + "keywords": [ + "text", + "table", + "align", + "ascii", + "rows", + "tabular" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "readme": "# text-table\n\ngenerate borderless text table strings suitable for printing to stdout\n\n[![build status](https://secure.travis-ci.org/substack/text-table.png)](http://travis-ci.org/substack/text-table)\n\n[![browser support](https://ci.testling.com/substack/text-table.png)](http://ci.testling.com/substack/text-table)\n\n# example\n\n## default align\n\n``` js\nvar table = require('text-table');\nvar t = table([\n [ 'master', '0123456789abcdef' ],\n [ 'staging', 'fedcba9876543210' ]\n]);\nconsole.log(t);\n```\n\n```\nmaster 0123456789abcdef\nstaging fedcba9876543210\n```\n\n## left-right align\n\n``` js\nvar table = require('text-table');\nvar t = table([\n [ 'beep', '1024' ],\n [ 'boop', '33450' ],\n [ 'foo', '1006' ],\n [ 'bar', '45' ]\n], { align: [ 'l', 'r' ] });\nconsole.log(t);\n```\n\n```\nbeep 1024\nboop 33450\nfoo 1006\nbar 45\n```\n\n## dotted align\n\n``` js\nvar table = require('text-table');\nvar t = table([\n [ 'beep', '1024' ],\n [ 'boop', '334.212' ],\n [ 'foo', '1006' ],\n [ 'bar', '45.6' ],\n [ 'baz', '123.' ]\n], { align: [ 'l', '.' ] });\nconsole.log(t);\n```\n\n```\nbeep 1024\nboop 334.212\nfoo 1006\nbar 45.6\nbaz 123.\n```\n\n## centered\n\n``` js\nvar table = require('text-table');\nvar t = table([\n [ 'beep', '1024', 'xyz' ],\n [ 'boop', '3388450', 'tuv' ],\n [ 'foo', '10106', 'qrstuv' ],\n [ 'bar', '45', 'lmno' ]\n], { align: [ 'l', 'c', 'l' ] });\nconsole.log(t);\n```\n\n```\nbeep 1024 xyz\nboop 3388450 tuv\nfoo 10106 qrstuv\nbar 45 lmno\n```\n\n# methods\n\n``` js\nvar table = require('text-table')\n```\n\n## var s = table(rows, opts={})\n\nReturn a formatted table string `s` from an array of `rows` and some options\n`opts`.\n\n`rows` should be an array of arrays containing strings, numbers, or other\nprintable values.\n\noptions can be:\n\n* `opts.hsep` - separator to use between columns, default `' '`\n* `opts.align` - array of alignment types for each column, default `['l','l',...]`\n* `opts.stringLength` - callback function to use when calculating the string length\n\nalignment types are:\n\n* `'l'` - left\n* `'r'` - right\n* `'c'` - center\n* `'.'` - decimal\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install text-table\n```\n\n# Use with ANSI-colors\n\nSince the string length of ANSI color schemes does not equal the length\nJavaScript sees internally it is necessary to pass the a custom string length\ncalculator during the main function call.\n\nSee the `test/ansi-colors.js` file for an example.\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/text-table/issues" + }, + "_id": "text-table@0.2.0", + "_from": "text-table@>=0.2.0 <0.3.0" +} diff --git a/tools/eslint/node_modules/text-table/readme.markdown b/tools/eslint/node_modules/text-table/readme.markdown new file mode 100644 index 00000000000000..18806acd9efbed --- /dev/null +++ b/tools/eslint/node_modules/text-table/readme.markdown @@ -0,0 +1,134 @@ +# text-table + +generate borderless text table strings suitable for printing to stdout + +[![build status](https://secure.travis-ci.org/substack/text-table.png)](http://travis-ci.org/substack/text-table) + +[![browser support](https://ci.testling.com/substack/text-table.png)](http://ci.testling.com/substack/text-table) + +# example + +## default align + +``` js +var table = require('text-table'); +var t = table([ + [ 'master', '0123456789abcdef' ], + [ 'staging', 'fedcba9876543210' ] +]); +console.log(t); +``` + +``` +master 0123456789abcdef +staging fedcba9876543210 +``` + +## left-right align + +``` js +var table = require('text-table'); +var t = table([ + [ 'beep', '1024' ], + [ 'boop', '33450' ], + [ 'foo', '1006' ], + [ 'bar', '45' ] +], { align: [ 'l', 'r' ] }); +console.log(t); +``` + +``` +beep 1024 +boop 33450 +foo 1006 +bar 45 +``` + +## dotted align + +``` js +var table = require('text-table'); +var t = table([ + [ 'beep', '1024' ], + [ 'boop', '334.212' ], + [ 'foo', '1006' ], + [ 'bar', '45.6' ], + [ 'baz', '123.' ] +], { align: [ 'l', '.' ] }); +console.log(t); +``` + +``` +beep 1024 +boop 334.212 +foo 1006 +bar 45.6 +baz 123. +``` + +## centered + +``` js +var table = require('text-table'); +var t = table([ + [ 'beep', '1024', 'xyz' ], + [ 'boop', '3388450', 'tuv' ], + [ 'foo', '10106', 'qrstuv' ], + [ 'bar', '45', 'lmno' ] +], { align: [ 'l', 'c', 'l' ] }); +console.log(t); +``` + +``` +beep 1024 xyz +boop 3388450 tuv +foo 10106 qrstuv +bar 45 lmno +``` + +# methods + +``` js +var table = require('text-table') +``` + +## var s = table(rows, opts={}) + +Return a formatted table string `s` from an array of `rows` and some options +`opts`. + +`rows` should be an array of arrays containing strings, numbers, or other +printable values. + +options can be: + +* `opts.hsep` - separator to use between columns, default `' '` +* `opts.align` - array of alignment types for each column, default `['l','l',...]` +* `opts.stringLength` - callback function to use when calculating the string length + +alignment types are: + +* `'l'` - left +* `'r'` - right +* `'c'` - center +* `'.'` - decimal + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install text-table +``` + +# Use with ANSI-colors + +Since the string length of ANSI color schemes does not equal the length +JavaScript sees internally it is necessary to pass the a custom string length +calculator during the main function call. + +See the `test/ansi-colors.js` file for an example. + +# license + +MIT diff --git a/tools/eslint/node_modules/text-table/test/align.js b/tools/eslint/node_modules/text-table/test/align.js new file mode 100644 index 00000000000000..245357f26a76b9 --- /dev/null +++ b/tools/eslint/node_modules/text-table/test/align.js @@ -0,0 +1,18 @@ +var test = require('tape'); +var table = require('../'); + +test('align', function (t) { + t.plan(1); + var s = table([ + [ 'beep', '1024' ], + [ 'boop', '33450' ], + [ 'foo', '1006' ], + [ 'bar', '45' ] + ], { align: [ 'l', 'r' ] }); + t.equal(s, [ + 'beep 1024', + 'boop 33450', + 'foo 1006', + 'bar 45' + ].join('\n')); +}); diff --git a/tools/eslint/node_modules/text-table/test/ansi-colors.js b/tools/eslint/node_modules/text-table/test/ansi-colors.js new file mode 100644 index 00000000000000..fbc5bb10ad732a --- /dev/null +++ b/tools/eslint/node_modules/text-table/test/ansi-colors.js @@ -0,0 +1,32 @@ +var test = require('tape'); +var table = require('../'); +var color = require('cli-color'); +var ansiTrim = require('cli-color/lib/trim'); + +test('center', function (t) { + t.plan(1); + var opts = { + align: [ 'l', 'c', 'l' ], + stringLength: function(s) { return ansiTrim(s).length } + }; + var s = table([ + [ + color.red('Red'), color.green('Green'), color.blue('Blue') + ], + [ + color.bold('Bold'), color.underline('Underline'), + color.italic('Italic') + ], + [ + color.inverse('Inverse'), color.strike('Strike'), + color.blink('Blink') + ], + [ 'bar', '45', 'lmno' ] + ], opts); + t.equal(ansiTrim(s), [ + 'Red Green Blue', + 'Bold Underline Italic', + 'Inverse Strike Blink', + 'bar 45 lmno' + ].join('\n')); +}); diff --git a/tools/eslint/node_modules/text-table/test/center.js b/tools/eslint/node_modules/text-table/test/center.js new file mode 100644 index 00000000000000..c2c7a62a8f8cca --- /dev/null +++ b/tools/eslint/node_modules/text-table/test/center.js @@ -0,0 +1,18 @@ +var test = require('tape'); +var table = require('../'); + +test('center', function (t) { + t.plan(1); + var s = table([ + [ 'beep', '1024', 'xyz' ], + [ 'boop', '3388450', 'tuv' ], + [ 'foo', '10106', 'qrstuv' ], + [ 'bar', '45', 'lmno' ] + ], { align: [ 'l', 'c', 'l' ] }); + t.equal(s, [ + 'beep 1024 xyz', + 'boop 3388450 tuv', + 'foo 10106 qrstuv', + 'bar 45 lmno' + ].join('\n')); +}); diff --git a/tools/eslint/node_modules/text-table/test/dotalign.js b/tools/eslint/node_modules/text-table/test/dotalign.js new file mode 100644 index 00000000000000..f804f9281ab135 --- /dev/null +++ b/tools/eslint/node_modules/text-table/test/dotalign.js @@ -0,0 +1,20 @@ +var test = require('tape'); +var table = require('../'); + +test('dot align', function (t) { + t.plan(1); + var s = table([ + [ 'beep', '1024' ], + [ 'boop', '334.212' ], + [ 'foo', '1006' ], + [ 'bar', '45.6' ], + [ 'baz', '123.' ] + ], { align: [ 'l', '.' ] }); + t.equal(s, [ + 'beep 1024', + 'boop 334.212', + 'foo 1006', + 'bar 45.6', + 'baz 123.' + ].join('\n')); +}); diff --git a/tools/eslint/node_modules/text-table/test/doubledot.js b/tools/eslint/node_modules/text-table/test/doubledot.js new file mode 100644 index 00000000000000..659b57c9314bca --- /dev/null +++ b/tools/eslint/node_modules/text-table/test/doubledot.js @@ -0,0 +1,24 @@ +var test = require('tape'); +var table = require('../'); + +test('dot align', function (t) { + t.plan(1); + var s = table([ + [ '0.1.2' ], + [ '11.22.33' ], + [ '5.6.7' ], + [ '1.22222' ], + [ '12345.' ], + [ '5555.' ], + [ '123' ] + ], { align: [ '.' ] }); + t.equal(s, [ + ' 0.1.2', + '11.22.33', + ' 5.6.7', + ' 1.22222', + '12345.', + ' 5555.', + ' 123' + ].join('\n')); +}); diff --git a/tools/eslint/node_modules/text-table/test/table.js b/tools/eslint/node_modules/text-table/test/table.js new file mode 100644 index 00000000000000..9c6701464cf66a --- /dev/null +++ b/tools/eslint/node_modules/text-table/test/table.js @@ -0,0 +1,14 @@ +var test = require('tape'); +var table = require('../'); + +test('table', function (t) { + t.plan(1); + var s = table([ + [ 'master', '0123456789abcdef' ], + [ 'staging', 'fedcba9876543210' ] + ]); + t.equal(s, [ + 'master 0123456789abcdef', + 'staging fedcba9876543210' + ].join('\n')); +}); diff --git a/tools/eslint/node_modules/user-home/cli.js b/tools/eslint/node_modules/user-home/cli.js new file mode 100755 index 00000000000000..bacbd22755e08f --- /dev/null +++ b/tools/eslint/node_modules/user-home/cli.js @@ -0,0 +1,26 @@ +#!/usr/bin/env node +'use strict'; +var pkg = require('./package.json'); +var userHome = require('./'); + +function help() { + console.log([ + pkg.description, + '', + 'Example', + ' $ user-home', + ' /Users/sindresorhus' + ].join('\n')); +} + +if (process.argv.indexOf('--help') !== -1) { + help(); + return; +} + +if (process.argv.indexOf('--version') !== -1) { + console.log(pkg.version); + return; +} + +process.stdout.write(userHome); diff --git a/tools/eslint/node_modules/user-home/index.js b/tools/eslint/node_modules/user-home/index.js new file mode 100644 index 00000000000000..d53b7939ae6a4f --- /dev/null +++ b/tools/eslint/node_modules/user-home/index.js @@ -0,0 +1,15 @@ +'use strict'; +var env = process.env; +var home = env.HOME; +var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME; + +if (process.platform === 'win32') { + module.exports = env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null; +} else if (process.platform === 'darwin') { + module.exports = home || (user ? '/Users/' + user : null) || null; +} else if (process.platform === 'linux') { + module.exports = home || + (user ? (process.getuid() === 0 ? '/root' : '/home/' + user) : null) || null; +} else { + module.exports = home || null; +} diff --git a/tools/eslint/node_modules/user-home/license b/tools/eslint/node_modules/user-home/license new file mode 100644 index 00000000000000..654d0bfe943437 --- /dev/null +++ b/tools/eslint/node_modules/user-home/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tools/eslint/node_modules/user-home/package.json b/tools/eslint/node_modules/user-home/package.json new file mode 100644 index 00000000000000..8b9e8b4854d16d --- /dev/null +++ b/tools/eslint/node_modules/user-home/package.json @@ -0,0 +1,69 @@ +{ + "name": "user-home", + "version": "1.1.1", + "description": "Get the path to the user home directory", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/user-home.git" + }, + "bin": { + "user-home": "cli.js" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "node test.js" + }, + "files": [ + "index.js", + "cli.js" + ], + "keywords": [ + "cli", + "bin", + "user", + "home", + "homedir", + "dir", + "directory", + "folder", + "path" + ], + "devDependencies": { + "ava": "0.0.3" + }, + "gitHead": "cf6ba885d3e6bf625fb3c15ad0334fa623968481", + "bugs": { + "url": "https://github.com/sindresorhus/user-home/issues" + }, + "homepage": "https://github.com/sindresorhus/user-home", + "_id": "user-home@1.1.1", + "_shasum": "2b5be23a32b63a7c9deb8d0f28d485724a3df190", + "_from": "user-home@>=1.0.0 <2.0.0", + "_npmVersion": "2.1.16", + "_nodeVersion": "0.10.32", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "dist": { + "shasum": "2b5be23a32b63a7c9deb8d0f28d485724a3df190", + "tarball": "http://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/user-home/readme.md b/tools/eslint/node_modules/user-home/readme.md new file mode 100644 index 00000000000000..5307a07ef5144c --- /dev/null +++ b/tools/eslint/node_modules/user-home/readme.md @@ -0,0 +1,42 @@ +# user-home [![Build Status](https://travis-ci.org/sindresorhus/user-home.svg?branch=master)](https://travis-ci.org/sindresorhus/user-home) + +> Get the path to the user home directory + + +## Install + +```sh +$ npm install --save user-home +``` + + +## Usage + +```js +var userHome = require('user-home'); + +console.log(userHome); +//=> /Users/sindresorhus +``` + +Returns `null` in the unlikely scenario that the home directory can't be found. + + +## CLI + +```sh +$ npm install --global user-home +``` + +```sh +$ user-home --help + +Example + $ user-home + /Users/sindresorhus +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/eslint/node_modules/xml-escape/.npmignore b/tools/eslint/node_modules/xml-escape/.npmignore new file mode 100644 index 00000000000000..a72b52ebe89779 --- /dev/null +++ b/tools/eslint/node_modules/xml-escape/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules diff --git a/tools/eslint/node_modules/xml-escape/LICENSE b/tools/eslint/node_modules/xml-escape/LICENSE new file mode 100644 index 00000000000000..bd261effaee331 --- /dev/null +++ b/tools/eslint/node_modules/xml-escape/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Michael Hernandez + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/eslint/node_modules/xml-escape/README.md b/tools/eslint/node_modules/xml-escape/README.md new file mode 100644 index 00000000000000..db55ce80c60b8c --- /dev/null +++ b/tools/eslint/node_modules/xml-escape/README.md @@ -0,0 +1,15 @@ +xml-escape +========== + +Escape XML in javascript (NodeJS) + + +npm install xml-escape + +// Warning escape is a reserved word, so maybe best to use xmlescape for var name +var xmlescape = require('xml-escape'); + +xmlescape('"hello" \'world\' & false < true > -1') + +// output +// '"hello" 'world' & true < false > -1' \ No newline at end of file diff --git a/tools/eslint/node_modules/xml-escape/index.js b/tools/eslint/node_modules/xml-escape/index.js new file mode 100644 index 00000000000000..d26715ddd5d546 --- /dev/null +++ b/tools/eslint/node_modules/xml-escape/index.js @@ -0,0 +1,15 @@ + + +var escape = module.exports = function escape(string) { + return string.replace(/([&"<>'])/g, function(str, item) { + return escape.map[item]; + }) +} + +var map = escape.map = { + '>': '>' + , '<': '<' + , "'": ''' + , '"': '"' + , '&': '&' +} \ No newline at end of file diff --git a/tools/eslint/node_modules/xml-escape/package.json b/tools/eslint/node_modules/xml-escape/package.json new file mode 100644 index 00000000000000..46412796d2a5c1 --- /dev/null +++ b/tools/eslint/node_modules/xml-escape/package.json @@ -0,0 +1,53 @@ +{ + "name": "xml-escape", + "version": "1.0.0", + "description": "Escape XML ", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/miketheprogrammer/xml-escape.git" + }, + "keywords": [ + "Escape", + "XML", + "Unesacpe", + "encoding", + "xml-escape" + ], + "author": { + "name": "Michael Hernandez - michael.hernandez1988@gmail.com" + }, + "license": "MIT License", + "bugs": { + "url": "https://github.com/miketheprogrammer/xml-escape/issues" + }, + "homepage": "https://github.com/miketheprogrammer/xml-escape", + "dependencies": {}, + "devDependencies": { + "tape": "~2.4.2" + }, + "_id": "xml-escape@1.0.0", + "dist": { + "shasum": "00963d697b2adf0c185c4e04e73174ba9b288eb2", + "tarball": "http://registry.npmjs.org/xml-escape/-/xml-escape-1.0.0.tgz" + }, + "_from": "xml-escape@>=1.0.0 <1.1.0", + "_npmVersion": "1.3.14", + "_npmUser": { + "name": "mhernandez", + "email": "michael.hernandez1988@gmail.com" + }, + "maintainers": [ + { + "name": "mhernandez", + "email": "michael.hernandez1988@gmail.com" + } + ], + "directories": {}, + "_shasum": "00963d697b2adf0c185c4e04e73174ba9b288eb2", + "_resolved": "https://registry.npmjs.org/xml-escape/-/xml-escape-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/eslint/node_modules/xml-escape/test.js b/tools/eslint/node_modules/xml-escape/test.js new file mode 100644 index 00000000000000..211c3b8164dd0a --- /dev/null +++ b/tools/eslint/node_modules/xml-escape/test.js @@ -0,0 +1,7 @@ +var test = require('tape'); +var escape = require('./index'); +test("Characters should be escaped properly", function (t) { + t.plan(1); + + t.equals(escape('" \' < > &'), '" ' < > &'); +}) \ No newline at end of file diff --git a/tools/eslint/package.json b/tools/eslint/package.json new file mode 100644 index 00000000000000..97d2ca2f1336d8 --- /dev/null +++ b/tools/eslint/package.json @@ -0,0 +1,119 @@ +{ + "name": "eslint", + "version": "0.20.0", + "author": { + "name": "Nicholas C. Zakas", + "email": "nicholas+npm@nczconsulting.com" + }, + "description": "An AST-based pattern checker for JavaScript.", + "bin": { + "eslint": "./bin/eslint.js" + }, + "main": "./lib/api.js", + "scripts": { + "test": "node Makefile.js test", + "lint": "node Makefile.js lint", + "patch": "node Makefile.js patch", + "minor": "node Makefile.js minor", + "major": "node Makefile.js major", + "docs": "node Makefile.js docs", + "gensite": "node Makefile.js gensite", + "browserify": "node Makefile.js browserify", + "perf": "node Makefile.js perf", + "profile": "beefy tests/bench/bench.js --open -- -t brfs -t ./tests/bench/xform-rules.js", + "coveralls": "cat ./coverage/lcov.info | coveralls" + }, + "files": [ + "LICENSE", + "README.md", + "bin", + "conf", + "lib" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/eslint.git" + }, + "homepage": "http://eslint.org", + "bugs": { + "url": "https://github.com/eslint/eslint/issues/" + }, + "dependencies": { + "chalk": "^1.0.0", + "concat-stream": "^1.4.6", + "debug": "^2.1.1", + "doctrine": "^0.6.2", + "escape-string-regexp": "^1.0.2", + "escope": "^3.0.0", + "espree": "^2.0.1", + "estraverse": "^2.0.0", + "estraverse-fb": "^1.3.1", + "globals": "^6.1.0", + "js-yaml": "^3.2.5", + "minimatch": "^2.0.1", + "mkdirp": "^0.5.0", + "object-assign": "^2.0.0", + "optionator": "^0.5.0", + "strip-json-comments": "~1.0.1", + "text-table": "~0.2.0", + "user-home": "^1.0.0", + "xml-escape": "~1.0.0" + }, + "devDependencies": { + "beefy": "^1.0.0", + "brfs": "0.0.9", + "browserify": "^8.1.3", + "chai": "^1.9.1", + "coveralls": "2.11.2", + "dateformat": "^1.0.8", + "esprima-fb": "^10001.1.0-dev-harmony-fb", + "eslint-tester": "^0.6.0", + "istanbul": "^0.3.5", + "jsdoc": "^3.3.0-beta1", + "jsonlint": "^1.6.2", + "markdownlint": "^0.0.4", + "mocha": "^2.1.0", + "mocha-phantomjs": "^3.5.0", + "npm-license": "^0.2.3", + "phantomjs": "^1.9.9", + "proxyquire": "^1.0.0", + "semver": "^4.1.0", + "shelljs": "^0.3.0", + "shelljs-nodecli": "~0.1.0", + "sinon": "^1.12.2", + "through": "^2.3.6" + }, + "keywords": [ + "ast", + "lint", + "javascript", + "ecmascript", + "espree" + ], + "license": "MIT", + "engines": { + "node": ">=0.10" + }, + "gitHead": "dc500e81162bf0cb4747a4a415c121b0c46975cb", + "_id": "eslint@0.20.0", + "_shasum": "796931e62d5ebd0a9b0fc1730820a73b2242ab85", + "_from": "eslint@*", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + }, + "maintainers": [ + { + "name": "nzakas", + "email": "nicholas@nczconsulting.com" + } + ], + "dist": { + "shasum": "796931e62d5ebd0a9b0fc1730820a73b2242ab85", + "tarball": "http://registry.npmjs.org/eslint/-/eslint-0.20.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/eslint/-/eslint-0.20.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/tools/install.py b/tools/install.py index a14e89426c6929..8d76a14860dc51 100755 --- a/tools/install.py +++ b/tools/install.py @@ -198,8 +198,8 @@ def run(args): # argv[2] is a custom install prefix for packagers (think DESTDIR) # argv[3] is a custom install prefix (think PREFIX) # Difference is that dst_dir won't be included in shebang lines etc. - if len(args) > 2: - dst_dir = args[2] + dst_dir = args[2] if len(args) > 2 else '' + if len(args) > 3: node_prefix = args[3] diff --git a/tools/test-npm.sh b/tools/test-npm.sh new file mode 100755 index 00000000000000..9e7f161e7f5046 --- /dev/null +++ b/tools/test-npm.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +set -e + +# always change the working directory to the project's root directory +cd $(dirname $0)/.. + +# pass NODE_EXE from something like Makefile +# it should point to either {./}node or {./}node.exe, depending on the platform +if [ -z $NODE_EXE ]; then + echo "No node executable provided. Bailing." >&2 + exit 0 +fi + +rm -rf test-npm +mkdir test-npm + +# make a copy of deps/npm to run the tests on +cp -r deps/npm/ test-npm/ + +cd test-npm + +# do a rm first just in case deps/npm contained these +rm -rf npm-cache npm-tmp npm-prefix +mkdir npm-cache npm-tmp npm-prefix + +# set some npm env varibles to point to our new temporary folders +export npm_config_cache="npm-cache" +export npm_config_prefix="npm-prefix" +export npm_config_tmp="npm-tmp" + +# install npm devDependencies and run npm's tests +../$NODE_EXE cli.js install --ignore-scripts +../$NODE_EXE cli.js run-script test-all + +# clean up everything one single shot +cd .. && rm -rf test-npm diff --git a/vcbuild.bat b/vcbuild.bat index 97d6ba3bbc5511..21e8d5411a7f4e 100644 --- a/vcbuild.bat +++ b/vcbuild.bat @@ -21,7 +21,7 @@ set snapshot_arg= set noprojgen= set nobuild= set nosign= -set snapshot= +set nosnapshot= set test_args= set msi= set licensertf= @@ -47,7 +47,7 @@ if /i "%1"=="x64" set target_arch=x64&goto arg-ok if /i "%1"=="noprojgen" set noprojgen=1&goto arg-ok if /i "%1"=="nobuild" set nobuild=1&goto arg-ok if /i "%1"=="nosign" set nosign=1&goto arg-ok -if /i "%1"=="snapshot" set snapshot=1&goto arg-ok +if /i "%1"=="nosnapshot" set nosnapshot=1&goto arg-ok if /i "%1"=="noetw" set noetw=1&goto arg-ok if /i "%1"=="noperfctr" set noperfctr=1&goto arg-ok if /i "%1"=="licensertf" set licensertf=1&goto arg-ok @@ -76,7 +76,7 @@ goto next-arg :args-done if "%config%"=="Debug" set debug_arg=--debug if "%target_arch%"=="x64" set msiplatform=x64 -if defined snapshot set snapshot_arg=--with-snapshot +if defined nosnapshot set snapshot_arg=--without-snapshot if defined noetw set noetw_arg=--without-etw& set noetw_msi_arg=/p:NoETW=1 if defined noperfctr set noperfctr_arg=--without-perfctr& set noperfctr_msi_arg=/p:NoPerfCtr=1 @@ -174,15 +174,14 @@ if "%config%"=="Debug" set test_args=--mode=debug %test_args% if "%config%"=="Release" set test_args=--mode=release %test_args% echo running 'cctest' "%config%\cctest" -echo running 'python tools/test.py %test_args%' -python tools/test.py %test_args% +echo running 'python tools\test.py %test_args%' +python tools\test.py %test_args% goto jslint :jslint if not defined jslint goto exit echo running jslint -set PYTHONPATH=tools/closure_linter/;tools/gflags/ -python tools/closure_linter/closure_linter/gjslint.py --unix_mode --strict --nojsdoc -r lib/ -r src/ --exclude_files lib/punycode.js +%config%\iojs tools\eslint\bin\eslint.js src lib test --reset --quiet goto exit :create-msvs-files-failed